pcapture 0.3.27

A Rust Library about Traffic Capture
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
#[cfg(feature = "pcap")]
use bitcode::Decode;
#[cfg(feature = "pcap")]
use bitcode::Encode;
#[cfg(feature = "pcap")]
use byteorder::BigEndian;
#[cfg(feature = "pcap")]
use byteorder::LittleEndian;
#[cfg(feature = "pcap")]
use byteorder::ReadBytesExt;
#[cfg(feature = "pcap")]
use byteorder::WriteBytesExt;
#[cfg(feature = "pcap")]
use serde::Deserialize;
#[cfg(feature = "pcap")]
use serde::Serialize;
#[cfg(feature = "pcap")]
use std::fs::File;
#[cfg(feature = "pcap")]
use std::io::Read;
#[cfg(feature = "pcap")]
use std::io::Write;
#[cfg(all(feature = "pcap", feature = "libpnet"))]
use std::time::SystemTime;
#[cfg(all(feature = "pcap", feature = "libpnet"))]
use std::time::UNIX_EPOCH;
#[cfg(feature = "pcap")]
use strum::IntoEnumIterator;
#[cfg(feature = "pcap")]
use strum_macros::EnumIter;
#[cfg(feature = "pcap")]
use strum_macros::EnumString;

#[cfg(feature = "pcap")]
use crate::PcapByteOrder;
#[cfg(feature = "pcap")]
use crate::error::PcaptureError;

#[cfg(feature = "pcap")]
#[repr(u32)]
#[derive(Debug, Clone, Copy, EnumString, EnumIter, Serialize, Deserialize, Encode, Decode)]
pub enum LinkType {
    NULL = 0,
    ETHERNET = 1,
    AX25 = 3,
    IEEE8025 = 6,
    ARCNETBSD = 7,
    SLIP = 8,
    PPP = 9,
    FDDI = 10,
    PPPHDLC = 50,
    PPPETHER = 51,
    ATMRFC1483 = 100,
    RAW = 101,
    CHDLC = 104,
    IEEE80211 = 105,
    FRELAY = 107,
    LOOP = 108,
    LINUXSLL = 113,
    LTALK = 114,
    PFLOG = 117,
    IEEE80211PRISM = 119,
    IPOVERFC = 122,
    SUNATM = 123,
    IEEE80211RADIOTAP = 127,
    ARCNETLINUX = 129,
    APPLEIPOVERIEEE1394 = 138,
    MTP2WITHPHDR = 139,
    MTP2 = 140,
    MTP3 = 141,
    SCCP = 142,
    DOCSIS = 143,
    LINUXIRDA = 144,
    IEEE80211AVS = 163,
    BACNETMSTP = 165,
    PPPPPPD = 166,
    GPRSLLC = 169,
    GPFT = 170,
    GPFF = 171,
    LINUXLAPD = 177,
    MFR = 182,
    BLUETOOTHHCIH4 = 187,
    USBLINUX = 189,
    PPI = 192,
    IEEE802154WITHFCS = 195,
    SITA = 196,
    ERF = 197,
    BLUETOOTHHCIH4WITHPHDR = 201,
    AX25KISS = 202,
    LAPD = 203,
    PPPWITHDIR = 204,
    CHDLCWITHDIR = 205,
    FRELAYWITHDIR = 206,
    LAPBWITHDIR = 207,
    IPMBLINUX = 209,
    IEEE802154NONASKPHY = 215,
    USBLINUXMMAPPED = 220,
    FC2 = 224,
    FC2WITHFRAMEDELIMS = 225,
    IPNET = 226,
    CANSOCKETCAN = 227,
    IPV4 = 228,
    IPV6 = 229,
    IEEE802154NOFCS = 230,
    DBUS = 231,
    DVBCI = 235,
    MUX27010 = 236,
    STANAG5066DPDU = 237,
    NFLOG = 239,
    NETANALYZER = 240,
    NETANALYZERTRANSPARENT = 241,
    IPOIB = 242,
    MPEG2TS = 243,
    NG40 = 244,
    NFCLLCP = 245,
    INFINIBAND = 247,
    SCTP = 248,
    USBPCAP = 249,
    RTACSERIAL = 250,
    BLUETOOTHLELL = 251,
    WIRESHARKUPPERPDU = 252,
    NETLINK = 253,
    BLUETOOTHLINUXMONITOR = 254,
    BLUETOOTHBREDRBB = 255,
    BLUETOOTHLELLWITHPHDR = 256,
    PROFIBUSDL = 257,
    PKTAP = 258,
    EPON = 259,
    IPMIHPM2 = 260,
    ZWAVER1R2 = 261,
    ZWAVER3 = 262,
    WATTSTOPPERDLM = 263,
    ISO14443 = 264,
    RDS = 265,
    USBDARWIN = 266,
    SDLC = 268,
    LORATAP = 270,
    VSOCK = 271,
    NORDICBLE = 272,
    DOCSIS31XRA31 = 273,
    ETHERNETMPACKET = 274,
    DISPLAYPORTAUX = 275,
    LINUXSLL2 = 276,
    OPENVIZSLA = 278,
    EBHSCR = 279,
    VPPDISPATCH = 280,
    DSATAGBRCM = 281,
    DSATAGBRCMPREPEND = 282,
    IEEE802154TAP = 283,
    DSATAGDSA = 284,
    DSATAGEDSA = 285,
    ELEE = 286,
    WAVESERIAL = 287,
    USB20 = 288,
    ATSCALP = 289,
}

