//! The shared, thread-safe writer of the record file. Every record is flushed at once, so a killed relay leaves a //! file that reads cleanly up to its last whole record. use std::fs::{File, OpenOptions}; use std::io::{self, BufWriter, Write}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::time::{Instant, SystemTime, UNIX_EPOCH}; use crate::record::{self, Direction, Header, Kind, Protocol, Record}; /// Writes records for one capture. pub struct Recorder { out: Mutex>, start: Instant, next_connection: AtomicU32, failed: AtomicBool, } impl Recorder { /// Creates `session-.dslr` in `dir` (never overwrites) and writes the header. /// /// # Errors /// I/O errors, including an existing file of the same name. pub fn create(dir: &Path) -> io::Result<(Self, PathBuf)> { let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default(); let path = dir.join(format!("session-{}.dslr", now.as_secs())); let file = OpenOptions::new().write(true).create_new(true).open(&path)?; let mut out = BufWriter::new(file); let start_unix_micros = u64::try_from(now.as_micros()).unwrap_or(u64::MAX); record::write_header(&mut out, Header { start_unix_micros })?; out.flush()?; let rec = Self { out: Mutex::new(out), start: Instant::now(), next_connection: AtomicU32::new(1), failed: AtomicBool::new(false), }; Ok((rec, path)) } /// A fresh connection or flow id. pub fn new_connection(&self) -> u32 { self.next_connection.fetch_add(1, Ordering::Relaxed) } /// Records bytes (split into several records if over [`record::MAX_PAYLOAD`]). pub fn log(&self, kind: Kind, protocol: Protocol, direction: Direction, connection: u32, payload: &[u8]) { let time_micros = u64::try_from(self.start.elapsed().as_micros()).unwrap_or(u64::MAX); let chunks: Vec<&[u8]> = if payload.is_empty() { vec![payload] } else { payload.chunks(record::MAX_PAYLOAD).collect() }; let Ok(mut out) = self.out.lock() else { return self.fail("lock poisoned") }; for chunk in chunks { let r = Record { kind, protocol, direction, connection, time_micros, payload: chunk.to_vec() }; if let Err(e) = record::write_record(&mut *out, &r).and_then(|()| out.flush()) { return self.fail(&e.to_string()); } } } /// Records a note (never pass key material here). pub fn note(&self, protocol: Protocol, connection: u32, text: &str) { self.log(Kind::Note, protocol, Direction::None, connection, text.as_bytes()); } /// Reports the first write failure on stderr; later ones stay silent. fn fail(&self, why: &str) { if !self.failed.swap(true, Ordering::Relaxed) { eprintln!("lab-relay: writing the record file failed: {why}"); } } }