freeswitch-sofia-trace-parser 0.8.1

Parser for FreeSWITCH mod_sofia SIP trace dump files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
use std::borrow::Cow;
use std::fmt;
use std::net::SocketAddr;

/// mod_sofia brackets IPv4 like IPv6 (`[198.51.100.7]:5060`); anything that
/// isn't an ip:port shape yields `None` rather than a guess.
fn parse_socket_addr(address: &str) -> Option<SocketAddr> {
    if let Ok(addr) = address.parse() {
        return Some(addr);
    }
    let (ip, port) = address.strip_prefix('[')?.split_once("]:")?;
    Some(SocketAddr::new(ip.parse().ok()?, port.parse().ok()?))
}

/// Why a region of the input stream was not parsed into a frame.
///
/// Every byte in the input is either parsed or classified with one of these
/// reasons, enabling byte-level coverage accounting via [`ParseStats`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkipReason {
    /// Truncated frame at the start of a file, typically from logrotate
    /// cutting mid-write. Capped at 65,535 bytes.
    PartialFirstFrame,
    /// Skip region exceeds 65,535 bytes at file start, indicating the input
    /// is not a dump file (e.g., compressed or binary data).
    OversizedFrame,
    /// Unrecoverable bytes skipped between valid frames mid-stream.
    MidStreamSkip,
    /// Logrotate wrote a partial frame tail at the start of the new file.
    /// Detected by the `\r\n\r\n\x0B\n` suffix pattern.
    ReplayedFrame,
    /// Frame at EOF with fewer content bytes than declared in the header.
    IncompleteFrame,
    /// Data starts with `recv`/`sent` but fails frame header parsing.
    InvalidHeader,
}

impl fmt::Display for SkipReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SkipReason::PartialFirstFrame => f.write_str("partial first frame"),
            SkipReason::OversizedFrame => f.write_str("oversized frame"),
            SkipReason::MidStreamSkip => f.write_str("mid-stream skip"),
            SkipReason::ReplayedFrame => f.write_str("replayed frame (logrotate)"),
            SkipReason::IncompleteFrame => f.write_str("incomplete frame"),
            SkipReason::InvalidHeader => f.write_str("invalid header"),
        }
    }
}

/// Controls how much detail the parser records about unparsed regions.
///
/// Defaults to `CountOnly` for constant-memory operation. Higher levels
/// allocate per-region and should only be enabled for diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkipTracking {
    /// Track only `bytes_read` and `bytes_skipped` counters. No allocation.
    CountOnly,
    /// Record offset, length, and reason for each unparsed region.
    TrackRegions,
    /// Like `TrackRegions`, but also capture the skipped bytes themselves.
    CaptureData,
}

/// A contiguous region of the input that was not parsed into a frame.
#[derive(Debug, Clone)]
pub struct UnparsedRegion {
    /// Byte offset from the start of the input stream.
    pub offset: u64,
    /// Number of bytes in this region.
    pub length: u64,
    /// Why this region was skipped.
    pub reason: SkipReason,
    /// The raw bytes, populated only when [`SkipTracking::CaptureData`] is enabled.
    pub data: Option<Vec<u8>>,
}

/// Byte-level parse coverage statistics.
///
/// Available from all three iterator levels via `stats()` or `parse_stats()`.
/// Every byte consumed from the reader is accounted for as either parsed
/// (`bytes_read - bytes_skipped`) or skipped (`bytes_skipped`).
#[derive(Debug, Default, Clone)]
pub struct ParseStats {
    /// Total bytes consumed from the reader.
    pub bytes_read: u64,
    /// Bytes that were skipped (not parsed into frames).
    pub bytes_skipped: u64,
    /// Detailed unparsed region records. Only populated when
    /// [`SkipTracking`] is `TrackRegions` or `CaptureData`.
    pub unparsed_regions: Vec<UnparsedRegion>,
}

impl ParseStats {
    /// Take all accumulated unparsed regions, leaving the list empty.
    pub fn drain_regions(&mut self) -> Vec<UnparsedRegion> {
        std::mem::take(&mut self.unparsed_regions)
    }
}

/// Whether a frame was received or sent by FreeSWITCH.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
    /// Received from the network.
    Recv,
    /// Sent to the network.
    Sent,
}

