sip-header 1.0.0-beta.2

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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! RFC 3326 `reason-value`, as a Reason header or a URI's `?Reason=`
//! header carries it.

use std::fmt;

use crate::check::checked_token;
use crate::diagnostic::{Field, ParseWarning, Parsed, WarningCode};
use crate::error::{FaultCode, ParseError};
use crate::list::CommaList;
use crate::params::HeaderParams;
use crate::span::Span;
use crate::traits::{sealed, UriHeaderParse};
use crate::RawParam;

/// An RFC 3326 `cause-value = 1*DIGIT`, kept as the digits were written.
///
/// ```
/// use sip_header::SipReasonCause;
///
/// let cause = SipReasonCause::new("0016")?;
/// assert_eq!((cause.as_str(), cause.as_u16()), ("0016", Some(16)));
/// assert_eq!(SipReasonCause::new("99999")?.as_u16(), None);
/// assert!(SipReasonCause::new("1a").is_err());
/// # Ok::<(), sip_header::ParseError>(())
/// ```
///
/// # Equality
///
/// Digit for digit: `016` and `16` differ, as their wire forms do.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(into = "String"))]
pub struct SipReasonCause(String);

impl SipReasonCause {
    /// Errors unless `digits` is one ASCII digit or more.
    pub fn new(digits: impl AsRef<str>) -> Result<Self, ParseError> {
        let digits = digits.as_ref();
        crate::check::only(Field::Cause, digits, |c| c.is_ascii_digit())?;
        Ok(SipReasonCause(digits.to_owned()))
    }

    /// The digits as written.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The cause as a number; `None` when it does not fit a `u16`.
    pub fn as_u16(&self) -> Option<u16> {
        self.0
            .parse()
            .ok()
    }
}

impl From<u16> for SipReasonCause {
    fn from(cause: u16) -> Self {
        SipReasonCause(cause.to_string())
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for SipReasonCause {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let digits = crate::serde_parts::leaf(
            deserializer,
            "Reason cause",
            "a string",
            <String as serde::Deserialize>::deserialize,
        )?;
        Self::new(digits).map_err(serde::de::Error::custom)
    }
}

impl TryFrom<String> for SipReasonCause {
    type Error = ParseError;

    fn try_from(digits: String) -> Result<Self, Self::Error> {
        Self::new(digits)
    }
}

impl From<SipReasonCause> for String {
    fn from(cause: SipReasonCause) -> Self {
        cause.0
    }
}

impl AsRef<str> for SipReasonCause {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

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

/// One RFC 3326 `reason-value = protocol *(SEMI reason-params)`.
///
/// Parsed as an entry of [`SipReasonList`], through [`UriHeaderParse`], or
/// alone through [`HeaderParse`](crate::HeaderParse), which drops text after
/// the entry's comma under [`TrailingContent`](crate::WarningCode::TrailingContent).
///
/// ```
/// use sip_header::{HeaderParse, SipReason};
///
/// let reason = SipReason::new("Q.850")?
///     .with_cause(16)
///     .with_text("Terminated")?;
/// assert_eq!(reason.to_string(), r#"Q.850;cause=16;text="Terminated""#);
/// assert_eq!(SipReason::parse_strict(&reason.to_string()), Ok(reason));
/// # Ok::<(), sip_header::ParseError>(())
/// ```
///
/// # Equality
///
/// The protocol compares in the case it was written in, and the parameters,
/// `cause` and `text` among them, as [`HeaderParams`] does. [`Hash`]
/// follows the same rule; [`HeaderEquivalence`](crate::HeaderEquivalence)
/// compares as RFC 3326 and RFC 3261 §7.3.1 do.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct SipReason {
    protocol: String,
    params: HeaderParams,
}

/// Parameters [`SipReason::with_param`] refuses, set through typed setters.
const RESERVED: &[&str] = &["cause", "text"];

header_params!(SipReason, reserved: RESERVED);
params_located!(SipReason);

impl SipReason {
    fn unchecked(protocol: String) -> Self {
        SipReason {
            protocol,
            params: HeaderParams::default(),
        }
    }

