wireforge-core 1.0.2

Zero-copy network packet parsers and builders — protocol types, checksums, core utilities
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
//! TCP packet parser and builder with option parsing.

use alloc::vec;
use alloc::vec::Vec;
use core::net::Ipv4Addr;

use crate::util::{pseudo_header_checksum, read_u16be, read_u32be, write_u16be, write_u32be};

pub const TCP_MIN_HEADER_LEN: usize = 20;

// TCP flag bit positions
const FLAG_FIN: u8 = 0x01;
const FLAG_SYN: u8 = 0x02;
const FLAG_RST: u8 = 0x04;
const FLAG_PSH: u8 = 0x08;
const FLAG_ACK: u8 = 0x10;
const FLAG_URG: u8 = 0x20;

// TCP option kinds
const OPT_END: u8 = 0;
const OPT_NOOP: u8 = 1;
const OPT_MSS: u8 = 2;
const OPT_WINDOW_SCALE: u8 = 3;
const OPT_SACK_PERMITTED: u8 = 4;
const OPT_SACK: u8 = 5;
const OPT_TIMESTAMP: u8 = 8;

/// Parsed TCP option.
#[derive(Debug, Clone)]
pub enum TcpOption {
    EndOfList,
    NoOp,
    MaximumSegmentSize(u16),
    WindowScale(u8),
    SackPermitted,
    Sack(Vec<(u32, u32)>),
    Timestamp { ts_val: u32, ts_ecr: u32 },
    Unknown { kind: u8, data: Vec<u8> },
}

/// Iterator over TCP options in the header.
pub struct TcpOptionsIter<'a> {
    data: &'a [u8],
}

impl<'a> TcpOptionsIter<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self { data }
    }
}

impl<'a> Iterator for TcpOptionsIter<'a> {
    type Item = TcpOption;

    fn next(&mut self) -> Option<Self::Item> {
        if self.data.is_empty() {
            return None;
        }
        let kind = self.data[0];
        match kind {
            OPT_END => {
                self.data = &[];
                Some(TcpOption::EndOfList)
            }
            OPT_NOOP => {
                self.data = &self.data[1..];
                Some(TcpOption::NoOp)
            }
            OPT_MSS => {
                if self.data.len() < 4 {
                    self.data = &[];
                    return Some(TcpOption::Unknown { kind, data: self.data.to_vec() });
                }
                let mss = read_u16be(&self.data[2..4]);
                self.data = &self.data[4..];
                Some(TcpOption::MaximumSegmentSize(mss))
            }
            OPT_WINDOW_SCALE => {
                if self.data.len() < 3 {
                    self.data = &[];
                    return Some(TcpOption::Unknown { kind, data: self.data.to_vec() });
                }
                let shift = self.data[2];
                self.data = &self.data[3..];
                Some(TcpOption::WindowScale(shift))
            }
            OPT_SACK_PERMITTED => {
                if self.data.len() < 2 {
                    self.data = &[];
                    return Some(TcpOption::Unknown { kind, data: self.data.to_vec() });
                }
                self.data = &self.data[2..];
                Some(TcpOption::SackPermitted)
            }
            OPT_SACK => {
                let len = self.data.get(1).copied().unwrap_or(0) as usize;
                if len < 2 || self.data.len() < len {
                    self.data = &[];
                    return Some(TcpOption::Unknown { kind, data: self.data.to_vec() });
                }
                let blocks_data = &self.data[2..len];
                let mut blocks = Vec::new();
                for chunk in blocks_data.chunks(8) {
                    if chunk.len() == 8 {
                        blocks.push((read_u32be(&chunk[..4]), read_u32be(&chunk[4..8])));
                    }
                }
                self.data = &self.data[len..];
                Some(TcpOption::Sack(blocks))
            }
            OPT_TIMESTAMP => {
                if self.data.len() < 10 {
                    self.data = &[];
                    return Some(TcpOption::Unknown { kind, data: self.data.to_vec() });
                }
                let ts_val = read_u32be(&self.data[2..6]);
                let ts_ecr = read_u32be(&self.data[6..10]);
                self.data = &self.data[10..];
                Some(TcpOption::Timestamp { ts_val, ts_ecr })
            }
            _ => {
                let len = self.data.get(1).copied().unwrap_or(0) as usize;
                if kind > 1 && len >= 2 && self.data.len() >= len {
                    let data = self.data[..len].to_vec();
                    self.data = &self.data[len..];
                    Some(TcpOption::Unknown { kind, data })
                } else {
                    let remaining = self.data.to_vec();
                    self.data = &[];
                    Some(TcpOption::Unknown { kind, data: remaining })
                }
            }
        }
    }
}

