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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! SIP History-Info header parser (RFC 7044) with embedded RFC 3326 Reason.

use std::fmt;
use std::str::Utf8Error;

use percent_encoding::percent_decode_str;

use crate::header_addr::{ParseSipHeaderAddrError, SipHeaderAddr};

/// Errors from parsing a History-Info header value (RFC 7044).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum HistoryInfoError {
    /// The input string was empty or whitespace-only.
    Empty,
    /// An entry could not be parsed as a SIP name-addr.
    InvalidEntry(ParseSipHeaderAddrError),
}

impl fmt::Display for HistoryInfoError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "empty History-Info header"),
            Self::InvalidEntry(e) => write!(f, "invalid History-Info entry: {e}"),
        }
    }
}

impl std::error::Error for HistoryInfoError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::InvalidEntry(e) => Some(e),
            _ => None,
        }
    }
}

impl From<ParseSipHeaderAddrError> for HistoryInfoError {
    fn from(e: ParseSipHeaderAddrError) -> Self {
        Self::InvalidEntry(e)
    }
}

/// Parsed RFC 3326 Reason header value extracted from a History-Info URI.
///
/// The Reason header embedded in History-Info URIs as `?Reason=...` follows
/// the format: `protocol ;cause=code ;text="description"`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryInfoReason {
    protocol: String,
    cause: Option<u16>,
    text: Option<String>,
}

impl HistoryInfoReason {
    /// The protocol token (e.g. `"SIP"`, `"Q.850"`, `"RouteAction"`).
    pub fn protocol(&self) -> &str {
        &self.protocol
    }

    /// The cause code, if present (e.g. `200`, `302`).
    pub fn cause(&self) -> Option<u16> {
        self.cause
    }

    /// The human-readable reason text, if present.
    pub fn text(&self) -> Option<&str> {
        self.text
            .as_deref()
    }
}

/// Parse a percent-decoded RFC 3326 Reason value.
///
/// Input format: `protocol;cause=N;text="description"`
fn parse_reason(decoded: &str) -> HistoryInfoReason {
    let (protocol, rest) = decoded
        .split_once(';')
        .unwrap_or((decoded, ""));

    let mut cause = None;
    let mut text = None;

    // Extract cause (always a simple integer, safe to find by prefix)
    if let Some(idx) = rest.find("cause=") {
        let val_start = idx + 6;
        let val_end = rest[val_start..]
            .find(';')
            .map(|i| val_start + i)
            .unwrap_or(rest.len());
        cause = rest[val_start..val_end]
            .trim()
            .parse::<u16>()
            .ok();
    }

    // Extract text (may be quoted, always appears after cause in practice)
    if let Some(idx) = rest.find("text=") {
        let val_start = idx + 5;
        let val = rest[val_start..].trim_start();
        if let Some(inner) = val.strip_prefix('"') {
            if let Some(end) = inner.find('"') {
                text = Some(inner[..end].to_string());
            } else {
                text = Some(inner.to_string());
            }
        } else {
            let end = val
                .find(';')
                .unwrap_or(val.len());
            text = Some(val[..end].to_string());
        }
    }

    HistoryInfoReason {
        protocol: protocol
            .trim()
            .to_string(),
        cause,
        text,
    }
}

/// A single entry from a History-Info header (RFC 7044).
///
/// Each entry is a SIP name-addr (`<URI>;params`) where the URI may contain
/// an embedded `?Reason=...` header and the params typically include `index`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryInfoEntry {
    addr: SipHeaderAddr,
}

impl HistoryInfoEntry {
    /// The underlying parsed name-addr with header-level parameters.
    pub fn addr(&self) -> &SipHeaderAddr {
        &self.addr
    }

    /// The URI from this entry.
    pub fn uri(&self) -> &sip_uri::Uri {
        self.addr
            .uri()
    }

    /// The SIP URI, if this entry uses a `sip:` or `sips:` scheme.
    pub fn sip_uri(&self) -> Option<&sip_uri::SipUri> {
        self.addr
            .sip_uri()
    }

    /// The `index` parameter value (e.g. `"1"`, `"1.1"`, `"1.2"`).
    pub fn index(&self) -> Option<&str> {
        self.addr
            .param_raw("index")
            .flatten()
    }

    /// Raw percent-encoded Reason value from the URI `?Reason=...` header.
    ///
    /// Returns `None` if the URI is not a SIP URI or has no Reason header.
    pub fn reason_raw(&self) -> Option<&str> {
        self.addr
            .sip_uri()?
            .header("Reason")
    }

    /// Parse the Reason header embedded in the URI.
    ///
    /// The Reason value is percent-decoded (with `+` treated as space,
    /// matching common SIP URI encoding conventions) and parsed into
    /// protocol, cause code, and text components per RFC 3326.
    ///
    /// Returns `None` if no Reason is present, `Err` if percent-decoding
    /// produces invalid UTF-8.
    pub fn reason(&self) -> Option<Result<HistoryInfoReason, Utf8Error>> {
        let raw = self.reason_raw()?;
        // SIP stacks commonly use + for space in URI header values
        // (form-encoding convention). Replace before percent-decoding
        // so %2B (literal +) is preserved correctly.
        let raw = raw.replace('+', " ");
        Some(
            percent_decode_str(&raw)
                .decode_utf8()
                .map(|decoded| parse_reason(&decoded)),
        )
    }
}

