Skip to main content

prolink_capture/
packet.rs

1// SPDX-License-Identifier: GPL-3.0-only
2
3//! One transport payload lifted out of a capture.
4
5use std::fmt;
6use std::net::SocketAddrV4;
7use std::time::Duration;
8
9/// One UDP datagram or TCP segment, with the addresses it travelled between.
10///
11/// Only IPv4 over Ethernet is modelled, and only UDP and TCP above it, because
12/// that is the whole of what a Pro DJ Link capture contains. Anything else in
13/// the file — ARP, IPv6, ICMP, a frame from a link layer we do not dissect —
14/// is not a packet in this sense and never appears.
15///
16/// The payload has already been IP-defragmented, so an 8 KiB NFS reply arrives
17/// here as one datagram and not as the six on the wire.
18#[derive(Clone, PartialEq, Eq)]
19pub struct Packet {
20    /// Position of the frame in the file, counting from one.
21    ///
22    /// A defragmented datagram carries the index of its *last* fragment, which
23    /// is the frame at which it became readable.
24    pub index: u64,
25
26    /// When the frame was captured, since the Unix epoch.
27    ///
28    /// A pcapng simple-packet block records no time at all; those arrive as
29    /// [`Duration::ZERO`] rather than as a guess.
30    pub timestamp: Duration,
31
32    /// Which of the capture's interfaces recorded it; `0` for classic pcap.
33    ///
34    /// Worth carrying because a capture of a bridge records the *same*
35    /// datagram once per interface. Two identical packets differing only here
36    /// are one datagram seen twice, not two datagrams — [`crate::tcp`] folds
37    /// them back together, but a UDP count does not, and cannot: nothing on
38    /// the wire distinguishes a duplicate from a genuine repeat.
39    pub interface: u32,
40
41    /// Who sent it.
42    ///
43    /// **Not** what to filter a corpus on. See [`Packet::destination`].
44    pub source: SocketAddrV4,
45
46    /// Who it was addressed to — the field a corpus filter belongs on.
47    ///
48    /// The Pro DJ Link type byte at offset `0x0a` is shared across UDP ports
49    /// and the layouts behind it are not: `0x06` is a keep-alive on 50000 and
50    /// a media response on 50002. A tool that binds one socket and sends its
51    /// keep-alives *from* 50002 therefore contributes packets that a
52    /// "either endpoint is 50002" filter accepts and the 50002 decoder reads
53    /// as confident nonsense. Filter on where a packet was going, which is the
54    /// only thing that decides which protocol wrote it.
55    pub destination: SocketAddrV4,
56
57    /// Which transport, and the fields reassembly needs from it.
58    pub transport: Transport,
59
60    /// The transport payload, with IP fragmentation already undone.
61    pub payload: Vec<u8>,
62}
63
64impl Packet {
65    /// The payload, if this datagram was addressed to `port` over UDP.
66    ///
67    /// The one-packet form of [`crate::Capture::udp_to`], and the same rule:
68    /// the *destination* decides, never the source.
69    pub fn udp_payload_to(&self, port: u16) -> Option<&[u8]> {
70        (self.transport == Transport::Udp && self.destination.port() == port)
71            .then_some(self.payload.as_slice())
72    }
73}
74
75impl fmt::Debug for Packet {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        let protocol = match self.transport {
78            Transport::Udp => "udp",
79            Transport::Tcp { .. } => "tcp",
80        };
81        write!(
82            f,
83            "#{} {:.6}s {protocol} {} -> {} {}B",
84            self.index,
85            self.timestamp.as_secs_f64(),
86            self.source,
87            self.destination,
88            self.payload.len()
89        )
90    }
91}
92
93/// Which transport carried a [`Packet`], and what reassembly needs from it.
94///
95/// A real enum rather than a protocol-number newtype because this crate owns
96/// every case: a payload we cannot attribute to UDP or TCP is not a
97/// [`Packet`] at all. The sequence number lives inside the TCP variant so that
98/// a UDP packet carrying one cannot be built.
99#[derive(Clone, Copy, PartialEq, Eq, Debug)]
100pub enum Transport {
101    /// A UDP datagram.
102    Udp,
103    /// One TCP segment.
104    Tcp {
105        /// Sequence number of this segment's first byte on the wire.
106        ///
107        /// On a SYN this numbers the SYN itself, so the first payload byte is
108        /// at `sequence + 1`; [`crate::tcp`] is where that is accounted for.
109        sequence: u32,
110        /// The SYN flag: this segment opens the connection in this direction.
111        syn: bool,
112        /// The FIN flag: the sender has no more data.
113        fin: bool,
114        /// The RST flag: the connection was aborted.
115        reset: bool,
116    },
117}
118
119impl Transport {
120    /// True for UDP.
121    pub fn is_udp(self) -> bool {
122        matches!(self, Self::Udp)
123    }
124
125    /// True for TCP.
126    pub fn is_tcp(self) -> bool {
127        matches!(self, Self::Tcp { .. })
128    }
129}
130
131/// One direction of one connection: the key a TCP byte stream is kept under.
132///
133/// The four-tuple *and* the direction, because the two directions of a
134/// dbserver conversation are different message types and interleaving them
135/// would produce a byte stream nobody ever sent.
136#[derive(Clone, Copy, PartialEq, Eq, Hash)]
137pub struct Flow {
138    /// Who sends on this half of the connection.
139    pub source: SocketAddrV4,
140    /// Who receives.
141    pub destination: SocketAddrV4,
142}
143
144impl Flow {
145    /// The flow a packet belongs to.
146    pub fn of(packet: &Packet) -> Self {
147        Self {
148            source: packet.source,
149            destination: packet.destination,
150        }
151    }
152
153    /// The same connection, the other way round.
154    #[must_use]
155    pub fn reversed(self) -> Self {
156        Self {
157            source: self.destination,
158            destination: self.source,
159        }
160    }
161
162    /// Whether either endpoint sits on `port`.
163    ///
164    /// **This is the right test for TCP and the wrong one for UDP.** A TCP
165    /// connection is a thing with two ends, and both directions of a dbserver
166    /// conversation belong to the server's port; a UDP datagram is a thing
167    /// with a destination, and its source port says nothing about which
168    /// protocol wrote it. See [`Packet::destination`].
169    pub fn involves(self, port: u16) -> bool {
170        self.source.port() == port || self.destination.port() == port
171    }
172}
173
174impl fmt::Debug for Flow {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        write!(f, "{} -> {}", self.source, self.destination)
177    }
178}