#[cfg(feature = "pcap")]
impl LinkType {
    pub fn to_u32(self) -> u32 {
        self as u32
    }
    pub fn from_u32(value: u32) -> Option<Self> {
        Self::iter().find(|&e| e.to_u32() == value)
    }
}

// File Header
// from https://www.ietf.org/archive/id/draft-gharris-opsawg-pcap-01.html#name-file-header
//
//                         1                   2                   3
//     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  0 |                          Magic Number                         |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  4 |          Major Version        |         Minor Version         |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  8 |                           Reserved1                           |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// 12 |                           Reserved2                           |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// 16 |                            SnapLen                            |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// 20 | FCS |f|0 0 0 0 0 0 0 0 0 0 0 0|         LinkType              |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

#[cfg(feature = "pcap")]
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode)]
pub struct FileHeader {
    /// Magic Number (32 bits):
    /// An unsigned magic number, whose value is either the hexadecimal number 0xA1B2C3D4 or the hexadecimal number 0xA1B23C4D.
    /// If the value is 0xA1B2C3D4, time stamps in Packet Records (see Figure 2) are in seconds and microseconds;
    /// if it is 0xA1B23C4D, time stamps in Packet Records are in seconds and nanoseconds.
    pub magic_number: u32,
    /// Major Version (16 bits):
    /// An unsigned value, giving the number of the current major version of the format.
    /// The value for the current version of the format is 2.
    pub major_version: u16,
    /// Minor Version (16 bits):
    /// An unsigned value, giving the number of the current minor version of the format.
    /// The value is for the current version of the format is 4.
    pub minor_version: u16,
    /// Reserved1 (32 bits):
    /// Not used - SHOULD be filled with 0 by pcap file writers, and MUST be ignored by pcap file readers.
    reserved1: u32,
    /// Reserved2 (32 bits):
    /// Not used - SHOULD be filled with 0 by pcap file writers, and MUST be ignored by pcap file readers.
    reserved2: u32,
    /// SnapLen (32 bits):
    /// An unsigned value indicating the maximum number of octets captured from each packet.
    /// The portion of each packet that exceeds this value will not be stored in the file.
    pub snaplen: u32,
    /// !!! Note: for wireshark, the Frame Cyclic Sequence (FCS) part is not used, and LinkType is 32 bits.
    /// LinkType (16 bits):
    /// A 16-bit unsigned value that defines the link layer type of packets in the file.
    /// This field is defined in the Section 8.1 IANA registry.
    pub linktype: LinkType,
}