impl fmt::Display for HistoryInfoEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.addr)
    }
}

/// Parsed History-Info header value (RFC 7044).
///
/// Contains one or more routing-chain entries, each with a SIP URI,
/// optional index, and optional embedded Reason header.
///
/// ```
/// use sip_header::HistoryInfo;
///
/// let raw = "<sip:alice@esrp.example.com>;index=1,<sip:sos@psap.example.com>;index=1.1";
/// let hi = HistoryInfo::parse(raw).unwrap();
/// assert_eq!(hi.len(), 2);
/// assert_eq!(hi.entries()[0].index(), Some("1"));
/// assert_eq!(hi.entries()[1].index(), Some("1.1"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryInfo(Vec<HistoryInfoEntry>);

impl HistoryInfo {
    /// Parse a standard comma-separated History-Info header value (RFC 7044).
    pub fn parse(raw: &str) -> Result<Self, HistoryInfoError> {
        let raw = raw.trim();
        if raw.is_empty() {
            return Err(HistoryInfoError::Empty);
        }
        Self::from_entries(crate::split_comma_entries(raw))
    }

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

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

    /// Consume self and return the entries as a `Vec`.
    pub fn into_entries(self) -> Vec<HistoryInfoEntry> {
        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()
    }
}

fn parse_entry(raw: &str) -> Result<HistoryInfoEntry, HistoryInfoError> {
    let addr: SipHeaderAddr = raw
        .trim()
        .parse()?;
    Ok(HistoryInfoEntry { addr })
}

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

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

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

impl IntoIterator for HistoryInfo {
    type Item = HistoryInfoEntry;
    type IntoIter = std::vec::IntoIter<HistoryInfoEntry>;

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

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

    const EXAMPLE_1: &str = "\
<sip:user1@esrp.example.com?Reason=RouteAction%3Bcause%3D200%3Btext%3D%22Normal+Next+Hop%22>;index=1,\
<sip:sos@psap.example.com>;index=2";

    const EXAMPLE_2: &str = "\
<sip:lsrg.example.com?Reason=SIP%3Bcause%3D200%3Btext%3D%22Legacy+routing%22>;index=1,\
<sip:user1@esrp2.example.com;lr;transport=udp?Reason=RouteAction%3Bcause%3D200%3Btext%3D%22Normal+Next+Hop%22>;index=1.1,\
<sip:sos@psap.example.com>;index=1.2";

    // -- Entry count tests --

    #[test]
    fn parse_two_entries() {
        let hi = HistoryInfo::parse(EXAMPLE_1).unwrap();
        assert_eq!(hi.len(), 2);
    }

    #[test]
    fn parse_three_entries() {
        let hi = HistoryInfo::parse(EXAMPLE_2).unwrap();
        assert_eq!(hi.len(), 3);
    }

    #[test]
    fn parse_single_entry() {
        let hi = HistoryInfo::parse("<sip:alice@example.com>;index=1").unwrap();
        assert_eq!(hi.len(), 1);
    }

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

    // -- Index accessor tests --

    #[test]
    fn index_simple() {
        let hi = HistoryInfo::parse(EXAMPLE_1).unwrap();
        assert_eq!(hi.entries()[0].index(), Some("1"));
        assert_eq!(hi.entries()[1].index(), Some("2"));
    }

    #[test]
    fn index_hierarchical() {
        let hi = HistoryInfo::parse(EXAMPLE_2).unwrap();
        assert_eq!(hi.entries()[0].index(), Some("1"));
        assert_eq!(hi.entries()[1].index(), Some("1.1"));
        assert_eq!(hi.entries()[2].index(), Some("1.2"));
    }

    #[test]
    fn index_absent() {
        let hi = HistoryInfo::parse("<sip:alice@example.com>").unwrap();
        assert_eq!(hi.entries()[0].index(), None);
    }

    // -- URI accessor tests --

    #[test]
    fn uri_with_user() {
        let hi = HistoryInfo::parse(EXAMPLE_1).unwrap();
        let sip = hi.entries()[0]
            .sip_uri()
            .unwrap();
        assert_eq!(sip.user(), Some("user1"));
        assert_eq!(
            sip.host()
                .to_string(),
            "esrp.example.com"
        );
    }

    #[test]
    fn uri_without_user() {
        let hi = HistoryInfo::parse(EXAMPLE_2).unwrap();
        let sip = hi.entries()[0]
            .sip_uri()
            .unwrap();
        assert_eq!(sip.user(), None);
        assert_eq!(
            sip.host()
                .to_string(),
            "lsrg.example.com"
        );
    }