    /// A reason for `protocol`, with no cause, text or parameters.
    ///
    /// Errors unless `protocol` is a `token`.
    pub fn new(protocol: impl AsRef<str>) -> Result<Self, ParseError> {
        checked_token(Field::Protocol, protocol.as_ref()).map(Self::unchecked)
    }

    /// Set the `cause` parameter, replacing every `cause` the reason held;
    /// a reason without one gets it last.
    pub fn with_cause(mut self, cause: impl Into<SipReasonCause>) -> Self {
        let SipReasonCause(digits) = cause.into();
        self.params
            .replace("cause", Some(digits), false);
        self
    }

    /// Set the `text` parameter, unquoted, as [`with_cause`](Self::with_cause)
    /// sets `cause`; [`Display`](fmt::Display) always quotes it.
    ///
    /// Errors when `text` holds CR, LF or NUL.
    pub fn with_text(mut self, text: impl AsRef<str>) -> Result<Self, ParseError> {
        let text = text.as_ref();
        crate::check::refuse_controls(Field::Text, text)?;
        self.params
            .replace("text", Some(text.to_owned()), true);
        Ok(self)
    }

    /// The protocol (e.g. `"SIP"`, `"Q.850"`), case as sent.
    pub fn protocol(&self) -> &str {
        &self.protocol
    }

    /// The first `cause`; the parser drops one that is not `1*DIGIT`.
    pub fn cause(&self) -> Option<SipReasonCause> {
        self.params
            .get("cause")
            .flatten()
            .map(|digits| SipReasonCause(digits.to_owned()))
    }

    /// The first `text` with a value, without its quotes and with
    /// `quoted-pair` unescaped.
    pub fn text(&self) -> Option<&str> {
        self.params
            .iter()
            .find_map(|(name, value)| value.filter(|_| name == "text"))
    }
}

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

impl sealed::Sealed for SipReason {}

impl UriHeaderParse for SipReason {
    fn parse_uri_header_with_warnings(raw: &str) -> Result<Parsed<Self>, ParseError> {
        crate::scrub::parse_uri_header(raw, crate::list::entry_from_str::<SipReasonList>)
    }
}

/// The Reason header: `reason-value *(COMMA reason-value)` (RFC 3326 §2),
/// one reason or more.
///
/// Parsed through [`HeaderParse`](crate::HeaderParse) and
/// [`ListParse`](crate::ListParse).
///
/// ```
/// use sip_header::{HeaderParse, SipReasonList};
///
/// let list = SipReasonList::parse(r#"SIP;cause=200;text="Call completed elsewhere", Q.850;cause=16"#)?;
/// assert_eq!(list.len(), 2);
/// assert_eq!(list.entries()[1].protocol(), "Q.850");
/// # Ok::<(), sip_header::ParseError>(())
/// ```
///
/// # Equality
///
/// Entry by entry, in order, each as [`SipReason`] compares. [`Hash`]
/// follows the same rule.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct SipReasonList(Vec<SipReason>);

list_type!(SipReasonList, SipReason, non_empty);

impl CommaList for SipReasonList {
    type Entry = SipReason;

    fn parse_entry(entry: &str, warnings: &mut Vec<ParseWarning>) -> Result<SipReason, ParseError> {
        parse_reason(entry, warnings)
    }

    fn from_parsed(entries: Vec<SipReason>) -> Result<Self, ParseError> {
        Self::new(entries)
    }
}

list_parse!(SipReasonList);
entry_parse!(SipReason, SipReasonList);

#[cfg(feature = "serde")]
serde_parts!(SipReason, SipReasonParts);

#[cfg(feature = "serde")]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct SipReasonParts {
    #[serde(deserialize_with = "crate::serde_parts::field::protocol")]
    protocol: String,
    #[serde(default, deserialize_with = "crate::params::deserialize_unchecked")]
    params: HeaderParams,
}

