diff --git a/src/main.rs b/src/main.rs index 8158b69..dfe4512 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,7 @@ use clap::Parser; use std::{ fs::File, - io, + io::{self, IsTerminal}, path::{Path, PathBuf}, sync::mpsc::{channel, Sender}, thread, @@ -10,7 +10,7 @@ use std::{ use anyhow::Result; use ax25::frame::Ax25Frame; use pcap_file::{ - pcap::{PcapHeader, PcapPacket, PcapWriter}, + pcap::{PcapHeader, PcapPacket, PcapReader, PcapWriter}, DataLink, }; use std::io::Read; @@ -28,6 +28,18 @@ struct KissPkt { data: Vec, } +fn pcap_loop(tx: Sender, stream: T) -> Result<()> { + let mut reader = PcapReader::new(stream)?; + + while let Some(Ok(pkt)) = reader.next_packet() { + tx.send(KissPkt { + timestamp: pkt.timestamp, + orig_len: pkt.orig_len, + data: pkt.data.into(), + })?; + } + todo!() +} fn tnc_loop(tx: Sender, mut stream: T) -> Result<()> { let mut buffer = [0_u8; 4096]; let mut frame = vec![]; @@ -110,8 +122,14 @@ fn main() -> Result<()> { thread::spawn(move || tnc_loop(tx, file).unwrap()); } path if Path::new(path).exists() => { - let file = io::BufReader::new(File::open(path)?); - thread::spawn(move || tnc_loop(tx, file).unwrap()); + let file = File::open(path)?; + let is_tty = file.is_terminal(); + let mut filebuf = io::BufReader::new(file); + if !is_tty && has_pcap_magic(&mut filebuf) { + thread::spawn(move || pcap_loop(tx, filebuf).unwrap()); + } else { + thread::spawn(move || tnc_loop(tx, filebuf).unwrap()); + } } addr => { let stream = TcpStream::connect(addr)?; @@ -155,3 +173,17 @@ fn main() -> Result<()> { Ok(()) } +fn has_pcap_magic(filebuf: &mut io::BufReader) -> bool { + const PCAP_MAGIC_MS: u32 = 0xA1B2C3D4; + const PCAP_MAGIC_NS: u32 = 0xA1B23C4D; + match io::BufRead::fill_buf(filebuf) { + Ok(buf) if buf.len() >= 4 => { + let mut tmp = [0_u8; 4]; + tmp.copy_from_slice(&buf[..4]); + let be = u32::from_be_bytes(tmp); + let le = u32::from_le_bytes(tmp); + be == PCAP_MAGIC_MS || be == PCAP_MAGIC_NS || le == PCAP_MAGIC_MS || le == PCAP_MAGIC_NS + } + _ => false, + } +}