//! Raw layer-2 socket — the only module in the crate allowed to use `unsafe`. //! //! AF_PACKET/SOCK_RAW with ETH_P_ALL, bound to a single interface via //! sockaddr_ll. In monitor mode delivered frames are radiotap + 802.11; //! transmitted frames must already carry the radiotap INJECT_HDR prefix. use std::ffi::CString; use std::io; use std::mem::size_of; /// Receive buffer size covering any real 802.11 frame: the largest A-MSDU /// aggregate tops out at 11454 octets (802.11-2020 §9.3.2.1 max MPDU) and a /// monitor-mode radiotap header is at most a few hundred bytes; 16 KiB /// leaves generous headroom. pub const RECV_BUFSZ: usize = 16384; /// Outcome of [`RawSocket::recv_msg`]: bytes copied into the caller's /// buffer plus the frame's true on-wire length, so truncation is visible /// instead of silent. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct RecvMsg { /// Bytes actually written into the caller's buffer. pub len: usize, /// Full frame length as reported by the kernel (MSG_TRUNC). pub orig_len: usize, } impl RecvMsg { /// True when the frame didn't fit the buffer and `len` bytes are a /// prefix of a longer packet. pub fn truncated(&self) -> bool { self.orig_len > self.len } } pub struct RawSocket { fd: i32, #[allow(dead_code)] ifindex: i32, } impl RawSocket { /// AF_PACKET SOCK_RAW ETH_P_ALL bound to ifname. Requires CAP_NET_RAW. pub fn open(ifname: &str) -> io::Result { let cname = CString::new(ifname) .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "ifname contains NUL"))?; // SAFETY: plain libc calls on stack-allocated data; fd/checks below. unsafe { let ifindex = libc::if_nametoindex(cname.as_ptr()); if ifindex == 0 { return Err(io::Error::new( io::ErrorKind::NotFound, format!("no such interface: {ifname}"), )); } let fd = libc::socket( libc::AF_PACKET, libc::SOCK_RAW | libc::SOCK_CLOEXEC, (libc::ETH_P_ALL as u16).to_be() as i32, ); if fd < 0 { return Err(io::Error::last_os_error()); } let sll = libc::sockaddr_ll { sll_family: libc::AF_PACKET as u16, sll_protocol: (libc::ETH_P_ALL as u16).to_be(), sll_ifindex: ifindex as i32, sll_hatype: 0, sll_pkttype: 0, sll_halen: 0, sll_addr: [0; 8], }; if libc::bind( fd, &sll as *const libc::sockaddr_ll as *const libc::sockaddr, size_of::() as libc::socklen_t, ) < 0 { let err = io::Error::last_os_error(); libc::close(fd); return Err(err); } Ok(RawSocket { fd, ifindex: ifindex as i32, }) } } /// Truncation-aware receive: passes MSG_TRUNC on a packet socket, so /// the kernel reports the frame's true length even when it exceeds /// `buf`. The caller MUST check [`RecvMsg::truncated`] and drop the /// prefix (or enlarge the buffer) — the buffer then holds only the /// first `len` bytes of a longer frame. pub fn recv_msg(&self, buf: &mut [u8]) -> io::Result { loop { // SAFETY: fd is a live socket owned by self; buf is valid for // buf.len() writable bytes. let n = unsafe { libc::recv(self.fd, buf.as_mut_ptr().cast(), buf.len(), libc::MSG_TRUNC) }; if n >= 0 { let orig_len = n as usize; return Ok(RecvMsg { len: orig_len.min(buf.len()), orig_len, }); } let err = io::Error::last_os_error(); if err.kind() != io::ErrorKind::Interrupted { return Err(err); } } } /// Transmit a frame prefixed with radiotap INJECT_HDR (len includes it). pub fn send(&self, frame_with_radiotap: &[u8]) -> io::Result { loop { // SAFETY: fd is a live socket; slice is valid readable memory. let n = unsafe { libc::send( self.fd, frame_with_radiotap.as_ptr().cast(), frame_with_radiotap.len(), 0, ) }; if n >= 0 { return Ok(n as usize); } let err = io::Error::last_os_error(); if err.kind() != io::ErrorKind::Interrupted { return Err(err); } } } /// Receive timeout toggle for poll-style loops. 0 disables the timeout. pub fn set_timeout(&self, ms: u32) -> io::Result<()> { let tv = libc::timeval { tv_sec: (ms / 1000) as libc::time_t, tv_usec: ((ms % 1000) * 1000) as libc::suseconds_t, }; // SAFETY: fd is a live socket; tv outlives the call. let rc = unsafe { libc::setsockopt( self.fd, libc::SOL_SOCKET, libc::SO_RCVTIMEO, &tv as *const libc::timeval as *const libc::c_void, size_of::() as libc::socklen_t, ) }; if rc < 0 { return Err(io::Error::last_os_error()); } Ok(()) } } impl Drop for RawSocket { fn drop(&mut self) { // SAFETY: fd came from socket() and is closed exactly once here. unsafe { libc::close(self.fd); } } } #[cfg(test)] mod tests { use super::*; /// Without root/CAP_NET_RAW this returns EPERM; with it, loopback opens /// fine. Both outcomes are acceptable — the point is no panic and that a /// successful open accepts a timeout. #[test] fn open_loopback_best_effort() { match RawSocket::open("lo") { Ok(sock) => { assert!(sock.set_timeout(100).is_ok()); } Err(e) => { let k = e.kind(); assert!(matches!( k, io::ErrorKind::PermissionDenied | io::ErrorKind::NotFound | io::ErrorKind::Other )); } } } #[test] fn bogus_iface_is_an_error_not_a_panic() { let res = RawSocket::open("no_such_iface_zz"); assert!(res.is_err()); } /// MSG_TRUNC reporting semantics: a frame longer than the buffer shows /// len == buf.len() < orig_len; anything else is complete. #[test] fn recv_msg_truncation_flag() { let m = RecvMsg { len: 100, orig_len: 200, }; assert!(m.truncated()); let m = RecvMsg { len: 200, orig_len: 200, }; assert!(!m.truncated()); let m = RecvMsg { len: 100, orig_len: 100, }; assert!(!m.truncated()); } /// Live MSG_TRUNC round-trip: send a big UDP datagram over loopback via /// an AF_PACKET socket and confirm recv_msg reports the full length /// while delivering only a prefix. Skipped silently without /// CAP_NET_RAW (same posture as `open_loopback_best_effort`). #[test] fn recv_msg_reports_full_length_on_truncation() { let Ok(sock) = RawSocket::open("lo") else { return; // no CAP_NET_RAW in the test sandbox }; // UDP needs root for raw sends on lo through AF_PACKET? No — we // send an ordinary UDP datagram; the packet socket sees it twice // (outgoing + incoming) with the full L2/L3/L4 framing. let udp = match std::net::UdpSocket::bind("127.0.0.1:0") { Ok(s) => s, Err(_) => return, }; if udp.connect("127.0.0.1:9").is_err() { return; } let payload = vec![0xabu8; 6000]; // fits loopback MTU (65536) if udp.send(&payload).is_err() { return; } sock.set_timeout(500).expect("set_timeout"); let mut tiny = [0u8; 128]; // Read until an over-long packet arrives: the datagram shows up as // outgoing + incoming copies, both >128 bytes. Small stray traffic // (ARP, ICMP errors) is skipped. for _ in 0..8 { match sock.recv_msg(&mut tiny) { Ok(m) if m.truncated() => { assert_eq!(m.len, tiny.len()); assert!(m.orig_len > tiny.len()); return; } Ok(_) => continue, // short frame — not ours, keep looking Err(e) if e.kind() == io::ErrorKind::WouldBlock || e.kind() == io::ErrorKind::TimedOut => { break; } Err(_) => continue, } } panic!("no over-long packet observed on loopback packet socket"); } }