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
//! `callid *(SEMI param)` with two mandatory tags: the core Replaces
//! (RFC 3891), Join (RFC 3911) and Target-Dialog (RFC 4538) share.

use std::fmt::{self, Write as _};

use crate::call_id::SipCallId;
use crate::check::checked_token;
use crate::diagnostic::{Field, ParseWarning, Parsed, WarningCode};
use crate::error::{FaultCode, ParseError};
use crate::params::HeaderParams;

pub(crate) mod sealed {
    pub trait Sealed {}
}

/// How a dialog identifier is framed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum DialogFraming {
    /// The value as a header field carries it.
    #[default]
    Header,
    /// Percent-encoded as a URI header (`<sip:…?Replaces=…>`), where `@`,
    /// `;` and `=` stay encoded.
    UriHeader,
}

#[cfg(feature = "serde")]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(
    remote = "DialogFraming",
    rename = "DialogFraming",
    rename_all = "kebab-case"
)]
enum DialogFramingDef {
    Header,
    UriHeader,
}

#[cfg(feature = "serde")]
impl crate::serde_parts::Expected for DialogFraming {
    const TEXT: &'static str = "\"header\" or \"uri-header\"";
}

#[cfg(feature = "serde")]
impl serde::Serialize for DialogFraming {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        DialogFramingDef::serialize(self, serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for DialogFraming {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        crate::serde_parts::leaf(
            deserializer,
            "dialog framing",
            <DialogFraming as crate::serde_parts::Expected>::TEXT,
            DialogFramingDef::deserialize,
        )
    }
}

/// The tag names a dialog-identifier header uses. Sealed.
pub trait DialogKind: sealed::Sealed {
    /// Name of the first mandatory tag parameter.
    const FIRST_TAG: &'static str;
    /// Name of the second mandatory tag parameter.
    const SECOND_TAG: &'static str;
    /// Whether the header defines the `early-only` flag.
    const EARLY_ONLY: bool;
    /// Parameter names set through typed setters, which `params_mut` refuses.
    const RESERVED: &'static [&'static str];
}

params_located!(DialogId);

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct DialogId {
    call_id: String,
    first_tag: String,
    second_tag: String,
    early_only: bool,
    params: HeaderParams,
    framing: DialogFraming,
}

impl DialogId {
    /// Errors unless `call_id` is a `callid` and both tags are `token`s.
    pub(crate) fn new(
        call_id: &str,
        first_tag: &str,
        second_tag: &str,
    ) -> Result<Self, ParseError> {
        Ok(DialogId {
            call_id: SipCallId::new(call_id)?.into(),
            first_tag: checked_token(Field::Tag, first_tag)?,
            second_tag: checked_token(Field::Tag, second_tag)?,
            early_only: false,
            params: HeaderParams::default(),
            framing: DialogFraming::Header,
        })
    }

    pub(crate) fn from_fields(fields: DialogFields, framing: DialogFraming) -> Self {
        DialogId {
            call_id: fields.call_id,
            first_tag: fields.first_tag,
            second_tag: fields.second_tag,
            early_only: fields.early_only,
            params: fields.params,
            framing,
        }
    }

    pub(crate) fn call_id(&self) -> &str {
        &self.call_id
    }

    /// Errors unless `call_id` is an RFC 3261 §25.1 `callid = word [ "@" word ]`.
    pub(crate) fn set_call_id(&mut self, call_id: &str) -> Result<(), ParseError> {
        self.call_id = SipCallId::new(call_id)?.into();
        self.params
            .clear_spans();
        Ok(())
    }

    pub(crate) fn host(&self) -> Option<&str> {
        self.call_id
            .split_once('@')
            .map(|(_, host)| host)
    }

    pub(crate) fn first_tag(&self) -> &str {
        &self.first_tag
    }

    pub(crate) fn second_tag(&self) -> &str {
        &self.second_tag
    }

    pub(crate) fn early_only(&self) -> bool {
        self.early_only
    }

    pub(crate) fn set_early_only(&mut self, early_only: bool) {
        self.early_only = early_only;
        self.params
            .clear_spans();
    }

    pub(crate) fn params(&self) -> &HeaderParams {
        &self.params
    }