/// Zero-copy TCP packet parser.
#[derive(Debug, Clone)]
pub struct TcpPacket<'a> {
    buf: &'a [u8],
}

impl<'a> TcpPacket<'a> {
    pub fn new(buf: &'a [u8]) -> Option<Self> {
        if buf.len() < TCP_MIN_HEADER_LEN {
            return None;
        }
        let data_offset = (buf[12] >> 4) as usize * 4;
        if data_offset < TCP_MIN_HEADER_LEN || buf.len() < data_offset {
            return None;
        }
        Some(Self { buf })
    }

    #[inline]
    pub fn source_port(&self) -> u16 {
        read_u16be(&self.buf[..2])
    }

    #[inline]
    pub fn destination_port(&self) -> u16 {
        read_u16be(&self.buf[2..4])
    }

    #[inline]
    pub fn sequence(&self) -> u32 {
        read_u32be(&self.buf[4..8])
    }

    #[inline]
    pub fn ack_number(&self) -> u32 {
        read_u32be(&self.buf[8..12])
    }

    #[inline]
    pub fn data_offset(&self) -> u8 {
        self.buf[12] >> 4
    }

    #[inline]
    pub fn flags(&self) -> u8 {
        self.buf[13] & 0x3F
    }

    #[inline]
    pub fn fin(&self) -> bool {
        self.flags() & FLAG_FIN != 0
    }

    #[inline]
    pub fn syn(&self) -> bool {
        self.flags() & FLAG_SYN != 0
    }

    #[inline]
    pub fn rst(&self) -> bool {
        self.flags() & FLAG_RST != 0
    }

    #[inline]
    pub fn psh(&self) -> bool {
        self.flags() & FLAG_PSH != 0
    }

    #[inline]
    pub fn ack(&self) -> bool {
        self.flags() & FLAG_ACK != 0
    }

    #[inline]
    pub fn urg(&self) -> bool {
        self.flags() & FLAG_URG != 0
    }

    #[inline]
    pub fn window(&self) -> u16 {
        read_u16be(&self.buf[14..16])
    }

    #[inline]
    pub fn checksum(&self) -> u16 {
        read_u16be(&self.buf[16..18])
    }

    #[inline]
    pub fn urgent_pointer(&self) -> u16 {
        read_u16be(&self.buf[18..20])
    }

    /// TCP options (if data_offset > 5).
    pub fn options(&self) -> TcpOptionsIter<'a> {
        let hdr_len = self.header_length();
        if hdr_len > TCP_MIN_HEADER_LEN {
            TcpOptionsIter::new(&self.buf[TCP_MIN_HEADER_LEN..hdr_len])
        } else {
            TcpOptionsIter::new(&[])
        }
    }

    /// Payload after the TCP header.
    #[inline]
    pub fn payload(&self) -> &'a [u8] {
        &self.buf[self.header_length()..]
    }

    #[inline]
    pub fn header_length(&self) -> usize {
        self.data_offset() as usize * 4
    }

    /// Verify the TCP checksum (includes IPv4 pseudo-header).
    pub fn verify_checksum(&self, src: Ipv4Addr, dst: Ipv4Addr) -> bool {
        pseudo_header_checksum(
            &src.octets(),
            &dst.octets(),
            6, // TCP protocol number
            &self.buf[..self.header_length() + self.payload().len()],
        ) == 0
    }
}

// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------

pub struct TcpPacketBuilder {
    buf: Vec<u8>,
    options: Vec<u8>,
    payload: Option<Vec<u8>>,
}

impl Default for TcpPacketBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl TcpPacketBuilder {
    pub fn new() -> Self {
        let mut buf = vec![0u8; TCP_MIN_HEADER_LEN];
        buf[12] = 0x50; // data_offset = 5, reserved
        Self { buf, options: Vec::new(), payload: None }
    }

    pub fn source_port(mut self, port: u16) -> Self {
        write_u16be(&mut self.buf[..2], port);
        self
    }

