use log::{debug, warn};
use std::mem;
#[repr(C)]
#[derive(Debug, Clone)]
pub struct PktapHeader {
pub pth_length: u32, pub pth_type_next: u32, pub pth_dlt: u32, pub pth_ifname: [u8; 24], pub pth_flags: u32, pub pth_protocol_family: u16, pub pth_frame_pre_length: u16, pub pth_frame_post_length: u16, pub pth_iftype: u16, pub pth_unit: u16, pub pth_epid: u32, pub pth_comm: [u8; 20], pub pth_svc_class: u32, pub pth_flowid: u32, pub pth_ipproto: u32, pub pth_pid: u32, pub pth_e_comm: [u8; 20], }
impl PktapHeader {
pub fn from_bytes(data: &[u8]) -> Option<Self> {
if data.len() < mem::size_of::<PktapHeader>() {
debug!("Packet too small for PKTAP header: {} bytes", data.len());
return None;
}
let length = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
if length < 108 || length as usize > data.len() {
debug!(
"Invalid PKTAP header length: {} (packet size: {})",
length,
data.len()
);
return None;
}
let header = unsafe { std::ptr::read_unaligned(data.as_ptr() as *const PktapHeader) };
Some(header)
}
pub fn get_process_info(&self) -> (Option<String>, Option<u32>) {
let process_name = extract_process_name_from_bytes(&self.pth_comm);
let pid = if self.pth_epid != 0 && self.pth_epid < 65535 {
Some(self.pth_epid)
} else if self.pth_pid != 0 && self.pth_pid < 65535 {
Some(self.pth_pid)
} else {
None
};
let final_process_name = if process_name.is_none() {
extract_process_name_from_bytes(&self.pth_e_comm)
} else {
process_name
};
debug!(
"PKTAP process info: name={:?}, pid={:?}",
final_process_name, pid
);
(final_process_name, pid)
}
pub fn get_interface(&self) -> String {
std::str::from_utf8(&self.pth_ifname)
.unwrap_or("")
.trim_end_matches('\0')
.trim()
.to_string()
}
pub fn payload_offset(&self) -> usize {
self.pth_length as usize
}
pub fn inner_dlt(&self) -> u32 {
self.pth_dlt
}
pub fn is_valid(&self) -> bool {
self.pth_length >= 108 &&
self.pth_length <= 4096 && self.pth_dlt > 0 &&
self.pth_dlt < 1000 }
}
fn extract_process_name_from_bytes(bytes: &[u8; 20]) -> Option<String> {
let mut end_pos = bytes.len();
for (i, &byte) in bytes.iter().enumerate() {
if byte == 0 {
end_pos = i;
break;
}
}
let raw_str = std::str::from_utf8(&bytes[..end_pos]).ok()?;
let normalized = raw_str
.chars()
.map(|c| {
if c.is_whitespace() || c.is_control() {
' ' } else {
c
}
})
.collect::<String>()
.split_whitespace() .collect::<Vec<&str>>()
.join(" ");
if normalized.is_empty() || !normalized.chars().all(|c| c.is_ascii_graphic() || c == ' ') {
debug!(
"🚫 Rejected PKTAP process name: raw='{:?}', normalized='{}'",
raw_str, normalized
);
None
} else {
debug!(
"✅ Extracted PKTAP process name: raw='{:?}' -> normalized='{}'",
raw_str, normalized
);
Some(normalized)
}
}
pub fn is_pktap_linktype(linktype: i32) -> bool {
match linktype {
149 => true, 258 => true, _ => false,
}
}
pub fn parse_pktap_packet(data: &[u8]) -> Option<(PktapHeader, &[u8])> {
let header = PktapHeader::from_bytes(data)?;
if !header.is_valid() {
warn!("Invalid PKTAP header detected");
return None;
}
let payload_offset = header.payload_offset();
if data.len() <= payload_offset {
warn!(
"PKTAP header claims payload at offset {} but packet is only {} bytes",
payload_offset,
data.len()
);
return None;
}
let payload = &data[payload_offset..];
debug!(
"PKTAP: header_len={}, inner_dlt={}, payload_len={}",
header.pth_length,
header.pth_dlt,
payload.len()
);
Some((header, payload))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pktap_linktype_detection() {
assert!(is_pktap_linktype(149)); assert!(is_pktap_linktype(258)); assert!(!is_pktap_linktype(1)); assert!(!is_pktap_linktype(12)); }
#[test]
fn test_pktap_header_size() {
assert!(mem::size_of::<PktapHeader>() >= 108);
}
#[test]
fn test_invalid_pktap_data() {
let small_data = [0u8; 50];
assert!(PktapHeader::from_bytes(&small_data).is_none());
let mut bad_data = [0u8; 200];
bad_data[0] = 50; assert!(PktapHeader::from_bytes(&bad_data).is_none());
}
}