#[cfg(feature = "pcap")]
impl FileHeader {
    pub fn new(if_name: &str) -> Self {
        let linktype = if if_name == "any" {
            LinkType::LINUXSLL
        } else {
            LinkType::ETHERNET
        };
        Self {
            // native order
            magic_number: 0xa1b2c3d4,
            major_version: 2,
            minor_version: 4,
            reserved1: 0,
            reserved2: 0,
            // init value, change when packet recv
            snaplen: 0,
            linktype,
        }
    }
    pub fn write(&self, fs: &mut File, pbo: PcapByteOrder) -> Result<(), PcaptureError> {
        match pbo {
            PcapByteOrder::LittleEndian | PcapByteOrder::WiresharkDefault => {
                fs.write_u32::<LittleEndian>(self.magic_number)?;
                fs.write_u16::<LittleEndian>(self.major_version)?;
                fs.write_u16::<LittleEndian>(self.minor_version)?;
                fs.write_u32::<LittleEndian>(self.reserved1)?;
                fs.write_u32::<LittleEndian>(self.reserved2)?;
                fs.write_u32::<LittleEndian>(self.snaplen)?;
                fs.write_u32::<LittleEndian>(self.linktype.to_u32())?;
            }
            PcapByteOrder::BigEndian => {
                fs.write_u32::<BigEndian>(self.magic_number)?;
                fs.write_u16::<BigEndian>(self.major_version)?;
                fs.write_u16::<BigEndian>(self.minor_version)?;
                fs.write_u32::<BigEndian>(self.reserved1)?;
                fs.write_u32::<BigEndian>(self.reserved2)?;
                fs.write_u32::<BigEndian>(self.snaplen)?;
                fs.write_u32::<BigEndian>(self.linktype.to_u32())?;
            }
        }
        Ok(())
    }
    pub fn read(fs: &mut File, pbo: PcapByteOrder) -> Result<Self, PcaptureError> {
        match pbo {
            PcapByteOrder::LittleEndian | PcapByteOrder::WiresharkDefault => {
                let magic_number = fs.read_u32::<LittleEndian>()?;
                let major_version = fs.read_u16::<LittleEndian>()?;
                let minor_version = fs.read_u16::<LittleEndian>()?;
                let reserved1 = fs.read_u32::<LittleEndian>()?;
                let reserved2 = fs.read_u32::<LittleEndian>()?;
                let snaplen = fs.read_u32::<LittleEndian>()?;
                let linktype_value = fs.read_u32::<LittleEndian>()?;
                let linktype = match LinkType::from_u32(linktype_value) {
                    Some(l) => l,
                    None => {
                        return Err(PcaptureError::UnknownLinkType {
                            linktype: linktype_value,
                        });
                    }
                };
                Ok(Self {
                    magic_number,
                    major_version,
                    minor_version,
                    reserved1,
                    reserved2,
                    snaplen,
                    linktype,
                })
            }
            PcapByteOrder::BigEndian => {
                let magic_number = fs.read_u32::<BigEndian>()?;
                let major_version = fs.read_u16::<BigEndian>()?;
                let minor_version = fs.read_u16::<BigEndian>()?;
                let reserved1 = fs.read_u32::<BigEndian>()?;
                let reserved2 = fs.read_u32::<BigEndian>()?;
                let snaplen = fs.read_u32::<BigEndian>()?;
                let linktype_value = fs.read_u32::<BigEndian>()?;
                let linktype = match LinkType::from_u32(linktype_value) {
                    Some(l) => l,
                    None => {
                        return Err(PcaptureError::UnknownLinkType {
                            linktype: linktype_value,
                        });
                    }
                };
                Ok(Self {
                    magic_number,
                    major_version,
                    minor_version,
                    reserved1,
                    reserved2,
                    snaplen,
                    linktype,
                })
            }
        }
    }
}