impl fmt::Display for Direction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Direction::Recv => f.write_str("recv"),
            Direction::Sent => f.write_str("sent"),
        }
    }
}

impl Direction {
    /// Returns `"from"` for `Recv`, `"to"` for `Sent`.
    pub fn preposition(&self) -> &'static str {
        match self {
            Direction::Recv => "from",
            Direction::Sent => "to",
        }
    }
}

/// SIP transport protocol as reported in the frame header.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Transport {
    /// Transmission Control Protocol.
    Tcp,
    /// User Datagram Protocol.
    Udp,
    /// Transport Layer Security.
    Tls,
    /// WebSocket Secure (RFC 7118).
    Wss,
}

impl fmt::Display for Transport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Transport::Tcp => f.write_str("tcp"),
            Transport::Udp => f.write_str("udp"),
            Transport::Tls => f.write_str("tls"),
            Transport::Wss => f.write_str("wss"),
        }
    }
}

/// Frame timestamp, either time-only or full date+time.
///
/// Older FreeSWITCH versions write `HH:MM:SS.usec`, newer versions write
/// `YYYY-MM-DD HH:MM:SS.usec`. Both formats are supported.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Timestamp {
    /// `HH:MM:SS.usec` — no date component.
    TimeOnly {
        /// Hour (0-23).
        hour: u8,
        /// Minute (0-59).
        min: u8,
        /// Second (0-59).
        sec: u8,
        /// Microseconds (0-999999).
        usec: u32,
    },
    /// `YYYY-MM-DD HH:MM:SS.usec` — full date and time.
    DateTime {
        /// Year.
        year: u16,
        /// Month (1-12).
        month: u8,
        /// Day (1-31).
        day: u8,
        /// Hour (0-23).
        hour: u8,
        /// Minute (0-59).
        min: u8,
        /// Second (0-59).
        sec: u8,
        /// Microseconds (0-999999).
        usec: u32,
    },
}

impl Timestamp {
    /// Seconds since midnight, ignoring microseconds.
    pub fn time_of_day_secs(&self) -> u32 {
        let (h, m, s) = match self {
            Timestamp::TimeOnly { hour, min, sec, .. } => (*hour, *min, *sec),
            Timestamp::DateTime { hour, min, sec, .. } => (*hour, *min, *sec),
        };
        h as u32 * 3600 + m as u32 * 60 + s as u32
    }

    /// Tuple suitable for chronological ordering.
    /// `TimeOnly` timestamps sort before any `DateTime` (year/month/day = 0).
    pub fn sort_key(&self) -> (u16, u8, u8, u8, u8, u8, u32) {
        match self {
            Timestamp::TimeOnly {
                hour,
                min,
                sec,
                usec,
            } => (0, 0, 0, *hour, *min, *sec, *usec),
            Timestamp::DateTime {
                year,
                month,
                day,
                hour,
                min,
                sec,
                usec,
            } => (*year, *month, *day, *hour, *min, *sec, *usec),
        }
    }
}

impl fmt::Display for Timestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Timestamp::TimeOnly {
                hour,
                min,
                sec,
                usec,
            } => write!(f, "{hour:02}:{min:02}:{sec:02}.{usec:06}"),
            Timestamp::DateTime {
                year,
                month,
                day,
                hour,
                min,
                sec,
                usec,
            } => write!(
                f,
                "{year:04}-{month:02}-{day:02} {hour:02}:{min:02}:{sec:02}.{usec:06}"
            ),
        }
    }
}

/// A single frame from the dump file (Level 1 output).
///
/// Each frame corresponds to one `send()` or `recv()` call logged by
/// `mod_sofia`. The `byte_count` field is the value FreeSWITCH wrote in the
/// header; `content` is the actual payload between boundaries.
#[derive(Debug, Clone)]
pub struct Frame {
    /// Whether this frame was received or sent.
    pub direction: Direction,
    /// Byte count declared in the frame header.
    pub byte_count: usize,
    /// Transport protocol.
    pub transport: Transport,
    /// Remote address as `ip:port` (e.g., `"10.0.0.1:5060"`).
    pub address: String,
    /// When this frame was logged.
    pub timestamp: Timestamp,
    /// Raw frame payload.
    pub content: Vec<u8>,
}

