Skip to main content

iphone_cli/tcp/
packets.rs

1// Jackson Coxson
2// I couldn't find a lib that parses IP/TCP, so I guess we'll write our own
3
4use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
5
6use tokio::io::{AsyncRead, AsyncReadExt};
7use tracing::debug;
8
9use crate::tcp::PcapLog;
10
11#[derive(Clone, Copy, Debug)]
12pub enum ProtocolNumber {
13    Tcp = 6,
14    Udp = 17,
15}
16
17#[derive(Debug)]
18pub struct Ipv4Packet {
19    pub version: u8,          // always 4 for IPv4
20    pub ihl: u8,              // len of header / 4
21    pub tos: u8,              // nobody can agree what this is for
22    pub total_length: u16,    // length of packet in bytes
23    pub identification: u16,  // ID from sender to help assemble datagram
24    pub flags: u8, // 3 bits; reserved: 0, may fragment: 0/1, last fragment 0 / more fragments 1
25    pub fragment_offset: u16, // where in the datagram this belongs
26    // If Google can ignore fragments, so can we
27    pub ttl: u8,              // max amount of time this packet can live
28    pub protocol: u8,         // protocol number, 6 for TCP
29    pub header_checksum: u16, // wrapping add all the u16 in header, then invert all bits
30    pub source: Ipv4Addr,
31    pub destination: Ipv4Addr,
32    pub options: Vec<u8>,
33    pub payload: Vec<u8>, // if smoltcp can ignore options, so can we
34}
35
36impl Ipv4Packet {
37    pub fn parse(packet: &[u8]) -> Option<Self> {
38        if packet.len() < 20 {
39            return None;
40        }
41
42        let version_ihl = packet[0];
43        let version = version_ihl >> 4;
44        let ihl = (version_ihl & 0x0F) * 4; // send help I don't understand bitwise ops
45
46        if version != 4 || packet.len() < ihl as usize {
47            return None;
48        }
49
50        let tos = packet[1];
51        let total_length = u16::from_be_bytes([packet[2], packet[3]]);
52        let identification = u16::from_be_bytes([packet[4], packet[5]]);
53        let flags_fragment = u16::from_be_bytes([packet[6], packet[7]]);
54        let flags = (flags_fragment >> 13) as u8;
55        let fragment_offset = flags_fragment & 0x1FFF;
56        let ttl = packet[8];
57        let protocol = packet[9];
58        let header_checksum = u16::from_be_bytes([packet[10], packet[11]]);
59        let source = Ipv4Addr::new(packet[12], packet[13], packet[14], packet[15]);
60        let destination = Ipv4Addr::new(packet[16], packet[17], packet[18], packet[19]);
61
62        let options_end = ihl as usize;
63        let options = if options_end > 20 {
64            packet[20..options_end].to_vec()
65        } else {
66            Vec::new()
67        };
68
69        let payload = if total_length as usize > options_end {
70            packet[options_end..total_length as usize].to_vec()
71        } else {
72            Vec::new()
73        };
74
75        Some(Self {
76            version,
77            ihl,
78            tos,
79            total_length,
80            identification,
81            flags,
82            fragment_offset,
83            ttl,
84            protocol,
85            header_checksum,
86            source,
87            destination,
88            options,
89            payload,
90        })
91    }
92
93    /// Asynchronously read an IPv4 packet from a Tokio AsyncRead source.
94    pub async fn from_reader<R: AsyncRead + Unpin + AsyncReadExt>(
95        reader: &mut R,
96        log: &Option<PcapLog>,
97    ) -> Result<Self, std::io::Error> {
98        let mut log_packet = Vec::new();
99
100        let mut header = [0u8; 20]; // Minimum IPv4 header size
101        reader.read_exact(&mut header).await?;
102        if log.is_some() {
103            log_packet.extend_from_slice(&header);
104        }
105
106        let version_ihl = header[0];
107        let version = version_ihl >> 4;
108        let ihl = (version_ihl & 0x0F) * 4;
109
110        if version != 4 || ihl < 20 {
111            debug!("Got an invalid IPv4 header from reader");
112            return Err(std::io::Error::new(
113                std::io::ErrorKind::InvalidData,
114                "Invalid IPv4 header",
115            ));
116        }
117
118        let tos = header[1];
119        let total_length = u16::from_be_bytes([header[2], header[3]]);
120        let identification = u16::from_be_bytes([header[4], header[5]]);
121        let flags_fragment = u16::from_be_bytes([header[6], header[7]]);
122        let flags = (flags_fragment >> 13) as u8;
123        let fragment_offset = flags_fragment & 0x1FFF;
124        let ttl = header[8];
125        let protocol = header[9];
126        let header_checksum = u16::from_be_bytes([header[10], header[11]]);
127        let source = Ipv4Addr::new(header[12], header[13], header[14], header[15]);
128        let destination = Ipv4Addr::new(header[16], header[17], header[18], header[19]);
129
130        // Read options if the header is larger than 20 bytes
131        let options_len = ihl as usize - 20;
132        let mut options = vec![0u8; options_len];
133        if options_len > 0 {
134            reader.read_exact(&mut options).await?;
135            if log.is_some() {
136                log_packet.extend_from_slice(&options);
137            }
138        }
139
140        // Read the payload
141        let payload_len = total_length as usize - ihl as usize;
142        let mut payload = vec![0u8; payload_len];
143        reader.read_exact(&mut payload).await?;
144        if let Some(log) = log {
145            log_packet.extend_from_slice(&payload);
146            crate::tcp::log_packet(log, &log_packet);
147        }
148
149        Ok(Self {
150            version,
151            ihl,
152            tos,
153            total_length,
154            identification,
155            flags,
156            fragment_offset,
157            ttl,
158            protocol,
159            header_checksum,
160            source,
161            destination,
162            options,
163            payload,
164        })
165    }
166
167    pub fn create(
168        source: Ipv4Addr,
169        destination: Ipv4Addr,
170        protocol: ProtocolNumber,
171        ttl: u8,
172        payload: &[u8],
173    ) -> Vec<u8> {
174        let ihl: u8 = 5;
175        let total_length = (ihl as usize * 4 + payload.len()) as u16;
176        let identification: u16 = 0;
177        let flags_fragment: u16 = 0;
178        let header_checksum: u16 = 0;
179
180        let mut packet = vec![0; total_length as usize];
181        packet[0] = (4 << 4) | (ihl & 0x0F);
182        packet[1] = 0;
183        packet[2..4].copy_from_slice(&total_length.to_be_bytes());
184        packet[4..6].copy_from_slice(&identification.to_be_bytes());
185        packet[6..8].copy_from_slice(&flags_fragment.to_be_bytes());
186        packet[8] = ttl;
187        packet[9] = protocol as u8;
188        packet[10..12].copy_from_slice(&header_checksum.to_be_bytes());
189        packet[12..16].copy_from_slice(&source.octets());
190        packet[16..20].copy_from_slice(&destination.octets());
191        packet[20..].copy_from_slice(payload);
192
193        Self::apply_checksum(&mut packet);
194        packet
195    }
196
197    fn apply_checksum(packet: &mut [u8]) {
198        let hdr_len = ((packet[0] & 0x0F) as usize) * 4;
199        debug_assert!(packet.len() >= hdr_len);
200        packet[10] = 0;
201        packet[11] = 0;
202        let mut sum: u32 = 0;
203        let mut i = 0;
204        while i + 1 < hdr_len {
205            sum += u16::from_be_bytes([packet[i], packet[i + 1]]) as u32;
206            i += 2;
207        }
208        // Fold carries.
209        while sum >> 16 != 0 {
210            sum = (sum & 0xFFFF) + (sum >> 16);
211        }
212        let checksum = !(sum as u16);
213        packet[10..12].copy_from_slice(&checksum.to_be_bytes());
214    }
215}
216
217pub struct Ipv6Packet {
218    pub version: u8,
219    pub traffic_class: u8,
220    pub flow_label: u32,
221    pub payload_length: u16,
222    pub next_header: u8,
223    pub hop_limit: u8,
224    pub source: Ipv6Addr,
225    pub destination: Ipv6Addr,
226    pub payload: Vec<u8>,
227}
228
229#[derive(Debug, Clone)]
230pub(crate) enum IpParseError<T> {
231    Ok { packet: T, bytes_consumed: usize },
232    NotEnough,
233    Invalid,
234}
235
236impl Ipv6Packet {
237    pub(crate) fn parse(packet: &[u8], log: &Option<PcapLog>) -> IpParseError<Ipv6Packet> {
238        if packet.len() < 40 {
239            return IpParseError::NotEnough;
240        }
241
242        let version = packet[0] >> 4;
243        if version != 6 {
244            return IpParseError::Invalid;
245        }
246
247        let traffic_class = ((packet[0] & 0x0F) << 4) | (packet[1] >> 4);
248        let flow_label =
249            ((packet[1] as u32 & 0x0F) << 16) | ((packet[2] as u32) << 8) | packet[3] as u32;
250        let payload_length = u16::from_be_bytes([packet[4], packet[5]]);
251        let total_packet_len = 40 + payload_length as usize;
252
253        if packet.len() < total_packet_len {
254            return IpParseError::NotEnough;
255        }
256
257        let next_header = packet[6];
258        let hop_limit = packet[7];
259        let source = Ipv6Addr::new(
260            u16::from_be_bytes([packet[8], packet[9]]),
261            u16::from_be_bytes([packet[10], packet[11]]),
262            u16::from_be_bytes([packet[12], packet[13]]),
263            u16::from_be_bytes([packet[14], packet[15]]),
264            u16::from_be_bytes([packet[16], packet[17]]),
265            u16::from_be_bytes([packet[18], packet[19]]),
266            u16::from_be_bytes([packet[20], packet[21]]),
267            u16::from_be_bytes([packet[22], packet[23]]),
268        );
269
270        let destination = Ipv6Addr::new(
271            u16::from_be_bytes([packet[24], packet[25]]),
272            u16::from_be_bytes([packet[26], packet[27]]),
273            u16::from_be_bytes([packet[28], packet[29]]),
274            u16::from_be_bytes([packet[30], packet[31]]),
275            u16::from_be_bytes([packet[32], packet[33]]),
276            u16::from_be_bytes([packet[34], packet[35]]),
277            u16::from_be_bytes([packet[36], packet[37]]),
278            u16::from_be_bytes([packet[38], packet[39]]),
279        );
280        let payload = packet[40..total_packet_len].to_vec();
281
282        if let Some(log) = log {
283            let mut log_packet = Vec::new();
284            log_packet.extend_from_slice(&packet[..40]);
285            log_packet.extend_from_slice(&payload);
286            crate::tcp::log_packet(log, &log_packet);
287        }
288
289        IpParseError::Ok {
290            packet: Self {
291                version,
292                traffic_class,
293                flow_label,
294                payload_length,
295                next_header,
296                hop_limit,
297                source,
298                destination,
299                payload,
300            },
301            bytes_consumed: total_packet_len,
302        }
303    }
304
305    pub async fn from_reader<R: AsyncRead + Unpin>(
306        reader: &mut R,
307        log: &Option<PcapLog>,
308    ) -> Result<Self, std::io::Error> {
309        let mut log_packet = Vec::new();
310
311        let mut header = [0u8; 40]; // IPv6 header size is fixed at 40 bytes
312        reader.read_exact(&mut header).await?;
313
314        if log.is_some() {
315            log_packet.extend_from_slice(&header);
316        }
317
318        let version = header[0] >> 4;
319        if version != 6 {
320            debug!("Got an invalid IPv6 header from reader");
321            return Err(std::io::Error::new(
322                std::io::ErrorKind::InvalidData,
323                "Invalid IPv6 header",
324            ));
325        }
326
327        let traffic_class = ((header[0] & 0x0F) << 4) | ((header[1] & 0xF0) >> 4);
328        let flow_label =
329            ((header[1] as u32 & 0x0F) << 16) | ((header[2] as u32) << 8) | (header[3] as u32);
330        let payload_length = u16::from_be_bytes([header[4], header[5]]);
331        let next_header = header[6];
332        let hop_limit = header[7];
333        let source = Ipv6Addr::new(
334            u16::from_be_bytes([header[8], header[9]]),
335            u16::from_be_bytes([header[10], header[11]]),
336            u16::from_be_bytes([header[12], header[13]]),
337            u16::from_be_bytes([header[14], header[15]]),
338            u16::from_be_bytes([header[16], header[17]]),
339            u16::from_be_bytes([header[18], header[19]]),
340            u16::from_be_bytes([header[20], header[21]]),
341            u16::from_be_bytes([header[22], header[23]]),
342        );
343        let destination = Ipv6Addr::new(
344            u16::from_be_bytes([header[24], header[25]]),
345            u16::from_be_bytes([header[26], header[27]]),
346            u16::from_be_bytes([header[28], header[29]]),
347            u16::from_be_bytes([header[30], header[31]]),
348            u16::from_be_bytes([header[32], header[33]]),
349            u16::from_be_bytes([header[34], header[35]]),
350            u16::from_be_bytes([header[36], header[37]]),
351            u16::from_be_bytes([header[38], header[39]]),
352        );
353
354        // Read the payload
355        let mut payload = vec![0u8; payload_length as usize];
356        reader.read_exact(&mut payload).await?;
357        if let Some(log) = log {
358            log_packet.extend_from_slice(&payload);
359            crate::tcp::log_packet(log, &log_packet);
360        }
361
362        Ok(Self {
363            version,
364            traffic_class,
365            flow_label,
366            payload_length,
367            next_header,
368            hop_limit,
369            source,
370            destination,
371            payload,
372        })
373    }
374
375    pub fn create(
376        source: Ipv6Addr,
377        destination: Ipv6Addr,
378        next_header: ProtocolNumber,
379        hop_limit: u8,
380        payload: &[u8],
381    ) -> Vec<u8> {
382        let mut packet = Vec::with_capacity(40 + payload.len());
383
384        // Version (6) and Traffic Class (0)
385        let version_traffic_class = 6 << 4;
386        packet.push(version_traffic_class);
387        packet.push(0); // The rest of the Traffic Class and the start of the Flow Label
388
389        // Flow Label (0)
390        let flow_label = 0u16;
391        packet.extend_from_slice(&flow_label.to_be_bytes()[..]);
392
393        // Payload Length (length of the payload only)
394        packet.extend_from_slice(&(payload.len() as u16).to_be_bytes());
395
396        // Next Header and Hop Limit
397        packet.push(next_header as u8);
398        packet.push(hop_limit);
399
400        // Source and Destination Addresses
401        packet.extend_from_slice(&source.octets());
402        packet.extend_from_slice(&destination.octets());
403
404        // Payload
405        packet.extend_from_slice(payload);
406
407        packet
408    }
409}
410
411impl std::fmt::Debug for Ipv6Packet {
412    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
413        f.debug_struct("Ipv6Packet")
414            .field("version", &self.version)
415            .field("traffic_class", &self.traffic_class)
416            .field("flow_label", &self.flow_label)
417            .field("payload_length", &self.payload_length)
418            .field("next_header", &self.next_header)
419            .field("hop_limit", &self.hop_limit)
420            .field("source", &self.source)
421            .field("destination", &self.destination)
422            .field("payload len", &self.payload.len())
423            .finish()
424    }
425}
426
427#[derive(Debug, Default, Clone, Copy)]
428pub struct TcpFlags {
429    pub urg: bool, // Urgent pointer flag
430    pub ack: bool, // Acknowledgment flag
431    pub psh: bool, // Push flag
432    pub rst: bool, // Reset flag
433    pub syn: bool, // Synchronize flag
434    pub fin: bool, // Finish flag
435}
436
437impl TcpFlags {
438    /// Create a new `TcpFlags` struct from a raw byte.
439    pub fn from_byte(flags: u8) -> Self {
440        Self {
441            urg: (flags & 0b0010_0000) != 0, // URG flag (bit 5)
442            ack: (flags & 0b0001_0000) != 0, // ACK flag (bit 4)
443            psh: (flags & 0b0000_1000) != 0, // PSH flag (bit 3)
444            rst: (flags & 0b0000_0100) != 0, // RST flag (bit 2)
445            syn: (flags & 0b0000_0010) != 0, // SYN flag (bit 1)
446            fin: (flags & 0b0000_0001) != 0, // FIN flag (bit 0)
447        }
448    }
449
450    /// Convert the `TcpFlags` struct into a raw byte.
451    pub fn to_byte(&self) -> u8 {
452        let mut flags = 0u8;
453        if self.urg {
454            flags |= 0b0010_0000;
455        }
456        if self.ack {
457            flags |= 0b0001_0000;
458        }
459        if self.psh {
460            flags |= 0b0000_1000;
461        }
462        if self.rst {
463            flags |= 0b0000_0100;
464        }
465        if self.syn {
466            flags |= 0b0000_0010;
467        }
468        if self.fin {
469            flags |= 0b0000_0001;
470        }
471        flags
472    }
473}
474
475pub struct TcpPacket {
476    pub source_port: u16,
477    pub destination_port: u16,
478    pub sequence_number: u32,
479    pub acknowledgment_number: u32,
480    pub data_offset: u8, // Header length in 32-bit words
481    pub flags: TcpFlags, // TCP flags
482    pub window_size: u16,
483    pub checksum: u16,
484    pub urgent_pointer: u16,
485    pub options: Vec<u8>, // Optional TCP options
486    pub payload: Vec<u8>, // TCP payload
487}
488
489impl TcpPacket {
490    pub fn parse(packet: &[u8]) -> Result<Self, std::io::Error> {
491        if packet.len() < 20 {
492            debug!("Got an invalid TCP header");
493            return Err(std::io::Error::new(
494                std::io::ErrorKind::InvalidData,
495                "Not enough bytes for TCP header",
496            ));
497        }
498
499        let source_port = u16::from_be_bytes([packet[0], packet[1]]);
500        let destination_port = u16::from_be_bytes([packet[2], packet[3]]);
501        let sequence_number = u32::from_be_bytes([packet[4], packet[5], packet[6], packet[7]]);
502        let acknowledgment_number =
503            u32::from_be_bytes([packet[8], packet[9], packet[10], packet[11]]);
504        let data_offset = (packet[12] >> 4) * 4; // Convert from 32-bit words to bytes
505        let flags = TcpFlags::from_byte(packet[13]); // Parse flags
506        let window_size = u16::from_be_bytes([packet[14], packet[15]]);
507        let checksum = u16::from_be_bytes([packet[16], packet[17]]);
508        let urgent_pointer = u16::from_be_bytes([packet[18], packet[19]]);
509
510        // Parse options if the header is longer than 20 bytes
511        let options_end = data_offset as usize;
512        let options = if options_end > 20 && options_end <= packet.len() {
513            packet[20..options_end].to_vec()
514        } else {
515            Vec::new()
516        };
517
518        // Payload starts after the header
519        let payload = if packet.len() > options_end {
520            packet[options_end..].to_vec()
521        } else {
522            Vec::new()
523        };
524
525        Ok(Self {
526            source_port,
527            destination_port,
528            sequence_number,
529            acknowledgment_number,
530            data_offset,
531            flags,
532            window_size,
533            checksum,
534            urgent_pointer,
535            options,
536            payload,
537        })
538    }
539
540    /// Build a TCP segment. `options` is appended verbatim and then
541    /// NOP-padded (kind=1) up to a 4-byte boundary; pass `&[]` if you don't
542    /// need any. See [`window_scale_option`] for a wscale builder.
543    #[allow(clippy::too_many_arguments)]
544    pub fn create(
545        source_ip: IpAddr,
546        destination_ip: IpAddr,
547        source_port: u16,
548        destination_port: u16,
549        sequence_number: u32,
550        acknowledgment_number: u32,
551        flags: TcpFlags,
552        window_size: u16,
553        options: &[u8],
554        payload: &[u8],
555    ) -> Vec<u8> {
556        // TCP options must end on a 4-byte boundary; pad with NOPs (kind 1).
557        let pad = (4 - options.len() % 4) % 4;
558        let opt_total = options.len() + pad;
559        debug_assert!(opt_total.is_multiple_of(4));
560        let data_offset = 5_u8 + (opt_total / 4) as u8;
561        let mut packet = Vec::with_capacity(20 + opt_total + payload.len());
562
563        // Source and Destination Ports
564        packet.extend_from_slice(&source_port.to_be_bytes());
565        packet.extend_from_slice(&destination_port.to_be_bytes());
566
567        // Sequence and Acknowledgment Numbers
568        packet.extend_from_slice(&sequence_number.to_be_bytes());
569        packet.extend_from_slice(&acknowledgment_number.to_be_bytes());
570
571        // Data Offset and Flags
572        packet.push(data_offset << 4); // Data offset (4 bits) and reserved bits (4 bits)
573        packet.push(flags.to_byte()); // Flags byte
574
575        // Window Size, Checksum (set to zero first), and Urgent Pointer
576        packet.extend_from_slice(&window_size.to_be_bytes());
577        packet.extend_from_slice(&[0, 0]); // Checksum placeholder
578        packet.extend_from_slice(&[0, 0]); // Urgent pointer
579
580        // Options + NOP padding to 4-byte boundary.
581        packet.extend_from_slice(options);
582        packet.extend(std::iter::repeat_n(1, pad));
583        packet.extend_from_slice(payload);
584
585        // Compute checksum with the appropriate pseudo-header
586        let checksum = match (source_ip, destination_ip) {
587            (IpAddr::V4(src), IpAddr::V4(dest)) => {
588                let src_bytes = src.octets();
589                let dest_bytes = dest.octets();
590                Self::calculate_checksum(&packet, &src_bytes, &dest_bytes, false)
591            }
592            (IpAddr::V6(src), IpAddr::V6(dest)) => {
593                let src_bytes = src.octets();
594                let dest_bytes = dest.octets();
595                Self::calculate_checksum(&packet, &src_bytes, &dest_bytes, true)
596            }
597            _ => panic!("Source and destination IP versions must match"),
598        };
599
600        packet[16..18].copy_from_slice(&checksum.to_be_bytes());
601
602        packet
603    }
604
605    fn calculate_checksum(
606        packet: &[u8],
607        source_ip: &[u8],
608        destination_ip: &[u8],
609        is_ipv6: bool,
610    ) -> u16 {
611        let mut sum = 0u32;
612
613        if is_ipv6 {
614            // IPv6 pseudo-header
615            // Add source and destination addresses (128 bits each)
616            for chunk in source_ip.chunks(2) {
617                sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
618            }
619            for chunk in destination_ip.chunks(2) {
620                sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
621            }
622
623            // Upper layer packet length (32 bits for IPv6)
624            let tcp_length = packet.len() as u32;
625            sum += (tcp_length >> 16) & 0xFFFF;
626            sum += tcp_length & 0xFFFF;
627
628            // Next Header value (8 bits of zeros + 8 bits of protocol value)
629            sum += 6u32; // TCP protocol number
630        } else {
631            // IPv4 pseudo-header
632            // Add source and destination addresses (32 bits each)
633            for chunk in source_ip.chunks(2) {
634                sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
635            }
636            for chunk in destination_ip.chunks(2) {
637                sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
638            }
639
640            // Zero byte + Protocol byte
641            sum += 6u32; // TCP protocol number
642
643            // TCP segment length (16 bits)
644            sum += packet.len() as u32;
645        }
646
647        // Create a copy of the packet with checksum field zeroed out
648        let mut packet_copy = packet.to_vec();
649        if packet_copy.len() >= 18 {
650            packet_copy[16] = 0;
651            packet_copy[17] = 0;
652        }
653
654        // Sum all 16-bit words in the packet
655        for chunk in packet_copy.chunks(2) {
656            let word = if chunk.len() == 2 {
657                u16::from_be_bytes([chunk[0], chunk[1]])
658            } else {
659                u16::from_be_bytes([chunk[0], 0]) // Padding for odd-length packets
660            };
661            sum += word as u32;
662        }
663
664        // Fold sum to 16 bits
665        while sum >> 16 != 0 {
666            sum = (sum & 0xFFFF) + (sum >> 16);
667        }
668
669        // One's complement
670        !(sum as u16)
671    }
672}
673
674/// Build a TCP Window Scale option
675pub fn window_scale_option(shift: u8) -> [u8; 3] {
676    // kind=3, length=3, shift_count
677    [3, 3, shift.min(14)]
678}
679
680/// Scan a TCP options blob for the Window Scale option. Returns the shift
681/// count if present and well-formed; otherwise None.
682pub fn parse_window_scale(options: &[u8]) -> Option<u8> {
683    let mut i = 0;
684    while i < options.len() {
685        match options[i] {
686            0 => return None, // End-of-options
687            1 => {
688                i += 1;
689                continue;
690            } // NOP
691            3 => {
692                // Window scale: kind=3, length=3, shift.
693                if i + 2 < options.len() && options[i + 1] == 3 {
694                    return Some(options[i + 2].min(14));
695                }
696                return None;
697            }
698            _ => {
699                // Skip unknown TLV option by its length byte.
700                if i + 1 >= options.len() {
701                    return None;
702                }
703                let len = options[i + 1] as usize;
704                if len < 2 {
705                    return None;
706                }
707                i += len;
708            }
709        }
710    }
711    None
712}
713
714impl std::fmt::Debug for TcpPacket {
715    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
716        f.debug_struct("TcpPacket")
717            .field("source_port", &self.source_port)
718            .field("destination_port", &self.destination_port)
719            .field("sequence_number", &self.sequence_number)
720            .field("acknowledgment_number", &self.acknowledgment_number)
721            .field("data_offset", &self.data_offset)
722            .field("flags", &self.flags)
723            .field("window_size", &self.window_size)
724            .field("checksum", &self.checksum)
725            .field("urgent_pointer", &self.urgent_pointer)
726            .field("options", &self.options)
727            .field("payload len", &self.payload.len())
728            .finish()
729    }
730}
731
732pub struct UdpPacket {
733    pub source_port: u16,
734    pub destination_port: u16,
735    pub length: u16,
736    pub checksum: u16,
737    pub payload: Vec<u8>,
738}
739
740impl UdpPacket {
741    pub fn parse(packet: &[u8]) -> Result<Self, std::io::Error> {
742        if packet.len() < 8 {
743            return Err(std::io::Error::new(
744                std::io::ErrorKind::InvalidData,
745                "not enough bytes for UDP header",
746            ));
747        }
748        let source_port = u16::from_be_bytes([packet[0], packet[1]]);
749        let destination_port = u16::from_be_bytes([packet[2], packet[3]]);
750        let length = u16::from_be_bytes([packet[4], packet[5]]);
751        let checksum = u16::from_be_bytes([packet[6], packet[7]]);
752        let payload = packet[8..].to_vec();
753        Ok(Self {
754            source_port,
755            destination_port,
756            length,
757            checksum,
758            payload,
759        })
760    }
761
762    /// Build a UDP datagram with the checksum filled in.
763    pub fn create(
764        source_ip: IpAddr,
765        destination_ip: IpAddr,
766        source_port: u16,
767        destination_port: u16,
768        payload: &[u8],
769    ) -> Vec<u8> {
770        let length = (8 + payload.len()) as u16;
771        let mut packet = Vec::with_capacity(length as usize);
772        packet.extend_from_slice(&source_port.to_be_bytes());
773        packet.extend_from_slice(&destination_port.to_be_bytes());
774        packet.extend_from_slice(&length.to_be_bytes());
775        packet.extend_from_slice(&[0, 0]); // checksum placeholder
776        packet.extend_from_slice(payload);
777
778        let checksum = match (source_ip, destination_ip) {
779            (IpAddr::V4(src), IpAddr::V4(dst)) => {
780                Self::checksum(&packet, &src.octets(), &dst.octets(), false)
781            }
782            (IpAddr::V6(src), IpAddr::V6(dst)) => {
783                Self::checksum(&packet, &src.octets(), &dst.octets(), true)
784            }
785            _ => panic!("source and destination IP versions must match"),
786        };
787        // For IPv4 a zero checksum means "not computed"; for IPv6 a computed
788        // checksum of 0 is transmitted as 0xFFFF.
789        let checksum = if checksum == 0 { 0xFFFF } else { checksum };
790        packet[6..8].copy_from_slice(&checksum.to_be_bytes());
791        packet
792    }
793
794    fn checksum(packet: &[u8], source_ip: &[u8], destination_ip: &[u8], _is_ipv6: bool) -> u16 {
795        let mut sum = 0u32;
796        for chunk in source_ip.chunks(2) {
797            sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
798        }
799        for chunk in destination_ip.chunks(2) {
800            sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
801        }
802        let udp_len = packet.len() as u32;
803        sum += (udp_len >> 16) & 0xFFFF;
804        sum += udp_len & 0xFFFF;
805        sum += 17u32;
806
807        for chunk in packet.chunks(2) {
808            let word = if chunk.len() == 2 {
809                u16::from_be_bytes([chunk[0], chunk[1]])
810            } else {
811                u16::from_be_bytes([chunk[0], 0])
812            };
813            sum += word as u32;
814        }
815        while sum >> 16 != 0 {
816            sum = (sum & 0xFFFF) + (sum >> 16);
817        }
818        !(sum as u16)
819    }
820}
821
822impl std::fmt::Debug for UdpPacket {
823    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
824        f.debug_struct("UdpPacket")
825            .field("source_port", &self.source_port)
826            .field("destination_port", &self.destination_port)
827            .field("length", &self.length)
828            .field("checksum", &self.checksum)
829            .field("payload len", &self.payload.len())
830            .finish()
831    }
832}
833
834#[cfg(test)]
835mod tests {
836    use super::*;
837
838    #[test]
839    fn ipv4_checksum_matches_rfc_1071() {
840        // Header from RFC 1071 ยง1 example: 20-byte IPv4 header.
841        let mut pkt = vec![
842            0x45, 0x00, 0x00, 0x73, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0xC0, 0xA8,
843            0x00, 0x01, 0xC0, 0xA8, 0x00, 0xC7,
844        ];
845        Ipv4Packet::apply_checksum(&mut pkt);
846        let got = u16::from_be_bytes([pkt[10], pkt[11]]);
847        assert_eq!(got, 0xB861);
848
849        let mut sum: u32 = 0;
850        for chunk in pkt.as_chunks::<2>().0 {
851            sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
852        }
853        while sum >> 16 != 0 {
854            sum = (sum & 0xFFFF) + (sum >> 16);
855        }
856        assert_eq!(sum as u16, 0xFFFF);
857    }
858
859    #[test]
860    fn ipv4() {
861        let b1 = Ipv4Packet::create(
862            Ipv4Addr::new(127, 0, 0, 1),
863            Ipv4Addr::new(1, 1, 1, 1),
864            ProtocolNumber::Tcp,
865            255,
866            &[1, 2, 3, 4, 5],
867        );
868        println!("{b1:02X?}");
869
870        let ip1 = Ipv4Packet::parse(&b1);
871        println!("{ip1:#?}");
872    }
873
874    #[test]
875    fn ipv6() {
876        let b1 = Ipv6Packet::create(
877            Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8),
878            Ipv6Addr::new(9, 10, 11, 12, 13, 14, 15, 16),
879            ProtocolNumber::Tcp,
880            255,
881            &[1, 2, 3, 4, 5],
882        );
883        println!("{b1:02X?}");
884
885        let ip1 = Ipv6Packet::parse(&b1, &None);
886        println!("{ip1:#?}");
887    }
888
889    #[test]
890    fn tcp() {
891        let b1 = TcpPacket::create(
892            IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
893            IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
894            1234,
895            5678,
896            420,
897            6969,
898            TcpFlags {
899                urg: false,
900                ack: false,
901                psh: true,
902                rst: false,
903                syn: false,
904                fin: false,
905            },
906            5555,
907            &[],
908            &[1, 2, 3, 4, 5],
909        );
910        let i1 = Ipv6Packet::create(
911            Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8),
912            Ipv6Addr::new(9, 10, 11, 12, 13, 14, 15, 16),
913            ProtocolNumber::Tcp,
914            255,
915            &b1,
916        );
917        println!("{i1:02X?}");
918
919        let t1 = TcpPacket::parse(&b1);
920        println!("{t1:#?}");
921    }
922}