forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

pcapout.rs92 lines, 3.1 KiBHistoryRawDownload
1//! libpcap (DLT) capture-file writer for the scan spool and `.pcap` export.
2//!
3//! File format (all multi-byte header fields little-endian):
4//! global header: magic `0xa1b2c3d4`, version 2.4, thiszone 0, sigfigs 0,
5//! snaplen 65535, linktype 127 (`DLT_IEEE802_11_RADIO`, radiotap). Each
6//! packet record: `ts_sec`/`ts_usec` ([`SystemTime::now`]),
7//! `incl_len == orig_len == frame.len()`, then the frame bytes.
8
9use std::fs::{File, OpenOptions};
10use std::io::{self, BufWriter, Write};
11use std::path::Path;
12use std::time::{SystemTime, UNIX_EPOCH};
13
14use byteorder::{LittleEndian as LE, WriteBytesExt};
15
16/// libpcap little-endian magic (as written byte order: d4 c3 b2 a1).
17const MAGIC_LE: u32 = 0xa1b2_c3d4;
18const VERSION_MAJOR: u16 = 2;
19const VERSION_MINOR: u16 = 4;
20const SNAPLEN: u32 = 65535;
21/// DLT_IEEE802_11_RADIO: frames carry a radiotap header.
22const LINKTYPE_RADIOTAP: u32 = 127;
23
24pub struct PcapWriter {
25 w: BufWriter<File>,
26}
27
28fn write_global_header(w: &mut impl Write) -> io::Result<()> {
29 w.write_u32::<LE>(MAGIC_LE)?;
30 w.write_u16::<LE>(VERSION_MAJOR)?;
31 w.write_u16::<LE>(VERSION_MINOR)?;
32 w.write_i32::<LE>(0)?; // thiszone
33 w.write_u32::<LE>(0)?; // sigfigs
34 w.write_u32::<LE>(SNAPLEN)?;
35 w.write_u32::<LE>(LINKTYPE_RADIOTAP)?;
36 Ok(())
37}
38
39/// Create a new capture file at `path`, truncating any existing content and
40/// writing the global header.
41pub fn create(path: &Path) -> io::Result<PcapWriter> {
42 let f = File::create(path)?;
43 let mut w = BufWriter::new(f);
44 write_global_header(&mut w)?;
45 Ok(PcapWriter { w })
46}
47
48/// Open `path` so new frames land after existing ones: an existing
49/// non-empty file is opened for append WITHOUT rewriting the global header
50/// (spool continuity across restarts); a missing or empty file gets the
51/// header written, exactly like [`create`].
52pub fn from_path_append(path: &Path) -> io::Result<PcapWriter> {
53 let needs_header = match std::fs::metadata(path) {
54 Ok(m) => m.len() == 0,
55 Err(e) if e.kind() == io::ErrorKind::NotFound => true,
56 Err(e) => return Err(e),
57 };
58 let f = OpenOptions::new().create(true).append(true).open(path)?;
59 let mut w = BufWriter::new(f);
60 if needs_header {
61 write_global_header(&mut w)?;
62 }
63 Ok(PcapWriter { w })
64}
65
66impl PcapWriter {
67 /// Append one frame: per-packet record header (current wall-clock
68 /// timestamp, `incl_len == orig_len`) followed by the frame bytes.
69 pub fn append(&mut self, frame: &[u8]) -> io::Result<()> {
70 let now = SystemTime::now()
71 .duration_since(UNIX_EPOCH)
72 .unwrap_or_default();
73 let len = frame.len().min(SNAPLEN as usize) as u32;
74 self.w.write_u32::<LE>(now.as_secs() as u32)?;
75 self.w.write_u32::<LE>(now.subsec_micros())?;
76 self.w.write_u32::<LE>(len)?; // incl_len
77 self.w.write_u32::<LE>(len)?; // orig_len
78 self.w.write_all(&frame[..len as usize])?;
79 Ok(())
80 }
81
82 /// Flush the buffered frames to disk.
83 pub fn finish(&mut self) -> io::Result<()> {
84 self.w.flush()
85 }
86}
87
88impl Drop for PcapWriter {
89 fn drop(&mut self) {
90 let _ = self.w.flush();
91 }
92}