impl Frame {
    /// The remote address as a typed [`SocketAddr`], preserving family and
    /// port. `None` when the recorded address is not `ip:port`; the raw string
    /// remains in [`address`](Self::address).
    pub fn socket_addr(&self) -> Option<SocketAddr> {
        parse_socket_addr(&self.address)
    }
}

/// A reassembled SIP message (Level 2 output).
///
/// For TCP, consecutive frames from the same connection are concatenated and
/// split by Content-Length. For UDP, each frame becomes one message (1:1).
#[derive(Debug, Clone)]
pub struct SipMessage {
    /// Whether this message was received or sent.
    pub direction: Direction,
    /// Transport protocol.
    pub transport: Transport,
    /// Remote address as `ip:port`.
    pub address: String,
    /// Timestamp of the first frame in this message.
    pub timestamp: Timestamp,
    /// Reassembled message bytes (headers + body).
    pub content: Vec<u8>,
    /// Number of Level 1 frames that were reassembled into this message.
    pub frame_count: usize,
}

impl SipMessage {
    /// The remote address as a typed [`SocketAddr`], preserving family and
    /// port. `None` when the recorded address is not `ip:port`; the raw string
    /// remains in [`address`](Self::address).
    pub fn socket_addr(&self) -> Option<SocketAddr> {
        parse_socket_addr(&self.address)
    }
}

/// SIP request or response first line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SipMessageType {
    /// `METHOD uri SIP/2.0`
    Request {
        /// SIP method (e.g., `"INVITE"`, `"BYE"`).
        method: String,
        /// Request URI.
        uri: String,
    },
    /// `SIP/2.0 code reason`
    Response {
        /// Status code (e.g., 200, 404).
        code: u16,
        /// Reason phrase (e.g., `"OK"`, `"Not Found"`).
        reason: String,
    },
}

impl fmt::Display for SipMessageType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SipMessageType::Request { method, uri } => write!(f, "{method} {uri}"),
            SipMessageType::Response { code, reason } => write!(f, "{code} {reason}"),
        }
    }
}

impl SipMessageType {
    /// Short description: the method name for requests, `"code reason"` for responses.
    pub fn summary(&self) -> Cow<'_, str> {
        match self {
            SipMessageType::Request { method, .. } => Cow::Borrowed(method),
            SipMessageType::Response { code, reason } => Cow::Owned(format!("{code} {reason}")),
        }
    }
}

/// Headers in wire order as `(name, value)` pairs. Names preserve original
/// casing; [`value`](Self::value) is the case-insensitive lookup.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Headers(pub Vec<(String, String)>);

impl Headers {
    /// Case-insensitive header lookup, first match in wire order. Compact
    /// forms are not resolved: ask for the name the message is expected to
    /// carry.
    pub fn value(&self, name: &str) -> Option<&str> {
        self.0
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }
}

