net_file/translator/packet.rs
1use std::fmt;
2use std::ops::Deref;
3
4use serde_derive::Serialize;
5
6// https://tshark.dev/formats/pcap_deconstruction/
7// Packet header
8// typedef struct pcaprec_hdr_s {
9// guint32 ts_sec; /* timestamp seconds */
10// guint32 ts_usec; /* timestamp microseconds */
11// guint32 incl_len; /* number of octets of packet saved in file */
12// guint32 orig_len; /* actual length of packet */
13// } pcaprec_hdr_t;
14// Packet header size = 16 bytes
15#[derive(Serialize)]
16pub struct Packet {
17 // ts_sec = 4 bytes (85 AD C7 50) *This is the number of seconds since the start of 1970, also known as Unix Epoch
18 tv_sec: u32,
19 // ts_usec = 4 bytes (AC 97 05 00) *microseconds part of the time at which the packet was captured
20 tv_usec: u32,
21 // The number of bytes of the packet that are available from the capture
22 // incl_len = 4 bytes (E0 04 00 00) = 1248 *contains the size of the saved packet data in our file in bytes (following the header)
23 caplen: u32,
24 // The length of the packet, in bytes (which might be more than the number of bytes available
25 // from the capture, if the length of the packet is larger than the maximum number of bytes to
26 // capture)
27 // orig_len = 4 bytes (E0 04 00 00) *Both fields' value is same here, but these may have different values in cases where we set the maximum packet length (whose value is 65535 in the global header of our file) to a smaller size.
28 len: u32,
29 #[serde(skip_serializing)]
30 data: Vec<u8>,
31}
32
33impl From<pcap::Packet<'_>> for Packet {
34 fn from(pcap_packet: pcap::Packet) -> Self {
35 Packet {
36 tv_sec: pcap_packet.header.ts.tv_sec as u32,
37 tv_usec: pcap_packet.header.ts.tv_usec as u32,
38 caplen: pcap_packet.header.caplen,
39 len: pcap_packet.header.len,
40 data: pcap_packet.data.to_vec(),
41 }
42 }
43}
44
45impl fmt::Debug for Packet {
46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47 write!(
48 f,
49 "Packet {{ ts: {}.{:06}, caplen: {}, len: {}, data: {:?}, binary: {:?} }}",
50 self.tv_sec, self.tv_usec, self.caplen, self.len, self.data, self.to_bytes()
51 )
52 }
53}
54
55
56impl Packet {
57 pub fn to_bytes(&self) -> Vec<u8> {
58 let mut bytes = bincode::serialize(&self).unwrap();
59 bytes.append(&mut self.data.deref().to_vec());
60
61 bytes
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use pcap::Capture;
68 use crate::test_resources;
69
70 use super::*;
71
72 #[test]
73 fn expected_encode_file() {
74 let mut capture = Capture::from_file(test_resources!("captures/arp.pcap")).unwrap();
75 let packet = capture.next_packet().unwrap();
76
77 let packet = Packet::from(packet);
78 println!("{:?}", packet);
79
80 assert_eq!(46, packet.to_bytes().len());
81 }
82}