    #[test]
    fn uri_with_params() {
        let hi = HistoryInfo::parse(EXAMPLE_2).unwrap();
        let sip = hi.entries()[1]
            .sip_uri()
            .unwrap();
        assert_eq!(sip.user(), Some("user1"));
        assert_eq!(
            sip.host()
                .to_string(),
            "esrp2.example.com"
        );
        assert!(sip
            .param("lr")
            .is_some());
        assert_eq!(sip.param("transport"), Some(&Some("udp".to_string())));
    }

    // -- Reason accessor tests --

    #[test]
    fn reason_raw_present() {
        let hi = HistoryInfo::parse(EXAMPLE_1).unwrap();
        assert_eq!(
            hi.entries()[0].reason_raw(),
            Some("RouteAction%3Bcause%3D200%3Btext%3D%22Normal+Next+Hop%22")
        );
    }

    #[test]
    fn reason_raw_absent() {
        let hi = HistoryInfo::parse(EXAMPLE_1).unwrap();
        assert_eq!(hi.entries()[1].reason_raw(), None);
    }

    #[test]
    fn reason_parsed_route_action() {
        let hi = HistoryInfo::parse(EXAMPLE_1).unwrap();
        let reason = hi.entries()[0]
            .reason()
            .unwrap()
            .unwrap();
        assert_eq!(reason.protocol(), "RouteAction");
        assert_eq!(reason.cause(), Some(200));
        assert_eq!(reason.text(), Some("Normal Next Hop"));
    }

    #[test]
    fn reason_parsed_sip() {
        let hi = HistoryInfo::parse(EXAMPLE_2).unwrap();
        let reason = hi.entries()[0]
            .reason()
            .unwrap()
            .unwrap();
        assert_eq!(reason.protocol(), "SIP");
        assert_eq!(reason.cause(), Some(200));
        assert_eq!(reason.text(), Some("Legacy routing"));
    }

    #[test]
    fn reason_absent_returns_none() {
        let hi = HistoryInfo::parse(EXAMPLE_2).unwrap();
        assert!(hi.entries()[2]
            .reason()
            .is_none());
    }

    #[test]
    fn reason_multiple_entries() {
        let hi = HistoryInfo::parse(EXAMPLE_2).unwrap();
        let r0 = hi.entries()[0]
            .reason()
            .unwrap()
            .unwrap();
        let r1 = hi.entries()[1]
            .reason()
            .unwrap()
            .unwrap();
        assert_eq!(r0.protocol(), "SIP");
        assert_eq!(r1.protocol(), "RouteAction");
        assert!(hi.entries()[2]
            .reason()
            .is_none());
    }

    // -- Display round-trip tests --

    #[test]
    fn display_roundtrip_simple() {
        let raw = "<sip:alice@example.com>;index=1";
        let hi = HistoryInfo::parse(raw).unwrap();
        assert_eq!(hi.to_string(), raw);
    }

    #[test]
    fn display_entry_count_matches_commas() {
        let hi = HistoryInfo::parse(EXAMPLE_2).unwrap();
        let s = hi.to_string();
        assert_eq!(
            s.matches(',')
                .count()
                + 1,
            hi.len()
        );
    }

    #[test]
    fn display_roundtrip_real_world() {
        let hi = HistoryInfo::parse(EXAMPLE_1).unwrap();
        let reparsed = HistoryInfo::parse(&hi.to_string()).unwrap();
        assert_eq!(hi.len(), reparsed.len());
        for (a, b) in hi
            .entries()
            .iter()
            .zip(reparsed.entries())
        {
            assert_eq!(a.index(), b.index());
            assert_eq!(a.reason_raw(), b.reason_raw());
        }
    }

    // -- Iterator tests --

    #[test]
    fn iter_by_ref() {
        let hi = HistoryInfo::parse(EXAMPLE_1).unwrap();
        let indices: Vec<_> = hi
            .entries()
            .iter()
            .map(|e| e.index())
            .collect();
        assert_eq!(indices, vec![Some("1"), Some("2")]);
    }

    #[test]
    fn into_entries() {
        let hi = HistoryInfo::parse(EXAMPLE_1).unwrap();
        let entries = hi.into_entries();
        assert_eq!(entries.len(), 2);
    }

    // -- parse_reason unit tests --

    #[test]
    fn parse_reason_full() {
        let r = parse_reason("SIP;cause=302;text=\"Moved\"");
        assert_eq!(r.protocol(), "SIP");
        assert_eq!(r.cause(), Some(302));
        assert_eq!(r.text(), Some("Moved"));
    }

    #[test]
    fn parse_reason_no_text() {
        let r = parse_reason("Q.850;cause=16");
        assert_eq!(r.protocol(), "Q.850");
        assert_eq!(r.cause(), Some(16));
        assert_eq!(r.text(), None);
    }

    #[test]
    fn parse_reason_protocol_only() {
        let r = parse_reason("SIP");
        assert_eq!(r.protocol(), "SIP");
        assert_eq!(r.cause(), None);
        assert_eq!(r.text(), None);
    }

    #[test]
    fn parse_reason_unquoted_text() {
        let r = parse_reason("SIP;cause=200;text=OK");
        assert_eq!(r.text(), Some("OK"));
    }
}