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
//! SIP Contact header value parser (RFC 3261 §20.10).
//!
//! `*` beside addresses is dropped with
//! [`WildcardNotAlone`](crate::WarningCode::WildcardNotAlone), keeping the
//! addresses.

use std::fmt;

use crate::diagnostic::{Field, ParseWarning, WarningCode};
use crate::error::{FaultCode, ParseError};
use crate::header_addr::parse_list_addr;
use crate::header_addr::SipHeaderAddr;
use crate::list::CommaList;
use crate::redact::{HeaderRedaction, Redact, RedactedList};

/// Contact header value: `STAR / (contact-param *(COMMA contact-param))`
/// (RFC 3261 §20.10), either the `*` wildcard or one address or more.
///
/// Parsed through [`HeaderParse`](crate::HeaderParse) and
/// [`ListParse`](crate::ListParse).
///
/// ```
/// use sip_header::{ContactList, HeaderParse, SipHeaderAddr};
///
/// assert!(ContactList::parse("*")?.is_wildcard());
/// let addr = SipHeaderAddr::parse("<sip:alice@example.com>;expires=60")?;
/// let list = ContactList::new(vec![addr])?;
/// assert_eq!(list.addrs()[0].param("expires"), Some(Some("60")));
/// assert_eq!(list.to_string(), "<sip:alice@example.com>;expires=60");
/// assert!(ContactList::new(Vec::new()).is_err());
/// # Ok::<(), sip_header::ParseError>(())
/// ```
///
/// # Equality
///
/// Two lists are equal when their wire forms are: both the wildcard, or
/// the same addresses in the same order, each as [`SipHeaderAddr`]
/// compares. [`Hash`] follows the same rule.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ContactList(Contacts);

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Contacts {
    Wildcard,
    Addrs(Vec<SipHeaderAddr>),
}

impl ContactList {
    /// The `*` wildcard (RFC 3261 §10.2.2, used in REGISTER).
    pub fn wildcard() -> Self {
        ContactList(Contacts::Wildcard)
    }

    /// Build from addresses; errors when `addrs` is empty, which the
    /// grammar forbids.
    pub fn new(addrs: Vec<SipHeaderAddr>) -> Result<Self, ParseError> {
        if addrs.is_empty() {
            return Err(ParseError::empty(Field::Value));
        }
        Ok(ContactList(Contacts::Addrs(addrs)))
    }

    /// Whether this is the `*` wildcard.
    pub fn is_wildcard(&self) -> bool {
        matches!(self.0, Contacts::Wildcard)
    }

    /// The addresses, in order; empty for the wildcard.
    pub fn addrs(&self) -> &[SipHeaderAddr] {
        match &self.0 {
            Contacts::Wildcard => &[],
            Contacts::Addrs(addrs) => addrs,
        }
    }

    /// Number of addresses; 0 for the wildcard.
    pub fn len(&self) -> usize {
        self.addrs()
            .len()
    }

    /// Returns `true` for the wildcard, the only list without an address.
    pub fn is_empty(&self) -> bool {
        self.addrs()
            .is_empty()
    }

    /// The addresses, in order; none for the wildcard.
    pub fn iter(&self) -> std::slice::Iter<'_, SipHeaderAddr> {
        self.addrs()
            .iter()
    }

    /// The addresses, in order, each changed only through its own checked
    /// methods; none for the wildcard.
    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, SipHeaderAddr> {
        self.addrs_mut()
            .iter_mut()
    }

    /// The address at `index`, changed only through its own checked
    /// methods; `None` when there is none or for the wildcard.
    pub fn get_mut(&mut self, index: usize) -> Option<&mut SipHeaderAddr> {
        self.addrs_mut()
            .get_mut(index)
    }

    fn addrs_mut(&mut self) -> &mut [SipHeaderAddr] {
        match &mut self.0 {
            Contacts::Wildcard => &mut [],
            Contacts::Addrs(addrs) => addrs,
        }
    }

    /// Append an address; errors on the wildcard, which stands alone.
    pub fn push(&mut self, addr: SipHeaderAddr) -> Result<(), ParseError> {
        match &mut self.0 {
            Contacts::Wildcard => Err(ParseError::malformed(
                Field::Entry,
                FaultCode::Misplaced,
                None,
            )),
            Contacts::Addrs(addrs) => {
                addrs.push(addr);
                Ok(())
            }
        }
    }

    /// Remove and return the address at `index`, `None` when there is none
    /// or for the wildcard; errors on the last address, which the grammar
    /// needs.
    pub fn remove(&mut self, index: usize) -> Result<Option<SipHeaderAddr>, ParseError> {
        match &mut self.0 {
            Contacts::Wildcard => Ok(None),
            Contacts::Addrs(addrs) => crate::list::remove_needed(addrs, index),
        }
    }

    /// Keep only the addresses for which `keep` returns `true`, in order;
    /// errors, the list unchanged, when none would be kept. The wildcard
    /// has none to offer and stays.
    pub fn retain(&mut self, keep: impl FnMut(&SipHeaderAddr) -> bool) -> Result<(), ParseError> {
        match &mut self.0 {
            Contacts::Wildcard => Ok(()),
            Contacts::Addrs(addrs) => crate::list::retain_needed(addrs, keep),
        }
    }

    /// Consume self and return the addresses; empty for the wildcard.
    pub fn into_addrs(self) -> Vec<SipHeaderAddr> {
        match self.0 {
            Contacts::Wildcard => Vec::new(),
            Contacts::Addrs(addrs) => addrs,
        }
    }
}

