sip-header 0.3.0

SIP header field parsers: Via, Warning, Auth, Accept, Contact, Call-Info, History-Info, Geolocation, Security, and full IANA header catalog
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Parser for SIP headers using `<absoluteURI> *(SEMI generic-param)` syntax.
//!
//! Shared by Call-Info (RFC 3261 §20.9), Alert-Info (RFC 3261 §20.4),
//! and Error-Info (RFC 3261 §20.18).

use std::fmt;

/// One `<uri>;key=value;key=value` entry from a URI-info-style header.
///
/// The data field contains the URI stripped of angle brackets.
/// Metadata keys are stored lowercased; values are preserved as-is.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UriInfoEntry {
    /// The URI or data inside the angle brackets, with brackets stripped.
    pub data: String,
    /// Semicolon-delimited parameters as `(key, value)` pairs.
    /// Keys are lowercased at parse time; values are preserved as-is.
    /// A key with no `=` sign is stored with an empty string value.
    pub metadata: Vec<(String, String)>,
}

impl UriInfoEntry {
    /// Look up a metadata parameter by key (case-insensitive).
    pub fn param(&self, key: &str) -> Option<&str> {
        self.metadata
            .iter()
            .find_map(|(k, v)| {
                if k.eq_ignore_ascii_case(key) {
                    Some(v.as_str())
                } else {
                    None
                }
            })
    }

    /// The `purpose` parameter value, if present.
    pub fn purpose(&self) -> Option<&str> {
        self.param("purpose")
    }
}

impl fmt::Display for UriInfoEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "<{}>", self.data)?;
        for (key, value) in &self.metadata {
            if value.is_empty() {
                write!(f, ";{key}")?;
            } else {
                write!(f, ";{key}={value}")?;
            }
        }
        Ok(())
    }
}

/// Parsed `<absoluteURI> *(SEMI generic-param)` header value.
///
/// Used by Call-Info, Alert-Info, and Error-Info. Contains one or more entries.
///
/// ```
/// use sip_header::UriInfo;
///
/// let raw = "<urn:example:call:123>;purpose=emergency-CallId,<https://example.com/data>;purpose=EmergencyCallData.ServiceInfo";
/// let info = UriInfo::parse(raw).unwrap();
/// assert_eq!(info.entries().len(), 2);
/// assert_eq!(info.entries()[0].purpose(), Some("emergency-CallId"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UriInfo(Vec<UriInfoEntry>);

/// Errors from parsing a URI-info-style header value.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum UriInfoError {
    /// The input string was empty or whitespace-only.
    Empty,
    /// An entry was found without angle brackets around the URI.
    MissingAngleBrackets(String),
}

impl fmt::Display for UriInfoError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "empty URI-info header value"),
            Self::MissingAngleBrackets(raw) => {
                write!(f, "missing angle brackets in URI-info entry: {raw}")
            }
        }
    }
}

impl std::error::Error for UriInfoError {}

fn parse_entry(raw: &str) -> Result<UriInfoEntry, UriInfoError> {
    let raw = raw.trim();
    if raw.is_empty() {
        return Err(UriInfoError::MissingAngleBrackets(raw.to_string()));
    }

    // Split on first ';' to separate the URI from parameters.
    // This avoids issues with ';' inside URIs before the parameter section.
    let (data_part, metadata_part) = match raw.split_once(';') {
        Some((d, m)) => (d, Some(m)),
        None => (raw, None),
    };

    let data = data_part
        .trim()
        .trim_matches(|c| c == '<' || c == '>')
        .to_string();
    if data.is_empty() {
        return Err(UriInfoError::MissingAngleBrackets(raw.to_string()));
    }

    let mut metadata = Vec::new();
    if let Some(meta_str) = metadata_part {
        if !meta_str.is_empty() {
            for segment in meta_str.split(';') {
                let segment = segment.trim();
                if segment.is_empty() {
                    continue;
                }
                if let Some((key, value)) = segment.split_once('=') {
                    metadata.push((
                        key.trim()
                            .to_ascii_lowercase(),
                        value
                            .trim()
                            .to_string(),
                    ));
                } else {
                    metadata.push((segment.to_ascii_lowercase(), String::new()));
                }
            }
        }
    }

    Ok(UriInfoEntry { data, metadata })
}