#[cfg(feature = "serde")]
impl SipReasonParts {
    fn into_value(p: Self) -> Result<SipReason, ParseError> {
        let reason = SipReason {
            protocol: p.protocol,
            params: p.params,
        };
        crate::list::entry_reads_back::<SipReasonList>(reason)
    }

    fn from_value(r: SipReason) -> Self {
        SipReasonParts {
            protocol: r.protocol,
            params: r.params,
        }
    }
}

/// Parse `protocol *(SEMI reason-params)`, positions relative to `input`.
pub(crate) fn parse_reason(
    input: &str,
    warnings: &mut Vec<ParseWarning>,
) -> Result<SipReason, ParseError> {
    if input
        .trim()
        .is_empty()
    {
        return Err(ParseError::empty(Field::Value));
    }
    let (protocol, rest) = crate::split_at_params(input);
    let raw_protocol = protocol.trim();
    let protocol = crate::token_field(input, raw_protocol, Field::Protocol, warnings);
    if protocol.is_empty() {
        return Err(ParseError::malformed(
            Field::Value,
            FaultCode::Missing,
            Some(0),
        ));
    }
    if !crate::is_token(&protocol) {
        warnings.push(
            ParseWarning::new(Field::Protocol, WarningCode::InvalidToken)
                .at(crate::offset_in(input, raw_protocol)),
        );
    }
    let mut reason = SipReason::unchecked(protocol.into_owned());
    for p in crate::parse_params(rest) {
        let at = crate::offset_in(input, p.key);
        let name = p.name();
        let typed = if name.eq_ignore_ascii_case("cause")
            && reason
                .param("cause")
                .is_none()
        {
            p.report_name(input, warnings);
            Some(("cause", parse_cause(&p, input, warnings)))
        } else if name.eq_ignore_ascii_case("text")
            && reason
                .text()
                .is_none()
            && p.value
                .is_some()
        {
            p.report_name(input, warnings);
            Some(("text", parse_text(&p, input, warnings)))
        } else {
            None
        };
        let Some((key, value)) = typed else {
            if name.eq_ignore_ascii_case("text")
                && p.value
                    .is_none()
            {
                warnings.push(ParseWarning::new(Field::Text, WarningCode::UnquotedText).at(at));
            }
            reason
                .params
                .push_raw(input, &p, warnings);
            continue;
        };
        if value.is_some() {
            reason
                .params
                .push_read(key, value, Field::Param, at, warnings);
        }
    }
    Ok(reason)
}

/// A typed parameter's value, with whether it is written quoted and where
/// it was read.
type TypedValue = Option<(String, bool, Span)>;

/// RFC 3326 `cause = "cause" EQUAL cause-value`, `cause-value = 1*DIGIT`.
fn parse_cause(p: &RawParam<'_>, input: &str, warnings: &mut Vec<ParseWarning>) -> TypedValue {
    if let Some(v) = p
        .value
        .filter(|v| SipReasonCause::new(v).is_ok())
    {
        return Some((v.to_owned(), false, Span::within(input, v)));
    }
    let at = crate::offset_in(
        input,
        p.value
            .unwrap_or(p.key),
    );
    let warning = ParseWarning::new(Field::Cause, WarningCode::InvalidCause).at(at);
    warnings.push(match p.value {
        Some(v) => warning.covering(Span::within(input, v)),
        None => warning,
    });
    None
}