// Packet Record
// from https://www.ietf.org/archive/id/draft-gharris-opsawg-pcap-01.html#name-packet-record
//                         1                   2                   3
//     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  0 |                      Timestamp (Seconds)                      |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  4 |            Timestamp (Microseconds or nanoseconds)            |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  8 |                    Captured Packet Length                     |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// 12 |                    Original Packet Length                     |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// 16 /                                                               /
//    /                          Packet Data                          /
//    /                        variable length                        /
//    /                                                               /
//    +---------------------------------------------------------------+

#[cfg(feature = "pcap")]
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode)]
pub struct PacketRecord {
    /// Timestamp (Seconds) and Timestamp (Microseconds or nanoseconds):
    /// Seconds and fraction of a seconds values of a timestamp.
    pub ts_sec: u32,
    pub ts_usec: u32,
    /// Captured Packet Length (32 bits):
    /// An unsigned value that indicates the number of octets captured from the packet
    /// (i.e. the length of the Packet Data field).
    pub captured_packet_length: u32,
    /// Original Packet Length (32 bits):
    /// An unsigned value that indicates the actual length of the packet when it was transmitted on the network.
    /// It can be different from the Captured Packet Length if the packet has been truncated by the capture process.
    pub original_packet_length: u32,
    /// Packet Data:
    /// The data coming from the network, including link-layer headers.
    /// The actual length of this field is Captured Packet Length.
    pub packet_data: Vec<u8>,
}

#[cfg(feature = "pcap")]
impl PacketRecord {
    #[cfg(feature = "libpnet")]
    pub fn new(packet_data: &[u8], snaplen: usize) -> Result<Self, PcaptureError> {
        let packet_slice = if packet_data.len() > snaplen {
            &packet_data[..snaplen]
        } else {
            packet_data
        };
        let dura = SystemTime::now().duration_since(UNIX_EPOCH)?;
        // let (ts_sec, ts_usec) = if magic_number == 0xa1b2c3d4 {
        //     let ts_sec = dura.as_secs() as u32;
        //     let ts_usec = dura.subsec_micros();
        //     (ts_sec, ts_usec)
        // } else {
        //     let ts_sec = dura.as_secs() as u32;
        //     let ts_usec = dura.subsec_nanos();
        //     (ts_sec, ts_usec)
        // };
        let ts_sec = dura.as_secs() as u32;
        let ts_usec = dura.subsec_micros();
        let captured_packet_length = packet_slice.len() as u32;
        let original_packet_length = packet_data.len() as u32;
        Ok(Self {
            ts_sec,
            ts_usec,
            captured_packet_length,
            original_packet_length,
            packet_data: packet_data.to_vec(),
        })
    }
    #[cfg(feature = "libpcap")]
    pub fn new(
        packet_data: &[u8],
        snaplen: usize,
        ts_sec: u32,
        ts_usec: u32,
    ) -> Result<Self, PcaptureError> {
        let packet_slice = if packet_data.len() > snaplen {
            &packet_data[..snaplen]
        } else {
            packet_data
        };
        // let (ts_sec, ts_usec) = if magic_number == 0xa1b2c3d4 {
        //     let ts_sec = dura.as_secs() as u32;
        //     let ts_usec = dura.subsec_micros();
        //     (ts_sec, ts_usec)
        // } else {
        //     let ts_sec = dura.as_secs() as u32;
        //     let ts_usec = dura.subsec_nanos();
        //     (ts_sec, ts_usec)
        // };
        let captured_packet_length = packet_slice.len() as u32;
        let original_packet_length = packet_data.len() as u32;
        Ok(Self {
            ts_sec,
            ts_usec,
            captured_packet_length,
            original_packet_length,
            packet_data: packet_data.to_vec(),
        })
    }
    pub fn write(&self, fs: &mut File, pbo: PcapByteOrder) -> Result<(), PcaptureError> {
        match pbo {
            PcapByteOrder::LittleEndian | PcapByteOrder::WiresharkDefault => {
                fs.write_u32::<LittleEndian>(self.ts_sec)?;
                fs.write_u32::<LittleEndian>(self.ts_usec)?;
                fs.write_u32::<LittleEndian>(self.captured_packet_length)?;
                fs.write_u32::<LittleEndian>(self.original_packet_length)?;
                fs.write_all(&self.packet_data)?;
            }
            PcapByteOrder::BigEndian => {
                fs.write_u32::<BigEndian>(self.ts_sec)?;
                fs.write_u32::<BigEndian>(self.ts_usec)?;
                fs.write_u32::<BigEndian>(self.captured_packet_length)?;
                fs.write_u32::<BigEndian>(self.original_packet_length)?;
                fs.write_all(&self.packet_data)?;
            }
        }
        Ok(())
    }
    pub fn read(fs: &mut File, pbo: PcapByteOrder) -> Result<Self, PcaptureError> {
        let (ts_sec, ts_usec, captured_packet_length, original_packet_length) = match pbo {
            PcapByteOrder::LittleEndian | PcapByteOrder::WiresharkDefault => {
                let ts_sec = fs.read_u32::<LittleEndian>()?;
                let ts_usec = fs.read_u32::<LittleEndian>()?;
                let captured_packet_length = fs.read_u32::<LittleEndian>()?;
                let original_packet_length = fs.read_u32::<LittleEndian>()?;
                (
                    ts_sec,
                    ts_usec,
                    captured_packet_length,
                    original_packet_length,
                )
            }
            PcapByteOrder::BigEndian => {
                let ts_sec = fs.read_u32::<BigEndian>()?;
                let ts_usec = fs.read_u32::<BigEndian>()?;
                let captured_packet_length = fs.read_u32::<BigEndian>()?;
                let original_packet_length = fs.read_u32::<BigEndian>()?;
                (
                    ts_sec,
                    ts_usec,
                    captured_packet_length,
                    original_packet_length,
                )
            }
        };
        let mut data = vec![0u8; captured_packet_length as usize]; // read only capt_len length
        fs.read_exact(&mut data)?;
        Ok(Self {
            ts_sec,
            ts_usec,
            captured_packet_length,
            original_packet_length,
            packet_data: data,
        })
    }
}

