sip-header 0.3.7

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
//! RFC 3891 `Replaces` header parser.
//!
//! Also serves `Join` (RFC 3911), whose grammar is identical:
//! `callid *(SEMI param)` with mandatory `to-tag` and `from-tag`.

use std::fmt;

use percent_encoding::percent_decode_str;

/// Error parsing a Replaces header.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SipReplacesError {
    /// The Replaces header value is empty.
    Empty,
    /// The Replaces header value has an invalid format.
    InvalidFormat(String),
}

impl fmt::Display for SipReplacesError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "Replaces header is empty"),
            Self::InvalidFormat(msg) => write!(f, "Invalid Replaces format: {}", msg),
        }
    }
}

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

impl From<DialogIdError> for SipReplacesError {
    fn from(e: DialogIdError) -> Self {
        match e {
            DialogIdError::Empty => Self::Empty,
            DialogIdError::Invalid(msg) => Self::InvalidFormat(msg),
        }
    }
}

pub(crate) enum DialogIdError {
    Empty,
    Invalid(String),
}

pub(crate) struct DialogId {
    pub call_id: String,
    pub first_tag: String,
    pub second_tag: String,
    pub early_only: bool,
    pub params: Vec<(String, Option<String>)>,
}

/// Parse `callid *(SEMI param)` with two mandatory tag params.
///
/// `early-only` is recognized as a flag only when `with_early_only` is set
/// (RFC 3891 defines it; RFC 4538 does not).
pub(crate) fn parse_dialog_id(
    raw: &str,
    first_tag_name: &str,
    second_tag_name: &str,
    with_early_only: bool,
) -> Result<DialogId, DialogIdError> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err(DialogIdError::Empty);
    }

    let mut segments = trimmed.split(';');
    let call_id = segments
        .next()
        .unwrap_or("")
        .trim();
    if call_id.is_empty() {
        return Err(DialogIdError::Invalid("missing call-id".to_string()));
    }

    let mut first_tag: Option<String> = None;
    let mut second_tag: Option<String> = None;
    let mut early_only = false;
    let mut params = Vec::new();

    for segment in segments {
        let segment = segment.trim();
        if segment.is_empty() {
            continue;
        }
        if let Some((key, value)) = segment.split_once('=') {
            let key = key
                .trim()
                .to_ascii_lowercase();
            let value = value.trim();
            let slot = if key == first_tag_name {
                Some(&mut first_tag)
            } else if key == second_tag_name {
                Some(&mut second_tag)
            } else {
                None
            };
            match slot {
                Some(slot) => {
                    if value.is_empty() {
                        return Err(DialogIdError::Invalid(format!("empty {}", key)));
                    }
                    if slot
                        .replace(value.to_string())
                        .is_some()
                    {
                        return Err(DialogIdError::Invalid(format!("duplicate {}", key)));
                    }
                }
                None => params.push((key, Some(value.to_string()))),
            }
        } else {
            let key = segment.to_ascii_lowercase();
            if with_early_only && key == "early-only" {
                early_only = true;
            } else {
                params.push((key, None));
            }
        }
    }

    let first_tag =
        first_tag.ok_or_else(|| DialogIdError::Invalid(format!("missing {}", first_tag_name)))?;
    let second_tag =
        second_tag.ok_or_else(|| DialogIdError::Invalid(format!("missing {}", second_tag_name)))?;

    Ok(DialogId {
        call_id: call_id.to_string(),
        first_tag,
        second_tag,
        early_only,
        params,
    })
}

fn is_word_char(c: char) -> bool {
    c.is_ascii_alphanumeric()
        || matches!(
            c,
            '-' | '.'
                | '!'
                | '%'
                | '*'
                | '_'
                | '+'
                | '`'
                | '\''
                | '~'
                | '('
                | ')'
                | '<'
                | '>'
                | ':'
                | '\\'
                | '"'
                | '/'
                | '['
                | ']'
                | '?'
                | '{'
                | '}'
        )
}