impl IntoIterator for ContactList {
    type Item = SipHeaderAddr;
    type IntoIter = std::vec::IntoIter<SipHeaderAddr>;

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

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

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

impl fmt::Display for ContactList {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            Contacts::Wildcard => f.write_str("*"),
            Contacts::Addrs(addrs) => crate::fmt_joined(f, addrs, ", "),
        }
    }
}

impl Redact for ContactList {
    /// Render for logs: `*`, or every address as
    /// [`SipHeaderAddr`]'s rendering writes it.
    fn redacted<'a>(&'a self, how: &'a HeaderRedaction) -> impl fmt::Display + 'a {
        RedactedContacts(self, how)
    }
}

struct RedactedContacts<'a>(&'a ContactList, &'a HeaderRedaction);

impl fmt::Display for RedactedContacts<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self
            .0
            .is_wildcard()
        {
            return f.write_str("*");
        }
        RedactedList(
            self.0
                .addrs(),
            self.1,
        )
        .fmt(f)
    }
}

impl CommaList for ContactList {
    /// `None` for a `*` entry.
    type Entry = Option<SipHeaderAddr>;
    const QUOTE_START: crate::QuoteStart = crate::QuoteStart::DisplayName;

    fn parse_entry(
        entry: &str,
        warnings: &mut Vec<ParseWarning>,
    ) -> Result<Option<SipHeaderAddr>, ParseError> {
        if entry.trim() == "*" {
            return Ok(None);
        }
        parse_list_addr(entry, warnings).map(Some)
    }

    fn from_parsed(entries: Vec<Option<SipHeaderAddr>>) -> Result<Self, ParseError> {
        Self::from_parsed_reporting(
            entries
                .into_iter()
                .enumerate()
                .collect(),
            &mut Vec::new(),
        )
    }

    fn from_parsed_reporting(
        entries: Vec<(usize, Option<SipHeaderAddr>)>,
        warnings: &mut Vec<ParseWarning>,
    ) -> Result<Self, ParseError> {
        let has_addr = entries
            .iter()
            .any(|(_, entry)| entry.is_some());
        let mut addrs = Vec::with_capacity(entries.len());
        let mut wildcard_seen = false;
        for (i, entry) in entries {
            match entry {
                Some(addr) => addrs.push(addr),
                None if has_addr || wildcard_seen => warnings.push(
                    ParseWarning::new(Field::Entry, WarningCode::WildcardNotAlone).in_entry(i),
                ),
                None => wildcard_seen = true,
            }
        }
        if addrs.is_empty() && wildcard_seen {
            return Ok(Self::wildcard());
        }
        Self::new(addrs)
    }
}

list_parse!(ContactList);

#[cfg(feature = "serde")]
impl serde::Serialize for ContactList {
    /// `"*"` for the wildcard, the addresses as a sequence otherwise.
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match &self.0 {
            Contacts::Wildcard => serializer.serialize_str("*"),
            Contacts::Addrs(addrs) => serializer.collect_seq(addrs),
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ContactList {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        crate::serde_parts::shaped(deserializer, "ContactList", "\"*\" or a sequence")
            .map(|Wire(c)| c)
    }
}

/// The `"*"` or sequence a [`ContactList`] reads from.
#[cfg(feature = "serde")]
struct Wire(ContactList);

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Wire {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct Visitor;

        impl<'de> serde::de::Visitor<'de> for Visitor {
            type Value = ContactList;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(r#""*" or a sequence of addresses"#)
            }

            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<ContactList, E> {
                if v == "*" {
                    Ok(ContactList::wildcard())
                } else {
                    Err(E::custom("a Contact string must be \"*\""))
                }
            }

            fn visit_seq<A: serde::de::SeqAccess<'de>>(
                self,
                mut seq: A,
            ) -> Result<ContactList, A::Error> {
                let mut addrs = Vec::new();
                while let Some(addr) = seq.next_element()? {
                    addrs.push(addr);
                }
                ContactList::new(addrs).map_err(<A::Error as serde::de::Error>::custom)
            }
        }

