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
pub enum WriteTarget {
    Log,
    Write(Box<dyn std::io::Write + Send>),
}

pub fn try_extract_from_ip_frame(frame: impl AsRef<[u8]>) -> Option<Vec<u8>> {
    let frame: &[u8] = frame.as_ref();

    if frame.len() > 55 && frame[12..14] == [0x08, 0x00] {
        Some(frame[54..].to_owned())
    } else {
        None
    }
}

#[cfg(feature = "enable")]
static WRITE_TARGET: std::sync::Mutex<WriteTarget> = std::sync::Mutex::new(WriteTarget::Log);

#[allow(unused_variables)]
pub fn set_write_target(wt: WriteTarget) {
    #[cfg(feature = "enable")]
    {
        *WRITE_TARGET.lock().unwrap() = wt;
    }
}

/// Logs location and hash of provided data
#[cfg(feature = "enable")]
#[macro_export]
macro_rules! packet_trace {
    ($location:expr, $payload:block) => {{
        $crate::helpers::do_write($location, $payload);
    }};
}

/// Logs location and hash of provided data
#[cfg(not(feature = "enable"))]
#[macro_export]
macro_rules! packet_trace {
    ($location:expr, $payload:block) => {};
}

/// Logs location and hash of provided data
#[cfg(feature = "enable")]
#[macro_export]
macro_rules! packet_trace_maybe {
    ($location:expr, $maybe_payload:block) => {{
        if let Some(payload) = $maybe_payload {
            $crate::packet_trace!($location, { payload })
        }
    }};
}

/// Logs location and hash of provided data
#[cfg(not(feature = "enable"))]
#[macro_export]
macro_rules! packet_trace_maybe {
    ($location:expr, $maybe_payload:block) => {};
}

/// Date format used for timestamps
pub const DATE_FORMAT_STR: &str = "%Y-%m-%dT%H:%M:%S%.6f%z";

/// Macro internals
///
/// While this module must be public due to the way Rust
/// expands declarative macros, no guarantees are made regarding
/// this module.
#[cfg(feature = "enable")]
pub mod helpers {
    pub fn do_write(location: impl std::fmt::Display, payload: impl AsRef<[u8]>) {
        use crate::{WriteTarget, WRITE_TARGET};

        let sz = payload.as_ref().len();
        let hash = do_hash(payload);
        let ts = ts();

        match &mut *WRITE_TARGET.lock().unwrap() {
            WriteTarget::Log => {
                log::trace!(target: "packet-trace", "{},{:016x},{},{}", location, hash, ts, sz);
            }
            WriteTarget::Write(w) => {
                writeln!(w, "{},{:016x},{},{}", location, hash, ts, sz).unwrap();
            }
        }
    }

    pub fn do_hash(data: impl AsRef<[u8]>) -> u64 {
        use std::hash::Hasher;

        let mut hasher = fxhash::FxHasher64::default();
        hasher.write(data.as_ref());

        hasher.finish()
    }

    pub fn ts() -> String {
        chrono::Utc::now()
            .format(crate::DATE_FORMAT_STR)
            .to_string()
    }
}

#[cfg(test)]
mod test {
    use log::LevelFilter;
    use once_cell::sync::OnceCell;
    use serial_test::serial;
    use std::fmt::Write;
    use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
    use std::sync::{Arc, Mutex};

    #[cfg(feature = "enable")]
    use regex::Regex;

    #[cfg(feature = "enable")]
    use crate::DATE_FORMAT_STR;

    struct StringLog(Arc<Mutex<String>>);

    static LOGGER: OnceCell<StringLog> = OnceCell::new();

    impl StringLog {
        fn new() -> Self {
            StringLog(Arc::new(Mutex::new(String::new())))
        }

        fn global() -> &'static Self {
            let first_init = AtomicBool::new(false);
            let result = LOGGER.get_or_init(|| {
                first_init.store(true, SeqCst);
                Self::new()
            });

            if first_init.load(SeqCst) {
                log::set_logger(StringLog::global()).unwrap();
                log::set_max_level(LevelFilter::Trace);
            }

            result
        }

        fn get_string() -> String {
            Self::global().0.lock().unwrap().clone()
        }