    pub fn destination_port(mut self, port: u16) -> Self {
        write_u16be(&mut self.buf[2..4], port);
        self
    }

    pub fn sequence(mut self, seq: u32) -> Self {
        write_u32be(&mut self.buf[4..8], seq);
        self
    }

    pub fn ack_number(mut self, ack: u32) -> Self {
        write_u32be(&mut self.buf[8..12], ack);
        self
    }

    pub fn window(mut self, w: u16) -> Self {
        write_u16be(&mut self.buf[14..16], w);
        self
    }

    pub fn urgent_pointer(mut self, up: u16) -> Self {
        write_u16be(&mut self.buf[18..20], up);
        self
    }

    pub fn syn(mut self, on: bool) -> Self {
        if on { self.buf[13] |= FLAG_SYN; } else { self.buf[13] &= !FLAG_SYN; }
        self
    }

    pub fn ack(mut self, on: bool) -> Self {
        if on { self.buf[13] |= FLAG_ACK; } else { self.buf[13] &= !FLAG_ACK; }
        self
    }

    pub fn fin(mut self, on: bool) -> Self {
        if on { self.buf[13] |= FLAG_FIN; } else { self.buf[13] &= !FLAG_FIN; }
        self
    }

    pub fn rst(mut self, on: bool) -> Self {
        if on { self.buf[13] |= FLAG_RST; } else { self.buf[13] &= !FLAG_RST; }
        self
    }

    pub fn psh(mut self, on: bool) -> Self {
        if on { self.buf[13] |= FLAG_PSH; } else { self.buf[13] &= !FLAG_PSH; }
        self
    }

    pub fn urg(mut self, on: bool) -> Self {
        if on { self.buf[13] |= FLAG_URG; } else { self.buf[13] &= !FLAG_URG; }
        self
    }

    /// Add a TCP option as raw bytes (kind + length + data).
    pub fn add_option(mut self, data: &[u8]) -> Self {
        self.options.extend_from_slice(data);
        self
    }

    /// Convenience: add MSS option.
    pub fn mss(mut self, mss: u16) -> Self {
        self.options.push(OPT_MSS);
        self.options.push(4);
        self.options.extend_from_slice(&mss.to_be_bytes());
        self
    }

    /// Convenience: add Window Scale option.
    pub fn window_scale(mut self, shift: u8) -> Self {
        self.options.push(OPT_WINDOW_SCALE);
        self.options.push(3);
        self.options.push(shift);
        self
    }

    /// Convenience: add SACK Permitted option.
    pub fn sack_permitted(mut self) -> Self {
        self.options.push(OPT_SACK_PERMITTED);
        self.options.push(2);
        self
    }

    /// Convenience: add Timestamp option.
    pub fn timestamp(mut self, ts_val: u32, ts_ecr: u32) -> Self {
        self.options.push(OPT_TIMESTAMP);
        self.options.push(10);
        self.options.extend_from_slice(&ts_val.to_be_bytes());
        self.options.extend_from_slice(&ts_ecr.to_be_bytes());
        self
    }

    pub fn payload(mut self, data: &[u8]) -> Self {
        self.payload = Some(data.to_vec());
        self
    }