        deserializer
            .deserialize_any(Visitor)
            .map(Wire)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{HeaderParse, ListParse};

    #[test]
    fn wildcard() {
        let contacts = ContactList::parse("*").unwrap();
        assert!(contacts.is_wildcard());
        assert_eq!(contacts.to_string(), "*");
    }

    #[test]
    fn single_addr() {
        let contacts = ContactList::parse("<sip:alice@198.51.100.1>").unwrap();
        assert_eq!(
            contacts
                .addrs()
                .len(),
            1
        );
        assert!(contacts.addrs()[0]
            .uri()
            .to_string()
            .contains("alice"));
    }

    #[test]
    fn multiple_addrs() {
        let contacts =
            ContactList::parse("<sip:alice@198.51.100.1>, \"Bob\" <sip:bob@198.51.100.2>").unwrap();
        assert_eq!(
            contacts
                .addrs()
                .len(),
            2
        );
        assert_eq!(contacts.addrs()[1].display_name(), Some("Bob"));
    }

    #[test]
    fn entries_matches_list() {
        let a = "<sip:alice@198.51.100.1>";
        let b = "\"Bob\" <sip:bob@example.com>;expires=60";
        let split = ContactList::from_entries([a, b]).unwrap();
        let joined = ContactList::parse(&format!("{a}, {b}")).unwrap();
        assert_eq!(split, joined);
        assert_eq!(
            split
                .into_addrs()
                .len(),
            2
        );
    }

    #[test]
    fn no_entries_is_empty_error() {
        assert_eq!(
            ContactList::from_entries(std::iter::empty::<&str>()),
            Err(ParseError::empty(Field::Value))
        );
    }

    #[test]
    fn wildcard_beside_addr_is_dropped_with_warning() {
        let parsed =
            ContactList::from_entries_with_warnings(["<sip:alice@example.com>", "*"]).unwrap();
        assert_eq!(
            parsed
                .value
                .addrs()
                .len(),
            1
        );
        let w = parsed.warnings[0];
        assert_eq!(
            (w.field, w.code, w.kind, w.entry),
            (
                Field::Entry,
                WarningCode::WildcardNotAlone,
                sip_uri::WarningKind::Lost,
                Some(1)
            )
        );
        assert!(matches!(
            ContactList::parse_strict("*, <sip:alice@example.com>"),
            Err(ParseError::NonConformant(w)) if w.entry == Some(0)
        ));
        assert!(ContactList::parse_strict("*").is_ok());
    }

    #[test]
    fn wildcard_after_blank_entry_gets_wire_entry_index() {
        let raw = "<sip:alice@example.com>,,*";
        let parsed = ContactList::parse_with_warnings(raw).unwrap();
        let w = parsed
            .warnings
            .iter()
            .find(|w| w.code == WarningCode::WildcardNotAlone)
            .unwrap();
        assert_eq!(w.entry, Some(2), "{:?}", parsed.warnings);
    }

    #[test]
    fn wildcard_after_blank_row_gets_its_own_row() {
        let rows = ["<sip:alice@example.com>", "", "*"];
        let parsed = ContactList::from_rows_with_warnings(rows).unwrap();
        let w = parsed
            .warnings
            .iter()
            .find(|w| w.code == WarningCode::WildcardNotAlone)
            .unwrap();
        assert_eq!(w.entry, Some(2), "{:?}", parsed.warnings);
        assert_eq!(w.row, Some(2), "{:?}", parsed.warnings);
    }

    #[test]
    fn contact_list_warnings_carry_entry_index() {
        let bad = "<sip:b@example.com>junk;expires=60";
        let parsed =
            ContactList::parse_with_warnings(&format!("<sip:a@example.com>, {bad}")).unwrap();
        assert_eq!(
            parsed
                .value
                .addrs()
                .len(),
            2
        );
        let w = parsed.warnings[0];
        assert_eq!(
            (w.code, w.entry, w.position),
            (
                WarningCode::TrailingContent,
                Some(1),
                Some(
                    "<sip:a@example.com>, ".len()
                        + bad
                            .find('j')
                            .unwrap()
                )
            )
        );
        assert!(ContactList::parse_strict(bad).is_err());
        let blank = ContactList::from_entries_with_warnings(["<sip:a@example.com>", " "]).unwrap();
        assert_eq!(
            blank
                .value
                .addrs()
                .len(),
            1
        );
        assert_eq!(
            (blank.warnings[0].code, blank.warnings[0].entry),
            (WarningCode::EmptyEntry, Some(1))
        );
    }
}