Skip to main content

sip_header_catalog/
lib.rs

1//! SIP header names with canonical wire casing (RFC 3261 and extensions),
2//! and the raw row lookup a header store implements.
3//!
4//! [`SipHeader`] covers the IANA SIP header field registry and deployed
5//! headers from expired drafts, with compact forms (RFC 3261 §7.3.3) and
6//! each header's list and repetition rules. [`SipHeaderRows`] is the lookup
7//! a key-value store implements; the parsing accessors over it live in
8//! [sip-header](https://docs.rs/sip-header). [`SipHeaderFields`] and
9//! [`SipHeaderField`] hold received rows as sent, and are such stores.
10
11#![forbid(unsafe_code)]
12
13mod fields;
14#[macro_use]
15mod macros;
16mod rows;
17#[cfg(feature = "serde")]
18mod serde_name;
19
20#[cfg(doctest)]
21#[doc = include_str!("../README.md")]
22struct ReadmeDoctests;
23
24pub use fields::{
25    SipHeaderField, SipHeaderFieldRows, SipHeaderFields, SipHeaderFieldsIntoIter,
26    SipHeaderFieldsIter,
27};
28pub use macros::HeaderName;
29pub use rows::{RowError, RowErrorKind, SipHeaderRows, SipHeaderRowsExt};
30
31/// Items `define_header_enum!` expands to; not public API.
32#[doc(hidden)]
33pub mod __private {
34    /// Seals [`HeaderName`](crate::HeaderName) to macro-generated enums.
35    pub trait HeaderNameSealed {}
36
37    #[cfg(feature = "serde")]
38    pub use crate::serde_name::{deserialize_name, serialize_name};
39    #[cfg(feature = "serde")]
40    pub use serde;
41}
42
43define_header_enum! {
44    tests_mod: sip_header_generated_tests,
45    error_type: ParseSipHeaderError => "unknown SIP header",
46    /// SIP header names with canonical wire casing.
47    ///
48    /// Each variant maps to the header's canonical form as defined in the
49    /// relevant RFC or draft; [`registry`](Self::registry) says which.
50    /// `FromStr` matches canonical names case-insensitively, and
51    /// [`parse_name`](Self::parse_name) also takes compact forms; `Display`
52    /// always emits the canonical form. With the `serde` feature a header
53    /// serializes as its canonical name and deserializes from any spelling
54    /// `parse_name` accepts.
55    ///
56    /// The order of `ALL` and the discriminant values are unspecified. `Ord`
57    /// compares the canonical wire names, as [`as_str`](Self::as_str) returns
58    /// them, byte by byte ignoring ASCII case.
59    pub enum SipHeader {
60        /// RFC 3261.
61        Accept => "Accept",
62        AcceptContact => "Accept-Contact",
63        /// RFC 3261.
64        AcceptEncoding => "Accept-Encoding",
65        /// RFC 3261.
66        AcceptLanguage => "Accept-Language",
67        AcceptResourcePriority => "Accept-Resource-Priority",
68        AdditionalIdentity => "Additional-Identity",
69        /// RFC 3261.
70        AlertInfo => "Alert-Info",
71        AlertmsgError => "AlertMsg-Error",
72        /// RFC 3261.
73        Allow => "Allow",
74        /// RFC 6665.
75        AllowEvents => "Allow-Events",
76        AnswerMode => "Answer-Mode",
77        AttestationInfo => "Attestation-Info",
78        AuthenticationInfo => "Authentication-Info",
79        /// RFC 3261.
80        Authorization => "Authorization",
81        /// RFC 3261.
82        CallId => "Call-ID",
83        /// RFC 3261.
84        CallInfo => "Call-Info",
85        CellularNetworkInfo => "Cellular-Network-Info",
86        /// RFC 3261.
87        Contact => "Contact",
88        /// RFC 3261.
89        ContentDisposition => "Content-Disposition",
90        /// RFC 3261.
91        ContentEncoding => "Content-Encoding",
92        ContentId => "Content-ID",
93        /// RFC 3261.
94        ContentLanguage => "Content-Language",
95        /// RFC 3261.
96        ContentLength => "Content-Length",
97        /// RFC 3261.
98        ContentType => "Content-Type",
99        /// RFC 3261.
100        Cseq => "CSeq",
101        /// RFC 3261.
102        Date => "Date",
103        DcInfo => "DC-Info",
104        /// Deprecated in RFC 3261.
105        Encryption => "Encryption",
106        /// RFC 3261.
107        ErrorInfo => "Error-Info",
108        /// RFC 6665.
109        Event => "Event",
110        /// RFC 3261.
111        Expires => "Expires",
112        FeatureCaps => "Feature-Caps",
113        FlowTimer => "Flow-Timer",
114        /// RFC 3261.
115        From => "From",
116        /// RFC 6442.
117        Geolocation => "Geolocation",
118        /// RFC 6442.
119        GeolocationError => "Geolocation-Error",
120        /// RFC 6442.
121        GeolocationRouting => "Geolocation-Routing",
122        /// Deprecated in RFC 3261.
123        Hide => "Hide",
124        /// RFC 7044.
125        HistoryInfo => "History-Info",
126        /// RFC 8224.
127        Identity => "Identity",
128        IdentityInfo => "Identity-Info",
129        InfoPackage => "Info-Package",
130        /// RFC 3261.
131        InReplyTo => "In-Reply-To",
132        /// RFC 3911.
133        Join => "Join",
134        MaxBreadth => "Max-Breadth",
135        /// RFC 3261.
136        MaxForwards => "Max-Forwards",
137        /// RFC 3261.
138        MimeVersion => "MIME-Version",
139        /// RFC 3261.
140        MinExpires => "Min-Expires",
141        /// RFC 4028.
142        MinSe => "Min-SE",
143        /// RFC 3261.
144        Organization => "Organization",
145        OriginationId => "Origination-Id",
146        PAccessNetworkInfo => "P-Access-Network-Info",
147        PAnswerState => "P-Answer-State",
148        /// RFC 3325.
149        PAssertedIdentity => "P-Asserted-Identity",
150        PAssertedService => "P-Asserted-Service",
151        PAssociatedUri => "P-Associated-URI",
152        PCalledPartyId => "P-Called-Party-ID",
153        PChargeInfo => "P-Charge-Info",
154        PChargingFunctionAddresses => "P-Charging-Function-Addresses",
155        PChargingVector => "P-Charging-Vector",
156        PDcsTracePartyId => "P-DCS-Trace-Party-ID",
157        PDcsOsps => "P-DCS-OSPS",
158        PDcsBillingInfo => "P-DCS-Billing-Info",
159        PDcsLaes => "P-DCS-LAES",
160        PDcsRedirect => "P-DCS-Redirect",
161        PEarlyMedia => "P-Early-Media",
162        PMediaAuthorization => "P-Media-Authorization",
163        /// RFC 3325.
164        PPreferredIdentity => "P-Preferred-Identity",
165        PPreferredService => "P-Preferred-Service",
166        PPrivateNetworkIndication => "P-Private-Network-Indication",
167        PProfileKey => "P-Profile-Key",
168        PRefusedUriList => "P-Refused-URI-List",
169        PServedUser => "P-Served-User",
170        PUserDatabase => "P-User-Database",
171        PVisitedNetworkId => "P-Visited-Network-ID",
172        /// RFC 3327.
173        Path => "Path",
174        PermissionMissing => "Permission-Missing",
175        PolicyContact => "Policy-Contact",
176        PolicyId => "Policy-ID",
177        /// RFC 3261.
178        Priority => "Priority",
179        PriorityShare => "Priority-Share",
180        PriorityVerstat => "Priority-Verstat",
181        PrivAnswerMode => "Priv-Answer-Mode",
182        /// RFC 3323.
183        Privacy => "Privacy",
184        /// RFC 3261.
185        ProxyAuthenticate => "Proxy-Authenticate",
186        /// RFC 3261.
187        ProxyAuthorization => "Proxy-Authorization",
188        /// RFC 3261.
189        ProxyRequire => "Proxy-Require",
190        Rack => "RAck",
191        /// RFC 3326.
192        Reason => "Reason",
193        ReasonPhrase => "Reason-Phrase",
194        /// RFC 3261.
195        RecordRoute => "Record-Route",
196        RecvInfo => "Recv-Info",
197        ReferEventsAt => "Refer-Events-At",
198        ReferSub => "Refer-Sub",
199        /// RFC 3515.
200        ReferTo => "Refer-To",
201        /// RFC 3892.
202        ReferredBy => "Referred-By",
203        RejectContact => "Reject-Contact",
204        RelayedCharge => "Relayed-Charge",
205        /// RFC 3891.
206        Replaces => "Replaces",
207        /// RFC 3261.
208        ReplyTo => "Reply-To",
209        RequestDisposition => "Request-Disposition",
210        /// RFC 3261.
211        Require => "Require",
212        ResourcePriority => "Resource-Priority",
213        ResourceShare => "Resource-Share",
214        /// Deprecated in RFC 3261.
215        ResponseKey => "Response-Key",
216        ResponseSource => "Response-Source",
217        RestorationInfo => "Restoration-Info",
218        /// RFC 3261.
219        RetryAfter => "Retry-After",
220        /// RFC 3261.
221        Route => "Route",
222        Rseq => "RSeq",
223        /// RFC 3329.
224        SecurityClient => "Security-Client",
225        /// RFC 3329.
226        SecurityServer => "Security-Server",
227        /// RFC 3329.
228        SecurityVerify => "Security-Verify",
229        /// RFC 3261.
230        Server => "Server",
231        ServiceInteractInfo => "Service-Interact-Info",
232        /// RFC 3608.
233        ServiceRoute => "Service-Route",
234        /// RFC 4028.
235        SessionExpires => "Session-Expires",
236        SessionId => "Session-ID",
237        SipEtag => "SIP-ETag",
238        SipIfMatch => "SIP-If-Match",
239        /// RFC 3261.
240        Subject => "Subject",
241        /// RFC 6665.
242        SubscriptionState => "Subscription-State",
243        /// RFC 3261.
244        Supported => "Supported",
245        SuppressIfMatch => "Suppress-If-Match",
246        /// RFC 4538.
247        TargetDialog => "Target-Dialog",
248        /// RFC 3261.
249        Timestamp => "Timestamp",
250        /// RFC 3261.
251        To => "To",
252        TriggerConsent => "Trigger-Consent",
253        /// RFC 3261.
254        Unsupported => "Unsupported",
255        /// RFC 3261.
256        UserAgent => "User-Agent",
257        /// RFC 7433.
258        UserToUser => "User-to-User",
259        /// RFC 3261.
260        Via => "Via",
261        /// RFC 3261.
262        Warning => "Warning",
263        /// RFC 3261.
264        WwwAuthenticate => "WWW-Authenticate",
265        /// From draft-levy-sip-diversion-08, superseded by RFC 7044.
266        Diversion => "Diversion",
267        /// From draft-ietf-sip-privacy-01, superseded by RFC 3325.
268        RemotePartyId => "Remote-Party-ID",
269    }
270}
271
272/// RFC 3261 §7.3.3 compact header form mappings.
273///
274/// Includes forms from RFC 3261, RFC 3515, RFC 3841, RFC 3892, RFC 4028,
275/// RFC 6665, and RFC 8224.
276const COMPACT_FORMS: &[(char, SipHeader)] = &[
277    ('a', SipHeader::AcceptContact),
278    ('b', SipHeader::ReferredBy),
279    ('c', SipHeader::ContentType),
280    ('d', SipHeader::RequestDisposition),
281    ('e', SipHeader::ContentEncoding),
282    ('f', SipHeader::From),
283    ('i', SipHeader::CallId),
284    ('j', SipHeader::RejectContact),
285    ('k', SipHeader::Supported),
286    ('l', SipHeader::ContentLength),
287    ('m', SipHeader::Contact),
288    ('o', SipHeader::Event),
289    ('r', SipHeader::ReferTo),
290    ('s', SipHeader::Subject),
291    ('t', SipHeader::To),
292    ('u', SipHeader::AllowEvents),
293    ('v', SipHeader::Via),
294    ('x', SipHeader::SessionExpires),
295    ('y', SipHeader::Identity),
296];
297
298impl SipHeader {
299    /// Resolve a compact form letter to the corresponding header (RFC 3261 §7.3.3).
300    ///
301    /// Case-insensitive: both `'f'` and `'F'` resolve to [`SipHeader::From`].
302    pub fn from_compact(ch: char) -> Option<Self> {
303        let lower = ch.to_ascii_lowercase();
304        COMPACT_FORMS
305            .iter()
306            .find(|(c, _)| *c == lower)
307            .map(|(_, h)| *h)
308    }
309
310    /// Return the compact form letter for this header, if one exists.
311    #[inline]
312    pub fn compact_form(&self) -> Option<char> {
313        COMPACT_FORMS
314            .iter()
315            .find(|(_, h)| h == self)
316            .map(|(c, _)| *c)
317    }
318
319    /// Whether the header's grammar is a comma list, `x *(COMMA x)` (RFC 3261
320    /// §7.3), so its rows may be joined and split at top-level commas.
321    pub fn is_list(&self) -> bool {
322        self.occurrence() == Occurrence::List
323    }
324
325    /// Whether a message may carry more than one row of this header.
326    ///
327    /// True for every comma list, and for the headers whose value is not a
328    /// list but whose RFC allows repeating the field: the authentication
329    /// headers (RFC 3261 §7.3.1), `Identity` (RFC 8224) and
330    /// `Remote-Party-ID`. Their rows are never joined or split.
331    pub fn may_repeat(&self) -> bool {
332        self.occurrence() != Occurrence::Single
333    }
334
335    /// Classification per each header's ABNF.
336    fn occurrence(&self) -> Occurrence {
337        use Occurrence::{List, Repeated, Single};
338        match self {
339            // RFC 3261 §25
340            Self::Accept
341            | Self::AcceptEncoding
342            | Self::AcceptLanguage
343            | Self::AlertInfo
344            | Self::Allow
345            | Self::CallInfo
346            | Self::Contact
347            | Self::ContentEncoding
348            | Self::ContentLanguage
349            | Self::ErrorInfo
350            | Self::InReplyTo
351            | Self::ProxyRequire
352            | Self::RecordRoute
353            | Self::Require
354            | Self::Route
355            | Self::Supported
356            | Self::Unsupported
357            | Self::Via
358            | Self::Warning => List,
359            // RFC 3261 §7.3.1: may repeat, never combined
360            Self::Authorization
361            | Self::ProxyAuthorization
362            | Self::ProxyAuthenticate
363            | Self::WwwAuthenticate => Repeated,
364            // RFC 3261 §25; Authentication-Info's commas separate one value's params
365            Self::AuthenticationInfo
366            | Self::CallId
367            | Self::ContentDisposition
368            | Self::ContentLength
369            | Self::ContentType
370            | Self::Cseq
371            | Self::Date
372            | Self::Expires
373            | Self::From
374            | Self::MaxForwards
375            | Self::MimeVersion
376            | Self::MinExpires
377            | Self::Organization
378            | Self::Priority
379            | Self::ReplyTo
380            | Self::RetryAfter
381            | Self::Server
382            | Self::Subject
383            | Self::Timestamp
384            | Self::To
385            | Self::UserAgent => Single,
386            // RFC 2543, deprecated by RFC 3261
387            Self::Encryption | Self::Hide | Self::ResponseKey => Single,
388            // RFC 3841
389            Self::AcceptContact | Self::RejectContact | Self::RequestDisposition => List,
390            // RFC 4412
391            Self::AcceptResourcePriority | Self::ResourcePriority => List,
392            // RFC 6665
393            Self::AllowEvents => List,
394            Self::Event | Self::SubscriptionState => Single,
395            // RFC 6809
396            Self::FeatureCaps => List,
397            // RFC 6442
398            Self::Geolocation => List,
399            Self::GeolocationError | Self::GeolocationRouting => Single,
400            // RFC 7044
401            Self::HistoryInfo => List,
402            // RFC 6086
403            Self::RecvInfo => List,
404            Self::InfoPackage => Single,
405            // RFC 7315 (RFC 7913 changes only PANI's access-info)
406            Self::PAccessNetworkInfo
407            | Self::PAssociatedUri
408            | Self::PChargingFunctionAddresses
409            | Self::PVisitedNetworkId => List,
410            Self::PCalledPartyId | Self::PChargingVector => Single,
411            // RFC 3325
412            Self::PAssertedIdentity | Self::PPreferredIdentity => List,
413            // RFC 6050
414            Self::PAssertedService | Self::PPreferredService => List,
415            // RFC 5009
416            Self::PEarlyMedia => List,
417            // RFC 3313
418            Self::PMediaAuthorization => List,
419            // RFC 5318
420            Self::PRefusedUriList => List,
421            // RFC 3327, RFC 3608
422            Self::Path | Self::ServiceRoute => List,
423            // RFC 5360
424            Self::PermissionMissing | Self::TriggerConsent => List,
425            // RFC 6794
426            Self::PolicyContact | Self::PolicyId => List,
427            // RFC 3326
428            Self::Reason => List,
429            // RFC 3329
430            Self::SecurityClient | Self::SecurityServer | Self::SecurityVerify => List,
431            // RFC 7433
432            Self::UserToUser => List,
433            // draft-levy-sip-diversion-08: `1#`
434            Self::Diversion => List,
435            // RFC 8224 §4: one signature per field, and more than one field may appear
436            Self::Identity => Repeated,
437            // draft-ietf-sip-privacy-01 §5.1: one party per field, and the field may repeat
438            Self::RemotePartyId => Repeated,
439            // RFC 3323: `priv-value *(";" priv-value)`
440            Self::Privacy => Single,
441            // One value each: RFC 8876, 5373, 8262, 5626, 4474, 3911, 5393, 4028,
442            // 4964, 8496, 5503, 7316, 5002, 5502, 4457, 3262, 7614, 4488, 3515,
443            // 3892, 3891, 7989, 3903, 5839, 4538
444            Self::AlertmsgError
445            | Self::AnswerMode
446            | Self::PrivAnswerMode
447            | Self::ContentId
448            | Self::FlowTimer
449            | Self::IdentityInfo
450            | Self::Join
451            | Self::MaxBreadth
452            | Self::MinSe
453            | Self::SessionExpires
454            | Self::PAnswerState
455            | Self::PChargeInfo
456            | Self::PDcsTracePartyId
457            | Self::PDcsOsps
458            | Self::PDcsBillingInfo
459            | Self::PDcsLaes
460            | Self::PDcsRedirect
461            | Self::PPrivateNetworkIndication
462            | Self::PProfileKey
463            | Self::PServedUser
464            | Self::PUserDatabase
465            | Self::Rack
466            | Self::Rseq
467            | Self::ReferEventsAt
468            | Self::ReferSub
469            | Self::ReferTo
470            | Self::ReferredBy
471            | Self::Replaces
472            | Self::SessionId
473            | Self::SipEtag
474            | Self::SipIfMatch
475            | Self::SuppressIfMatch
476            | Self::TargetDialog => Single,
477            // 3GPP TS 24.229, grammar not checked: never split or repeated
478            Self::AdditionalIdentity
479            | Self::AttestationInfo
480            | Self::CellularNetworkInfo
481            | Self::DcInfo
482            | Self::OriginationId
483            | Self::PriorityShare
484            | Self::PriorityVerstat
485            | Self::RelayedCharge
486            | Self::ResourceShare
487            | Self::ResponseSource
488            | Self::RestorationInfo
489            | Self::ServiceInteractInfo => Single,
490            // reserved by IANA against RFC 6873, no grammar
491            Self::ReasonPhrase => Single,
492        }
493    }
494
495    /// The registry this header's name comes from.
496    pub fn registry(&self) -> Registry {
497        match self {
498            Self::Diversion | Self::RemotePartyId => Registry::Draft,
499            _ => Registry::Iana,
500        }
501    }
502
503    /// Whether `wire_name`, as a message spells it, names this header:
504    /// case-insensitively, or as its compact form.
505    ///
506    /// Resolves the header on each call: a loop over many wire names builds
507    /// one [`NameMatcher`] and reuses it.
508    #[inline]
509    pub fn matches(&self, wire_name: &str) -> bool {
510        NameMatcher::from(*self).matches(wire_name)
511    }
512
513    /// [`matches`](Self::matches) for a name the catalog may not register:
514    /// an unregistered `name` matches `wire_name` case-insensitively only.
515    /// Matching many wire names against one `name` resolves it once through
516    /// [`NameMatcher`].
517    pub fn name_matches(name: &str, wire_name: &str) -> bool {
518        NameMatcher::new(name).matches(wire_name)
519    }
520
521    /// Parse a header name, including RFC 3261 §7.3.3 compact forms.
522    ///
523    /// Tries compact form resolution for single-character input, then
524    /// falls back to case-insensitive canonical name matching.
525    pub fn parse_name(name: &str) -> Result<Self, ParseSipHeaderError> {
526        Self::lookup(name).ok_or_else(|| ParseSipHeaderError(name.to_string()))
527    }
528
529    fn lookup(name: &str) -> Option<Self> {
530        match name.as_bytes() {
531            [c] => Self::from_compact(char::from(*c)),
532            _ => Self::ALL
533                .iter()
534                .copied()
535                .find(|h| name.eq_ignore_ascii_case(h.as_str())),
536        }
537    }
538}
539
540/// A header name resolved once, for testing many wire names against it as
541/// [`SipHeader::name_matches`] does.
542///
543/// A registered name matches every spelling of its header, compact form
544/// included; an unregistered one matches case-insensitively only. A store
545/// keyed by wire name builds one per lookup and tests each row's name with
546/// [`matches`](Self::matches), so the query is never re-resolved per row.
547///
548/// ```
549/// use sip_header_catalog::{NameMatcher, SipHeader};
550///
551/// let via = NameMatcher::new("Via");
552/// assert!(via.matches("v") && via.matches("VIA") && !via.matches("f"));
553/// assert!(NameMatcher::from(SipHeader::From).matches("f"));
554/// let custom = NameMatcher::new("X-Custom");
555/// assert!(custom.matches("x-custom") && !custom.matches("x"));
556/// ```
557#[derive(Debug, Clone, Copy)]
558pub struct NameMatcher<'a> {
559    name: &'a str,
560    header: Option<SipHeader>,
561    /// The header's compact letter, lowercase ASCII; none when unregistered.
562    compact: Option<u8>,
563}
564
565impl<'a> NameMatcher<'a> {
566    /// Resolve `name`, a canonical name, a compact form or a name the
567    /// catalog does not register.
568    pub fn new(name: &'a str) -> Self {
569        match SipHeader::lookup(name) {
570            Some(h) => h.into(),
571            None => NameMatcher {
572                name,
573                header: None,
574                compact: None,
575            },
576        }
577    }
578
579    /// Whether `wire_name`, as a message spells it, names the resolved
580    /// header.
581    #[inline]
582    pub fn matches(&self, wire_name: &str) -> bool {
583        wire_name.eq_ignore_ascii_case(self.name)
584            || matches!(
585                (self.compact, wire_name.as_bytes()),
586                (Some(letter), [c]) if c.to_ascii_lowercase() == letter
587            )
588    }
589}
590
591impl From<SipHeader> for NameMatcher<'_> {
592    #[inline]
593    fn from(header: SipHeader) -> Self {
594        NameMatcher {
595            name: header.as_str(),
596            header: Some(header),
597            // COMPACT_FORMS letters are all ASCII, so the cast is lossless.
598            compact: header
599                .compact_form()
600                .map(|c| c as u8),
601        }
602    }
603}
604
605/// By canonical wire name ignoring ASCII case, never by discriminant; no two
606/// wire names differ only by case, so this agrees with `Eq`.
607impl Ord for SipHeader {
608    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
609        let fold = |h: &Self| {
610            h.as_str()
611                .bytes()
612                .map(|b| b.to_ascii_lowercase())
613        };
614        fold(self).cmp(fold(other))
615    }
616}
617
618impl PartialOrd for SipHeader {
619    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
620        Some(self.cmp(other))
621    }
622}
623
624#[derive(Clone, Copy, PartialEq, Eq)]
625enum Occurrence {
626    Single,
627    List,
628    Repeated,
629}
630
631/// The registry a [`SipHeader`] name comes from.
632#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
633#[non_exhaustive]
634pub enum Registry {
635    /// The IANA SIP header field registry.
636    Iana,
637    /// An expired or superseded IETF draft, still deployed.
638    Draft,
639}
640
641#[cfg(feature = "serde")]
642impl serde::Serialize for SipHeader {
643    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
644        serde_name::serialize_name(self.as_str(), serializer)
645    }
646}
647
648#[cfg(feature = "serde")]
649impl<'de> serde::Deserialize<'de> for SipHeader {
650    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
651        serde_name::deserialize_name(deserializer, "SIP header name", SipHeader::parse_name)
652    }
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658
659    #[test]
660    fn no_two_wire_names_differ_only_by_case() {
661        for a in SipHeader::ALL {
662            for b in SipHeader::ALL {
663                assert_eq!(
664                    a.as_str()
665                        .eq_ignore_ascii_case(b.as_str()),
666                    a == b,
667                    "{a} {b}"
668                );
669            }
670        }
671    }
672
673    #[test]
674    fn ord_is_wire_name_order_ignoring_case() {
675        for a in SipHeader::ALL {
676            for b in SipHeader::ALL {
677                assert_eq!(
678                    a.cmp(b),
679                    a.as_str()
680                        .to_ascii_lowercase()
681                        .cmp(
682                            &b.as_str()
683                                .to_ascii_lowercase()
684                        ),
685                    "{a} {b}"
686                );
687                assert_eq!(a.partial_cmp(b), Some(a.cmp(b)));
688                assert_eq!(
689                    a.cmp(b)
690                        .is_eq(),
691                    a == b,
692                    "{a} {b}"
693                );
694            }
695        }
696    }
697}
698
699#[cfg(test)]
700mod compact_form_tests {
701    use super::*;
702
703    #[test]
704    fn from_compact_unknown() {
705        assert_eq!(SipHeader::from_compact('z'), None);
706        assert_eq!(SipHeader::from_compact('g'), None);
707    }
708
709    #[test]
710    fn parse_name_full() {
711        assert_eq!(SipHeader::parse_name("From"), Ok(SipHeader::From));
712        assert_eq!(SipHeader::parse_name("Via"), Ok(SipHeader::Via));
713    }
714
715    #[test]
716    fn parse_name_unknown() {
717        assert!(SipHeader::parse_name("X-Custom").is_err());
718    }
719
720    #[test]
721    fn compact_form_round_trips_through_from_compact() {
722        for h in SipHeader::ALL {
723            let back = h
724                .compact_form()
725                .and_then(SipHeader::from_compact);
726            assert_eq!(
727                back,
728                h.compact_form()
729                    .map(|_| *h),
730                "{h}"
731            );
732        }
733    }
734
735    #[test]
736    fn from_compact_resolves_exactly_the_compact_forms() {
737        for ch in (0..=0x2ff).filter_map(char::from_u32) {
738            let expected = SipHeader::ALL
739                .iter()
740                .copied()
741                .find(|h| h.compact_form() == Some(ch.to_ascii_lowercase()));
742            assert_eq!(SipHeader::from_compact(ch), expected, "{ch:?}");
743        }
744    }
745
746    fn wire_names() -> Vec<String> {
747        let mut names: Vec<String> = [
748            "é",
749            "L",
750            "",
751            "Content-Lengt",
752            "Content-Lengths",
753            "l ",
754            " l",
755        ]
756        .map(String::from)
757        .into();
758        names.extend((0u8..=0x7f).map(|b| char::from(b).to_string()));
759        for h in SipHeader::ALL {
760            let name = h.as_str();
761            names.extend([
762                name.into(),
763                name.to_ascii_uppercase(),
764                name.to_ascii_lowercase(),
765            ]);
766            if let Some(ch) = h.compact_form() {
767                names.extend([
768                    ch.to_string(),
769                    ch.to_ascii_uppercase()
770                        .to_string(),
771                ]);
772            }
773        }
774        names
775    }
776
777    fn reference(h: Option<SipHeader>, name: &str, wire: &str) -> bool {
778        match h {
779            Some(h) => {
780                wire.eq_ignore_ascii_case(h.as_str())
781                    || matches!(wire.as_bytes(), [c] if SipHeader::from_compact(char::from(*c)) == Some(h))
782            }
783            None => wire.eq_ignore_ascii_case(name),
784        }
785    }
786
787    #[test]
788    fn matches_agrees_with_the_resolving_definition() {
789        let names = wire_names();
790        for h in SipHeader::ALL {
791            let matcher = NameMatcher::from(*h);
792            for w in &names {
793                let want = reference(Some(*h), h.as_str(), w);
794                assert_eq!(matcher.matches(w), want, "{h} {w:?}");
795                assert_eq!(h.matches(w), want, "{h} {w:?}");
796            }
797        }
798    }
799
800    #[test]
801    fn name_matcher_new_agrees_with_the_resolving_definition() {
802        let names = wire_names();
803        for query in names
804            .iter()
805            .map(String::as_str)
806            .chain(["X-Custom", "x-custom"])
807        {
808            let matcher = NameMatcher::new(query);
809            let resolved = SipHeader::parse_name(query).ok();
810            for w in &names {
811                let want = reference(resolved, query, w);
812                assert_eq!(matcher.matches(w), want, "{query:?} {w:?}");
813                assert_eq!(SipHeader::name_matches(query, w), want, "{query:?} {w:?}");
814            }
815        }
816    }
817
818    #[test]
819    fn parse_name_takes_compact_forms_in_either_case() {
820        for h in SipHeader::ALL {
821            if let Some(ch) = h.compact_form() {
822                for spelling in [ch, ch.to_ascii_uppercase()] {
823                    assert_eq!(
824                        SipHeader::parse_name(&spelling.to_string()),
825                        Ok(*h),
826                        "{spelling}"
827                    );
828                }
829            }
830        }
831    }
832}
833
834#[cfg(test)]
835mod occurrence_tests {
836    use super::*;
837
838    #[test]
839    fn authentication_headers_repeat_but_never_split() {
840        for h in [
841            SipHeader::Authorization,
842            SipHeader::ProxyAuthorization,
843            SipHeader::WwwAuthenticate,
844            SipHeader::ProxyAuthenticate,
845        ] {
846            assert!(h.may_repeat() && !h.is_list(), "{h}");
847        }
848        assert!(!SipHeader::AuthenticationInfo.is_list());
849        assert!(!SipHeader::AuthenticationInfo.may_repeat());
850    }
851
852    #[test]
853    fn single_values() {
854        for h in [
855            SipHeader::From,
856            SipHeader::To,
857            SipHeader::CallId,
858            SipHeader::Cseq,
859            SipHeader::Privacy,
860            SipHeader::Server,
861            SipHeader::UserAgent,
862            SipHeader::Replaces,
863        ] {
864            assert!(!h.is_list() && !h.may_repeat(), "{h}");
865        }
866    }
867}
868
869#[cfg(test)]
870mod registry_tests {
871    use super::*;
872
873    /// Each line: wire name, then its compact form if the registry gives one.
874    fn listed(file: &str) -> Vec<(&str, Option<char>)> {
875        let mut rows: Vec<(&str, Option<char>)> = file
876            .lines()
877            .filter_map(|l| {
878                let mut cols = l
879                    .split('#')
880                    .next()?
881                    .split_whitespace();
882                let name = cols.next()?;
883                let compact = cols
884                    .next()
885                    .map(|c| {
886                        let mut chars = c.chars();
887                        match (chars.next(), chars.next()) {
888                            (Some(ch), None) => ch,
889                            _ => panic!("{name}: compact form {c:?} is not one letter"),
890                        }
891                    });
892                assert_eq!(cols.next(), None, "{name}: extra column");
893                Some((name, compact))
894            })
895            .collect();
896        rows.sort_unstable();
897        rows
898    }
899
900    fn catalog(registry: Registry) -> Vec<(&'static str, Option<char>)> {
901        let mut rows: Vec<(&str, Option<char>)> = SipHeader::ALL
902            .iter()
903            .filter(|h| h.registry() == registry)
904            .map(|h| (h.as_str(), h.compact_form()))
905            .collect();
906        rows.sort_unstable();
907        rows
908    }
909
910    #[test]
911    fn iana_list_matches_catalog() {
912        assert_eq!(
913            catalog(Registry::Iana),
914            listed(include_str!("../iana-sip-headers.txt"))
915        );
916    }
917
918    #[test]
919    fn draft_list_matches_catalog() {
920        assert_eq!(
921            catalog(Registry::Draft),
922            listed(include_str!("../draft-sip-headers.txt"))
923        );
924    }
925
926    #[test]
927    fn from_str_takes_canonical_names_only() {
928        assert!("v"
929            .parse::<SipHeader>()
930            .is_err());
931        assert_eq!(SipHeader::parse_name("v"), Ok(SipHeader::Via));
932    }
933}
934
935#[cfg(all(test, feature = "serde"))]
936mod serde_tests {
937    use super::*;
938
939    #[test]
940    fn serializes_as_the_wire_name() {
941        for h in SipHeader::ALL {
942            assert_eq!(
943                serde_json::to_string(h).unwrap(),
944                format!("\"{}\"", h.as_str())
945            );
946        }
947    }
948
949    #[test]
950    fn deserializes_any_spelling_parse_name_accepts() {
951        for h in SipHeader::ALL {
952            for spelling in [
953                h.as_str()
954                    .to_string(),
955                h.as_str()
956                    .to_lowercase(),
957                h.as_str()
958                    .to_uppercase(),
959            ] {
960                let json = format!("\"{spelling}\"");
961                assert_eq!(serde_json::from_str::<SipHeader>(&json).unwrap(), *h);
962            }
963        }
964        assert_eq!(
965            serde_json::from_str::<Vec<SipHeader>>(r#"["v","F","call-id"]"#).unwrap(),
966            vec![SipHeader::Via, SipHeader::From, SipHeader::CallId]
967        );
968    }
969
970    #[test]
971    fn unknown_name_error_omits_the_input() {
972        let e = serde_json::from_str::<SipHeader>(r#""X-Secret-Token""#).unwrap_err();
973        let msg = e.to_string();
974        assert!(msg.contains("unknown SIP header name"), "{msg}");
975        assert!(!msg.contains("Secret"), "{msg}");
976    }
977}