#[cfg(feature = "pcap")]
#[repr(C)]
#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode)]
pub struct Pcap {
    pub pbo: PcapByteOrder,
    pub header: FileHeader,
    pub records: Vec<PacketRecord>,
}

#[cfg(feature = "pcap")]
impl Pcap {
    pub fn new(if_name: &str, pbo: PcapByteOrder) -> Self {
        Self {
            pbo,
            header: FileHeader::new(if_name),
            records: Vec::new(),
        }
    }
    pub fn append(&mut self, record: PacketRecord) {
        if record.packet_data.len() as u32 > self.header.snaplen {
            self.header.snaplen = record.packet_data.len() as u32;
        }
        self.records.push(record);
    }
    pub fn write(&self, fs: &mut File) -> Result<(), PcaptureError> {
        self.header.write(fs, self.pbo)?;
        for r in &self.records {
            r.write(fs, self.pbo)?;
        }
        Ok(())
    }
    pub fn write_all(&self, path: &str) -> Result<(), PcaptureError> {
        let mut fs = File::create(path)?;
        Self::write(self, &mut fs)?;
        Ok(())
    }
    pub fn read_all(path: &str, pbo: PcapByteOrder) -> Result<Self, PcaptureError> {
        let mut fs = File::open(path)?;
        let header = FileHeader::read(&mut fs, pbo)?;
        let mut record = Vec::new();
        loop {
            match PacketRecord::read(&mut fs, pbo) {
                Ok(r) => record.push(r),
                Err(e) => match e {
                    PcaptureError::IOError(_) => break, // file end
                    _ => return Err(e),
                },
            }
        }
        Ok(Self {
            pbo,
            header,
            records: record,
        })
    }
}