#![allow(dead_code)]
use std::path::PathBuf;
pub fn data(name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("data")
.join(name)
}
fn resolve(name: &str) -> PathBuf {
let p = PathBuf::from(name);
if p.exists() {
p
} else {
data(name)
}
}
pub fn read_pcap(name: &str) -> Vec<(u32, Vec<u8>)> {
let b = std::fs::read(resolve(name)).unwrap();
assert_eq!(&b[..4], &[0xd4, 0xc3, 0xb2, 0xa1], "little endian pcap");
let lt = u32::from_le_bytes(b[20..24].try_into().unwrap());
let mut off = 24;
let mut out = Vec::new();
while off + 16 <= b.len() {
let cl = u32::from_le_bytes(b[off + 8..off + 12].try_into().unwrap()) as usize;
off += 16;
out.push((lt, b[off..off + cl].to_vec()));
off += cl;
}
out
}
pub fn read_pcapng(name: &str) -> Vec<(u32, Vec<u8>)> {
let b = std::fs::read(resolve(name)).unwrap();
let mut off = 0;
let mut linktypes = Vec::new();
let mut out = Vec::new();
while off + 12 <= b.len() {
let bt = u32::from_le_bytes(b[off..off + 4].try_into().unwrap());
let bl = u32::from_le_bytes(b[off + 4..off + 8].try_into().unwrap()) as usize;
let body = &b[off + 8..off + bl - 4];
match bt {
1 => linktypes.push(u16::from_le_bytes(body[..2].try_into().unwrap()) as u32),
6 => {
let iface = u32::from_le_bytes(body[..4].try_into().unwrap()) as usize;
let cl = u32::from_le_bytes(body[12..16].try_into().unwrap()) as usize;
out.push((linktypes[iface], body[20..20 + cl].to_vec()));
}
_ => {}
}
off += bl;
}
out
}
pub fn nordic_ble_adv(pkt: &[u8]) -> Option<([u8; 6], Vec<u8>, bool)> {
let hdr = 1 + 6;
let flags = *pkt.get(hdr + 1)?;
let crc_ok = flags & 0x01 != 0;
let coded = (flags >> 4) & 0x07 == 2;
let ble = &pkt[hdr + 10..];
let h = if coded { 5 } else { 4 };
let pdu_type = ble.get(h)? & 0x0F;
let len = *ble.get(h + 1)? as usize;
let pdu = ble.get(h + 2..h + 2 + len)?;
match pdu_type {
0 | 2 | 6 => Some((pdu[..6].try_into().ok()?, pdu[6..].to_vec(), crc_ok)),
7 => {
let ext_len = (pdu[0] & 0x3F) as usize;
let ext = &pdu[1..1 + ext_len];
let mut addr = [0u8; 6];
if ext_len > 0 {
let ehf = ext[0];
if ehf & 0x01 != 0 {
addr.copy_from_slice(&ext[1..7]);
}
}
Some((addr, pdu[1 + ext_len..].to_vec(), crc_ok))
}
_ => None,
}
}
pub fn unhex(s: &str) -> Vec<u8> {
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
.collect()
}