    pub(crate) fn params_mut(&mut self) -> &mut HeaderParams {
        &mut self.params
    }

    pub(crate) fn set_first_tag(&mut self, tag: &str) -> Result<(), ParseError> {
        self.first_tag = checked_token(Field::Tag, tag)?;
        self.params
            .clear_spans();
        Ok(())
    }

    pub(crate) fn set_second_tag(&mut self, tag: &str) -> Result<(), ParseError> {
        self.second_tag = checked_token(Field::Tag, tag)?;
        self.params
            .clear_spans();
        Ok(())
    }

    pub(crate) fn framing(&self) -> DialogFraming {
        self.framing
    }

    pub(crate) fn set_framing(&mut self, framing: DialogFraming) {
        self.framing = framing;
        self.params
            .clear_spans();
    }

    fn wire_form<K: DialogKind>(&self) -> Result<String, fmt::Error> {
        let mut s = format!(
            "{};{}={};{}={}",
            self.call_id,
            K::FIRST_TAG,
            self.first_tag,
            K::SECOND_TAG,
            self.second_tag
        );
        if self.early_only {
            s.push_str(";early-only");
        }
        write!(s, "{}", self.params)?;
        Ok(s)
    }

    pub(crate) fn write<K: DialogKind>(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let wire = self.wire_form::<K>()?;
        match self.framing {
            DialogFraming::Header => f.write_str(&wire),
            DialogFraming::UriHeader => f.write_str(&sip_uri::encoding::encode_header(&wire)),
        }
    }
}