impl std::ops::Deref for Headers {
    type Target = [(String, String)];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for Headers {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl From<Vec<(String, String)>> for Headers {
    fn from(headers: Vec<(String, String)>) -> Self {
        Headers(headers)
    }
}

impl FromIterator<(String, String)> for Headers {
    fn from_iter<I: IntoIterator<Item = (String, String)>>(iter: I) -> Self {
        Headers(iter.into_iter().collect())
    }
}

impl<'a> IntoIterator for &'a Headers {
    type Item = &'a (String, String);
    type IntoIter = std::slice::Iter<'a, (String, String)>;

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

/// A fully parsed SIP message (Level 3 output).
///
/// Provides typed access to the request/response line, headers, and body.
/// For JSON content types, [`body_text()`](Self::body_text) unescapes RFC 8259
/// string sequences. For multipart bodies, [`body_parts()`](Self::body_parts)
/// splits into individual MIME parts.
#[derive(Debug, Clone)]
pub struct ParsedSipMessage {
    /// Whether this message was received or sent.
    pub direction: Direction,
    /// Transport protocol.
    pub transport: Transport,
    /// Remote address as `ip:port`.
    pub address: String,
    /// When this message was logged.
    pub timestamp: Timestamp,
    /// Parsed request or response first line.
    pub message_type: SipMessageType,
    /// Message headers in wire order.
    pub headers: Headers,
    /// Raw body bytes after the `\r\n\r\n` header terminator.
    pub body: Vec<u8>,
    /// Number of Level 1 frames that were reassembled into this message.
    pub frame_count: usize,
}

/// A `message/sipfrag` body (RFC 3420): any prefix of a SIP message.
///
/// Unlike [`ParsedSipMessage`], every element is optional — a fragment may
/// carry a start line, headers, a body, or any combination, and needs no
/// trailing CRLF. It has no transport metadata of its own; that belongs to
/// the message carrying it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SipFragment {
    /// Request or status line, when the fragment begins with one.
    pub message_type: Option<SipMessageType>,
    /// Fragment headers in wire order.
    pub headers: Headers,
    /// Body bytes after the `\r\n\r\n` terminator, empty when absent.
    pub body: Vec<u8>,
}

impl SipFragment {
    /// Case-insensitive header lookup, first match in wire order.
    pub fn header_value(&self, name: &str) -> Option<&str> {
        self.headers.value(name)
    }

    /// Returns the Content-Type header value. Checks both `Content-Type` and
    /// the compact form `c`.
    pub fn content_type(&self) -> Option<&str> {
        self.header_value("Content-Type")
            .or_else(|| self.header_value("c"))
    }
}

/// A single part from a multipart MIME body.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MimePart {
    /// Part headers in wire order (e.g., Content-Type, Content-ID).
    pub headers: Headers,
    /// Part body bytes.
    pub body: Vec<u8>,
}

impl MimePart {
    /// Returns the Content-Type header value, if present.
    pub fn content_type(&self) -> Option<&str> {
        self.headers.value("Content-Type")
    }

    /// Case-insensitive header lookup, first match in wire order.
    pub fn header_value(&self, name: &str) -> Option<&str> {
        self.headers.value(name)
    }

    /// Returns the Content-ID header value, if present.
    pub fn content_id(&self) -> Option<&str> {
        self.header_value("Content-ID")
    }

    /// Returns the Content-Disposition header value, if present.
    pub fn content_disposition(&self) -> Option<&str> {
        self.header_value("Content-Disposition")
    }

    /// Returns the Content-Transfer-Encoding header value, if present. A value
    /// the caller does not recognize means the part's bytes are not what its
    /// media type describes.
    pub fn content_transfer_encoding(&self) -> Option<&str> {
        self.header_value("Content-Transfer-Encoding")
    }
}

impl ParsedSipMessage {
    /// The remote address as a typed [`SocketAddr`], preserving family and
    /// port. `None` when the recorded address is not `ip:port`; the raw string
    /// remains in [`address`](Self::address).
    pub fn socket_addr(&self) -> Option<SocketAddr> {
        parse_socket_addr(&self.address)
    }

    /// Returns the Call-ID header value. Checks both `Call-ID` and
    /// the compact form `i`.
    pub fn call_id(&self) -> Option<&str> {
        self.header_value("Call-ID")
            .or_else(|| self.header_value("i"))
    }

    /// Returns the Content-Type header value. Checks both `Content-Type` and
    /// the compact form `c`.
    pub fn content_type(&self) -> Option<&str> {
        self.header_value("Content-Type")
            .or_else(|| self.header_value("c"))
    }

    /// Returns the Content-Length header value as `usize`. Checks both
    /// `Content-Length` and the compact form `l`.
    pub fn content_length(&self) -> Option<usize> {
        self.header_value("Content-Length")
            .or_else(|| self.header_value("l"))
            .and_then(|v| v.trim().parse().ok())
    }

    /// Returns the CSeq header value (e.g., `"1 INVITE"`).
    pub fn cseq(&self) -> Option<&str> {
        self.header_value("CSeq")
    }

    /// Returns the SIP method: from the request line for requests,
    /// or from the CSeq header for responses.
    pub fn method(&self) -> Option<&str> {
        match &self.message_type {
            SipMessageType::Request { method, .. } => Some(method),
            SipMessageType::Response { .. } => {
                self.cseq().and_then(|cs| cs.split_whitespace().nth(1))
            }
        }
    }

    /// Raw body bytes interpreted as UTF-8 (lossy). No processing is applied
    /// regardless of Content-Type.
    pub fn body_data(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(&self.body)
    }

