Skip to main content

rsipstack/sip/
message.rs

1use crate::prelude::*;
2use crate::sip::{
3    headers::untyped::*,
4    headers::{Header, Headers},
5    uri::Branch,
6    Error, Method, StatusCode, Uri, Version,
7};
8
9pub trait HasHeaders {
10    fn headers(&self) -> &Headers;
11    fn headers_mut(&mut self) -> &mut Headers;
12}
13
14macro_rules! header_get {
15    ($iter:expr, $variant:path, $err:expr) => {
16        $iter
17            .find_map(|h| {
18                if let $variant(inner) = h {
19                    Some(inner)
20                } else {
21                    None
22                }
23            })
24            .ok_or_else(|| $err)
25    };
26}
27
28macro_rules! header_get_mut {
29    ($iter:expr, $variant:path, $err:expr) => {
30        $iter
31            .find_map(|h| {
32                if let $variant(inner) = h {
33                    Some(inner)
34                } else {
35                    None
36                }
37            })
38            .ok_or_else(|| $err)
39    };
40}
41
42macro_rules! header_opt {
43    ($iter:expr, $variant:path) => {
44        $iter.find_map(|h| {
45            if let $variant(inner) = h {
46                Some(inner)
47            } else {
48                None
49            }
50        })
51    };
52}
53
54macro_rules! all_headers {
55    ($iter:expr, $variant:path) => {
56        $iter
57            .filter_map(|h| {
58                if let $variant(inner) = h {
59                    Some(inner)
60                } else {
61                    None
62                }
63            })
64            .collect()
65    };
66}
67
68pub trait HeadersExt: HasHeaders {
69    fn to_header(&self) -> Result<&To, Error> {
70        header_get!(
71            self.headers().iter(),
72            Header::To,
73            Error::MissingHeader("To".into())
74        )
75    }
76    fn to_header_mut(&mut self) -> Result<&mut To, Error> {
77        header_get_mut!(
78            self.headers_mut().iter_mut(),
79            Header::To,
80            Error::MissingHeader("To".into())
81        )
82    }
83    fn from_header(&self) -> Result<&From, Error> {
84        header_get!(
85            self.headers().iter(),
86            Header::From,
87            Error::MissingHeader("From".into())
88        )
89    }
90    fn from_header_mut(&mut self) -> Result<&mut From, Error> {
91        header_get_mut!(
92            self.headers_mut().iter_mut(),
93            Header::From,
94            Error::MissingHeader("From".into())
95        )
96    }
97    fn via_header(&self) -> Result<&Via, Error> {
98        header_get!(
99            self.headers().iter(),
100            Header::Via,
101            Error::MissingHeader("Via".into())
102        )
103    }
104    fn top_via_header(&self) -> Result<Via, Error> {
105        self.via_header()?.first_value()
106    }
107    /// Whether Via contains another hop, including comma-separated entries.
108    /// Inconclusive values do not make an otherwise usable message invalid.
109    fn has_multiple_vias(&self) -> bool {
110        let mut seen = false;
111        for header in self.headers().iter() {
112            if let Header::Via(via) = header {
113                if seen {
114                    return true;
115                }
116                seen = true;
117                // Only split to find another entry in this same header.
118                if let Ok(first) = via.first_value() {
119                    let rest = via.value().trim()[first.value().len()..].trim();
120                    if rest
121                        .strip_prefix(',')
122                        .is_some_and(|rest| !rest.trim().is_empty())
123                    {
124                        return true;
125                    }
126                }
127            }
128        }
129        false
130    }
131    fn via_header_mut(&mut self) -> Result<&mut Via, Error> {
132        header_get_mut!(
133            self.headers_mut().iter_mut(),
134            Header::Via,
135            Error::MissingHeader("Via".into())
136        )
137    }
138    fn call_id_header(&self) -> Result<&CallId, Error> {
139        header_get!(
140            self.headers().iter(),
141            Header::CallId,
142            Error::MissingHeader("Call-ID".into())
143        )
144    }
145    fn call_id_header_mut(&mut self) -> Result<&mut CallId, Error> {
146        header_get_mut!(
147            self.headers_mut().iter_mut(),
148            Header::CallId,
149            Error::MissingHeader("Call-ID".into())
150        )
151    }
152    fn cseq_header(&self) -> Result<&CSeq, Error> {
153        header_get!(
154            self.headers().iter(),
155            Header::CSeq,
156            Error::MissingHeader("CSeq".into())
157        )
158    }
159    fn cseq_header_mut(&mut self) -> Result<&mut CSeq, Error> {
160        header_get_mut!(
161            self.headers_mut().iter_mut(),
162            Header::CSeq,
163            Error::MissingHeader("CSeq".into())
164        )
165    }
166    fn max_forwards_header(&self) -> Result<&MaxForwards, Error> {
167        header_get!(
168            self.headers().iter(),
169            Header::MaxForwards,
170            Error::MissingHeader("Max-Forwards".into())
171        )
172    }
173    fn max_forwards_header_mut(&mut self) -> Result<&mut MaxForwards, Error> {
174        header_get_mut!(
175            self.headers_mut().iter_mut(),
176            Header::MaxForwards,
177            Error::MissingHeader("Max-Forwards".into())
178        )
179    }
180    fn contact_header(&self) -> Result<&Contact, Error> {
181        header_get!(
182            self.headers().iter(),
183            Header::Contact,
184            Error::MissingHeader("Contact".into())
185        )
186    }
187    fn contact_header_mut(&mut self) -> Result<&mut Contact, Error> {
188        header_get_mut!(
189            self.headers_mut().iter_mut(),
190            Header::Contact,
191            Error::MissingHeader("Contact".into())
192        )
193    }
194    fn contact_headers(&self) -> Vec<&Contact> {
195        all_headers!(self.headers().iter(), Header::Contact)
196    }
197    /// RFC 7989 Session-ID header, when present.
198    fn session_id_header(&self) -> Option<&crate::sip::headers::SessionId> {
199        self.headers().iter().find_map(|h| match h {
200            Header::SessionId(s) => Some(s),
201            _ => None,
202        })
203    }
204    /// All History-Info header lines (RFC 7044 allows multiple lines, each
205    /// possibly holding comma-joined hi-entries).
206    fn history_info_headers(&self) -> Vec<&crate::sip::headers::HistoryInfo> {
207        self.headers()
208            .iter()
209            .filter_map(|h| match h {
210                Header::HistoryInfo(hi) => Some(hi),
211                _ => None,
212            })
213            .collect()
214    }
215    /// Flattened typed hi-entries across every History-Info header line.
216    fn history_info_entries(&self) -> Result<Vec<crate::sip::typed::HistoryInfoEntry>, Error> {
217        let mut entries = Vec::new();
218        for hi in self.history_info_headers() {
219            entries.extend(hi.clone().into_typed()?.entries);
220        }
221        Ok(entries)
222    }
223    fn typed_contact_headers(&self) -> Result<Vec<crate::sip::typed::Contact>, Error> {
224        let mut contacts = Vec::new();
225        for contact in self.contact_headers() {
226            contacts.extend(crate::sip::typed::Contact::parse_header_list(
227                contact.value(),
228            )?);
229        }
230        Ok(contacts)
231    }
232    fn record_route_headers(&self) -> Vec<&RecordRoute> {
233        all_headers!(self.headers().iter(), Header::RecordRoute)
234    }
235    fn record_route_header(&self) -> Option<&RecordRoute> {
236        header_opt!(self.headers().iter(), Header::RecordRoute)
237    }
238    fn typed_record_route_headers(&self) -> Result<Vec<crate::sip::typed::RecordRoute>, Error> {
239        let mut rrs = Vec::new();
240        for rr in self.record_route_headers() {
241            rrs.extend(crate::sip::typed::RecordRoute::parse_header_list(
242                rr.value(),
243            )?);
244        }
245        Ok(rrs)
246    }
247    fn route_headers(&self) -> Vec<&Route> {
248        all_headers!(self.headers().iter(), Header::Route)
249    }
250    fn route_header(&self) -> Option<&Route> {
251        header_opt!(self.headers().iter(), Header::Route)
252    }
253    fn typed_route_headers(&self) -> Result<Vec<crate::sip::typed::Route>, Error> {
254        let mut routes = Vec::new();
255        for r in self.route_headers() {
256            routes.extend(crate::sip::typed::Route::parse_header_list(r.value())?);
257        }
258        Ok(routes)
259    }
260    fn service_route_headers(&self) -> Vec<&ServiceRoute> {
261        all_headers!(self.headers().iter(), Header::ServiceRoute)
262    }
263    fn service_route_header(&self) -> Option<&ServiceRoute> {
264        header_opt!(self.headers().iter(), Header::ServiceRoute)
265    }
266    fn typed_service_route_headers(&self) -> Result<Vec<crate::sip::typed::ServiceRoute>, Error> {
267        let mut routes = Vec::new();
268        for r in self.service_route_headers() {
269            routes.extend(crate::sip::typed::ServiceRoute::parse_header_list(
270                r.value(),
271            )?);
272        }
273        Ok(routes)
274    }
275    fn user_agent_header(&self) -> Option<&UserAgent> {
276        header_opt!(self.headers().iter(), Header::UserAgent)
277    }
278    fn authorization_header(&self) -> Option<&Authorization> {
279        header_opt!(self.headers().iter(), Header::Authorization)
280    }
281    fn www_authenticate_header(&self) -> Option<&WwwAuthenticate> {
282        header_opt!(self.headers().iter(), Header::WwwAuthenticate)
283    }
284    fn expires_header(&self) -> Option<&Expires> {
285        header_opt!(self.headers().iter(), Header::Expires)
286    }
287    fn min_expires_header(&self) -> Option<&MinExpires> {
288        header_opt!(self.headers().iter(), Header::MinExpires)
289    }
290    fn reason_header(&self) -> Option<&crate::sip::headers::untyped::Reason> {
291        header_opt!(self.headers().iter(), Header::Reason)
292    }
293    fn refer_to_header(&self) -> Option<&crate::sip::headers::untyped::ReferTo> {
294        header_opt!(self.headers().iter(), Header::ReferTo)
295    }
296    fn referred_by_header(&self) -> Option<&crate::sip::headers::untyped::ReferredBy> {
297        header_opt!(self.headers().iter(), Header::ReferredBy)
298    }
299    fn session_expires_header(&self) -> Option<&crate::sip::headers::untyped::SessionExpires> {
300        header_opt!(self.headers().iter(), Header::SessionExpires)
301    }
302    fn p_asserted_identity_header(
303        &self,
304    ) -> Option<&crate::sip::headers::untyped::PAssertedIdentity> {
305        header_opt!(self.headers().iter(), Header::PAssertedIdentity)
306    }
307    fn call_info_header(&self) -> Option<&CallInfo> {
308        header_opt!(self.headers().iter(), Header::CallInfo)
309    }
310    fn call_info_headers(&self) -> Vec<&CallInfo> {
311        all_headers!(self.headers().iter(), Header::CallInfo)
312    }
313    fn user_to_user_header(&self) -> Option<&UserToUser> {
314        header_opt!(self.headers().iter(), Header::UserToUser)
315    }
316    fn user_to_user_headers(&self) -> Vec<&UserToUser> {
317        all_headers!(self.headers().iter(), Header::UserToUser)
318    }
319    fn replaces_header(&self) -> Option<&crate::sip::headers::untyped::Replaces> {
320        header_opt!(self.headers().iter(), Header::Replaces)
321    }
322    fn privacy_header(&self) -> Option<&crate::sip::headers::untyped::Privacy> {
323        header_opt!(self.headers().iter(), Header::Privacy)
324    }
325    fn path_headers(&self) -> Vec<&crate::sip::headers::untyped::Path> {
326        all_headers!(self.headers().iter(), Header::Path)
327    }
328    fn rseq_value(&self) -> Option<u32> {
329        self.headers().iter().find_map(|h| {
330            if let Header::RSeq(r) = h {
331                r.value().trim().parse().ok()
332            } else {
333                None
334            }
335        })
336    }
337    fn rack_value(&self) -> Option<(u32, u32, Method)> {
338        self.headers().iter().find_map(|h| {
339            if let Header::RAck(r) = h {
340                let v = r.value();
341                let mut parts = v.split_whitespace();
342                let rseq = parts.next()?.parse::<u32>().ok()?;
343                let cseq = parts.next()?.parse::<u32>().ok()?;
344                let method = parts.next()?.parse::<Method>().ok()?;
345                Some((rseq, cseq, method))
346            } else {
347                None
348            }
349        })
350    }
351    fn header_value(&self, name: &str) -> Option<String> {
352        self.headers().iter().find_map(|h| {
353            if h.name().eq_ignore_ascii_case(name) {
354                Some(h.value().trim().to_string())
355            } else {
356                None
357            }
358        })
359    }
360    fn header_contains_token(&self, name: &str, token: &str) -> bool {
361        self.headers().iter().any(|header| match header {
362            Header::Supported(value) if name.eq_ignore_ascii_case("Supported") => value
363                .value()
364                .split(',')
365                .any(|item| item.trim().eq_ignore_ascii_case(token)),
366            Header::Require(value) if name.eq_ignore_ascii_case("Require") => value
367                .value()
368                .split(',')
369                .any(|item| item.trim().eq_ignore_ascii_case(token)),
370            _ => false,
371        })
372    }
373    fn transaction_id(&self) -> Result<Option<Branch>, Error> {
374        use crate::sip::headers::untyped::ToTypedHeader;
375        Ok(self.top_via_header()?.typed()?.branch().cloned())
376    }
377}
378
379#[derive(Debug, PartialEq, Eq, Clone)]
380pub struct Request {
381    pub method: Method,
382    pub uri: Uri,
383    pub version: Version,
384    pub headers: Headers,
385    pub body: Vec<u8>,
386}
387
388impl Request {
389    pub fn method(&self) -> &Method {
390        &self.method
391    }
392    pub fn uri(&self) -> &Uri {
393        &self.uri
394    }
395    pub fn destination(&self) -> Uri {
396        for route in self.route_headers() {
397            if let Ok(mut routes) = crate::sip::typed::Route::parse_header_list(route.value()) {
398                if let Some(route) = routes.drain(..).next() {
399                    return route.uri;
400                }
401            }
402        }
403        self.uri.clone()
404    }
405    pub fn version(&self) -> &Version {
406        &self.version
407    }
408    pub fn body(&self) -> &Vec<u8> {
409        &self.body
410    }
411    pub fn body_mut(&mut self) -> &mut Vec<u8> {
412        &mut self.body
413    }
414}
415
416impl HasHeaders for Request {
417    fn headers(&self) -> &Headers {
418        &self.headers
419    }
420    fn headers_mut(&mut self) -> &mut Headers {
421        &mut self.headers
422    }
423}
424
425impl HeadersExt for Request {}
426
427impl core::fmt::Display for Request {
428    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
429        write!(
430            f,
431            "{} {} {}\r\n{}\r\n{}",
432            self.method,
433            self.uri,
434            self.version,
435            self.headers,
436            String::from_utf8_lossy(&self.body)
437        )
438    }
439}
440
441impl Request {
442    /// Serialize the request to its on-the-wire byte representation.
443    ///
444    /// The request line and headers are ASCII; the body is appended verbatim.
445    /// A SIP message body is an opaque octet sequence (RFC 3261 ยง7.4) and may
446    /// contain arbitrary bytes โ€” e.g. a binary ISUP part or an eCall MSD โ€” so
447    /// it must not be forced through UTF-8.
448    ///
449    /// Prefer this over [`Display`](core::fmt::Display) / `to_string()` when
450    /// putting a message on the wire: `Display` renders the body with
451    /// [`String::from_utf8_lossy`], which is fine for logging but corrupts
452    /// non-UTF-8 bytes.
453    pub fn to_bytes(&self) -> Vec<u8> {
454        let head = format!(
455            "{} {} {}\r\n{}\r\n",
456            self.method, self.uri, self.version, self.headers
457        );
458        let mut buf = head.into_bytes();
459        buf.extend_from_slice(&self.body);
460        buf
461    }
462}
463
464impl core::convert::TryFrom<Vec<u8>> for Request {
465    type Error = Error;
466    fn try_from(bytes: Vec<u8>) -> Result<Self, Error> {
467        match crate::sip::parser::parse_message(&bytes)? {
468            SipMessage::Request(r) => Ok(r),
469            SipMessage::Response(_) => {
470                Err(Error::Unexpected("expected Request, got Response".into()))
471            }
472        }
473    }
474}
475
476impl core::convert::TryFrom<&[u8]> for Request {
477    type Error = Error;
478    fn try_from(bytes: &[u8]) -> Result<Self, Error> {
479        match crate::sip::parser::parse_message(bytes)? {
480            SipMessage::Request(r) => Ok(r),
481            SipMessage::Response(_) => {
482                Err(Error::Unexpected("expected Request, got Response".into()))
483            }
484        }
485    }
486}
487
488impl core::convert::TryFrom<&str> for Request {
489    type Error = Error;
490    fn try_from(s: &str) -> Result<Self, Error> {
491        Self::try_from(s.as_bytes())
492    }
493}
494
495impl core::convert::TryFrom<String> for Request {
496    type Error = Error;
497    fn try_from(s: String) -> Result<Self, Error> {
498        Self::try_from(s.as_bytes())
499    }
500}
501
502impl core::convert::From<Request> for String {
503    fn from(r: Request) -> String {
504        r.to_string()
505    }
506}
507
508impl core::convert::From<Request> for Vec<u8> {
509    fn from(r: Request) -> Vec<u8> {
510        r.to_bytes()
511    }
512}
513
514#[derive(Debug, PartialEq, Eq, Clone)]
515pub struct Response {
516    pub status_code: StatusCode,
517    pub version: Version,
518    pub headers: Headers,
519    pub body: Vec<u8>,
520}
521
522impl Response {
523    pub fn status_code(&self) -> &StatusCode {
524        &self.status_code
525    }
526    pub fn version(&self) -> &Version {
527        &self.version
528    }
529    pub fn body(&self) -> &Vec<u8> {
530        &self.body
531    }
532    pub fn body_mut(&mut self) -> &mut Vec<u8> {
533        &mut self.body
534    }
535    pub fn reason_phrase(&self) -> Option<&str> {
536        self.headers.iter().find_map(|h| {
537            if let Header::Reason(r) = h {
538                Some(r.value())
539            } else {
540                None
541            }
542        })
543    }
544
545    /// Get the received address from the Via header (including rport if present)
546    pub fn via_received(&self) -> Option<crate::sip::uri::HostWithPort> {
547        use crate::sip::HeadersExt;
548        self.top_via_header().ok().and_then(|via| {
549            via.typed()
550                .ok()
551                .and_then(|typed_via: crate::sip::typed::Via| {
552                    let received = typed_via.params.iter().find_map(|p| {
553                        if let crate::sip::uri::Param::Received(r) = p {
554                            r.parse().ok().map(crate::sip::uri::Host::IpAddr)
555                        } else {
556                            None
557                        }
558                    });
559                    let rport = typed_via.params.iter().find_map(|p| {
560                        if let crate::sip::uri::Param::Rport(rport) = p {
561                            *rport
562                        } else {
563                            None
564                        }
565                    });
566                    received.map(|host| crate::sip::uri::HostWithPort {
567                        host,
568                        port: rport.map(crate::sip::transport::Port),
569                    })
570                })
571        })
572    }
573}
574
575impl HasHeaders for Response {
576    fn headers(&self) -> &Headers {
577        &self.headers
578    }
579    fn headers_mut(&mut self) -> &mut Headers {
580        &mut self.headers
581    }
582}
583
584impl HeadersExt for Response {}
585
586impl Default for Response {
587    fn default() -> Self {
588        Response {
589            status_code: StatusCode::OK,
590            version: Version::V2,
591            headers: Headers::default(),
592            body: Vec::new(),
593        }
594    }
595}
596
597impl core::fmt::Display for Response {
598    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
599        write!(
600            f,
601            "{} {} {}\r\n{}\r\n{}",
602            self.version,
603            self.status_code.code(),
604            self.status_code.text(),
605            self.headers,
606            String::from_utf8_lossy(&self.body)
607        )
608    }
609}
610
611impl Response {
612    /// Serialize the response to its on-the-wire byte representation.
613    ///
614    /// See [`Request::to_bytes`]: the body is written verbatim because a SIP
615    /// body is an opaque octet sequence (RFC 3261 ยง7.4), not necessarily UTF-8.
616    pub fn to_bytes(&self) -> Vec<u8> {
617        let head = format!(
618            "{} {} {}\r\n{}\r\n",
619            self.version,
620            self.status_code.code(),
621            self.status_code.text(),
622            self.headers
623        );
624        let mut buf = head.into_bytes();
625        buf.extend_from_slice(&self.body);
626        buf
627    }
628}
629
630impl core::convert::TryFrom<Vec<u8>> for Response {
631    type Error = Error;
632    fn try_from(bytes: Vec<u8>) -> Result<Self, Error> {
633        match crate::sip::parser::parse_message(&bytes)? {
634            SipMessage::Response(r) => Ok(r),
635            SipMessage::Request(_) => {
636                Err(Error::Unexpected("expected Response, got Request".into()))
637            }
638        }
639    }
640}
641
642impl core::convert::TryFrom<&[u8]> for Response {
643    type Error = Error;
644    fn try_from(bytes: &[u8]) -> Result<Self, Error> {
645        match crate::sip::parser::parse_message(bytes)? {
646            SipMessage::Response(r) => Ok(r),
647            SipMessage::Request(_) => {
648                Err(Error::Unexpected("expected Response, got Request".into()))
649            }
650        }
651    }
652}
653
654impl core::convert::TryFrom<&str> for Response {
655    type Error = Error;
656    fn try_from(s: &str) -> Result<Self, Error> {
657        Self::try_from(s.as_bytes())
658    }
659}
660
661impl core::convert::TryFrom<String> for Response {
662    type Error = Error;
663    fn try_from(s: String) -> Result<Self, Error> {
664        Self::try_from(s.as_bytes())
665    }
666}
667
668impl core::convert::From<Response> for String {
669    fn from(r: Response) -> String {
670        r.to_string()
671    }
672}
673
674impl core::convert::From<Response> for Vec<u8> {
675    fn from(r: Response) -> Vec<u8> {
676        r.to_bytes()
677    }
678}
679
680impl core::convert::TryFrom<bytes::Bytes> for SipMessage {
681    type Error = Error;
682    fn try_from(bytes: bytes::Bytes) -> Result<Self, Error> {
683        crate::sip::parser::parse_message(&bytes)
684    }
685}
686
687#[derive(Debug, PartialEq, Eq, Clone)]
688pub enum SipMessage {
689    Request(Request),
690    Response(Response),
691}
692
693impl SipMessage {
694    pub fn is_request(&self) -> bool {
695        matches!(self, SipMessage::Request(_))
696    }
697    pub fn is_response(&self) -> bool {
698        matches!(self, SipMessage::Response(_))
699    }
700
701    /// The start line (request/status line) of the message โ€” the first line of
702    /// its on-wire representation, e.g. `CANCEL sip:2001@localhost SIP/2.0` or
703    /// `SIP/2.0 200 OK`. Useful for single-line transport logging without
704    /// spilling the multi-line headers/body into the log.
705    pub fn start_line(&self) -> String {
706        match self {
707            SipMessage::Request(r) => format!("{} {} {}", r.method, r.uri, r.version),
708            SipMessage::Response(r) => format!(
709                "{} {} {}",
710                r.version,
711                r.status_code.code(),
712                r.status_code.text()
713            ),
714        }
715    }
716}
717
718impl HasHeaders for SipMessage {
719    fn headers(&self) -> &Headers {
720        match self {
721            SipMessage::Request(r) => r.headers(),
722            SipMessage::Response(r) => r.headers(),
723        }
724    }
725    fn headers_mut(&mut self) -> &mut Headers {
726        match self {
727            SipMessage::Request(r) => r.headers_mut(),
728            SipMessage::Response(r) => r.headers_mut(),
729        }
730    }
731}
732
733impl HeadersExt for SipMessage {}
734
735impl core::fmt::Display for SipMessage {
736    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
737        match self {
738            SipMessage::Request(r) => write!(f, "{}", r),
739            SipMessage::Response(r) => write!(f, "{}", r),
740        }
741    }
742}
743
744impl SipMessage {
745    /// Serialize the message to its on-the-wire byte representation.
746    ///
747    /// See [`Request::to_bytes`]. Transports should use this rather than
748    /// `to_string()` so binary bodies are preserved byte-for-byte.
749    pub fn to_bytes(&self) -> Vec<u8> {
750        match self {
751            SipMessage::Request(r) => r.to_bytes(),
752            SipMessage::Response(r) => r.to_bytes(),
753        }
754    }
755}
756
757impl core::convert::TryFrom<Vec<u8>> for SipMessage {
758    type Error = Error;
759    fn try_from(bytes: Vec<u8>) -> Result<Self, Error> {
760        crate::sip::parser::parse_message(&bytes)
761    }
762}
763
764impl core::convert::TryFrom<&[u8]> for SipMessage {
765    type Error = Error;
766    fn try_from(bytes: &[u8]) -> Result<Self, Error> {
767        crate::sip::parser::parse_message(bytes)
768    }
769}
770
771impl core::convert::TryFrom<&str> for SipMessage {
772    type Error = Error;
773    fn try_from(s: &str) -> Result<Self, Error> {
774        Self::try_from(s.as_bytes())
775    }
776}
777
778impl core::convert::TryFrom<String> for SipMessage {
779    type Error = Error;
780    fn try_from(s: String) -> Result<Self, Error> {
781        Self::try_from(s.as_bytes())
782    }
783}
784
785impl core::convert::From<Request> for SipMessage {
786    fn from(r: Request) -> SipMessage {
787        SipMessage::Request(r)
788    }
789}
790
791impl core::convert::From<Response> for SipMessage {
792    fn from(r: Response) -> SipMessage {
793        SipMessage::Response(r)
794    }
795}
796
797impl core::convert::TryFrom<SipMessage> for Request {
798    type Error = Error;
799    fn try_from(m: SipMessage) -> Result<Self, Error> {
800        match m {
801            SipMessage::Request(r) => Ok(r),
802            SipMessage::Response(_) => Err(Error::Unexpected("expected Request".into())),
803        }
804    }
805}
806
807impl core::convert::TryFrom<SipMessage> for Response {
808    type Error = Error;
809    fn try_from(m: SipMessage) -> Result<Self, Error> {
810        match m {
811            SipMessage::Response(r) => Ok(r),
812            SipMessage::Request(_) => Err(Error::Unexpected("expected Response".into())),
813        }
814    }
815}
816
817impl core::convert::From<SipMessage> for String {
818    fn from(m: SipMessage) -> String {
819        m.to_string()
820    }
821}
822
823impl core::convert::From<SipMessage> for Vec<u8> {
824    fn from(m: SipMessage) -> Vec<u8> {
825        m.to_bytes()
826    }
827}
828
829#[cfg(test)]
830mod tests {
831    use super::{HasHeaders, HeadersExt, Request, Response, SipMessage};
832    use crate::sip::{Header, Method};
833
834    fn invite_request() -> &'static str {
835        concat!(
836            "INVITE sip:bob@restsend.com SIP/2.0\r\n",
837            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bK776asdhds\r\n",
838            "Max-Forwards: 70\r\n",
839            "To: Bob <sip:bob@restsend.com>\r\n",
840            "From: Alice <sip:alice@restsend.com>;tag=1928301774\r\n",
841            "Call-ID: a84b4c76e66710@ua.restsend.com\r\n",
842            "CSeq: 314159 INVITE\r\n",
843            "Contact: <sip:alice@ua.restsend.com>\r\n",
844            "Content-Type: application/sdp\r\n",
845            "Content-Length: 0\r\n",
846            "\r\n"
847        )
848    }
849
850    fn register_request() -> &'static str {
851        concat!(
852            "REGISTER sip:registrar.restsend.com SIP/2.0\r\n",
853            "Via: SIP/2.0/UDP ua.restsend.com:5060;branch=z9hG4bKnashds8\r\n",
854            "Max-Forwards: 70\r\n",
855            "To: Bob <sip:bob@restsend.com>\r\n",
856            "From: Bob <sip:bob@restsend.com>;tag=456248\r\n",
857            "Call-ID: 843817637684230@998sdasdh09\r\n",
858            "CSeq: 1826 REGISTER\r\n",
859            "Contact: <sip:bob@192.0.2.4>\r\n",
860            "Expires: 7200\r\n",
861            "Content-Length: 0\r\n",
862            "\r\n"
863        )
864    }
865
866    fn ok_response() -> &'static str {
867        concat!(
868            "SIP/2.0 200 OK\r\n",
869            "Via: SIP/2.0/UDP proxy1.restsend.com;branch=z9hG4bK4b43c2ff8.1;received=192.0.2.3\r\n",
870            "Via: SIP/2.0/UDP proxy2.restsend.com;branch=z9hG4bK77ef4c2312983.1;received=192.0.2.2\r\n",
871            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bK776asdhds;received=192.0.2.1\r\n",
872            "To: Bob <sip:bob@restsend.com>;tag=a6c85cf\r\n",
873            "From: Alice <sip:alice@restsend.com>;tag=1928301774\r\n",
874            "Call-ID: a84b4c76e66710@ua.restsend.com\r\n",
875            "CSeq: 314159 INVITE\r\n",
876            "Contact: <sip:bob@192.0.2.4>\r\n",
877            "Content-Type: application/sdp\r\n",
878            "Content-Length: 131\r\n",
879            "\r\n",
880            "v=0\r\no=bob 2890844527 2890844527 IN IP4 192.0.2.4\r\ns=-\r\nc=IN IP4 192.0.2.4\r\nt=0 0\r\nm=audio 3456 RTP/AVP 0\r\na=rtpmap:0 PCMU/8000"
881        )
882    }
883
884    #[test]
885    fn parse_invite_request() {
886        let req: Request = invite_request().try_into().unwrap();
887        assert_eq!(req.method, Method::Invite);
888        assert_eq!(req.uri.to_string(), "sip:bob@restsend.com");
889        assert_eq!(
890            req.from_header().unwrap().value(),
891            "Alice <sip:alice@restsend.com>;tag=1928301774"
892        );
893        assert_eq!(
894            req.to_header().unwrap().value(),
895            "Bob <sip:bob@restsend.com>"
896        );
897        assert_eq!(
898            req.call_id_header().unwrap().value(),
899            "a84b4c76e66710@ua.restsend.com"
900        );
901    }
902
903    #[test]
904    fn parse_register_request() {
905        let req: Request = register_request().try_into().unwrap();
906        assert_eq!(req.method, Method::Register);
907        let contacts = req.typed_contact_headers().unwrap();
908        assert_eq!(contacts.len(), 1);
909        assert_eq!(contacts[0].uri.to_string(), "sip:bob@192.0.2.4");
910    }
911
912    #[test]
913    fn parse_ok_response() {
914        let resp: Response = ok_response().try_into().unwrap();
915        assert_eq!(resp.status_code.code(), 200);
916        assert_eq!(resp.body, b"v=0\r\no=bob 2890844527 2890844527 IN IP4 192.0.2.4\r\ns=-\r\nc=IN IP4 192.0.2.4\r\nt=0 0\r\nm=audio 3456 RTP/AVP 0\r\na=rtpmap:0 PCMU/8000");
917    }
918
919    #[test]
920    fn request_binary_body_survives_serialization() {
921        // A SIP message body is an opaque octet payload (RFC 3261 ยง7.4), not
922        // necessarily UTF-8 text. e.g. an NG-eCall INVITE carries a binary
923        // ASN.1 PER-encoded MSD. Serialization to the wire must preserve every
924        // byte, including bytes that are invalid as UTF-8.
925        let mut req: Request = invite_request().try_into().unwrap();
926        let binary_body: Vec<u8> = vec![0x00, 0x01, 0x80, 0xFF, 0xC0, 0xC1, 0xFE, 0x02, 0x7F, 0x90];
927        req.body = binary_body.clone();
928
929        let wire: Vec<u8> = req.into();
930
931        assert!(
932            wire.ends_with(&binary_body),
933            "binary body corrupted during serialization: got tail {:?}",
934            &wire[wire.len().saturating_sub(binary_body.len() + 4)..]
935        );
936    }
937
938    #[test]
939    fn response_binary_body_survives_serialization() {
940        let mut resp: Response = ok_response().try_into().unwrap();
941        let binary_body: Vec<u8> = vec![0x00, 0x80, 0xFF, 0xC0, 0xC1, 0xFE, 0x02];
942        resp.body = binary_body.clone();
943
944        let wire: Vec<u8> = resp.into();
945
946        assert!(
947            wire.ends_with(&binary_body),
948            "binary body corrupted during serialization"
949        );
950    }
951
952    #[test]
953    fn response_has_multiple_via_headers() {
954        let resp: Response = ok_response().try_into().unwrap();
955        let vias: Vec<_> = resp
956            .headers()
957            .iter()
958            .filter(|h| matches!(h, Header::Via(_)))
959            .collect();
960        assert_eq!(vias.len(), 3);
961    }
962
963    #[test]
964    fn top_via_header_returns_first_value_from_combined_header() {
965        let resp: Response = concat!(
966            "SIP/2.0 401 Unauthorized\r\n",
967            "Via: SIP/2.0/UDP 172.22.22.80:5062;received=172.22.22.80;rport=5062;branch=z9hG4bKfirst,SIP/2.0/TCP 10.0.13.70:5060;branch=z9hG4bKsecond\r\n",
968            "From: <sip:001010000000001@ims.example.com>;tag=e80c1d8c\r\n",
969            "To: <sip:001010000000001@ims.example.com>;tag=2e518\r\n",
970            "Call-ID: 9e353fc94f78064f@10.0.13.70\r\n",
971            "CSeq: 1 REGISTER\r\n",
972            "Content-Length: 0\r\n",
973            "\r\n",
974        )
975        .try_into()
976        .unwrap();
977
978        assert_eq!(
979            resp.via_header().unwrap().value(),
980            "SIP/2.0/UDP 172.22.22.80:5062;received=172.22.22.80;rport=5062;branch=z9hG4bKfirst,SIP/2.0/TCP 10.0.13.70:5060;branch=z9hG4bKsecond"
981        );
982        assert_eq!(
983            resp.top_via_header().unwrap().value(),
984            "SIP/2.0/UDP 172.22.22.80:5062;received=172.22.22.80;rport=5062;branch=z9hG4bKfirst"
985        );
986    }
987
988    #[test]
989    fn headers_push_front() {
990        let mut req: Request = invite_request().try_into().unwrap();
991        let orig_first = req.headers.iter().next().unwrap().name().to_string();
992        req.headers
993            .push_front(Header::MaxForwards(crate::sip::MaxForwards::new("10")));
994        assert_eq!(req.headers.iter().next().unwrap().name(), "Max-Forwards");
995        assert_eq!(req.headers.iter().nth(1).unwrap().name(), orig_first);
996    }
997
998    #[test]
999    fn new_headers_reason_roundtrip() {
1000        let msg: SipMessage = concat!(
1001            "BYE sip:alice@restsend.com SIP/2.0\r\n",
1002            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bK776asdhds\r\n",
1003            "From: <sip:bob@restsend.com>;tag=a6c85cf\r\n",
1004            "To: <sip:alice@restsend.com>;tag=1928301774\r\n",
1005            "Call-ID: a84b4c76e66710@ua.restsend.com\r\n",
1006            "CSeq: 231 BYE\r\n",
1007            "Reason: SIP ;cause=200 ;text=\"Call completed elsewhere\"\r\n",
1008            "Content-Length: 0\r\n",
1009            "\r\n"
1010        )
1011        .try_into()
1012        .unwrap();
1013        let reason = msg.reason_header().unwrap();
1014        assert!(reason.value().contains("200"));
1015        assert!(reason.value().contains("Call completed elsewhere"));
1016    }
1017
1018    #[test]
1019    fn new_headers_refer_to_roundtrip() {
1020        let msg: SipMessage = concat!(
1021            "REFER sip:bob@restsend.com SIP/2.0\r\n",
1022            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKkjshdyff\r\n",
1023            "To: <sip:bob@restsend.com>\r\n",
1024            "From: <sip:alice@restsend.com>;tag=xyz\r\n",
1025            "Call-ID: 12345600@ua.restsend.com\r\n",
1026            "CSeq: 1 REFER\r\n",
1027            "Refer-To: <sip:carol@restsend.com>\r\n",
1028            "Content-Length: 0\r\n",
1029            "\r\n"
1030        )
1031        .try_into()
1032        .unwrap();
1033        assert!(msg.refer_to_header().is_some());
1034        assert_eq!(
1035            msg.refer_to_header().unwrap().value(),
1036            "<sip:carol@restsend.com>"
1037        );
1038    }
1039
1040    #[test]
1041    fn new_headers_session_expires_roundtrip() {
1042        let msg: SipMessage = concat!(
1043            "INVITE sip:bob@restsend.com SIP/2.0\r\n",
1044            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKtest\r\n",
1045            "From: <sip:alice@restsend.com>;tag=abc\r\n",
1046            "To: <sip:bob@restsend.com>\r\n",
1047            "Call-ID: test@ua.restsend.com\r\n",
1048            "CSeq: 1 INVITE\r\n",
1049            "Session-Expires: 1800;refresher=uac\r\n",
1050            "Min-SE: 90\r\n",
1051            "Content-Length: 0\r\n",
1052            "\r\n"
1053        )
1054        .try_into()
1055        .unwrap();
1056        let se = msg.session_expires_header().unwrap();
1057        assert!(se.value().contains("1800"));
1058        let min_se = msg.headers().iter().find_map(|h| {
1059            if let Header::MinSE(m) = h {
1060                Some(m)
1061            } else {
1062                None
1063            }
1064        });
1065        assert!(min_se.is_some());
1066        assert_eq!(min_se.unwrap().value(), "90");
1067    }
1068
1069    #[test]
1070    fn new_headers_call_info() {
1071        let msg: SipMessage = concat!(
1072            "INVITE sip:bob@restsend.com SIP/2.0\r\n",
1073            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKtest\r\n",
1074            "From: <sip:alice@restsend.com>;tag=abc\r\n",
1075            "To: <sip:bob@restsend.com>\r\n",
1076            "Call-ID: call-info-test@ua.restsend.com\r\n",
1077            "CSeq: 1 INVITE\r\n",
1078            "Call-Info: <http://www.example.com/alice/photo.jpg>;purpose=icon\r\n",
1079            "Call-Info: <http://www.example.com/alice/>;purpose=info\r\n",
1080            "Content-Length: 0\r\n",
1081            "\r\n"
1082        )
1083        .try_into()
1084        .unwrap();
1085        let first = msg.call_info_header().unwrap();
1086        assert!(first.value().contains("photo.jpg"));
1087        assert!(first.value().contains("purpose=icon"));
1088        let all = msg.call_info_headers();
1089        assert_eq!(all.len(), 2);
1090        assert!(all[1].value().contains("purpose=info"));
1091    }
1092
1093    #[test]
1094    fn new_headers_user_to_user() {
1095        let msg: SipMessage = concat!(
1096            "INVITE sip:bob@restsend.com SIP/2.0\r\n",
1097            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKtest\r\n",
1098            "From: <sip:alice@restsend.com>;tag=abc\r\n",
1099            "To: <sip:bob@restsend.com>\r\n",
1100            "Call-ID: uui-test@ua.restsend.com\r\n",
1101            "CSeq: 1 INVITE\r\n",
1102            "User-to-User: 56a390f3d2b7310023a;encoding=hex;purpose=isdn-uui;content=isdn-uui\r\n",
1103            "Content-Length: 0\r\n",
1104            "\r\n"
1105        )
1106        .try_into()
1107        .unwrap();
1108        let uui = msg.user_to_user_header().unwrap();
1109        assert!(uui.value().starts_with("56a390f3d2b7310023a"));
1110        assert!(uui.value().contains("encoding=hex"));
1111        assert!(uui.value().contains("purpose=isdn-uui"));
1112        assert_eq!(msg.user_to_user_headers().len(), 1);
1113    }
1114
1115    #[test]
1116    fn new_headers_p_asserted_identity() {
1117        let msg: SipMessage = concat!(
1118            "INVITE sip:bob@restsend.com SIP/2.0\r\n",
1119            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKtest\r\n",
1120            "From: <sip:anonymous@anonymous.invalid>;tag=abc\r\n",
1121            "To: <sip:bob@restsend.com>\r\n",
1122            "Call-ID: pai-test@ua.restsend.com\r\n",
1123            "CSeq: 1 INVITE\r\n",
1124            "P-Asserted-Identity: <sip:alice@restsend.com>\r\n",
1125            "Privacy: id\r\n",
1126            "Content-Length: 0\r\n",
1127            "\r\n"
1128        )
1129        .try_into()
1130        .unwrap();
1131        assert!(msg.p_asserted_identity_header().is_some());
1132        assert_eq!(
1133            msg.p_asserted_identity_header().unwrap().value(),
1134            "<sip:alice@restsend.com>"
1135        );
1136        assert!(msg.privacy_header().is_some());
1137    }
1138
1139    #[test]
1140    fn new_headers_replaces() {
1141        let msg: SipMessage = concat!(
1142            "INVITE sip:bob@restsend.com SIP/2.0\r\n",
1143            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKtest\r\n",
1144            "From: <sip:alice@restsend.com>;tag=abc\r\n",
1145            "To: <sip:bob@restsend.com>\r\n",
1146            "Call-ID: transfer-test@ua.restsend.com\r\n",
1147            "CSeq: 1 INVITE\r\n",
1148            "Replaces: original-call-id@ua.restsend.com;to-tag=orig-to;from-tag=orig-from\r\n",
1149            "Content-Length: 0\r\n",
1150            "\r\n"
1151        )
1152        .try_into()
1153        .unwrap();
1154        let replaces = msg.replaces_header().unwrap();
1155        assert!(replaces.value().contains("original-call-id"));
1156    }
1157
1158    #[test]
1159    fn new_headers_rseq_rack() {
1160        let prack: SipMessage = concat!(
1161            "PRACK sip:bob@restsend.com SIP/2.0\r\n",
1162            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKtest\r\n",
1163            "From: <sip:alice@restsend.com>;tag=abc\r\n",
1164            "To: <sip:bob@restsend.com>;tag=xyz\r\n",
1165            "Call-ID: prack-test@ua.restsend.com\r\n",
1166            "CSeq: 2 PRACK\r\n",
1167            "RAck: 776656 1 INVITE\r\n",
1168            "Content-Length: 0\r\n",
1169            "\r\n"
1170        )
1171        .try_into()
1172        .unwrap();
1173
1174        let rack = prack.rack_value().unwrap();
1175        assert_eq!(rack.0, 776656);
1176        assert_eq!(rack.1, 1);
1177        assert_eq!(rack.2, Method::Invite);
1178
1179        let provisional: SipMessage = concat!(
1180            "SIP/2.0 183 Session Progress\r\n",
1181            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKtest\r\n",
1182            "From: <sip:alice@restsend.com>;tag=abc\r\n",
1183            "To: <sip:bob@restsend.com>;tag=xyz\r\n",
1184            "Call-ID: prack-test@ua.restsend.com\r\n",
1185            "CSeq: 1 INVITE\r\n",
1186            "RSeq: 776656\r\n",
1187            "Content-Length: 0\r\n",
1188            "\r\n"
1189        )
1190        .try_into()
1191        .unwrap();
1192
1193        assert_eq!(provisional.rseq_value(), Some(776656));
1194    }
1195
1196    #[test]
1197    fn new_headers_path_header() {
1198        let msg: SipMessage = concat!(
1199            "REGISTER sip:registrar.restsend.com SIP/2.0\r\n",
1200            "Via: SIP/2.0/TCP edge.restsend.com;branch=z9hG4bKtest\r\n",
1201            "From: <sip:alice@restsend.com>;tag=abc\r\n",
1202            "To: <sip:alice@restsend.com>\r\n",
1203            "Call-ID: path-test@edge.restsend.com\r\n",
1204            "CSeq: 1 REGISTER\r\n",
1205            "Path: <sip:edge.restsend.com;lr>\r\n",
1206            "Contact: <sip:alice@192.0.2.5:5060>\r\n",
1207            "Content-Length: 0\r\n",
1208            "\r\n"
1209        )
1210        .try_into()
1211        .unwrap();
1212        let paths = msg.path_headers();
1213        assert_eq!(paths.len(), 1);
1214        assert!(paths[0].value().contains("edge.restsend.com"));
1215    }
1216
1217    #[test]
1218    fn new_headers_service_route_header() {
1219        // REGISTER 200 OK carrying an IMS-style Service-Route set. RFC 3608
1220        // allows the entries to arrive either as one comma-separated header or
1221        // as several header lines; both must fold into the same route set.
1222        let msg: SipMessage = concat!(
1223            "SIP/2.0 200 OK\r\n",
1224            "Via: SIP/2.0/TCP edge.home.net;branch=z9hG4bKtest\r\n",
1225            "From: <sip:alice@home.net>;tag=abc\r\n",
1226            "To: <sip:alice@home.net>;tag=xyz\r\n",
1227            "Call-ID: sr-test@edge.home.net\r\n",
1228            "CSeq: 1 REGISTER\r\n",
1229            "Service-Route: <sip:scscf.home.net;lr>\r\n",
1230            "Service-Route: <sip:pcscf.visited.net;lr>\r\n",
1231            "Contact: <sip:alice@192.0.2.5:5060>;expires=600\r\n",
1232            "Content-Length: 0\r\n",
1233            "\r\n"
1234        )
1235        .try_into()
1236        .unwrap();
1237
1238        let raw = msg.service_route_headers();
1239        assert_eq!(raw.len(), 2);
1240
1241        let routes = msg.typed_service_route_headers().unwrap();
1242        assert_eq!(routes.len(), 2);
1243        assert_eq!(routes[0].uri.to_string(), "sip:scscf.home.net;lr");
1244        assert_eq!(routes[1].uri.to_string(), "sip:pcscf.visited.net;lr");
1245        assert!(routes[0].has_lr());
1246        assert!(routes[1].has_lr());
1247    }
1248
1249    #[test]
1250    fn header_value_helper_case_insensitive() {
1251        let req: Request = invite_request().try_into().unwrap();
1252        let val = req.header_value("content-type");
1253        assert!(val.is_some());
1254        assert!(val.unwrap().contains("application/sdp"));
1255    }
1256
1257    #[test]
1258    fn header_contains_token_helper() {
1259        let msg: SipMessage = concat!(
1260            "INVITE sip:bob@restsend.com SIP/2.0\r\n",
1261            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKtest\r\n",
1262            "From: <sip:alice@restsend.com>;tag=abc\r\n",
1263            "To: <sip:bob@restsend.com>\r\n",
1264            "Call-ID: test@pc33\r\n",
1265            "CSeq: 1 INVITE\r\n",
1266            "Supported: timer, 100rel, replaces\r\n",
1267            "Content-Length: 0\r\n",
1268            "\r\n"
1269        )
1270        .try_into()
1271        .unwrap();
1272        assert!(msg.header_contains_token("supported", "timer"));
1273        assert!(msg.header_contains_token("supported", "100rel"));
1274        assert!(!msg.header_contains_token("supported", "gruu"));
1275        assert!(!msg.header_contains_token("content-type", "application/sdp"));
1276    }
1277
1278    #[test]
1279    fn destination_from_request_without_route() {
1280        let req: Request = invite_request().try_into().unwrap();
1281        let dest = req.destination();
1282        assert_eq!(dest.to_string(), "sip:bob@restsend.com");
1283    }
1284
1285    #[test]
1286    fn destination_from_request_with_route() {
1287        let req: Request = concat!(
1288            "INVITE sip:bob@restsend.com SIP/2.0\r\n",
1289            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKtest\r\n",
1290            "Route: <sip:proxy.restsend.com;lr>\r\n",
1291            "From: <sip:alice@restsend.com>;tag=abc\r\n",
1292            "To: <sip:bob@restsend.com>\r\n",
1293            "Call-ID: routed@pc33\r\n",
1294            "CSeq: 1 INVITE\r\n",
1295            "Content-Length: 0\r\n",
1296            "\r\n"
1297        )
1298        .try_into()
1299        .unwrap();
1300        let dest = req.destination();
1301        assert_eq!(dest.to_string(), "sip:proxy.restsend.com;lr");
1302    }
1303
1304    #[test]
1305    fn compact_form_headers_are_parsed() {
1306        let message: SipMessage = concat!(
1307            "INVITE sip:bob@restsend.com SIP/2.0\r\n",
1308            "v: SIP/2.0/UDP restsend.com:5060;branch=z9hG4bK-1\r\n",
1309            "f: <sip:alice@restsend.com>;tag=123\r\n",
1310            "t: <sip:bob@restsend.com>\r\n",
1311            "i: call-id-1\r\n",
1312            "m: <sip:alice@restsend.com>\r\n",
1313            "e: gzip\r\n",
1314            "l: 0\r\n",
1315            "c: application/sdp\r\n",
1316            "s: hello\r\n",
1317            "k: timer\r\n",
1318            "\r\n"
1319        )
1320        .try_into()
1321        .unwrap();
1322
1323        assert!(message.via_header().is_ok());
1324        assert!(message.from_header().is_ok());
1325        assert!(message.to_header().is_ok());
1326        assert!(message.call_id_header().is_ok());
1327        assert!(message.contact_header().is_ok());
1328        assert!(message
1329            .headers()
1330            .iter()
1331            .any(|header| matches!(header, Header::ContentEncoding(_))));
1332        assert!(message
1333            .headers()
1334            .iter()
1335            .any(|header| matches!(header, Header::ContentLength(_))));
1336        assert!(message
1337            .headers()
1338            .iter()
1339            .any(|header| matches!(header, Header::ContentType(_))));
1340        assert!(message
1341            .headers()
1342            .iter()
1343            .any(|header| matches!(header, Header::Subject(_))));
1344        assert!(message
1345            .headers()
1346            .iter()
1347            .any(|header| matches!(header, Header::Supported(_))));
1348    }
1349
1350    #[test]
1351    fn compact_form_refer_to_alias_r() {
1352        let msg: SipMessage = concat!(
1353            "REFER sip:bob@restsend.com SIP/2.0\r\n",
1354            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKtest\r\n",
1355            "From: <sip:alice@restsend.com>;tag=abc\r\n",
1356            "To: <sip:bob@restsend.com>\r\n",
1357            "Call-ID: refer-compact@host\r\n",
1358            "CSeq: 1 REFER\r\n",
1359            "r: <sip:carol@restsend.com>\r\n",
1360            "Content-Length: 0\r\n",
1361            "\r\n"
1362        )
1363        .try_into()
1364        .unwrap();
1365        assert!(msg.refer_to_header().is_some());
1366    }
1367
1368    #[test]
1369    fn compact_form_session_expires_alias_x() {
1370        let msg: SipMessage = concat!(
1371            "INVITE sip:bob@restsend.com SIP/2.0\r\n",
1372            "Via: SIP/2.0/UDP ua.restsend.com;branch=z9hG4bKtest\r\n",
1373            "From: <sip:alice@restsend.com>;tag=abc\r\n",
1374            "To: <sip:bob@restsend.com>\r\n",
1375            "Call-ID: se-compact@host\r\n",
1376            "CSeq: 1 INVITE\r\n",
1377            "x: 1800\r\n",
1378            "Content-Length: 0\r\n",
1379            "\r\n"
1380        )
1381        .try_into()
1382        .unwrap();
1383        assert!(msg.session_expires_header().is_some());
1384        assert_eq!(msg.session_expires_header().unwrap().value(), "1800");
1385    }
1386}