net_file/translator/
pcap_translator.rs

1use subprocess::{Exec, Redirection};
2
3use super::translator::Translator;
4use crate::file::files::Files;
5
6pub struct PcapTranslator;
7
8const TSHARK_APP_NAME: &str = "tshark";
9const TSHARK_CMD: &str = "TZ=UTC tshark -V --no-duplicate-keys -Tjson -n -r -";
10
11impl Translator for PcapTranslator {
12    type Input = Vec<u8>;
13    type Output = Vec<u8>;
14
15    /// https://tshark.dev/capture/tshark/
16    /// Translate pcap file to json format
17    ///
18    /// The behavior experiencing with tshark may be due to differences in the default system time zone between Linux and macOS.
19    //
20    // On Linux, tshark (and the underlying libpcap library) will use UTC as the default time zone unless otherwise specified. On macOS, the default time zone is typically set to the system time zone. This means that if your system time zone is not set to UTC, tshark will display timestamps in your local time zone by default.
21    //
22    // To ensure that tshark behaves consistently across different platforms, will explicitly specify a specific time zone using the TZ=UTC environment variable.
23    // This sets the TZ environment variable to UTC before running tshark, which will force tshark to use UTC as the time zone.
24    ///
25    /// # Arguments
26    ///
27    /// * `buf`:
28    ///
29    /// returns: String
30    ///
31    /// # Examples
32    ///
33    /// ```
34    ///
35    /// ```
36    fn translate(buf: Vec<u8>) -> Vec<u8> {
37        if !Files::which(TSHARK_APP_NAME).success() {
38            panic!("An application {} is not installed", TSHARK_APP_NAME)
39        }
40
41        Exec::cmd("sh")
42            .args(&["-c"])
43            .arg(TSHARK_CMD)
44            .stdin(buf)
45            .stdout(Redirection::Pipe)
46            .capture().unwrap()
47            .stdout
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use crate::file::files::Files;
54    use crate::test_resources;
55
56    use super::*;
57
58    #[test]
59    fn expected_translate_arp_packet() {
60        let pcap_buffer = Files::read_vector(test_resources!("captures/arp.pcap"));
61        let json_result = PcapTranslator::translate(pcap_buffer);
62
63        let json_buffer = Files::read_vector(test_resources!("captures/arp.json"));
64
65        assert_eq!(std::str::from_utf8(&json_result).unwrap(), std::str::from_utf8(&json_buffer).unwrap());
66    }
67
68    #[test]
69    fn expected_translate_dhcp_packet() {
70        let pcap_buffer = Files::read_vector(test_resources!("captures/dhcp.pcap"));
71        let json_buffer = Files::read_vector(test_resources!("captures/dhcp.json"));
72
73        let json_result = PcapTranslator::translate(pcap_buffer);
74
75        assert_eq!(std::str::from_utf8(&json_result).unwrap(), std::str::from_utf8(&json_buffer).unwrap());
76    }
77}