use crate::split_comma_entries;

impl UriInfo {
    /// Parse a comma-separated `<absoluteURI> *(SEMI generic-param)` value.
    pub fn parse(raw: &str) -> Result<Self, UriInfoError> {
        let raw = raw.trim();
        if raw.is_empty() {
            return Err(UriInfoError::Empty);
        }
        Self::from_entries(split_comma_entries(raw))
    }

    /// Build from pre-split header entries.
    ///
    /// Each entry should be a single `<uri>;param=value` string. Use this
    /// when entries have already been split by an external mechanism (e.g.
    /// a transport-specific array encoding).
    pub fn from_entries<'a>(
        entries: impl IntoIterator<Item = &'a str>,
    ) -> Result<Self, UriInfoError> {
        let entries: Vec<_> = entries
            .into_iter()
            .map(parse_entry)
            .collect::<Result<_, _>>()?;
        if entries.is_empty() {
            return Err(UriInfoError::Empty);
        }
        Ok(Self(entries))
    }

    /// The parsed entries as a slice.
    pub fn entries(&self) -> &[UriInfoEntry] {
        &self.0
    }

    /// Consume self and return the entries as a `Vec`.
    pub fn into_entries(self) -> Vec<UriInfoEntry> {
        self.0
    }

    /// Number of entries.
    pub fn len(&self) -> usize {
        self.0
            .len()
    }

    /// Returns `true` if there are no entries.
    pub fn is_empty(&self) -> bool {
        self.0
            .is_empty()
    }
}

impl fmt::Display for UriInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        crate::fmt_joined(f, &self.0, ",")
    }
}

impl<'a> IntoIterator for &'a UriInfo {
    type Item = &'a UriInfoEntry;
    type IntoIter = std::slice::Iter<'a, UriInfoEntry>;

    fn into_iter(self) -> Self::IntoIter {
        self.0
            .iter()
    }
}

impl IntoIterator for UriInfo {
    type Item = UriInfoEntry;
    type IntoIter = std::vec::IntoIter<UriInfoEntry>;