        fn clear() {
            Self::global().0.lock().unwrap().clear();
        }
    }

    impl log::Log for StringLog {
        fn enabled(&self, _metadata: &log::Metadata) -> bool {
            true
        }

        fn log(&self, record: &log::Record) {
            if record.target() == "packet-trace" {
                let mut buf = self.0.lock().unwrap();
                writeln!(&mut buf, "{}", record.args()).unwrap()
            }
        }

        fn flush(&self) {}
    }

    impl std::io::Write for &StringLog {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            let text = std::str::from_utf8(buf).unwrap();
            let mut string = self.0.lock().unwrap();
            string.push_str(text);

            Ok(buf.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn test_invocation_compiles() {
        if false {
            packet_trace!("test-1", { &[1, 2, 3] });
        }
    }

    #[cfg(feature = "enable")]
    #[test]
    #[serial]
    pub fn test_date() {
        StringLog::clear();

        packet_trace!("test-date", { &[1, 2, 3] });
        let output = StringLog::get_string();
        let date = &output["test-date,0123456789abcdef,".len()..output.len() - ",3\n".len()];

        assert!(chrono::DateTime::parse_from_str(&date, DATE_FORMAT_STR).is_ok());
    }

    #[cfg(feature = "enable")]
    #[test]
    #[serial]
    pub fn test_hash() {
        StringLog::clear();

        packet_trace!("test-foo", { &[1, 2, 3] });
        let expected = Regex::new(r#"test-foo,[0-9A-Fa-f]{16}.*\n"#).unwrap();

        assert!(expected.is_match(&StringLog::get_string()));
    }

    #[cfg(feature = "enable")]
    #[test]
    #[serial]
    pub fn test_twice() {
        {
            StringLog::clear();

            packet_trace!("test-foo", { &[1, 2, 3] });
            let expected = Regex::new(r#"test-foo,[0-9A-Fa-f]{16}.*\n"#).unwrap();

            assert!(expected.is_match(&StringLog::get_string()));
        }

        {
            StringLog::clear();

            packet_trace!("test-bar", { &[1, 2, 3] });
            let expected = Regex::new(r#"test-bar,[0-9A-Fa-f]{16}.*\n"#).unwrap();

            assert!(expected.is_match(&StringLog::get_string()));
        }
    }

    #[cfg(feature = "enable")]
    #[test]
    #[serial]
    pub fn test_seq_3() {
        StringLog::clear();

        packet_trace!("test-foo", { &[1, 2, 3] });
        packet_trace!("test-bar", { b"test data" });
        packet_trace!("test-baz", { vec![0u8, 12, 13, 22] });
        let expected = Regex::new(&format!(
            "{}{}{}",
            r#"test-foo,[0-9A-Fa-f]{16}.*\n"#,
            r#"test-bar,[0-9A-Fa-f]{16}.*\n"#,
            r#"test-baz,[0-9A-Fa-f]{16}.*\n"#,
        ))
        .unwrap();

        assert!(expected.is_match(&StringLog::get_string()));
    }

    #[cfg(feature = "enable")]
    #[test]
    #[serial]
    pub fn test_custom_write_target() {
        use crate::{set_write_target, WriteTarget};

        StringLog::clear();

        set_write_target(WriteTarget::Write(Box::new(StringLog::global())));
        packet_trace!("test-foo", { &[1, 2, 3] });
        set_write_target(WriteTarget::Log);

        let output = StringLog::get_string();

        let expected = Regex::new(r#"test-foo,[0-9A-Fa-f]{16}.*\n"#).unwrap();
        assert!(expected.is_match(&output));

        let date = &output["test-date,0123456789abcdef,".len()..output.len() - ",3\n".len()];
        assert!(chrono::DateTime::parse_from_str(&date, DATE_FORMAT_STR).is_ok());
    }

    #[cfg(not(feature = "enable"))]
    #[test]
    #[serial]
    pub fn test_disable() {
        StringLog::clear();

        packet_trace!("test-foo", { &[1, 2, 3] });
        packet_trace!("test-bar", { b"test data" });
        packet_trace!("test-baz", { vec![0u8, 12, 13, 22] });
        let expected = "";

        assert_eq!(StringLog::get_string(), expected);
    }
}