/// Constructor, builders, accessors and Display for a `struct $Type(DialogId)`.
macro_rules! dialog_id_type {
    ($Type:ident, $first:ident, $set_first:ident => $first_name:literal, $second:ident, $set_second:ident => $second_name:literal, early_only: $early:literal) => {
        impl $crate::dialog_id::sealed::Sealed for $Type {}

        impl $crate::equivalence::sealed::Sealed for $Type {}

        impl $crate::HeaderEquivalence for $Type {
            fn equivalent(&self, other: &Self) -> bool {
                $crate::equivalence::dialogs_equivalent(&self.0, &other.0)
            }
        }

        impl $crate::dialog_id::DialogKind for $Type {
            const FIRST_TAG: &'static str = $first_name;
            const SECOND_TAG: &'static str = $second_name;
            const EARLY_ONLY: bool = $early;
            const RESERVED: &'static [&'static str] = if $early {
                &[$first_name, $second_name, "early-only"]
            } else {
                &[$first_name, $second_name]
            };
        }

        impl $Type {
            #[doc = concat!("A header-framed value from its Call-ID, `", $first_name, "` and `", $second_name, "`.")]
            ///
            /// Errors unless the Call-ID is an RFC 3261 §25.1
            /// `callid = word [ "@" word ]` and both tags are `token`s.
            pub fn new(
                call_id: impl AsRef<str>,
                $first: impl AsRef<str>,
                $second: impl AsRef<str>,
            ) -> Result<Self, $crate::error::ParseError> {
                $crate::dialog_id::DialogId::new(call_id.as_ref(), $first.as_ref(), $second.as_ref())
                    .map(Self)
            }

            /// The generic parameters, to edit through a guard that refuses
            /// the names this header sets through its typed setters.
            pub fn params_mut(&mut self) -> $crate::params::ParamsMut<'_> {
                $crate::params::ParamsMut::new(
                    self.0
                        .params_mut(),
                    $crate::params::ParamRule {
                        reserved: <Self as $crate::dialog_id::DialogKind>::RESERVED,
                        check: $crate::params::any_value,
                    },
                    $crate::params::Owner::Plain,
                )
            }

            #[doc = concat!("Returns this value with a different `", $first_name, "`, a `token`.")]
            pub fn $set_first(
                mut self,
                tag: impl AsRef<str>,
            ) -> Result<Self, $crate::error::ParseError> {
                self.0
                    .set_first_tag(tag.as_ref())?;
                Ok(self)
            }

            #[doc = concat!("Returns this value with a different `", $second_name, "`, a `token`.")]
            pub fn $set_second(
                mut self,
                tag: impl AsRef<str>,
            ) -> Result<Self, $crate::error::ParseError> {
                self.0
                    .set_second_tag(tag.as_ref())?;
                Ok(self)
            }

            /// Returns this value with a different Call-ID.
            ///
            /// Framing, both tags and all other parameters are preserved. Errors
            /// unless `call_id` is an RFC 3261 §25.1 `callid = word [ "@" word ]`;
            /// [`parse`](crate::HeaderParse::parse) is lenient about this token, a value
            /// that never came off the wire is not.
            ///
            /// ```
            #[doc = concat!("use sip_header::{HeaderParse, ", stringify!($Type), "};")]
            ///
            #[doc = concat!("let v = ", stringify!($Type), "::parse(\"abc@203.0.113.5;", $first_name, "=t1;", $second_name, "=f1\")?")]
            ///     .with_call_id("abc@example.com")?;
            #[doc = concat!("assert_eq!(v.to_string(), \"abc@example.com;", $first_name, "=t1;", $second_name, "=f1\");")]
            /// assert!(v.with_call_id("a b").is_err());
            /// # Ok::<(), sip_header::ParseError>(())
            /// ```
            pub fn with_call_id(
                mut self,
                call_id: impl AsRef<str>,
            ) -> Result<Self, $crate::error::ParseError> {
                self.0
                    .set_call_id(call_id.as_ref())?;
                Ok(self)
            }

            /// Set the framing [`Display`](std::fmt::Display) emits.
            pub fn with_framing(mut self, framing: $crate::dialog_id::DialogFraming) -> Self {
                self.0
                    .set_framing(framing);
                self
            }

            /// The framing [`Display`](std::fmt::Display) emits.
            pub fn framing(&self) -> $crate::dialog_id::DialogFraming {
                self.0
                    .framing()
            }

            /// The Call-ID of the dialog, case as sent.
            pub fn call_id(&self) -> &str {
                self.0
                    .call_id()
            }

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

            #[doc = concat!("The mandatory `", $first_name, "` value, case as sent.")]
            pub fn $first(&self) -> &str {
                self.0
                    .first_tag()
            }

            #[doc = concat!("The mandatory `", $second_name, "` value, case as sent.")]
            pub fn $second(&self) -> &str {
                self.0
                    .second_tag()
            }

            /// The generic parameters, the tags and flags this header defines excluded.
            pub fn params(&self) -> &$crate::params::HeaderParams {
                self.0
                    .params()
            }

            /// [`HeaderParams::get`](crate::HeaderParams::get) on [`params`](Self::params).
            pub fn param(&self, key: &str) -> Option<Option<&str>> {
                self.0
                    .params()
                    .get(key)
            }
        }

        header_params!(@builders $Type);

        impl std::fmt::Display for $Type {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                self.0
                    .write::<Self>(f)
            }
        }
    };
}

params_located!(DialogFields);

/// A dialog identifier's parts, as parsing reads them.
pub(crate) struct DialogFields {
    pub(crate) call_id: String,
    pub(crate) first_tag: String,
    pub(crate) second_tag: String,
    pub(crate) early_only: bool,
    pub(crate) params: HeaderParams,
}

/// Building a dialog-identifier type from its parts.
pub(crate) trait DialogBuild: DialogKind + Sized {
    fn build(fields: DialogFields, framing: DialogFraming) -> Self;

    #[cfg(feature = "serde")]
    fn dialog(&self) -> &DialogId;
}

pub(crate) fn parse<T: DialogBuild>(raw: &str) -> Result<Parsed<T>, ParseError> {
    crate::scrub::parse_scrubbed_located(raw, parse_framed::<T>)
        .map(|p| p.map(|f| T::build(f, DialogFraming::Header)))
}

/// Error positions are dropped; warning positions point into the decoded text.
pub(crate) fn parse_uri_header<T: DialogBuild>(raw: &str) -> Result<Parsed<T>, ParseError> {
    crate::scrub::parse_uri_header(raw, parse_framed::<T>)
        .map(|p| p.map(|f| T::build(f, DialogFraming::UriHeader)))
}