    /// Build the TCP packet, computing the checksum (IPv4 pseudo-header).
    pub fn build(mut self, src: Ipv4Addr, dst: Ipv4Addr) -> Vec<u8> {
        // Pad options to 4-byte boundary with NoOps
        while !self.options.len().is_multiple_of(4) {
            self.options.push(OPT_NOOP);
        }
        // Update data_offset
        let total_hdr_words = (TCP_MIN_HEADER_LEN + self.options.len()) / 4;
        self.buf[12] = (total_hdr_words as u8) << 4;

        // Zero checksum
        self.buf[16] = 0;
        self.buf[17] = 0;

        let mut packet = self.buf;
        if !self.options.is_empty() {
            packet.extend_from_slice(&self.options);
        }
        if let Some(ref p) = self.payload {
            packet.extend_from_slice(p);
        }

        let csum = pseudo_header_checksum(
            &src.octets(),
            &dst.octets(),
            6, // TCP
            &packet,
        );
        write_u16be(&mut packet[16..18], csum);

        packet
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // Minimal TCP header: src=1234, dst=80, seq=1, ack=0, data_offset=5, flags=SYN
    fn sample_tcp_syn() -> Vec<u8> {
        let mut data = vec![0u8; TCP_MIN_HEADER_LEN];
        write_u16be(&mut data[..2], 1234);
        write_u16be(&mut data[2..4], 80);
        write_u32be(&mut data[4..8], 1);      // seq
        write_u32be(&mut data[8..12], 0);      // ack
        data[12] = 0x50; // data_offset=5
        data[13] = FLAG_SYN;
        write_u16be(&mut data[14..16], 65535); // window
        data
    }

    #[test]
    fn parse_tcp_no_options() {
        let data = sample_tcp_syn();
        let pkt = TcpPacket::new(&data).unwrap();
        assert_eq!(pkt.source_port(), 1234);
        assert_eq!(pkt.destination_port(), 80);
        assert_eq!(pkt.sequence(), 1);
        assert_eq!(pkt.ack_number(), 0);
        assert_eq!(pkt.data_offset(), 5);
        assert_eq!(pkt.header_length(), 20);
        assert!(pkt.syn());
        assert!(!pkt.ack());
        assert!(!pkt.fin());
        assert!(!pkt.rst());
        assert_eq!(pkt.window(), 65535);
    }

    #[test]
    fn parse_tcp_too_short() {
        assert!(TcpPacket::new(&[]).is_none());
        assert!(TcpPacket::new(&[0u8; 19]).is_none());
        // 20 bytes with data_offset=5 is valid
        let mut d = [0u8; 20];
        d[12] = 0x50;
        assert!(TcpPacket::new(&d).is_some());
    }

    #[test]
    fn parse_tcp_data_offset_exceeds_buffer() {
        let mut data = vec![0u8; 22];
        data[12] = 0x60; // data_offset=6 (24 bytes)
        assert!(TcpPacket::new(&data).is_none());
    }

    #[test]
    fn tcp_options_mss_and_window_scale() {
        let mut data = sample_tcp_syn();
        // MSS: kind=2, len=4, mss=1460
        data.extend_from_slice(&[OPT_MSS, 4, 0x05, 0xB4]);
        // Window Scale: kind=3, len=3, shift=7
        data.extend_from_slice(&[OPT_WINDOW_SCALE, 3, 7]);
        // Pad to 4-byte boundary with NoOps (1 byte padding)
        data.push(OPT_NOOP);
        // data_offset: (20 + 8) / 4 = 7
        data[12] = 0x70;

        let pkt = TcpPacket::new(&data).unwrap();
        assert_eq!(pkt.data_offset(), 7);
        assert_eq!(pkt.header_length(), 28);

        let opts: Vec<_> = pkt.options().collect();
        assert_eq!(opts.len(), 3); // MSS, WindowScale, NoOp
        match &opts[0] {
            TcpOption::MaximumSegmentSize(mss) => assert_eq!(*mss, 1460),
            _ => panic!("expected MSS"),
        }
        match &opts[1] {
            TcpOption::WindowScale(shift) => assert_eq!(*shift, 7),
            _ => panic!("expected WindowScale"),
        }
    }

    #[test]
    fn tcp_options_timestamp() {
        let mut data = sample_tcp_syn();
        data.extend_from_slice(&[OPT_TIMESTAMP, 10,
            0x00, 0x00, 0x00, 0x01,  // ts_val
            0x00, 0x00, 0x00, 0x02,  // ts_ecr
        ]);
        // Pad to 4-byte boundary (10 + 2 = 12)
        data.push(OPT_NOOP);
        data.push(OPT_NOOP);
        data[12] = 0x80; // data_offset=8 (32 bytes)

        let pkt = TcpPacket::new(&data).unwrap();
        let opts: Vec<_> = pkt.options().collect();
        match &opts[0] {
            TcpOption::Timestamp { ts_val, ts_ecr } => {
                assert_eq!(*ts_val, 1);
                assert_eq!(*ts_ecr, 2);
            }
            _ => panic!("expected Timestamp"),
        }
    }

    #[test]
    fn tcp_options_sack() {
        let mut data = sample_tcp_syn();
        // SACK: kind=5, len=18, 2 blocks (each 8 bytes: left_edge + right_edge)
        data.extend_from_slice(&[OPT_SACK, 18]);
        // Block 1: left=100, right=200
        data.extend_from_slice(&100u32.to_be_bytes());
        data.extend_from_slice(&200u32.to_be_bytes());
        // Block 2: left=300, right=400
        data.extend_from_slice(&300u32.to_be_bytes());
        data.extend_from_slice(&400u32.to_be_bytes());
        // Pad to 4-byte boundary (18 + 2 = 20)
        data.push(OPT_NOOP);
        data.push(OPT_NOOP);
        data[12] = 0xA0; // data_offset=10 (40 bytes)

        let pkt = TcpPacket::new(&data).unwrap();
        let opts: Vec<_> = pkt.options().collect();
        match &opts[0] {
            TcpOption::Sack(blocks) => {
                assert_eq!(blocks.len(), 2);
                assert_eq!(blocks[0], (100, 200));
                assert_eq!(blocks[1], (300, 400));
            }
            _ => panic!("expected SACK"),
        }
    }

    #[test]
    fn tcp_sack_permitted() {
        let mut data = sample_tcp_syn();
        data.extend_from_slice(&[OPT_SACK_PERMITTED, 2]);
        data.push(OPT_NOOP);
        data.push(OPT_NOOP);
        data[12] = 0x60; // data_offset=6

        let pkt = TcpPacket::new(&data).unwrap();
        let opts: Vec<_> = pkt.options().collect();
        assert!(matches!(opts[0], TcpOption::SackPermitted));
    }

    #[test]
    fn tcp_build_and_verify_checksum() {
        let src = Ipv4Addr::new(10, 0, 0, 1);
        let dst = Ipv4Addr::new(10, 0, 0, 2);
        let pkt_bytes = TcpPacketBuilder::new()
            .source_port(12345)
            .destination_port(80)
            .sequence(1000)
            .syn(true)
            .window(65535)
            .mss(1460)
            .build(src, dst);

        let pkt = TcpPacket::new(&pkt_bytes).unwrap();
        assert!(pkt.syn());
        assert_eq!(pkt.source_port(), 12345);
        assert_eq!(pkt.destination_port(), 80);
        assert_eq!(pkt.sequence(), 1000);
        assert!(pkt.verify_checksum(src, dst));
    }

    #[test]
    fn tcp_build_roundtrip_with_options() {
        let src = Ipv4Addr::new(192, 168, 1, 1);
        let dst = Ipv4Addr::new(192, 168, 1, 2);
        let pkt_bytes = TcpPacketBuilder::new()
            .source_port(54321)
            .destination_port(443)
            .sequence(0x12345678)
            .ack_number(0x87654321)
            .syn(true)
            .ack(true)
            .window(8192)
            .mss(1460)
            .window_scale(7)
            .sack_permitted()
            .timestamp(0x100, 0x200)
            .payload(&[0x01, 0x02, 0x03])
            .build(src, dst);

        let pkt = TcpPacket::new(&pkt_bytes).unwrap();
        assert_eq!(pkt.source_port(), 54321);
        assert_eq!(pkt.destination_port(), 443);
        assert_eq!(pkt.sequence(), 0x12345678);
        assert_eq!(pkt.ack_number(), 0x87654321);
        assert!(pkt.syn());
        assert!(pkt.ack());
        assert_eq!(pkt.window(), 8192);
        assert_eq!(pkt.payload(), &[0x01, 0x02, 0x03]);
        assert!(pkt.verify_checksum(src, dst));

        // Check options
        let opts: Vec<_> = pkt.options().collect();
        assert!(opts.iter().any(|o| matches!(o, TcpOption::MaximumSegmentSize(1460))));
        assert!(opts.iter().any(|o| matches!(o, TcpOption::WindowScale(7))));
        assert!(opts.iter().any(|o| matches!(o, TcpOption::SackPermitted)));
        assert!(opts.iter().any(|o| matches!(o, TcpOption::Timestamp { ts_val: 0x100, ts_ecr: 0x200 })));
    }

    #[test]
    fn tcp_end_of_list_option() {
        let mut data = sample_tcp_syn();
        data.push(OPT_END); // End of list
        data.extend_from_slice(&[OPT_MSS, 4, 0x05, 0xB4]); // should not be parsed
        data.push(OPT_NOOP);
        data.push(OPT_NOOP);
        data[12] = 0x60;

        let pkt = TcpPacket::new(&data).unwrap();
        let opts: Vec<_> = pkt.options().collect();
        assert_eq!(opts.len(), 1);
        assert!(matches!(opts[0], TcpOption::EndOfList));
    }
}