    fn into_iter(self) -> Self::IntoIter {
        self.0
            .into_iter()
    }
}

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

    // -- UriInfoEntry tests --

    #[test]
    fn entry_no_metadata() {
        let entry = parse_entry("<data>").unwrap();
        assert_eq!(entry.data, "data");
        assert!(entry
            .metadata
            .is_empty());
    }

    #[test]
    fn entry_no_metadata_trailing_semicolon() {
        let entry = parse_entry("<data>;").unwrap();
        assert_eq!(entry.data, "data");
        assert!(entry
            .metadata
            .is_empty());
    }

    #[test]
    fn entry_no_value_metadata() {
        let entry = parse_entry("<data>;meta1").unwrap();
        assert_eq!(
            entry
                .metadata
                .len(),
            1
        );
        assert_eq!(entry.metadata[0], ("meta1".to_string(), String::new()));
    }

    #[test]
    fn entry_empty_value_metadata() {
        let entry = parse_entry("<data>;meta1=").unwrap();
        assert_eq!(
            entry
                .metadata
                .len(),
            1
        );
        assert_eq!(entry.metadata[0], ("meta1".to_string(), String::new()));
    }

    #[test]
    fn entry_two_metadata_items() {
        let entry = parse_entry("<data>;meta1=one;meta2=two;").unwrap();
        assert_eq!(entry.data, "data");
        assert_eq!(
            entry
                .metadata
                .len(),
            2
        );
        assert_eq!(entry.param("meta1"), Some("one"));
        assert_eq!(entry.param("meta2"), Some("two"));
    }

    #[test]
    fn entry_strips_angle_brackets() {
        let entry = parse_entry("<data>;meta1=one;meta2=two;").unwrap();
        assert_eq!(entry.data, "data");
    }

    #[test]
    fn entry_uppercase_metadata_key_lowercased() {
        let entry = parse_entry("<data>;Meta-1=one").unwrap();
        assert!(entry
            .metadata
            .iter()
            .all(|(k, _)| k == &k.to_ascii_lowercase()));
        assert_eq!(entry.param("meta-1"), Some("one"));
    }

    #[test]
    fn entry_display_no_trailing_semicolon() {
        let entry = parse_entry("<data>;").unwrap();
        let s = entry.to_string();
        assert!(!s.ends_with(';'));
    }

    #[test]
    fn entry_display_metadata_no_trailing_semicolon() {
        let entry = parse_entry("<data>;meta=one;").unwrap();
        let s = entry.to_string();
        assert!(!s.ends_with(';'));
    }

    #[test]
    fn entry_display_contains_all_metadata() {
        let entry = parse_entry("<http://somedata/?arg=123>").unwrap();
        // Build entry with metadata manually since the URL contains ? and =
        let mut entry = entry;
        entry
            .metadata
            .push(("meta1".to_string(), "one".to_string()));
        entry
            .metadata
            .push(("meta2".to_string(), "two".to_string()));
        let s = entry.to_string();
        assert!(
            s.matches(';')
                .count()
                >= 2
        );
    }

    #[test]
    fn entry_display_no_value_key() {
        let entry = parse_entry("<data>;flagkey").unwrap();
        assert_eq!(entry.to_string(), "<data>;flagkey");
    }

    // -- UriInfo tests --

    const SAMPLE_EMERGENCY: &str = "\
<urn:emergency:uid:callid:20250401080740945abc123:bcf.example.com>;purpose=emergency-CallId,\
<urn:emergency:uid:incidentid:20250401080740945def456:bcf.example.com>;purpose=emergency-IncidentId,\
<https://adr.example.com/api/v1/adr/call/providerInfo/access?token=abc>;purpose=EmergencyCallData.ProviderInfo,\
<https://adr.example.com/api/v1/adr/call/serviceInfo?token=ghi>;purpose=EmergencyCallData.ServiceInfo";

    const SAMPLE_WITH_SITE: &str = "\
<urn:emergency:uid:callid:test:bcf.example.com>;purpose=emergency-CallId;site=bcf.example.com,\
<urn:emergency:uid:incidentid:test:bcf.example.com>;purpose=emergency-IncidentId";

    // 8-entry fixture exercising legacy nena- prefix, EIDO purpose, trailing
    // semicolons, site param, and all 5 ADR subtypes.
    const SAMPLE_FULL: &str = "\
<urn:nena:callid:20190912100022147abc:bcf1.example.com>;purpose=nena-CallId,\
<https://eido.psap.example.com/EidoRetrievalService/urn:nena:incidentid:test>;purpose=emergency_incident_data_object,\
<urn:nena:incidentid:20190912100022147def:bcf1.example.com>;purpose=nena-IncidentId,\
<https://adr.example.com/api/v1/adr/call/providerInfo/access?token=a>;purpose=EmergencyCallData.ProviderInfo,\
<https://adr.example.com/api/v1/adr/call/providerInfo/telecom?token=b>;purpose=EmergencyCallData.ProviderInfo;site=bcf.example.com;,\
<https://adr.example.com/api/v1/adr/call/serviceInfo?token=c>;purpose=EmergencyCallData.ServiceInfo,\
<https://adr.example.com/api/v1/adr/call/subscriberInfo?token=d>;purpose=EmergencyCallData.SubscriberInfo,\
<https://adr.example.com/api/v1/adr/call/comment?token=e>;purpose=EmergencyCallData.Comment";

    #[test]
    fn parse_comma_separated() {
        let info = UriInfo::parse(SAMPLE_EMERGENCY).unwrap();
        assert_eq!(info.len(), 4);
        assert_eq!(info.entries()[0].purpose(), Some("emergency-CallId"));
        assert_eq!(info.entries()[1].purpose(), Some("emergency-IncidentId"));
    }

    #[test]
    fn parse_full_fixture_all_entries() {
        let info = UriInfo::parse(SAMPLE_FULL).unwrap();
        assert_eq!(info.len(), 8);
    }

    #[test]
    fn full_fixture_nena_prefix_callid() {
        let info = UriInfo::parse(SAMPLE_FULL).unwrap();
        let entry = info
            .entries()
            .iter()
            .find(|e| e.purpose() == Some("nena-CallId"))
            .unwrap();
        assert!(entry
            .data
            .contains("callid"));
    }

    #[test]
    fn full_fixture_legacy_eido_purpose() {
        let info = UriInfo::parse(SAMPLE_FULL).unwrap();
        let eido: Vec<_> = info
            .entries()
            .iter()
            .filter(|e| {
                e.purpose()
                    .is_some_and(|p| p.contains("incident_data_object"))
            })
            .collect();
        assert_eq!(eido.len(), 1);
        assert!(eido[0]
            .data
            .contains("EidoRetrievalService"));
    }

    #[test]
    fn full_fixture_trailing_semicolon_with_site() {
        let info = UriInfo::parse(SAMPLE_FULL).unwrap();
        let with_site: Vec<_> = info
            .entries()
            .iter()
            .filter(|e| {
                e.param("site")
                    .is_some()
            })
            .collect();
        assert_eq!(with_site.len(), 1);
        assert_eq!(with_site[0].param("site"), Some("bcf.example.com"));
    }

    #[test]
    fn find_by_purpose() {
        let info = UriInfo::parse(SAMPLE_EMERGENCY).unwrap();

        let call_id = info
            .entries()
            .iter()
            .find(|e| e.purpose() == Some("emergency-CallId"))
            .unwrap();
        assert!(call_id
            .data
            .contains("callid"));

        let incident = info
            .entries()
            .iter()
            .find(|e| e.purpose() == Some("emergency-IncidentId"))
            .unwrap();
        assert!(incident
            .data
            .contains("incidentid"));
    }

    #[test]
    fn param_lookup_by_purpose() {
        let legacy = "<urn:nena:callid:test:example.ca>;purpose=nena-CallId";
        let info = UriInfo::parse(legacy).unwrap();
        assert_eq!(info.entries()[0].purpose(), Some("nena-CallId"));

        let modern = "<urn:emergency:uid:callid:test:example.ca>;purpose=emergency-CallId";
        let info = UriInfo::parse(modern).unwrap();
        assert_eq!(info.entries()[0].purpose(), Some("emergency-CallId"));
    }

    #[test]
    fn filter_entries_by_param() {
        let info = UriInfo::parse(SAMPLE_EMERGENCY).unwrap();
        let adr: Vec<_> = info
            .entries()
            .iter()
            .filter(|e| {
                e.purpose()
                    .is_some_and(|p| p.ends_with("Info"))
            })
            .collect();
        assert_eq!(adr.len(), 2);
    }

    #[test]
    fn metadata_param_lookup() {
        let info = UriInfo::parse(SAMPLE_WITH_SITE).unwrap();
        assert_eq!(info.entries()[0].param("site"), Some("bcf.example.com"));
        assert_eq!(info.entries()[0].param("purpose"), Some("emergency-CallId"));
        assert!(info.entries()[1]
            .param("site")
            .is_none());
    }

    #[test]
    fn display_roundtrip() {
        let raw = "<urn:example:test>;purpose=test-purpose;site=example.com";
        let info = UriInfo::parse(raw).unwrap();
        assert_eq!(info.to_string(), raw);
    }

    #[test]
    fn display_comma_count_matches_entries() {
        let info = UriInfo::parse(SAMPLE_EMERGENCY).unwrap();
        let s = info.to_string();
        assert_eq!(
            s.matches(',')
                .count()
                + 1,
            info.len()
        );
    }

    #[test]
    fn empty_input() {
        assert!(matches!(UriInfo::parse(""), Err(UriInfoError::Empty)));
    }
}