/// Validate `callid = word [ "@" word ]` (RFC 3261 §25.1).
pub(crate) fn validate_call_id(raw: &str) -> Result<(), DialogIdError> {
    let (word, host) = match raw.split_once('@') {
        Some((word, host)) => (word, Some(host)),
        None => (raw, None),
    };
    for part in std::iter::once(word).chain(host) {
        if part.is_empty() {
            return Err(DialogIdError::Invalid("empty call-id word".to_string()));
        }
        if let Some(c) = part
            .chars()
            .find(|c| !is_word_char(*c))
        {
            return Err(DialogIdError::Invalid(format!(
                "call-id contains {:?}, not an RFC 3261 word character",
                c
            )));
        }
    }
    Ok(())
}

/// Decode a percent-encoded URI-header value for dialog-id parsing.
pub(crate) fn decode_uri_header_value(raw: &str) -> Result<String, DialogIdError> {
    percent_decode_str(raw)
        .decode_utf8()
        .map(|s| s.into_owned())
        .map_err(|e| DialogIdError::Invalid(format!("percent-decoded value is not UTF-8: {}", e)))
}

/// A parsed `Replaces` header value (RFC 3891 §6.1).
///
/// Identifies the dialog to be replaced: Call-ID plus the mandatory
/// `to-tag` and `from-tag`. Also used for `Join` (RFC 3911 §7.1), whose
/// grammar is identical.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SipReplaces {
    call_id: String,
    to_tag: String,
    from_tag: String,
    early_only: bool,
    params: Vec<(String, Option<String>)>,
    uri_header_framing: bool,
}

impl SipReplaces {
    /// Parse a wire-form header value: `callid;to-tag=x;from-tag=y`.
    pub fn parse(raw: &str) -> Result<Self, SipReplacesError> {
        let id = parse_dialog_id(raw, "to-tag", "from-tag", true)?;
        Ok(Self {
            call_id: id.call_id,
            to_tag: id.first_tag,
            from_tag: id.second_tag,
            early_only: id.early_only,
            params: id.params,
            uri_header_framing: false,
        })
    }

    /// Parse the percent-encoded framing found in a URI header
    /// (`<sip:…?Replaces=…>`), e.g. `callid%40host%3Bto-tag%3Dx%3Bfrom-tag%3Dy`.
    ///
    /// Accepts the canonicalised value returned by
    /// [`sip_uri::SipUri::header`]; [`Display`](fmt::Display) re-encodes to
    /// that same canonical form (uppercase hex).
    pub fn parse_uri_header(raw: &str) -> Result<Self, SipReplacesError> {
        let decoded = decode_uri_header_value(raw)?;
        let mut parsed = Self::parse(&decoded)?;
        parsed.uri_header_framing = true;
        Ok(parsed)
    }

    /// The Call-ID of the dialog being replaced.
    pub fn call_id(&self) -> &str {
        &self.call_id
    }

    /// Returns this value with a different Call-ID.
    ///
    /// Framing, both tags, `early-only` and all generic parameters are
    /// preserved, so [`Display`](fmt::Display) re-emits the parsed input with
    /// only the Call-ID changed.
    ///
    /// Errors unless `call_id` is an RFC 3261 §25.1
    /// `callid = word [ "@" word ]`. [`parse`](Self::parse) is lenient about
    /// this token; a value that never came off the wire is not.
    ///
    /// ```
    /// use sip_header::SipReplaces;
    ///
    /// let r = SipReplaces::parse("abc@203.0.113.5;to-tag=t1;from-tag=f1;early-only")?
    ///     .with_call_id("abc@example.com")?;
    /// assert_eq!(r.to_string(), "abc@example.com;to-tag=t1;from-tag=f1;early-only");
    /// # Ok::<(), sip_header::SipReplacesError>(())
    /// ```
    pub fn with_call_id(mut self, call_id: impl Into<String>) -> Result<Self, SipReplacesError> {
        let call_id = call_id.into();
        validate_call_id(&call_id)?;
        self.call_id = call_id;
        Ok(self)
    }

    /// The host part of the Call-ID (after `@`), if present.
    pub fn host(&self) -> Option<&str> {
        self.call_id
            .split_once('@')
            .map(|(_, host)| host)
    }

    /// The mandatory `to-tag` value.
    pub fn to_tag(&self) -> &str {
        &self.to_tag
    }

    /// The mandatory `from-tag` value.
    pub fn from_tag(&self) -> &str {
        &self.from_tag
    }

    /// Whether the `early-only` flag is present (RFC 3891 §3).
    pub fn early_only(&self) -> bool {
        self.early_only
    }