/// `value` when parsing its wire form in its own framing gives it back.
#[cfg(feature = "serde")]
pub(crate) fn reads_back<T>(value: T) -> Result<T, ParseError>
where
    T: DialogBuild + std::fmt::Display + PartialEq,
{
    let framing = value
        .dialog()
        .framing;
    crate::check::reads_back(value, |wire| {
        match framing {
            DialogFraming::Header => parse::<T>(wire),
            DialogFraming::UriHeader => parse_uri_header::<T>(wire),
        }
        .map(|p| p.value)
    })
}

fn parse_framed<K: DialogKind>(raw: &str) -> Result<Parsed<DialogFields>, ParseError> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err(ParseError::empty(Field::Value));
    }

    // A call-id `word` may contain `"`, so it ends at the first raw `;`.
    let (call_id, rest) = crate::split_at_params(trimmed);
    let call_id = call_id.trim();
    if call_id.is_empty() {
        return Err(ParseError::malformed(
            Field::CallId,
            FaultCode::Missing,
            Some(crate::offset_in(raw, trimmed)),
        ));
    }
    let mut warnings = Vec::new();
    crate::call_id::report_breach(call_id, crate::offset_in(raw, call_id), &mut warnings);

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

    for param in crate::parse_params(rest) {
        let key = param
            .name()
            .to_ascii_lowercase();
        let Some(value) = param.value else {
            let flag = K::EARLY_ONLY && key == "early-only";
            if flag && !early_only {
                param.report_name(raw, &mut warnings);
                early_only = true;
            } else {
                if flag
                    && params
                        .get(&key)
                        .is_none()
                {
                    warnings.push(
                        ParseWarning::new(Field::Param, WarningCode::DuplicateParam)
                            .at(crate::offset_in(raw, param.key)),
                    );
                }
                params.push_raw(raw, &param, &mut warnings);
            }
            continue;
        };
        let slot = if key == K::FIRST_TAG {
            &mut first_tag
        } else if key == K::SECOND_TAG {
            &mut second_tag
        } else {
            params.push_raw(raw, &param, &mut warnings);
            continue;
        };
        param.report_name(raw, &mut warnings);
        // A value the reader framed as quoted prints verbatim to frame the same.
        let tag = if !param.unterminated && value.starts_with('"') {
            param.report_quoting(raw, &mut warnings);
            value.to_string()
        } else {
            crate::token_field(raw, value, Field::Tag, &mut warnings).into_owned()
        };
        if tag.is_empty() {
            return Err(ParseError::malformed(
                Field::Tag,
                FaultCode::Missing,
                Some(crate::offset_in(raw, value)),
            ));
        }
        if slot
            .replace(tag)
            .is_some()
        {
            return Err(ParseError::malformed(
                Field::Tag,
                FaultCode::Duplicate,
                Some(crate::offset_in(raw, param.key)),
            ));
        }
    }

    let missing_tag = || ParseError::malformed(Field::Tag, FaultCode::Missing, None);
    let fields = DialogFields {
        call_id: call_id.to_string(),
        first_tag: first_tag.ok_or_else(missing_tag)?,
        second_tag: second_tag.ok_or_else(missing_tag)?,
        early_only,
        params,
    };
    Ok(Parsed::new(fields, warnings))
}

/// HeaderParse and UriHeaderParse for a type implementing [`DialogBuild`].
macro_rules! dialog_id_parse {
    ($Type:ident) => {
        impl $crate::traits::sealed::Sealed for $Type {}

        impl $crate::span::Located for $Type {
            fn relocate_spans(&mut self, to: &$crate::span::Relocation<'_>) {
                $crate::span::Located::relocate_spans(&mut self.0, to);
            }
        }

        impl $crate::traits::HeaderParse for $Type {
            fn parse_with_warnings(
                raw: &str,
            ) -> Result<$crate::diagnostic::Parsed<Self>, $crate::error::ParseError> {
                $crate::dialog_id::parse(raw)
            }
        }

        /// [`Display`](std::fmt::Display) re-encodes a value parsed this way
        /// to the canonical form (uppercase hex) [`sip_uri::SipUri::header`]
        /// returns.
        impl $crate::traits::UriHeaderParse for $Type {
            fn parse_uri_header_with_warnings(
                raw: &str,
            ) -> Result<$crate::diagnostic::Parsed<Self>, $crate::error::ParseError> {
                $crate::dialog_id::parse_uri_header(raw)
            }
        }
    };
}