/// RFC 3326 `"text" EQUAL quoted-string`, unescaped.
fn parse_text(p: &RawParam<'_>, input: &str, warnings: &mut Vec<ParseWarning>) -> TypedValue {
    let v = p.value?;
    let at = crate::offset_in(input, v);
    let unquoted = p.unquoted()?;
    let mut warn = |code, position| {
        warnings.push(ParseWarning::new(Field::Text, code).at(position));
    };
    if p.unterminated {
        warn(WarningCode::UnterminatedQuote, at);
    } else if !unquoted.quoted {
        warn(WarningCode::UnquotedText, at);
    }
    if unquoted.trailing_backslash {
        warn(WarningCode::TrailingBackslash, at + v.len() - 2);
    }
    Some((unquoted.value, true, Span::within(input, v)))
}

#[cfg(test)]
mod tests {
    use sip_uri::WarningKind;

    use super::*;
    use crate::HeaderParse;

    fn parsed(input: &str) -> Parsed<SipReason> {
        SipReason::parse_with_warnings(input).unwrap()
    }

    fn value(input: &str) -> SipReason {
        parsed(input).value
    }

    fn cause(r: &SipReason) -> Option<u16> {
        r.cause()
            .and_then(|c| c.as_u16())
    }

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

    #[test]
    fn protocol_only() {
        let r = value("SIP");
        assert_eq!(r.protocol(), "SIP");
        assert_eq!(r.cause(), None);
        assert_eq!(r.text(), None);
        assert!(r
            .params()
            .is_empty());
    }

    #[test]
    fn unquoted_text_is_kept_with_warning() {
        let p = parsed("SIP;cause=200;text=OK");
        assert_eq!(
            p.value
                .text(),
            Some("OK")
        );
        let w = p.warnings[0];
        assert_eq!(
            (w.field, w.code, w.kind, w.position),
            (
                Field::Text,
                WarningCode::UnquotedText,
                WarningKind::Recovered,
                Some(19)
            )
        );
        assert_eq!(
            p.value
                .to_string(),
            r#"SIP;cause=200;text="OK""#
        );
    }

