//! The structured log: one JSON object per line (`log.jsonl` in the run folder), flushed after every record so a //! crash keeps everything before it. //! //! ```text //! {"n":7,"t_ms":812.441,"step":"rtsp.describe","kind":"recv","u":["U5","U26"],"data":{…}} //! ``` //! //! `kind` is one of `send`, `recv`, `note`, `parse_error`, `stop`, `summary`. A `stop` record is the //! stop-and-report rule of docs/LIVE-INTEROP.md: something unexpected happened, the probe ends the step and the //! operator reports before changing anything. //! //! Secrets: HTTP paths and bodies are redacted by the callers (`crate::redact`), and every line is scanned once more //! for the hex of each registered secret (the session's `rikey`) before it is written. The PIN is never passed to //! the log at all. use std::fs::File; use std::io::{self, BufWriter, Write}; use std::path::{Path, PathBuf}; use std::time::Instant; use crate::redact::MARK; /// Bytes shown per byte field; the rest is cut and marked `truncated`. pub const MAX_LOGGED_BYTES: usize = 4096; /// Characters shown per text field. pub const MAX_LOGGED_TEXT: usize = 64 * 1024; /// A JSON value, built by the probe and written by [`J::write`]. #[derive(Clone, Debug, PartialEq)] pub enum J { Null, Bool(bool), U(u64), I(i64), F(f64), S(String), A(Vec), O(Vec<(&'static str, J)>), } impl J { pub fn s(v: impl Into) -> Self { Self::S(v.into()) } /// A string via `Debug` (for DomiStream's own types, which never print key material). pub fn dbg(v: &impl std::fmt::Debug) -> Self { let mut s = format!("{v:?}"); cut(&mut s, MAX_LOGGED_TEXT); Self::S(s) } pub fn write(&self, out: &mut String) { match self { Self::Null => out.push_str("null"), Self::Bool(b) => out.push_str(if *b { "true" } else { "false" }), Self::U(n) => out.push_str(&n.to_string()), Self::I(n) => out.push_str(&n.to_string()), Self::F(f) if f.is_finite() => out.push_str(&format!("{f:.3}")), Self::F(_) => out.push_str("null"), Self::S(s) => escape(s, out), Self::A(items) => { out.push('['); for (i, v) in items.iter().enumerate() { if i > 0 { out.push(','); } v.write(out); } out.push(']'); } Self::O(fields) => { out.push('{'); for (i, (k, v)) in fields.iter().enumerate() { if i > 0 { out.push(','); } escape(k, out); out.push(':'); v.write(out); } out.push('}'); } } } } fn cut(s: &mut String, max: usize) { if s.len() > max { let mut end = max; while !s.is_char_boundary(end) { end -= 1; } s.truncate(end); s.push_str("…"); } } /// A JSON string literal. pub fn escape(s: &str, out: &mut String) { out.push('"'); for c in s.chars() { match c { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"), '\n' => out.push_str("\\n"), '\r' => out.push_str("\\r"), '\t' => out.push_str("\\t"), c if (c as u32) < 0x20 || c == '\u{7f}' => out.push_str(&format!("\\u{:04x}", c as u32)), c => out.push(c), } } out.push('"'); } /// Lower-case hex. pub fn hex(bytes: &[u8]) -> String { const D: &[u8; 16] = b"0123456789abcdef"; let mut s = String::with_capacity(bytes.len() * 2); for b in bytes { s.push(char::from(D[usize::from(b >> 4)])); s.push(char::from(D[usize::from(b & 0xF)])); } s } /// `{"len":n,"hex":"…"}`, the hex cut at [`MAX_LOGGED_BYTES`] bytes (`"truncated":true`). pub fn bytes(b: &[u8]) -> J { let shown = b.get(..MAX_LOGGED_BYTES).unwrap_or(b); let mut f = vec![("len", J::U(b.len() as u64)), ("hex", J::S(hex(shown)))]; if shown.len() < b.len() { f.push(("truncated", J::Bool(true))); } J::O(f) } /// `{"len":n,"text":"…"}` when `b` is UTF-8 text (tabs and line ends allowed), else [`bytes`]. pub fn text(b: &[u8]) -> J { match std::str::from_utf8(b) { Ok(s) if !s.chars().any(|c| c.is_control() && !matches!(c, '\r' | '\n' | '\t')) => { let mut t = s.to_owned(); cut(&mut t, MAX_LOGGED_TEXT); J::O(vec![("len", J::U(b.len() as u64)), ("text", J::S(t))]) } _ => bytes(b), } } /// What a record is. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { Send, Recv, Note, ParseError, Stop, Summary, } impl Kind { pub const fn as_str(self) -> &'static str { match self { Self::Send => "send", Self::Recv => "recv", Self::Note => "note", Self::ParseError => "parse_error", Self::Stop => "stop", Self::Summary => "summary", } } } /// One log line, without the trailing newline, with every registered secret's hex replaced by [`MARK`]. pub fn format_line(n: u64, t_ms: f64, step: &str, kind: Kind, us: &[&str], data: &J, secrets: &[String]) -> String { let rec = J::O(vec![ ("n", J::U(n)), ("t_ms", J::F(t_ms)), ("step", J::s(step)), ("kind", J::s(kind.as_str())), ("u", J::A(us.iter().map(|u| J::s(*u)).collect())), ("data", data.clone()), ]); let mut line = String::new(); rec.write(&mut line); for s in secrets { if line.contains(s.as_str()) { line = line.replace(s.as_str(), MARK); } } line } /// The run's log file. pub struct Log { out: Option>, start: Instant, n: u64, secrets: Vec, pub path: PathBuf, pub stops: u32, pub parse_errors: u32, } impl Log { /// Creates `path` (it must not exist yet). pub fn create(path: &Path, start: Instant) -> io::Result { let f = File::options().write(true).create_new(true).open(path)?; Ok(Self { out: Some(BufWriter::new(f)), start, n: 0, secrets: Vec::new(), path: path.to_owned(), stops: 0, parse_errors: 0, }) } /// A log that writes nothing (tests of code that logs). #[cfg(test)] pub fn discard() -> Self { Self { out: None, start: Instant::now(), n: 0, secrets: Vec::new(), path: PathBuf::new(), stops: 0, parse_errors: 0, } } /// From now on, the hex of `secret` (both cases) never reaches the file. pub fn register_secret(&mut self, secret: &[u8]) { let lower = hex(secret); self.secrets.push(lower.to_ascii_uppercase()); self.secrets.push(lower); } /// Milliseconds since the run started. pub fn t_ms(&self) -> f64 { self.start.elapsed().as_secs_f64() * 1000.0 } pub fn record(&mut self, step: &str, kind: Kind, us: &[&str], data: J) { self.n += 1; match kind { Kind::Stop => self.stops += 1, Kind::ParseError => self.parse_errors += 1, _ => {} } let line = format_line(self.n, self.t_ms(), step, kind, us, &data, &self.secrets); if let Some(out) = &mut self.out { // A log that cannot be written is reported once on stderr; the probe goes on. if writeln!(out, "{line}").and_then(|()| out.flush()).is_err() { eprintln!("probe: cannot write the log {}", self.path.display()); self.out = None; } } } pub fn note(&mut self, step: &str, us: &[&str], text: impl Into) { self.record(step, Kind::Note, us, J::O(vec![("text", J::S(text.into()))])); } /// A parser refused something: the error and the bytes that caused it. pub fn parse_error(&mut self, step: &str, us: &[&str], error: &dyn std::fmt::Display, input: J) { self.record(step, Kind::ParseError, us, J::O(vec![("error", J::s(error.to_string())), ("input", input)])); } /// The stop-and-report rule: records why, and tells the operator on stderr. pub fn stop(&mut self, step: &str, us: &[&str], reason: impl Into, data: J) { let reason = reason.into(); eprintln!("STOP AND REPORT [{step}]: {reason}"); eprintln!(" log: {}", self.path.display()); self.record(step, Kind::Stop, us, J::O(vec![("reason", J::S(reason)), ("data", data)])); } } /// `YYYYMMDDTHHMMSSZ` for Unix seconds (UTC), for run folder names. pub fn utc_stamp(unix_secs: u64) -> String { let days = (unix_secs / 86_400) as i64; let rem = unix_secs % 86_400; // Civil date from days since 1970-01-01 (H. Hinnant's algorithm). let z = days + 719_468; let era = z.div_euclid(146_097); let doe = z.rem_euclid(146_097); let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; let y = yoe + era * 400 + i64::from(m <= 2); format!("{y:04}{m:02}{d:02}T{:02}{:02}{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60) } #[cfg(test)] mod tests { use super::*; fn line(data: J, secrets: &[String]) -> String { format_line(3, 12.5, "pair.1", Kind::Send, &["U1", "U2"], &data, secrets) } #[test] fn line_has_the_documented_fields_in_order() { assert_eq!( line(J::O(vec![("x", J::U(1))]), &[]), r#"{"n":3,"t_ms":12.500,"step":"pair.1","kind":"send","u":["U1","U2"],"data":{"x":1}}"# ); } #[test] fn strings_are_escaped() { let mut s = String::new(); escape("a\"b\\c\nd\u{1}é", &mut s); assert_eq!(s, r#""a\"b\\c\nd\u0001é""#); let mut n = String::new(); J::A(vec![J::Null, J::Bool(false), J::I(-2), J::F(f64::NAN)]).write(&mut n); assert_eq!(n, "[null,false,-2,null]"); } #[test] fn registered_secrets_never_reach_a_line() { let key = [0x5Au8, 0x01, 0xFE, 0x33, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB]; let mut log = Log::discard(); log.register_secret(&key); let lower = hex(&key); let upper = lower.to_ascii_uppercase(); let data = J::O(vec![ ("in_bytes", bytes(&[&[1, 2][..], &key, &[3][..]].concat())), ("in_text", J::s(format!("rikey={upper}&x=1"))), ]); let l = line(data, &log.secrets); assert!(!l.contains(&lower) && !l.contains(&upper), "{l}"); assert!(l.contains("010203"), "{l}"); assert!(l.contains("rikey=&x=1"), "{l}"); } #[test] fn byte_fields_are_capped() { let big = vec![0xABu8; MAX_LOGGED_BYTES + 10]; let mut s = String::new(); bytes(&big).write(&mut s); assert!(s.starts_with(&format!(r#"{{"len":{},"hex":"abab"#, big.len()))); assert!(s.ends_with(r#","truncated":true}"#)); assert_eq!(s.matches("ab").count(), MAX_LOGGED_BYTES); } #[test] fn text_or_hex() { let mut s = String::new(); text(b"RTSP/1.0 200 OK\r\nCSeq: 1\r\n\r\n").write(&mut s); assert_eq!(s, r#"{"len":28,"text":"RTSP/1.0 200 OK\r\nCSeq: 1\r\n\r\n"}"#); let mut b = String::new(); text(&[0x80, 0x00]).write(&mut b); assert_eq!(b, r#"{"len":2,"hex":"8000"}"#); } #[test] fn utc_stamps() { assert_eq!(utc_stamp(0), "19700101T000000Z"); assert_eq!(utc_stamp(951_782_400), "20000229T000000Z"); assert_eq!(utc_stamp(951_782_400 + 86_399), "20000229T235959Z"); assert_eq!(utc_stamp(946_684_799), "19991231T235959Z"); } }