    /// Reconstruct the SIP message as wire-format bytes (first line + headers + body).
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        match &self.message_type {
            SipMessageType::Request { method, uri } => {
                out.extend_from_slice(format!("{method} {uri} SIP/2.0\r\n").as_bytes());
            }
            SipMessageType::Response { code, reason } => {
                out.extend_from_slice(format!("SIP/2.0 {code} {reason}\r\n").as_bytes());
            }
        }
        for (name, value) in &self.headers {
            out.extend_from_slice(format!("{name}: {value}\r\n").as_bytes());
        }
        out.extend_from_slice(b"\r\n");
        if !self.body.is_empty() {
            out.extend_from_slice(&self.body);
        }
        out
    }

    /// Case-insensitive header lookup, first match in wire order. Compact
    /// forms are not resolved; the typed accessors above check both names.
    pub fn header_value(&self, name: &str) -> Option<&str> {
        self.headers.value(name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_parsed(
        msg_type: SipMessageType,
        headers: Vec<(&str, &str)>,
        body: &[u8],
    ) -> ParsedSipMessage {
        ParsedSipMessage {
            direction: Direction::Recv,
            transport: Transport::Tcp,
            address: "10.0.0.1:5060".into(),
            timestamp: Timestamp::TimeOnly {
                hour: 12,
                min: 0,
                sec: 0,
                usec: 0,
            },
            message_type: msg_type,
            headers: Headers(
                headers
                    .iter()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect(),
            ),
            body: body.to_vec(),
            frame_count: 1,
        }
    }

    fn make_frame(address: &str) -> Frame {
        Frame {
            direction: Direction::Recv,
            byte_count: 0,
            transport: Transport::Tcp,
            address: address.into(),
            timestamp: Timestamp::TimeOnly {
                hour: 0,
                min: 0,
                sec: 0,
                usec: 0,
            },
            content: Vec::new(),
        }
    }

    fn make_message(address: &str) -> SipMessage {
        SipMessage {
            direction: Direction::Recv,
            transport: Transport::Tcp,
            address: address.into(),
            timestamp: Timestamp::TimeOnly {
                hour: 0,
                min: 0,
                sec: 0,
                usec: 0,
            },
            content: Vec::new(),
            frame_count: 1,
        }
    }

    fn parsed_with_address(address: &str) -> ParsedSipMessage {
        let mut msg = make_parsed(
            SipMessageType::Request {
                method: "OPTIONS".into(),
                uri: "sip:host".into(),
            },
            vec![],
            b"",
        );
        msg.address = address.into();
        msg
    }

    #[test]
    fn socket_addr_ipv4() {
        let addr = make_frame("10.0.0.1:5060").socket_addr().unwrap();
        assert!(addr.is_ipv4());
        assert_eq!(addr.port(), 5060);
        assert_eq!(addr.ip().to_string(), "10.0.0.1");
    }

    #[test]
    fn socket_addr_ipv6_bracketed() {
        let addr = make_message("[2001:db8::1]:5061").socket_addr().unwrap();
        assert!(addr.is_ipv6());
        assert_eq!(addr.port(), 5061);
        assert_eq!(addr.ip().to_string(), "2001:db8::1");
    }

    #[test]
    fn socket_addr_ipv4_bracketed() {
        let addr = make_frame("[198.51.100.7]:5060").socket_addr().unwrap();
        assert!(addr.is_ipv4());
        assert_eq!(addr.port(), 5060);
        assert_eq!(addr.ip().to_string(), "198.51.100.7");
    }

    #[test]
    fn socket_addr_on_parsed_message() {
        let addr = parsed_with_address("192.0.2.4:5080").socket_addr().unwrap();
        assert_eq!(addr.port(), 5080);
    }

    #[test]
    fn socket_addr_rejects_non_addresses() {
        for bad in [
            "345.678.987.654:5060",
            "10.0.0.1",
            "host.example.test:5060",
            "2001:db8::1:5060",
            "",
        ] {
            assert!(
                make_frame(bad).socket_addr().is_none(),
                "should not parse: {bad}"
            );
            assert!(make_message(bad).socket_addr().is_none());
            assert!(parsed_with_address(bad).socket_addr().is_none());
        }
    }

    #[test]
    fn to_bytes_request_no_body() {
        let msg = make_parsed(
            SipMessageType::Request {
                method: "OPTIONS".into(),
                uri: "sip:host".into(),
            },
            vec![("Call-ID", "test")],
            b"",
        );
        let bytes = msg.to_bytes();
        let text = String::from_utf8(bytes).unwrap();
        assert!(text.starts_with("OPTIONS sip:host SIP/2.0\r\n"));
        assert!(text.contains("Call-ID: test\r\n"));
        assert!(text.ends_with("\r\n\r\n"));
    }

    #[test]
    fn to_bytes_request_with_body() {
        let body = b"v=0\r\ns=-\r\n";
        let msg = make_parsed(
            SipMessageType::Request {
                method: "INVITE".into(),
                uri: "sip:host".into(),
            },
            vec![("Call-ID", "test")],
            body,
        );
        let bytes = msg.to_bytes();
        assert!(bytes.ends_with(body));
    }

    #[test]
    fn to_bytes_response() {
        let msg = make_parsed(
            SipMessageType::Response {
                code: 200,
                reason: "OK".into(),
            },
            vec![("Call-ID", "resp-test")],
            b"",
        );
        let bytes = msg.to_bytes();
        let text = String::from_utf8(bytes).unwrap();
        assert!(text.starts_with("SIP/2.0 200 OK\r\n"));
    }

    #[test]
    fn body_data_valid_utf8() {
        let msg = make_parsed(
            SipMessageType::Request {
                method: "MESSAGE".into(),
                uri: "sip:host".into(),
            },
            vec![],
            b"hello world",
        );
        assert_eq!(&*msg.body_data(), "hello world");
    }

    #[test]
    fn body_data_empty() {
        let msg = make_parsed(
            SipMessageType::Request {
                method: "OPTIONS".into(),
                uri: "sip:host".into(),
            },
            vec![],
            b"",
        );
        assert_eq!(&*msg.body_data(), "");
    }

    #[test]
    fn body_data_binary() {
        let msg = make_parsed(
            SipMessageType::Request {
                method: "MESSAGE".into(),
                uri: "sip:host".into(),
            },
            vec![],
            &[0xFF, 0xFE],
        );
        assert!(msg.body_data().contains('\u{FFFD}'));
    }

    #[test]
    fn body_text_non_json_passthrough() {
        let msg = make_parsed(
            SipMessageType::Request {
                method: "INVITE".into(),
                uri: "sip:host".into(),
            },
            vec![("Content-Type", "application/sdp")],
            b"v=0\r\ns=-\r\n",
        );
        assert_eq!(msg.body_text().as_ref(), msg.body_data().as_ref());
    }

    #[test]
    fn body_text_json_unescapes_newlines() {
        let msg = make_parsed(
            SipMessageType::Request {
                method: "NOTIFY".into(),
                uri: "sip:host".into(),
            },
            vec![("Content-Type", "application/json")],
            br#"{"invite":"INVITE sip:host SIP/2.0\r\nTo: <sip:host>\r\n"}"#,
        );
        let text = msg.body_text();
        assert!(
            text.contains("INVITE sip:host SIP/2.0\r\nTo: <sip:host>\r\n"),
            "JSON \\r\\n should be unescaped to actual CRLF, got: {text:?}"
        );
    }

    #[test]
    fn body_text_plus_json_content_type() {
        let msg = make_parsed(
            SipMessageType::Request {
                method: "NOTIFY".into(),
                uri: "sip:host".into(),
            },
            vec![(
                "Content-Type",
                "application/emergencyCallData.AbandonedCall+json",
            )],
            br#"{"invite":"line1\nline2"}"#,
        );
        let text = msg.body_text();
        assert!(
            text.contains("line1\nline2"),
            "application/*+json should trigger unescaping, got: {text:?}"
        );
    }

    #[test]
    fn body_data_preserves_json_escapes() {
        let raw = br#"{"key":"value\nwith\\escapes"}"#;
        let msg = make_parsed(
            SipMessageType::Request {
                method: "NOTIFY".into(),
                uri: "sip:host".into(),
            },
            vec![("Content-Type", "application/json")],
            raw,
        );
        assert_eq!(
            msg.body_data().as_ref(),
            r#"{"key":"value\nwith\\escapes"}"#,
            "body_data() must preserve raw escapes"
        );
    }
}