    /// Returns all generic parameters (tags and `early-only` excluded).
    pub fn params(&self) -> &[(String, Option<String>)] {
        &self.params
    }

    /// Returns a specific generic parameter by key (case-insensitive).
    pub fn param(&self, key: &str) -> Option<Option<&str>> {
        let key_lower = key.to_ascii_lowercase();
        self.params
            .iter()
            .find(|(k, _)| k == &key_lower)
            .map(|(_, v)| v.as_deref())
    }

    fn wire_form(&self) -> String {
        let mut s = format!(
            "{};to-tag={};from-tag={}",
            self.call_id, self.to_tag, self.from_tag
        );
        if self.early_only {
            s.push_str(";early-only");
        }
        write_params(&mut s, &self.params);
        s
    }
}

pub(crate) fn write_params(s: &mut String, params: &[(String, Option<String>)]) {
    for (key, value) in params {
        s.push(';');
        s.push_str(key);
        if let Some(value) = value {
            s.push('=');
            s.push_str(value);
        }
    }
}

impl fmt::Display for SipReplaces {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let wire = self.wire_form();
        if self.uri_header_framing {
            f.write_str(&sip_uri::encode_uri_header(&wire))
        } else {
            f.write_str(&wire)
        }
    }
}

impl_from_str_via_parse!(SipReplaces, SipReplacesError);

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

    #[test]
    fn parse_basic() {
        let r = SipReplaces::parse("abc123@203.0.113.5;to-tag=t1;from-tag=f1").unwrap();
        assert_eq!(r.call_id(), "abc123@203.0.113.5");
        assert_eq!(r.host(), Some("203.0.113.5"));
        assert_eq!(r.to_tag(), "t1");
        assert_eq!(r.from_tag(), "f1");
        assert!(!r.early_only());
    }

    #[test]
    fn host_none_without_at() {
        let r = SipReplaces::parse("abc123;to-tag=t1;from-tag=f1").unwrap();
        assert_eq!(r.call_id(), "abc123");
        assert_eq!(r.host(), None);
    }

    #[test]
    fn early_only_flag() {
        let r = SipReplaces::parse("abc@example.com;to-tag=t1;from-tag=f1;early-only").unwrap();
        assert!(r.early_only());
    }

    #[test]
    fn param_names_case_insensitive_values_preserved() {
        let r = SipReplaces::parse("abc@example.com;TO-TAG=T1abc;From-Tag=F1xyz").unwrap();
        assert_eq!(r.to_tag(), "T1abc");
        assert_eq!(r.from_tag(), "F1xyz");
    }

    #[test]
    fn generic_params_preserved() {
        let r = SipReplaces::parse("abc@example.com;to-tag=t1;from-tag=f1;foo=bar;flag").unwrap();
        assert_eq!(r.param("foo"), Some(Some("bar")));
        assert_eq!(r.param("flag"), Some(None));
        assert_eq!(r.param("missing"), None);
        assert_eq!(
            r.params()
                .len(),
            2
        );
    }

    #[test]
    fn missing_to_tag_fails() {
        assert!(SipReplaces::parse("abc@example.com;from-tag=f1").is_err());
    }

    #[test]
    fn missing_from_tag_fails() {
        assert!(SipReplaces::parse("abc@example.com;to-tag=t1").is_err());
    }

    #[test]
    fn duplicate_to_tag_fails() {
        assert!(SipReplaces::parse("abc@example.com;to-tag=t1;to-tag=t2;from-tag=f1").is_err());
    }

    #[test]
    fn empty_fails() {
        assert!(matches!(
            SipReplaces::parse(""),
            Err(SipReplacesError::Empty)
        ));
        assert!(matches!(
            SipReplaces::parse("  "),
            Err(SipReplacesError::Empty)
        ));
    }

    #[test]
    fn parse_uri_header_encoded() {
        let r = SipReplaces::parse_uri_header("abc123%40203.0.113.5%3Bto-tag%3Dt1%3Bfrom-tag%3Df1")
            .unwrap();
        assert_eq!(r.call_id(), "abc123@203.0.113.5");
        assert_eq!(r.host(), Some("203.0.113.5"));
        assert_eq!(r.to_tag(), "t1");
        assert_eq!(r.from_tag(), "f1");
    }

    #[test]
    fn parse_uri_header_lowercase_hex() {
        let r = SipReplaces::parse_uri_header("abc123%40203.0.113.5%3bto-tag%3dt1%3bfrom-tag%3df1")
            .unwrap();
        assert_eq!(r.host(), Some("203.0.113.5"));
        assert_eq!(r.to_tag(), "t1");
    }

    #[test]
    fn parse_uri_header_early_only() {
        let r = SipReplaces::parse_uri_header(
            "abc123%40203.0.113.5%3Bto-tag%3Dt1%3Bfrom-tag%3Df1%3Bearly-only",
        )
        .unwrap();
        assert!(r.early_only());
    }

    #[test]
    fn parse_uri_header_invalid_utf8_fails() {
        assert!(SipReplaces::parse_uri_header("abc%C0%80;to-tag=t1;from-tag=f1").is_err());
    }

    #[test]
    fn display_roundtrip_wire() {
        let input = "abc123@203.0.113.5;to-tag=t1;from-tag=f1;early-only;foo=bar";
        let r = SipReplaces::parse(input).unwrap();
        assert_eq!(r.to_string(), input);
        assert_eq!(SipReplaces::parse(&r.to_string()).unwrap(), r);
    }

    #[test]
    fn display_roundtrip_uri_header() {
        let input = "abc123%40203.0.113.5%3Bto-tag%3Dt1%3Bfrom-tag%3Df1";
        let r = SipReplaces::parse_uri_header(input).unwrap();
        assert_eq!(r.to_string(), input);
        assert_eq!(SipReplaces::parse_uri_header(&r.to_string()).unwrap(), r);
    }

    #[test]
    fn with_call_id_wire_changes_only_call_id() {
        let input = "abc123@203.0.113.5;to-tag=t1;from-tag=f1;early-only;foo=bar";
        let r = SipReplaces::parse(input)
            .unwrap()
            .with_call_id("xyz789@example.com")
            .unwrap();
        assert_eq!(
            r.to_string(),
            "xyz789@example.com;to-tag=t1;from-tag=f1;early-only;foo=bar"
        );
    }

    #[test]
    fn with_call_id_keeps_uri_header_framing() {
        let input = "abc123%40203.0.113.5%3Bto-tag%3Dt1%3Bfrom-tag%3Df1";
        let r = SipReplaces::parse_uri_header(input)
            .unwrap()
            .with_call_id("abc123@example.com")
            .unwrap();
        assert_eq!(
            r.to_string(),
            "abc123%40example.com%3Bto-tag%3Dt1%3Bfrom-tag%3Df1"
        );
    }

    #[test]
    fn with_call_id_replacing_host_only() {
        let r = SipReplaces::parse("abc123@203.0.113.5;to-tag=t1;from-tag=f1").unwrap();
        let host = r
            .host()
            .unwrap();
        let call_id = format!(
            "{}example.com",
            &r.call_id()[..r
                .call_id()
                .len()
                - host.len()]
        );
        let r = r
            .with_call_id(call_id)
            .unwrap();
        assert_eq!(r.call_id(), "abc123@example.com");
    }

    #[test]
    fn with_call_id_rejects_non_word() {
        let r = SipReplaces::parse("abc@example.com;to-tag=t1;from-tag=f1").unwrap();
        for bad in [
            "",
            "a;to-tag=t2",
            "a,b",
            "a b",
            "a\r\nSubject: x",
            "a@b@c",
            "a@",
            "@b",
            "a@ b",
        ] {
            assert!(
                r.clone()
                    .with_call_id(bad)
                    .is_err(),
                "accepted {bad:?}"
            );
        }
    }

    #[test]
    fn with_call_id_accepts_full_word_charset() {
        let call_id = "a%b!*_+`'~()<>:\\\"/[]?{}.-@example.com";
        let r = SipReplaces::parse("abc@example.com;to-tag=t1;from-tag=f1")
            .unwrap()
            .with_call_id(call_id)
            .unwrap();
        assert_eq!(r.call_id(), call_id);
    }

    #[test]
    fn from_str_is_wire_framing() {
        let r: SipReplaces = "abc123@203.0.113.5;to-tag=t1;from-tag=f1"
            .parse()
            .unwrap();
        assert_eq!(r.call_id(), "abc123@203.0.113.5");
    }
}