    #[test]
    fn quoted_text_hides_cause_lookalike() {
        let r = value(r#"SIP;text="because=5";cause=200"#);
        assert_eq!(cause(&r), Some(200));
        assert_eq!(r.text(), Some("because=5"));
    }

    #[test]
    fn text_unescapes_quoted_pair() {
        let r = value(r#"SIP;cause=480;text="say \"hi\"""#);
        assert_eq!(r.text(), Some(r#"say "hi""#));
        assert_eq!(r.to_string(), r#"SIP;cause=480;text="say \"hi\"""#);
    }

    #[test]
    fn keys_case_insensitive_and_sws() {
        let r = value(r#"SIP ; Cause = 486 ; TEXT = "Busy; here""#);
        assert_eq!(r.protocol(), "SIP");
        assert_eq!(cause(&r), Some(486));
        assert_eq!(r.text(), Some("Busy; here"));
    }

    #[test]
    fn key_suffix_not_matched() {
        let r = value(r#"SIP;xcause=1;subtext="no";cause=2"#);
        assert_eq!(cause(&r), Some(2));
        assert_eq!(r.text(), None);
        assert_eq!(r.param("xcause"), Some(Some("1")));
    }

    #[test]
    fn cause_that_is_not_digits_is_dropped_with_warning() {
        for (input, at) in [
            ("SIP;cause=abc", 10),
            ("SIP;cause=+5", 10),
            ("SIP;cause", 4),
        ] {
            let p = parsed(input);
            assert_eq!(
                p.value
                    .cause(),
                None,
                "{input}"
            );
            let w = p.warnings[0];
            assert_eq!(
                (w.field, w.code, w.kind, w.position),
                (
                    Field::Cause,
                    WarningCode::InvalidCause,
                    WarningKind::Lost,
                    Some(at)
                ),
                "{input}"
            );
            assert_eq!(
                SipReason::parse_strict(input),
                Err(ParseError::NonConformant(w))
            );
        }
        let wide = parsed("SIP;cause=70000");
        assert!(wide
            .warnings
            .is_empty());
        assert_eq!(
            wide.value
                .cause()
                .as_ref()
                .map(|c| c.as_str()),
            Some("70000")
        );
    }

    #[test]
    fn repeated_cause_is_kept_among_params_with_warning() {
        let input = "SIP;cause=1;cause=2";
        let p = parsed(input);
        assert_eq!(cause(&p.value), Some(1));
        assert_eq!(
            p.value
                .params()
                .iter()
                .collect::<Vec<_>>(),
            [("cause", Some("1")), ("cause", Some("2"))]
        );
        assert_eq!(p.warnings[0].code, WarningCode::DuplicateParam);
        assert_eq!(p.warnings[0].position, input.rfind("cause"));
        assert_eq!(
            p.value
                .to_string(),
            input
        );
    }

    #[test]
    fn cause_and_text_are_parameters_in_received_order() {
        let input = r#"SIP;text="a;b";x=1;cause=200"#;
        let r = value(input);
        assert_eq!(r.to_string(), input);
        assert_eq!(r.param("cause"), Some(Some("200")));
        assert_eq!(
            r.param("text"),
            r.text()
                .map(Some)
        );
        assert_eq!(
            r.params()
                .value_span("cause")
                .map(|s| s.get(input)),
            Some(Ok("200"))
        );
        assert_eq!(
            r.params()
                .value_span("text")
                .map(|s| s.get(input)),
            Some(Ok(r#""a;b""#))
        );
        let reset = r
            .with_cause(SipReasonCause::new("3").unwrap())
            .with_text("c")
            .unwrap();
        assert_eq!(reset.to_string(), r#"SIP;text="c";x=1;cause=3"#);
        assert_eq!(
            reset
                .params()
                .value_span("x"),
            None
        );
    }

    #[test]
    fn built_reason_prints_in_setter_order_and_reads_back() {
        let reason = || SipReason::new("SIP").unwrap();
        let canonical = reason()
            .with_cause(200)
            .with_text("x")
            .unwrap();
        let swapped = reason()
            .with_text("x")
            .unwrap()
            .with_cause(200);
        assert_eq!(canonical.to_string(), r#"SIP;cause=200;text="x""#);
        assert_eq!(swapped.to_string(), r#"SIP;text="x";cause=200"#);
        for r in [canonical, swapped] {
            assert_eq!(SipReason::parse_strict(&r.to_string()), Ok(r));
        }
    }

    #[test]
    fn text_after_comma_is_dropped_as_trailing_content() {
        let input = "SIP;cause=1, Q.850";
        let one = value("SIP;cause=1");
        assert_eq!(SipReason::parse(input), Ok(one.clone()));
        let p = parsed(input);
        assert_eq!(p.value, one);
        let w = p.warnings[0];
        assert_eq!(
            (
                p.warnings
                    .len(),
                w.code,
                w.position
            ),
            (1, WarningCode::TrailingContent, input.find(','))
        );
        assert_eq!(
            SipReason::parse_strict(input),
            Err(ParseError::NonConformant(w))
        );
    }

    #[test]
    fn empty_and_missing_protocol_are_errors() {
        assert_eq!(SipReason::parse(" "), Err(ParseError::empty(Field::Value)));
        assert_eq!(
            SipReason::parse(" ;cause=16"),
            Err(ParseError::malformed(
                Field::Value,
                FaultCode::Missing,
                Some(0)
            ))
        );
    }

    #[test]
    fn text_trailing_backslash_warns() {
        let input = r#"SIP;text="a\""#;
        let p = parsed(input);
        assert_eq!(
            p.value
                .text(),
            Some("a")
        );
        let w = p
            .warnings
            .iter()
            .find(|w| w.code == WarningCode::TrailingBackslash)
            .copied()
            .unwrap();
        assert_eq!(
            (w.field, w.kind, w.position),
            (Field::Text, WarningKind::Lost, input.find('\\'))
        );
    }
}