Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 44 additions & 4 deletions sip/sip-core/src/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,14 +263,14 @@ impl Endpoint {

if let Some(maddr) = via
.params
.get_val("maddr")
.get_val_ignore_ascii_case("maddr")
.and_then(|maddr| maddr.parse::<IpAddr>().ok())
{
// TODO maddr default port guessing (currently defaulting to 5060)
SocketAddr::new(maddr, via.sent_by.port.unwrap_or(5060))
} else if let Some(rport) = via
.params
.get_val("rport")
.get_val_ignore_ascii_case("rport")
.and_then(|rport| rport.parse::<u16>().ok())
{
SocketAddr::new(request.tp_info.source.ip(), rport)
Expand Down Expand Up @@ -483,10 +483,11 @@ fn add_received_rport(via: &mut Via, source: SocketAddr) {
let source_host: Host = source.ip().into();

if source_host != via.sent_by.host {
via.params.push_or_edit("received", source.ip().to_string());
via.params
.push_or_edit_ignore_ascii_case("received", source.ip().to_string());
}

if let Some(rport) = via.params.get_mut("rport") {
if let Some(rport) = via.params.get_mut_ignore_ascii_case("rport") {
rport.value = Some(source.port().to_string().into());
}
}
Expand Down Expand Up @@ -661,3 +662,42 @@ impl EndpointBuilder {
endpoint
}
}

#[cfg(test)]
mod parameter_case_tests {
use super::*;
use sip_types::uri::params::Param;

#[test]
fn updates_mixed_case_received_and_rport_without_duplicates() {
let mut headers = Headers::new();
headers.insert(
Name::VIA,
"SIP/2.0/UDP 192.0.2.1:5060;BrAnCh=z9hG4bK-AbC;ReCeIvEd=192.0.2.2;RPORT",
);
let mut via: Via = headers.get_named().unwrap();
let source = "198.51.100.1:12345".parse().unwrap();
add_received_rport(&mut via, source);
assert_eq!(
via.params.get_val_ignore_ascii_case("received").unwrap(),
"198.51.100.1"
);
assert_eq!(
via.params.get_val_ignore_ascii_case("rport").unwrap(),
"12345"
);
assert_eq!(
via.params.get_val_ignore_ascii_case("branch").unwrap(),
"z9hG4bK-AbC"
);
assert_eq!(
via.params.to_string(),
";BrAnCh=z9hG4bK-AbC;ReCeIvEd=198.51.100.1;RPORT=12345"
);

via.params = Default::default();
via.params.push(Param::value("branch", "z9hG4bK-AbC"));
add_received_rport(&mut via, source);
assert!(via.params.get_ignore_ascii_case("rport").is_none());
}
}
27 changes: 26 additions & 1 deletion sip/sip-core/src/transaction/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl TsxKey {
sent_by, params, ..
} = &headers.via[0];

let branch = params.get_val("branch").unwrap_or(&EMPTY);
let branch = params.get_val_ignore_ascii_case("branch").unwrap_or(&EMPTY);

let CSeq { method, cseq } = &headers.cseq;
let method = filter_method(method);
Expand Down Expand Up @@ -152,3 +152,28 @@ impl TsxKey {
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use sip_types::Headers;

#[test]
fn branch_name_ignores_case_but_branch_value_does_not() {
let key = |name: &str, value: &str| {
let mut headers = Headers::new();
headers.insert(Name::VIA, format!("SIP/2.0/UDP 127.0.0.1;{name}={value}"));
headers.insert(Name::FROM, "<sip:alice@example.com>;TaG=AbC");
headers.insert(Name::TO, "<sip:bob@example.com>");
headers.insert(Name::CALL_ID, "CallID");
headers.insert(Name::CSEQ, "1 INVITE");
let headers = BaseHeaders::extract_from(&headers).unwrap();
TsxKey::from_headers(&headers, Role::Server).unwrap()
};
let lower = key("branch", "z9hG4bK-AbC");
let mixed = key("BrAnCh", "z9hG4bK-AbC");
assert_eq!(lower, mixed);
assert_eq!(mixed.branch(), "z9hG4bK-AbC");
assert_ne!(lower, key("BRANCH", "z9hG4bK-abc"));
}
}
2 changes: 1 addition & 1 deletion sip/sip-core/src/transport/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ impl Transports {
) -> Result<(TpHandle, SocketAddr)> {
log::trace!("select transport for {:?}", uri);

if let Some(transport) = uri.uri_params.get_val("transport") {
if let Some(transport) = uri.uri_params.get_val_ignore_ascii_case("transport") {
return self
.select_transport_by_uri_param(endpoint, uri, transport)
.await;
Expand Down
34 changes: 32 additions & 2 deletions sip/sip-types/src/header/typed/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ impl DigestChallenge {
let mut other = vec![];

for param in params {
match param.name.as_ref() {
match param.name.to_ascii_lowercase().as_str() {
"realm" => realm = Some(param.value),
"domain" => domain = Some(param.value),
"nonce" => nonce = Some(param.value),
Expand Down Expand Up @@ -335,7 +335,7 @@ impl DigestResponse {
let mut other = vec![];

for param in params {
match param.name.as_ref() {
match param.name.to_ascii_lowercase().as_str() {
"username" => username = Some(param.value),
"username*" => username_non_ascii = Some(param.value),
"realm" => realm = Some(param.value),
Expand Down Expand Up @@ -644,6 +644,36 @@ mod test {
use crate::print::AppendCtx;
use crate::{Headers, Name};

#[test]
fn digest_parameter_names_ignore_case_and_preserve_values() {
let input = BytesStr::from_static(
r#"Digest ReAlM="EXAMPLE.com", NONCE="AbC", Opaque="DeF", Stale=true, Algorithm=MD5, QOP="auth", UserHash=true"#,
);
let (_, auth) = AuthChallenge::parse(input.as_ref(), &input).unwrap();
let AuthChallenge::Digest(challenge) = auth else {
panic!("expected Digest")
};
assert_eq!(challenge.realm, "EXAMPLE.com");
assert_eq!(challenge.nonce, "AbC");
assert_eq!(challenge.opaque.as_deref(), Some("DeF"));
assert!(challenge.stale && challenge.userhash);
assert!(challenge.other.is_empty());
assert_eq!(challenge.qop, vec![QopOption::Auth]);

let input = BytesStr::from_static(
r#"Digest UserName="Alice", ReAlM="EXAMPLE.com", NONCE="AbC", URI="sip:bob@example.com", RESPONSE="DeF", Algorithm=MD5, QOP=auth, CNonce="GhI", NC=00000001, UserHash=true"#,
);
let (_, auth) = AuthResponse::parse(input.as_ref(), &input).unwrap();
let AuthResponse::Digest(response) = auth else {
panic!("expected Digest")
};
assert_eq!(response.realm, "EXAMPLE.com");
assert_eq!(response.nonce, "AbC");
assert_eq!(response.response, "DeF");
assert!(response.userhash);
assert!(response.other.is_empty());
}

#[test]
fn parse_simple_digest_challenge() {
let input = BytesStr::from_static(r#"Digest realm="example.com", nonce="abc123""#);
Expand Down
2 changes: 1 addition & 1 deletion sip/sip-types/src/header/typed/from_to.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ impl HeaderParse for FromTo {
tuple((NameAddr::parse_no_params(src), Params::<CPS>::parse(src))),
|(uri, mut params)| FromTo {
uri,
tag: params.take("tag"),
tag: params.take_ignore_ascii_case("tag"),
params,
},
)(i)
Expand Down
10 changes: 7 additions & 3 deletions sip/sip-types/src/header/typed/replaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,13 @@ impl HeaderParse for Replaces {
|(call_id, mut params)| -> anyhow::Result<Self> {
Ok(Self {
call_id: BytesStr::from_parse(src, call_id),
from_tag: params.take("from-tag").context("missing from-tag")?,
to_tag: params.take("to-tag").context("missing to-tag")?,
early_only: params.get("early-only").is_some(),
from_tag: params
.take_ignore_ascii_case("from-tag")
.context("missing from-tag")?,
to_tag: params
.take_ignore_ascii_case("to-tag")
.context("missing to-tag")?,
early_only: params.get_ignore_ascii_case("early-only").is_some(),
})
},
)(i)
Expand Down
6 changes: 3 additions & 3 deletions sip/sip-types/src/header/typed/subscription_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ impl HeaderParse for SubscriptionState {
_ => bail!("Received invalid state in Subscription-State header"),
},
reason: {
if let Some(r) = params.take("reason") {
if let Some(r) = params.take_ignore_ascii_case("reason") {
use EventReasonValue::*;
Some(match r.as_ref() {
"deactivated" => Deactivated,
Expand All @@ -150,11 +150,11 @@ impl HeaderParse for SubscriptionState {
}
},
expires: params
.take("expires")
.take_ignore_ascii_case("expires")
.as_ref()
.and_then(|e| u32::from_str(e).ok()),
retry_after: params
.take("retry-after")
.take_ignore_ascii_case("retry-after")
.as_ref()
.and_then(|after| u32::from_str(after).ok()),
params,
Expand Down
2 changes: 1 addition & 1 deletion sip/sip-types/src/header/typed/timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl HeaderParse for SessionExpires {
Params::<CPS>::parse(src),
)),
|(delta_secs, mut params)| -> Self {
let refresher = if let Some(param) = params.take("refresher") {
let refresher = if let Some(param) = params.take_ignore_ascii_case("refresher") {
match param.as_str() {
"uas" => Refresher::Uas,
"uac" => Refresher::Uac,
Expand Down
126 changes: 125 additions & 1 deletion sip/sip-types/src/uri/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ impl<S> Clone for Params<S> {
}

impl<S: ParamsSpec> Params<S> {
pub(crate) fn iter(&self) -> impl Iterator<Item = &Param> {
self.params.iter()
}

pub fn new() -> Params<S> {
Params {
params: Vec::new(),
Expand Down Expand Up @@ -76,6 +80,68 @@ impl<S: ParamsSpec> Params<S> {
self.get(name.as_ref()).and_then(|p| p.value.as_ref())
}

/// Returns the first matching parameter, ignoring ASCII case in its name.
///
/// Unlike `get`, this explicitly opts into case-insensitive name matching.
#[inline]
pub fn get_ignore_ascii_case<N>(&self, name: N) -> Option<&Param>
where
N: AsRef<str>,
{
self.params
.iter()
.find(|p| p.name.eq_ignore_ascii_case(name.as_ref()))
}

/// Returns the first matching parameter's value, ignoring ASCII case in its name.
#[inline]
pub fn get_val_ignore_ascii_case<N>(&self, name: N) -> Option<&BytesStr>
where
N: AsRef<str>,
{
self.get_ignore_ascii_case(name)
.and_then(|p| p.value.as_ref())
}

/// Returns the first matching parameter mutably, ignoring ASCII name case.
#[inline]
pub fn get_mut_ignore_ascii_case<N>(&mut self, name: N) -> Option<&mut Param>
where
N: AsRef<str>,
{
self.params
.iter_mut()
.find(|p| p.name.eq_ignore_ascii_case(name.as_ref()))
}

/// Removes the first matching parameter and returns its value, ignoring ASCII name case.
#[inline]
pub fn take_ignore_ascii_case<N>(&mut self, name: N) -> Option<BytesStr>
where
N: AsRef<str>,
{
let pos = self
.params
.iter()
.position(|p| p.name.eq_ignore_ascii_case(name.as_ref()))?;
self.params.remove(pos).value
}

/// Updates the first matching parameter or appends one, ignoring ASCII name case.
/// Existing name spelling and the supplied value's casing are preserved.
#[inline]
pub fn push_or_edit_ignore_ascii_case<N, V>(&mut self, name: N, value: V)
where
N: Into<BytesStr> + AsRef<str>,
V: Into<BytesStr>,
{
if let Some(param) = self.get_mut_ignore_ascii_case(name.as_ref()) {
param.value = Some(value.into());
} else {
self.push(Param::value(name, value));
}
}

#[inline]
pub fn take<N>(&mut self, name: N) -> Option<BytesStr>
where
Expand Down Expand Up @@ -335,7 +401,7 @@ macro_rules! impl_with_params {
N: Into<bytesstr::BytesStr> + AsRef<str>,
V: Into<bytesstr::BytesStr> + AsRef<str>,
{
self.$field.push_or_edit(name, value);
self.$field.push_or_edit_ignore_ascii_case(name, value);
self
}
};
Expand All @@ -346,6 +412,64 @@ mod test {
use super::*;
use bytesstr::BytesStr;

#[test]
fn case_insensitive_mutation_preserves_names_and_values() {
let mut params = Params::<CPS>::new()
.with(Param::value("TaG", "AbC"))
.with(Param::name("RPORT"));
assert!(params.get_mut("tag").is_none());
params.get_mut_ignore_ascii_case("rport").unwrap().value = Some("5060".into());
params.push_or_edit_ignore_ascii_case("tag", "DeF");
params.push_or_edit_ignore_ascii_case("received", "EXAMPLE.com");
assert_eq!(
params.to_string(),
";TaG=DeF;RPORT=5060;received=EXAMPLE.com"
);
assert!(params.take("tag").is_none());
assert_eq!(params.take_ignore_ascii_case("TAG").unwrap(), "DeF");
assert!(params.get_ignore_ascii_case("tag").is_none());
assert!(params.take_ignore_ascii_case("missing").is_none());
params.push(Param::name("FLAG"));
assert!(params.take_ignore_ascii_case("flag").is_none());
assert!(params.get_ignore_ascii_case("flag").is_none());
}

#[test]
fn value_lookup_can_explicitly_ignore_ascii_case() {
for name in ["expires", "Expires", "ExPiReS"] {
let params = Params::<CPS>::new().with(Param::value(name, "10"));

assert_eq!(
params
.get_val_ignore_ascii_case("expires")
.map(BytesStr::as_ref),
Some("10")
);
assert_eq!(params.get_val("expires").is_some(), name == "expires");
assert!(params.get_val_ignore_ascii_case("missing").is_none());
}
}

#[test]
fn case_insensitive_value_lookup_uses_first_match() {
let params = Params::<CPS>::new()
.with(Param::value("Expires", "10"))
.with(Param::value("expires", "20"));
assert_eq!(
params
.get_val_ignore_ascii_case("expires")
.map(BytesStr::as_ref),
Some("10")
);

let params = Params::<CPS>::new()
.with(Param::name("Expires"))
.with(Param::value("expires", "20"));
assert!(params.get_val_ignore_ascii_case("expires").is_none());
assert!(params.get_ignore_ascii_case("expires").is_some());
assert!(params.get_ignore_ascii_case("missing").is_none());
}

#[test]
fn common_params_parse() {
let input = BytesStr::from_static(";some_single_key;some_key=with_value");
Expand Down
Loading
Loading