Skip to main content

raw_ether/
wifi.rs

1//! 802.11 Action frames on Linux through nl80211, with the times the
2//! radio stamped on them: what gPTP over Wi-Fi (802.1AS-2020 clause 12)
3//! needs of a station's or an access point's interface. A Timing
4//! Measurement frame goes out with [`Radio::send_action`], and when it
5//! left and when its Ack came back arrive in [`Event::TxStatus`]; one
6//! received arrives in [`Event::Frame`], with when it came and when its
7//! Ack left. The radio stamps the frames to and from the station named
8//! to [`Radio::set_hw_timestamp`], one station at a time on Intel's.
9//!
10//! The times are the driver's, on the radio's clock: Intel's iwlwifi
11//! gives them on its "iwlwifi-PTP" hardware clock. On an access point,
12//! hostapd takes every Action frame received, so there frames can only
13//! be sent; a station's wpa_supplicant leaves those this needs.
14
15use std::cell::{Cell, RefCell};
16use std::collections::VecDeque;
17use std::io;
18use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
19
20use crate::MacAddress;
21
22/// Generic netlink's controller, which names the families.
23const GENL_ID_CTRL: u16 = 0x10;
24const CTRL_CMD_GETFAMILY: u8 = 3;
25const CTRL_ATTR_FAMILY_ID: u16 = 1;
26const CTRL_ATTR_FAMILY_NAME: u16 = 2;
27const CTRL_ATTR_MCAST_GROUPS: u16 = 7;
28const CTRL_ATTR_MCAST_GRP_NAME: u16 = 1;
29const CTRL_ATTR_MCAST_GRP_ID: u16 = 2;
30
31/// nl80211's commands and attributes (linux/nl80211.h).
32const CMD_GET_INTERFACE: u8 = 5;
33const CMD_GET_STATION: u8 = 17;
34const CMD_NEW_STATION: u8 = 19;
35const CMD_DEL_STATION: u8 = 20;
36const CMD_REGISTER_FRAME: u8 = 58;
37const CMD_FRAME: u8 = 59;
38const CMD_FRAME_TX_STATUS: u8 = 60;
39const CMD_SET_HW_TIMESTAMP: u8 = 153;
40const ATTR_IFINDEX: u16 = 3;
41const ATTR_IFTYPE: u16 = 5;
42const ATTR_MAC: u16 = 6;
43const ATTR_FRAME: u16 = 51;
44const ATTR_COOKIE: u16 = 88;
45const ATTR_FRAME_MATCH: u16 = 91;
46const ATTR_ACK: u16 = 92;
47const ATTR_FRAME_TYPE: u16 = 101;
48const ATTR_TX_HW_TIMESTAMP: u16 = 319;
49const ATTR_RX_HW_TIMESTAMP: u16 = 320;
50const ATTR_HW_TIMESTAMP_ENABLED: u16 = 324;
51const IFTYPE_AP: u32 = 3;
52
53/// The multicast group carrying frame transmit status and stations
54/// joining and leaving.
55const MLME_GROUP: &str = "mlme";
56/// An Action frame's frame control: a management frame of subtype 13.
57const ACTION_FRAME_TYPE: u16 = 0x00d0;
58/// A management frame's header: frame control, duration, three addresses
59/// and the sequence control.
60const MANAGEMENT_HEADER: usize = 24;
61
62const NETLINK_HEADER: usize = 16;
63const GENERIC_HEADER: usize = 4;
64const ATTRIBUTE_HEADER: usize = 4;
65/// How long a request waits for the kernel's answer.
66const ANSWER_WAIT_MS: i32 = 1_000;
67
68/// Word from the radio.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum Event {
71    /// An Action frame received, from its Category on: when it arrived and
72    /// when the radio's Ack for it left, both in nanoseconds on the radio's
73    /// clock, where the radio stamped them.
74    Frame {
75        source: MacAddress,
76        action: Vec<u8>,
77        received: Option<i128>,
78        ack_sent: Option<i128>,
79    },
80    /// What became of a frame sent: whether its Ack came, when it left and
81    /// when the Ack arrived.
82    TxStatus {
83        cookie: u64,
84        acked: bool,
85        sent: Option<i128>,
86        ack_received: Option<i128>,
87    },
88    /// A station associated with the access point, or left it.
89    Station { peer: MacAddress, joined: bool },
90}
91
92/// An 802.11 interface's Action frames, through nl80211.
93pub struct Radio {
94    fd: OwnedFd,
95    family: u16,
96    interface: u32,
97    address: MacAddress,
98    sequence: Cell<u32>,
99    /// Events read while waiting for an answer, for [`take`](Self::take).
100    held: RefCell<VecDeque<Vec<u8>>>,
101}
102
103impl Radio {
104    /// Opens `interface`'s radio, listening for the transmit status of the
105    /// frames it sends and for stations joining and leaving. Registering
106    /// for frames and stamping them need CAP_NET_ADMIN.
107    pub fn open(interface: &str) -> io::Result<Self> {
108        let address = crate::interfaces::mac_of(interface).ok_or_else(|| {
109            io::Error::new(io::ErrorKind::NotFound, format!("{interface}: no address"))
110        })?;
111        let index = crate::interfaces::index_of(interface).ok_or_else(|| {
112            io::Error::new(
113                io::ErrorKind::NotFound,
114                format!("{interface}: no such interface"),
115            )
116        })?;
117        let fd = socket::open()?;
118        let mut radio = Self {
119            fd,
120            family: GENL_ID_CTRL,
121            interface: index as u32,
122            address,
123            sequence: Cell::new(1),
124            held: RefCell::new(VecDeque::new()),
125        };
126        let answers = radio.request(
127            GENL_ID_CTRL,
128            CTRL_CMD_GETFAMILY,
129            &[(CTRL_ATTR_FAMILY_NAME, b"nl80211\0")],
130        )?;
131        let (family, mlme) = answers
132            .iter()
133            .find_map(|answer| family_of(answer, MLME_GROUP))
134            .ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "no nl80211"))?;
135        radio.family = family;
136        socket::join(&radio.fd, mlme)?;
137        Ok(radio)
138    }
139
140    /// The interface's own address.
141    pub fn address(&self) -> MacAddress {
142        self.address
143    }
144
145    /// Whether the interface is an access point, not a station.
146    pub fn access_point(&self) -> io::Result<bool> {
147        let index = self.interface.to_ne_bytes();
148        let answers = self.request(self.family, CMD_GET_INTERFACE, &[(ATTR_IFINDEX, &index)])?;
149        Ok(answers.iter().any(|answer| is_access_point(answer)))
150    }
151
152    /// The stations associated with the access point, or on a station the
153    /// access point it is associated with.
154    pub fn stations(&self) -> io::Result<Vec<MacAddress>> {
155        let index = self.interface.to_ne_bytes();
156        let answers = self.dump(CMD_GET_STATION, &[(ATTR_IFINDEX, &index)])?;
157        Ok(answers
158            .iter()
159            .filter_map(|answer| station_in(answer))
160            .collect())
161    }
162
163    /// Has Action frames starting with `prefix` (their Category, then
164    /// action and more as needed) come to this radio as [`Event::Frame`].
165    /// Fails if another program already takes frames that overlap.
166    pub fn register_action(&self, prefix: &[u8]) -> io::Result<()> {
167        let index = self.interface.to_ne_bytes();
168        let frame_type = ACTION_FRAME_TYPE.to_ne_bytes();
169        self.request(
170            self.family,
171            CMD_REGISTER_FRAME,
172            &[
173                (ATTR_IFINDEX, &index),
174                (ATTR_FRAME_TYPE, &frame_type),
175                (ATTR_FRAME_MATCH, prefix),
176            ],
177        )
178        .map(drop)
179    }
180
181    /// Has the radio stamp the Timing Measurement and Fine Timing
182    /// Measurement frames to and from `peer`, or stop.
183    pub fn set_hw_timestamp(&self, peer: MacAddress, enable: bool) -> io::Result<()> {
184        let index = self.interface.to_ne_bytes();
185        let mut attributes: Vec<(u16, &[u8])> = vec![(ATTR_IFINDEX, &index), (ATTR_MAC, &peer.0)];
186        if enable {
187            attributes.push((ATTR_HW_TIMESTAMP_ENABLED, &[]));
188        }
189        self.request(self.family, CMD_SET_HW_TIMESTAMP, &attributes)
190            .map(drop)
191    }
192
193    /// Sends an Action frame, `action` from its Category on, to
194    /// `destination` in the BSS `bssid` (the access point's address),
195    /// returning the cookie its [`Event::TxStatus`] will carry.
196    pub fn send_action(
197        &self,
198        destination: MacAddress,
199        bssid: MacAddress,
200        action: &[u8],
201    ) -> io::Result<u64> {
202        let frame = action_frame(destination, self.address, bssid, action);
203        let index = self.interface.to_ne_bytes();
204        let answers = self.request(
205            self.family,
206            CMD_FRAME,
207            &[(ATTR_IFINDEX, &index), (ATTR_FRAME, &frame)],
208        )?;
209        answers
210            .iter()
211            .find_map(|answer| {
212                let (_, attributes) = generic(answer)?;
213                attribute(attributes, ATTR_COOKIE).and_then(u64_of)
214            })
215            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "no cookie for the frame"))
216    }
217
218    /// The next word from the radio, without blocking.
219    pub fn take(&self) -> io::Result<Option<Event>> {
220        loop {
221            let held = self.held.borrow_mut().pop_front();
222            let message = match held {
223                Some(message) => message,
224                None => {
225                    let mut buffer = vec![0; 16_384];
226                    let Some(length) = socket::receive(&self.fd, &mut buffer)? else {
227                        return Ok(None);
228                    };
229                    buffer.truncate(length);
230                    let mut events = VecDeque::new();
231                    for message in messages(&buffer) {
232                        events.push_back(message.to_vec());
233                    }
234                    self.held.borrow_mut().extend(events);
235                    continue;
236                }
237            };
238            if let Some(event) = event_of(&message, self.family, self.interface) {
239                return Ok(Some(event));
240            }
241        }
242    }
243
244    /// Sends a request and waits for its answer: the messages of its
245    /// sequence before the acknowledgement. Others read meanwhile are held
246    /// for [`take`](Self::take).
247    fn request(
248        &self,
249        family: u16,
250        command: u8,
251        attributes: &[(u16, &[u8])],
252    ) -> io::Result<Vec<Vec<u8>>> {
253        self.exchange(request(family, command, 0, attributes))
254    }
255
256    /// Asks nl80211 for every entry of a kind: the messages up to the
257    /// dump's end.
258    fn dump(&self, command: u8, attributes: &[(u16, &[u8])]) -> io::Result<Vec<Vec<u8>>> {
259        let mut message = request(self.family, command, 0, attributes);
260        let flags = (libc::NLM_F_REQUEST | libc::NLM_F_DUMP) as u16;
261        message[6..8].copy_from_slice(&flags.to_ne_bytes());
262        self.exchange(message)
263    }
264
265    /// Sends `message`, numbered afresh, and gathers its answer.
266    fn exchange(&self, mut message: Vec<u8>) -> io::Result<Vec<Vec<u8>>> {
267        let sequence = self.sequence.get();
268        self.sequence.set(sequence.wrapping_add(1));
269        message[8..12].copy_from_slice(&sequence.to_ne_bytes());
270        socket::send(&self.fd, &message)?;
271        let mut answers = Vec::new();
272        let mut buffer = vec![0; 16_384];
273        loop {
274            if !socket::wait(&self.fd, ANSWER_WAIT_MS)? {
275                return Err(io::Error::new(
276                    io::ErrorKind::TimedOut,
277                    "no answer from nl80211",
278                ));
279            }
280            let Some(length) = socket::receive(&self.fd, &mut buffer)? else {
281                continue;
282            };
283            for message in messages(&buffer[..length]) {
284                if sequence_of(message) != Some(sequence) {
285                    self.held.borrow_mut().push_back(message.to_vec());
286                    continue;
287                }
288                if u16_at(message, 4) == Some(libc::NLMSG_DONE as u16) {
289                    return Ok(answers);
290                }
291                match error_of(message) {
292                    Some(0) => return Ok(answers),
293                    Some(error) => return Err(io::Error::from_raw_os_error(-error)),
294                    None => answers.push(message.to_vec()),
295                }
296            }
297        }
298    }
299}
300
301impl AsFd for Radio {
302    fn as_fd(&self) -> BorrowedFd<'_> {
303        self.fd.as_fd()
304    }
305}
306
307/// An Action frame from `source` to `destination` in BSS `bssid`, `action`
308/// from its Category on.
309fn action_frame(
310    destination: MacAddress,
311    source: MacAddress,
312    bssid: MacAddress,
313    action: &[u8],
314) -> Vec<u8> {
315    let mut frame = Vec::with_capacity(MANAGEMENT_HEADER + action.len());
316    frame.extend_from_slice(&ACTION_FRAME_TYPE.to_le_bytes());
317    frame.extend_from_slice(&[0, 0]);
318    frame.extend_from_slice(&destination.0);
319    frame.extend_from_slice(&source.0);
320    frame.extend_from_slice(&bssid.0);
321    frame.extend_from_slice(&[0, 0]);
322    frame.extend_from_slice(action);
323    frame
324}
325
326/// A generic netlink request, asking for an acknowledgement.
327fn request(family: u16, command: u8, sequence: u32, attributes: &[(u16, &[u8])]) -> Vec<u8> {
328    let mut message = vec![0; NETLINK_HEADER];
329    message.extend_from_slice(&[command, 1, 0, 0]);
330    for (kind, payload) in attributes {
331        let length = ATTRIBUTE_HEADER + payload.len();
332        message.extend_from_slice(&(length as u16).to_ne_bytes());
333        message.extend_from_slice(&kind.to_ne_bytes());
334        message.extend_from_slice(payload);
335        message.resize(aligned(message.len()), 0);
336    }
337    let length = message.len() as u32;
338    let flags = (libc::NLM_F_REQUEST | libc::NLM_F_ACK) as u16;
339    message[..4].copy_from_slice(&length.to_ne_bytes());
340    message[4..6].copy_from_slice(&family.to_ne_bytes());
341    message[6..8].copy_from_slice(&flags.to_ne_bytes());
342    message[8..12].copy_from_slice(&sequence.to_ne_bytes());
343    message
344}
345
346fn aligned(length: usize) -> usize {
347    (length + 3) & !3
348}
349
350fn u16_at(octets: &[u8], at: usize) -> Option<u16> {
351    Some(u16::from_ne_bytes(octets.get(at..at + 2)?.try_into().ok()?))
352}
353
354fn u32_at(octets: &[u8], at: usize) -> Option<u32> {
355    Some(u32::from_ne_bytes(octets.get(at..at + 4)?.try_into().ok()?))
356}
357
358fn u64_of(octets: &[u8]) -> Option<u64> {
359    Some(u64::from_ne_bytes(octets.try_into().ok()?))
360}
361
362/// The netlink messages in what one read returned.
363fn messages(mut buffer: &[u8]) -> impl Iterator<Item = &[u8]> {
364    std::iter::from_fn(move || {
365        let length = u32_at(buffer, 0)? as usize;
366        if length < NETLINK_HEADER || length > buffer.len() {
367            return None;
368        }
369        let message = &buffer[..length];
370        buffer = &buffer[aligned(length).min(buffer.len())..];
371        Some(message)
372    })
373}
374
375fn sequence_of(message: &[u8]) -> Option<u32> {
376    u32_at(message, 8)
377}
378
379/// An error message's error, 0 for an acknowledgement; none for any
380/// other message.
381fn error_of(message: &[u8]) -> Option<i32> {
382    if u16_at(message, 4)? != libc::NLMSG_ERROR as u16 {
383        return None;
384    }
385    Some(u32_at(message, NETLINK_HEADER)? as i32)
386}
387
388/// A generic netlink message's type, command and attributes.
389fn generic(message: &[u8]) -> Option<(u8, &[u8])> {
390    let command = *message.get(NETLINK_HEADER)?;
391    Some((command, message.get(NETLINK_HEADER + GENERIC_HEADER..)?))
392}
393
394/// The attributes in `octets`, kind and payload; nested ones are another
395/// call's.
396fn attributes(mut octets: &[u8]) -> impl Iterator<Item = (u16, &[u8])> {
397    std::iter::from_fn(move || {
398        let length = usize::from(u16_at(octets, 0)?);
399        let kind = u16_at(octets, 2)? & 0x3fff;
400        if length < ATTRIBUTE_HEADER || length > octets.len() {
401            return None;
402        }
403        let payload = &octets[ATTRIBUTE_HEADER..length];
404        octets = &octets[aligned(length).min(octets.len())..];
405        Some((kind, payload))
406    })
407}
408
409fn attribute(octets: &[u8], wanted: u16) -> Option<&[u8]> {
410    attributes(octets).find_map(|(kind, payload)| (kind == wanted).then_some(payload))
411}
412
413/// The family's number and the named multicast group's, from the
414/// controller's answer.
415fn family_of(answer: &[u8], group: &str) -> Option<(u16, u32)> {
416    let (_, attributes_octets) = generic(answer)?;
417    let family = attribute(attributes_octets, CTRL_ATTR_FAMILY_ID).and_then(|id| u16_at(id, 0))?;
418    let groups = attribute(attributes_octets, CTRL_ATTR_MCAST_GROUPS)?;
419    let id = attributes(groups).find_map(|(_, entry)| {
420        let name = attribute(entry, CTRL_ATTR_MCAST_GRP_NAME)?;
421        (name.strip_suffix(&[0]).unwrap_or(name) == group.as_bytes())
422            .then(|| attribute(entry, CTRL_ATTR_MCAST_GRP_ID).and_then(|id| u32_at(id, 0)))
423            .flatten()
424    })?;
425    Some((family, id))
426}
427
428fn time_of(octets: &[u8]) -> Option<i128> {
429    u64_of(octets).map(i128::from)
430}
431
432fn mac_at(frame: &[u8], at: usize) -> Option<MacAddress> {
433    let octets: [u8; 6] = frame.get(at..at + 6)?.try_into().ok()?;
434    Some(MacAddress(octets))
435}
436
437/// Whether an answer about an interface says it is an access point.
438fn is_access_point(answer: &[u8]) -> bool {
439    generic(answer)
440        .and_then(|(_, attributes)| attribute(attributes, ATTR_IFTYPE))
441        .and_then(|kind| u32_at(kind, 0))
442        == Some(IFTYPE_AP)
443}
444
445/// The station an answer about one names.
446fn station_in(answer: &[u8]) -> Option<MacAddress> {
447    let (_, attributes) = generic(answer)?;
448    attribute(attributes, ATTR_MAC).and_then(|mac| mac_at(mac, 0))
449}
450
451/// The event a message from nl80211 tells of, for this interface.
452fn event_of(message: &[u8], family: u16, interface: u32) -> Option<Event> {
453    if u16_at(message, 4)? != family {
454        return None;
455    }
456    let (command, attributes_octets) = generic(message)?;
457    let index = attribute(attributes_octets, ATTR_IFINDEX).and_then(|index| u32_at(index, 0));
458    if index != Some(interface) {
459        return None;
460    }
461    let time = |kind| attribute(attributes_octets, kind).and_then(time_of);
462    match command {
463        CMD_FRAME => {
464            let frame = attribute(attributes_octets, ATTR_FRAME)?;
465            if u16::from_le_bytes([*frame.first()?, *frame.get(1)?]) & 0x00fc != ACTION_FRAME_TYPE {
466                return None;
467            }
468            Some(Event::Frame {
469                source: mac_at(frame, 10)?,
470                action: frame.get(MANAGEMENT_HEADER..)?.to_vec(),
471                received: time(ATTR_RX_HW_TIMESTAMP),
472                ack_sent: time(ATTR_TX_HW_TIMESTAMP),
473            })
474        }
475        CMD_FRAME_TX_STATUS => Some(Event::TxStatus {
476            cookie: attribute(attributes_octets, ATTR_COOKIE).and_then(u64_of)?,
477            acked: attribute(attributes_octets, ATTR_ACK).is_some(),
478            sent: time(ATTR_TX_HW_TIMESTAMP),
479            ack_received: time(ATTR_RX_HW_TIMESTAMP),
480        }),
481        CMD_NEW_STATION | CMD_DEL_STATION => Some(Event::Station {
482            peer: attribute(attributes_octets, ATTR_MAC).and_then(|mac| mac_at(mac, 0))?,
483            joined: command == CMD_NEW_STATION,
484        }),
485        _ => None,
486    }
487}
488
489/// The socket's system calls.
490#[allow(unsafe_code)]
491mod socket {
492    use std::io;
493    use std::mem::{size_of, zeroed};
494    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
495
496    pub fn open() -> io::Result<OwnedFd> {
497        // SAFETY: socket(2) takes no memory.
498        let fd = unsafe {
499            libc::socket(
500                libc::AF_NETLINK,
501                libc::SOCK_RAW | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC,
502                libc::NETLINK_GENERIC,
503            )
504        };
505        if fd < 0 {
506            return Err(io::Error::last_os_error());
507        }
508        // SAFETY: `fd` is a new socket nothing else owns.
509        let fd = unsafe { OwnedFd::from_raw_fd(fd) };
510        // SAFETY: sockaddr_nl is plain data, valid when zeroed.
511        let mut address: libc::sockaddr_nl = unsafe { zeroed() };
512        address.nl_family = libc::AF_NETLINK as libc::sa_family_t;
513        // SAFETY: `address` is a sockaddr_nl of the length given.
514        let bound = unsafe {
515            libc::bind(
516                fd.as_raw_fd(),
517                std::ptr::from_ref(&address).cast(),
518                size_of::<libc::sockaddr_nl>() as libc::socklen_t,
519            )
520        };
521        if bound < 0 {
522            return Err(io::Error::last_os_error());
523        }
524        Ok(fd)
525    }
526
527    pub fn join(fd: &OwnedFd, group: u32) -> io::Result<()> {
528        // SAFETY: `group` is a u32 of the length given.
529        let joined = unsafe {
530            libc::setsockopt(
531                fd.as_raw_fd(),
532                libc::SOL_NETLINK,
533                libc::NETLINK_ADD_MEMBERSHIP,
534                std::ptr::from_ref(&group).cast(),
535                size_of::<u32>() as libc::socklen_t,
536            )
537        };
538        if joined < 0 {
539            return Err(io::Error::last_os_error());
540        }
541        Ok(())
542    }
543
544    pub fn send(fd: &OwnedFd, message: &[u8]) -> io::Result<()> {
545        // SAFETY: `message` is readable for its length.
546        let sent = unsafe { libc::send(fd.as_raw_fd(), message.as_ptr().cast(), message.len(), 0) };
547        if sent < 0 {
548            return Err(io::Error::last_os_error());
549        }
550        Ok(())
551    }
552
553    /// What one read returned, or none if nothing waits.
554    pub fn receive(fd: &OwnedFd, buffer: &mut [u8]) -> io::Result<Option<usize>> {
555        loop {
556            // SAFETY: `buffer` is writable for its length.
557            let length = unsafe {
558                libc::recv(
559                    fd.as_raw_fd(),
560                    buffer.as_mut_ptr().cast(),
561                    buffer.len(),
562                    libc::MSG_DONTWAIT,
563                )
564            };
565            if length >= 0 {
566                return Ok(Some(length as usize));
567            }
568            let error = io::Error::last_os_error();
569            match error.raw_os_error() {
570                Some(libc::EAGAIN) => return Ok(None),
571                Some(libc::EINTR) => {}
572                _ => return Err(error),
573            }
574        }
575    }
576
577    /// Whether something came to read within `milliseconds`.
578    pub fn wait(fd: &OwnedFd, milliseconds: i32) -> io::Result<bool> {
579        let mut poll = libc::pollfd {
580            fd: fd.as_raw_fd(),
581            events: libc::POLLIN,
582            revents: 0,
583        };
584        loop {
585            // SAFETY: `poll` is one pollfd.
586            let ready = unsafe { libc::poll(&mut poll, 1, milliseconds) };
587            if ready >= 0 {
588                return Ok(ready > 0);
589            }
590            let error = io::Error::last_os_error();
591            if error.raw_os_error() != Some(libc::EINTR) {
592                return Err(error);
593            }
594        }
595    }
596}
597
598#[cfg(test)]
599mod tests;