Skip to main content

webbluetooth_linux/
hci.rs

1//! LE scanning over a raw HCI socket.
2//!
3//! The one thing ATT cannot do. An L2CAP socket can reach a peer you already
4//! know the address of, but *finding* one means listening to advertising
5//! reports, and those only come from the controller.
6//!
7//! ```text
8//!   socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)
9//!   bind(&sockaddr_hci { dev, channel = HCI_CHANNEL_RAW })
10//!   setsockopt(HCI_FILTER)                 -- or every packet arrives
11//!   << LE Set Scan Parameters
12//!   << LE Set Scan Enable
13//!   >> HCI Event 0x3E (LE Meta) / 0x02 (Advertising Report)
14//! ```
15//!
16//! **This needs `CAP_NET_RAW`**, and a controller that `bluetoothd` is not
17//! already scanning on. That is the whole cost of the daemon-free path: reading
18//! and writing GATT is unprivileged, discovery is not.
19//!
20//! The advertising-data parser is portable and unit-tested anywhere; only the
21//! socket is Linux-only.
22
23/// One parsed advertising report.
24#[derive(Debug, Clone, Default, PartialEq)]
25pub struct Advertisement {
26    /// `AA:BB:CC:DD:EE:FF`, written order.
27    pub address: String,
28    /// `true` if the peer uses a random (often resolvable) address.
29    pub random_address: bool,
30    pub rssi: i8,
31    pub local_name: Option<String>,
32    pub tx_power: Option<i8>,
33    /// GAP Appearance, from AD type `0x19`.
34    pub appearance: Option<u16>,
35    /// Canonical 128-bit service UUIDs.
36    pub service_uuids: Vec<String>,
37    /// Company identifier → payload.
38    pub manufacturer_data: Option<(u16, Vec<u8>)>,
39    /// Service UUID → payload.
40    pub service_data: Vec<(String, Vec<u8>)>,
41    /// Whether the advertisement said connections are accepted.
42    pub connectable: bool,
43}
44
45/// Format a wire-order address as it is written.
46///
47/// Mirrors [`crate::sys::format_address`], which is Linux-only; the report
48/// parser is portable so that it can be tested anywhere.
49#[cfg(target_os = "linux")]
50use crate::sys::format_address;
51
52#[cfg(not(target_os = "linux"))]
53fn format_address(wire: &[u8; 6]) -> String {
54    let mut out = String::with_capacity(17);
55    for (i, b) in wire.iter().rev().enumerate() {
56        if i > 0 {
57            out.push(':');
58        }
59        out.push_str(&format!("{b:02X}"));
60    }
61    out
62}
63
64/// AD types, from the Core Specification Supplement.
65mod ad {
66    pub const FLAGS: u8 = 0x01;
67    pub const INCOMPLETE_16: u8 = 0x02;
68    pub const COMPLETE_16: u8 = 0x03;
69    pub const INCOMPLETE_32: u8 = 0x04;
70    pub const COMPLETE_32: u8 = 0x05;
71    pub const INCOMPLETE_128: u8 = 0x06;
72    pub const COMPLETE_128: u8 = 0x07;
73    pub const SHORTENED_NAME: u8 = 0x08;
74    pub const COMPLETE_NAME: u8 = 0x09;
75    pub const TX_POWER: u8 = 0x0A;
76    pub const APPEARANCE: u8 = 0x19;
77    pub const SERVICE_DATA_16: u8 = 0x16;
78    pub const SERVICE_DATA_32: u8 = 0x20;
79    pub const SERVICE_DATA_128: u8 = 0x21;
80    pub const MANUFACTURER_DATA: u8 = 0xFF;
81}
82
83/// Expand a 16-bit assigned number into the canonical 128-bit form.
84fn canonical_16(value: u16) -> String {
85    format!("0000{value:04x}-0000-1000-8000-00805f9b34fb")
86}
87
88fn canonical_32(value: u32) -> String {
89    format!("{value:08x}-0000-1000-8000-00805f9b34fb")
90}
91
92/// Format 16 wire-order bytes as a canonical UUID.
93fn canonical_128(wire: &[u8]) -> Option<String> {
94    if wire.len() != 16 {
95        return None;
96    }
97    let hex: String = wire.iter().rev().map(|b| format!("{b:02x}")).collect();
98    Some(format!(
99        "{}-{}-{}-{}-{}",
100        &hex[0..8],
101        &hex[8..12],
102        &hex[12..16],
103        &hex[16..20],
104        &hex[20..32]
105    ))
106}
107
108/// Parse the AD structures in an advertising payload.
109///
110/// The payload is a sequence of `length, type, data…` records. A zero length
111/// terminates it — padding after that is not a record, and treating it as one
112/// is a classic way to read garbage.
113pub fn parse_advertising_data(data: &[u8], into: &mut Advertisement) {
114    let mut i = 0;
115    while i < data.len() {
116        let length = data[i] as usize;
117        if length == 0 {
118            break;
119        }
120        // A length that runs past the end means a truncated or hostile report.
121        if i + 1 + length > data.len() {
122            break;
123        }
124        let ad_type = data[i + 1];
125        let value = &data[i + 2..i + 1 + length];
126
127        match ad_type {
128            ad::FLAGS => {
129                // Bit 0 LE limited discoverable, bit 1 LE general discoverable.
130                if let Some(flags) = value.first() {
131                    into.connectable = flags & 0x03 != 0;
132                }
133            }
134            ad::SHORTENED_NAME | ad::COMPLETE_NAME => {
135                if let Ok(name) = std::str::from_utf8(value) {
136                    // A complete name wins over a shortened one.
137                    if ad_type == ad::COMPLETE_NAME || into.local_name.is_none() {
138                        into.local_name = Some(name.to_owned());
139                    }
140                }
141            }
142            ad::TX_POWER => into.tx_power = value.first().map(|b| *b as i8),
143            ad::INCOMPLETE_16 | ad::COMPLETE_16 => {
144                for pair in value.chunks_exact(2) {
145                    into.service_uuids
146                        .push(canonical_16(u16::from_le_bytes([pair[0], pair[1]])));
147                }
148            }
149            ad::INCOMPLETE_32 | ad::COMPLETE_32 => {
150                for quad in value.chunks_exact(4) {
151                    into.service_uuids.push(canonical_32(u32::from_le_bytes([
152                        quad[0], quad[1], quad[2], quad[3],
153                    ])));
154                }
155            }
156            ad::INCOMPLETE_128 | ad::COMPLETE_128 => {
157                for block in value.chunks_exact(16) {
158                    if let Some(uuid) = canonical_128(block) {
159                        into.service_uuids.push(uuid);
160                    }
161                }
162            }
163            ad::APPEARANCE => {
164                if value.len() >= 2 {
165                    into.appearance = Some(u16::from_le_bytes([value[0], value[1]]));
166                }
167            }
168            ad::MANUFACTURER_DATA => {
169                if value.len() >= 2 {
170                    into.manufacturer_data = Some((
171                        u16::from_le_bytes([value[0], value[1]]),
172                        value[2..].to_vec(),
173                    ));
174                }
175            }
176            ad::SERVICE_DATA_16 => {
177                if value.len() >= 2 {
178                    into.service_data.push((
179                        canonical_16(u16::from_le_bytes([value[0], value[1]])),
180                        value[2..].to_vec(),
181                    ));
182                }
183            }
184            ad::SERVICE_DATA_32 => {
185                if value.len() >= 4 {
186                    into.service_data.push((
187                        canonical_32(u32::from_le_bytes([value[0], value[1], value[2], value[3]])),
188                        value[4..].to_vec(),
189                    ));
190                }
191            }
192            ad::SERVICE_DATA_128 => {
193                if value.len() >= 16 {
194                    if let Some(uuid) = canonical_128(&value[..16]) {
195                        into.service_data.push((uuid, value[16..].to_vec()));
196                    }
197                }
198            }
199            _ => {}
200        }
201        i += 1 + length;
202    }
203}
204
205/// Parse an HCI `LE Advertising Report` sub-event body.
206///
207/// Layout: number of reports, then per report — event type, address type,
208/// 6-byte address, data length, data, RSSI.
209pub fn parse_advertising_report(body: &[u8]) -> Vec<Advertisement> {
210    let mut out = Vec::new();
211    let Some(&count) = body.first() else {
212        return out;
213    };
214    let mut i = 1;
215    for _ in 0..count {
216        if i + 9 > body.len() {
217            break;
218        }
219        let event_type = body[i];
220        let address_type = body[i + 1];
221        let mut wire = [0u8; 6];
222        wire.copy_from_slice(&body[i + 2..i + 8]);
223        let data_len = body[i + 8] as usize;
224        if i + 9 + data_len + 1 > body.len() {
225            break;
226        }
227        let data = &body[i + 9..i + 9 + data_len];
228        let rssi = body[i + 9 + data_len] as i8;
229
230        let mut advertisement = Advertisement {
231            address: format_address(&wire),
232            random_address: address_type == 0x01 || address_type == 0x03,
233            rssi,
234            // Event type 0x00 ADV_IND and 0x01 ADV_DIRECT_IND accept connections.
235            connectable: event_type == 0x00 || event_type == 0x01,
236            ..Default::default()
237        };
238        parse_advertising_data(data, &mut advertisement);
239        out.push(advertisement);
240
241        i += 9 + data_len + 1;
242    }
243    out
244}
245
246/// `LE Extended Advertising Report`, the 5.0 form of the same event.
247///
248/// A legacy scan gets legacy reports, so this is not on the usual path — but a
249/// controller configured through the extended commands can emit these anyway,
250/// and a peer advertising extended-only PDUs is invisible without it. The
251/// layout is fixed-width per report and much longer than the legacy one, with
252/// the data length near the end rather than at offset 8.
253pub fn parse_extended_advertising_report(body: &[u8]) -> Vec<Advertisement> {
254    // event_type(2) addr_type(1) addr(6) primary_phy(1) secondary_phy(1)
255    // sid(1) tx_power(1) rssi(1) periodic_interval(2) direct_addr_type(1)
256    // direct_addr(6) data_len(1)
257    const FIXED: usize = 24;
258
259    let mut out = Vec::new();
260    let Some(&count) = body.first() else {
261        return out;
262    };
263    let mut i = 1;
264    for _ in 0..count {
265        if i + FIXED > body.len() {
266            break;
267        }
268        let event_type = u16::from_le_bytes([body[i], body[i + 1]]);
269        let address_type = body[i + 2];
270        let mut wire = [0u8; 6];
271        wire.copy_from_slice(&body[i + 3..i + 9]);
272        let tx_power = body[i + 12] as i8;
273        let rssi = body[i + 13] as i8;
274        let data_len = body[i + FIXED - 1] as usize;
275        if i + FIXED + data_len > body.len() {
276            break;
277        }
278        let data = &body[i + FIXED..i + FIXED + data_len];
279
280        let mut advertisement = Advertisement {
281            address: format_address(&wire),
282            random_address: address_type == 0x01 || address_type == 0x03,
283            rssi,
284            // Bit 0 of the event-type properties is "connectable", which
285            // replaces the legacy PDU-type comparison.
286            connectable: event_type & 0x0001 != 0,
287            ..Default::default()
288        };
289        parse_advertising_data(data, &mut advertisement);
290        // 127 means "not available" in this field, unlike the legacy report
291        // where tx power only appears as an AD record.
292        if tx_power != 127 && advertisement.tx_power.is_none() {
293            advertisement.tx_power = Some(tx_power);
294        }
295        out.push(advertisement);
296
297        i += FIXED + data_len;
298    }
299    out
300}
301
302// ── The socket ──────────────────────────────────────────────────────────────
303
304#[cfg(target_os = "linux")]
305mod socket {
306    use super::{parse_advertising_report, parse_extended_advertising_report, Advertisement};
307    use crate::sys::{
308        close, errno, read, socket, write, AF_BLUETOOTH, BTPROTO_HCI, EINTR, SOCK_RAW,
309    };
310    use std::ffi::{c_int, c_ulong};
311    use std::sync::atomic::{AtomicBool, Ordering};
312    use std::sync::Arc;
313
314    const HCI_CHANNEL_RAW: u16 = 0;
315    const SOL_HCI: c_int = 0;
316    const HCI_FILTER: c_int = 2;
317    const HCI_EVENT_PKT: u8 = 0x04;
318    const EVT_LE_META: u8 = 0x3E;
319    const SUBEVT_LE_ADVERTISING_REPORT: u8 = 0x02;
320    const SUBEVT_LE_EXTENDED_ADVERTISING_REPORT: u8 = 0x0D;
321    const OGF_LE_CTL: u16 = 0x08;
322    const OCF_LE_SET_SCAN_PARAMETERS: u16 = 0x000B;
323    const OCF_LE_SET_SCAN_ENABLE: u16 = 0x000C;
324
325    // Only the HCI-specific calls; the rest come from `crate::sys`.
326    use crate::sys::bind;
327    unsafe extern "C" {
328        /// Declared variadic because it is: giving it a concrete third
329        /// parameter would be a different function to the one that exists.
330        fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
331
332        fn setsockopt(
333            fd: c_int,
334            level: c_int,
335            name: c_int,
336            val: *const HciFilter,
337            len: u32,
338        ) -> c_int;
339    }
340
341    #[repr(C, packed)]
342    struct SockAddrHci {
343        family: u16,
344        dev: u16,
345        channel: u16,
346    }
347
348    /// `struct hci_filter`. Without one the socket delivers every packet the
349    /// controller produces, including ACL data for other connections.
350    #[repr(C)]
351    struct HciFilter {
352        type_mask: u32,
353        event_mask: [u32; 2],
354        opcode: u16,
355    }
356
357    /// A raw HCI socket bound to one controller.
358    pub struct HciSocket {
359        fd: c_int,
360        scanning: AtomicBool,
361    }
362
363    impl Drop for HciSocket {
364        fn drop(&mut self) {
365            if self.scanning.load(Ordering::Acquire) {
366                let _ = self.set_scan_enable(false);
367            }
368            unsafe { close(self.fd) };
369        }
370    }
371
372    /// One controller, as `HCIGETDEVLIST` and `HCIGETDEVINFO` describe it.
373    #[derive(Debug, Clone, PartialEq, Eq)]
374    pub struct DeviceInfo {
375        /// The controller index: 0 for `hci0`.
376        pub id: u16,
377        /// The kernel's name for it, which is `hci` followed by the index.
378        pub name: String,
379        /// The controller's own address, big-endian as written down.
380        pub address: String,
381        /// Whether the controller is up, which is `HCI_UP` in its flags.
382        pub powered: bool,
383    }
384
385    // The ioctl numbers are built rather than written down. `_IOR(type, nr,
386    // size)` packs a direction, a size, a type letter and a number into one
387    // word; hardcoding the result would be four transcription errors waiting
388    // to happen, and the layout is the same on every architecture this crate
389    // targets (all of them use asm-generic's `ioctl.h`).
390    const IOC_READ: u32 = 2;
391    const fn ior(kind: u8, number: u8, size: u32) -> u32 {
392        (IOC_READ << 30) | (size << 16) | ((kind as u32) << 8) | number as u32
393    }
394    /// `HCIGETDEVLIST` — `_IOR('H', 210, int)`.
395    const HCIGETDEVLIST: u32 = ior(b'H', 210, 4);
396    /// `HCIGETDEVINFO` — `_IOR('H', 211, int)`.
397    const HCIGETDEVINFO: u32 = ior(b'H', 211, 4);
398
399    /// `HCI_UP` is the first entry of the device-flags enum, so bit 0.
400    const HCI_UP: u32 = 1 << 0;
401
402    /// `struct hci_dev_info` is 92 bytes; the buffer is rounded up because the
403    /// kernel writes exactly `sizeof(di)` and a longer one costs nothing.
404    const DEV_INFO_LEN: usize = 128;
405    /// Offsets into `struct hci_dev_info`, from `include/net/bluetooth/hci_sock.h`.
406    const DEV_INFO_NAME: usize = 2;
407    const DEV_INFO_BDADDR: usize = 10;
408    const DEV_INFO_FLAGS: usize = 16;
409
410    /// Every controller the kernel knows about.
411    ///
412    /// This is what `hciconfig` prints. It needs no elevated privilege — the
413    /// ioctls are on an ordinary HCI socket, and reading the list is not a
414    /// privileged operation the way opening a raw controller is.
415    pub fn devices() -> Result<Vec<DeviceInfo>, String> {
416        // A control socket, only to have a descriptor to ioctl on. Which
417        // controller it is bound to does not matter and it is never bound.
418        let fd = unsafe { socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI) };
419        if fd < 0 {
420            return Err(format!(
421                "could not open an HCI control socket (errno {})",
422                errno()
423            ));
424        }
425        struct Fd(c_int);
426        impl Drop for Fd {
427            fn drop(&mut self) {
428                unsafe { close(self.0) };
429            }
430        }
431        let fd = Fd(fd);
432
433        // `struct hci_dev_list_req` is a count followed by that many
434        // `struct hci_dev_req`, which the kernel pads to 8 bytes each. The
435        // request array starts at offset 4, not 2, because `dev_opt` is a
436        // `__u32` and so the struct is 4-aligned.
437        const MAX: u16 = 16;
438        const REQ: usize = 8;
439        let mut buffer = vec![0u8; 4 + REQ * MAX as usize];
440        buffer[0..2].copy_from_slice(&MAX.to_ne_bytes());
441        let rc = unsafe { ioctl(fd.0, HCIGETDEVLIST as _, buffer.as_mut_ptr()) };
442        if rc < 0 {
443            return Err(format!("HCIGETDEVLIST failed (errno {})", errno()));
444        }
445
446        let count = u16::from_ne_bytes([buffer[0], buffer[1]]).min(MAX);
447        let mut out = Vec::with_capacity(count as usize);
448        for i in 0..count as usize {
449            let at = 4 + i * REQ;
450            let id = u16::from_ne_bytes([buffer[at], buffer[at + 1]]);
451            if let Some(info) = device_info(fd.0, id) {
452                out.push(info);
453            }
454        }
455        out.sort_by_key(|d| d.id);
456        Ok(out)
457    }
458
459    /// `HCIGETDEVINFO` for one controller, or `None` if it vanished between
460    /// being listed and being asked about.
461    fn device_info(fd: c_int, id: u16) -> Option<DeviceInfo> {
462        let mut buffer = vec![0u8; DEV_INFO_LEN];
463        buffer[0..2].copy_from_slice(&id.to_ne_bytes());
464        let rc = unsafe { ioctl(fd, HCIGETDEVINFO as _, buffer.as_mut_ptr()) };
465        if rc < 0 {
466            return None;
467        }
468
469        let name = &buffer[DEV_INFO_NAME..DEV_INFO_NAME + 8];
470        let name = name.iter().position(|b| *b == 0).unwrap_or(name.len());
471        let name =
472            String::from_utf8_lossy(&buffer[DEV_INFO_NAME..DEV_INFO_NAME + name]).into_owned();
473
474        let flags = u32::from_ne_bytes([
475            buffer[DEV_INFO_FLAGS],
476            buffer[DEV_INFO_FLAGS + 1],
477            buffer[DEV_INFO_FLAGS + 2],
478            buffer[DEV_INFO_FLAGS + 3],
479        ]);
480
481        Some(DeviceInfo {
482            id,
483            name: if name.is_empty() {
484                format!("hci{id}")
485            } else {
486                name
487            },
488            address: format_address(&buffer[DEV_INFO_BDADDR..DEV_INFO_BDADDR + 6]),
489            powered: flags & HCI_UP != 0,
490        })
491    }
492
493    /// A `bdaddr_t` is little-endian on the wire and written big-endian, so
494    /// the bytes are reversed before formatting — the same convention the
495    /// advertisement parser uses.
496    fn format_address(bytes: &[u8]) -> String {
497        bytes
498            .iter()
499            .rev()
500            .map(|b| format!("{b:02X}"))
501            .collect::<Vec<_>>()
502            .join(":")
503    }
504
505    impl HciSocket {
506        /// Open controller `device` — 0 for `hci0`.
507        pub fn open(device: u16) -> Result<Self, String> {
508            let fd = unsafe { socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI) };
509            if fd < 0 {
510                return Err(format!(
511                    "could not open an HCI socket (errno {}); this needs CAP_NET_RAW",
512                    errno()
513                ));
514            }
515            let socket = Self {
516                fd,
517                scanning: AtomicBool::new(false),
518            };
519
520            // Take only HCI events, and within them only LE Meta.
521            let filter = HciFilter {
522                type_mask: 1 << HCI_EVENT_PKT,
523                event_mask: [0, 1 << (EVT_LE_META - 32)],
524                opcode: 0,
525            };
526            let rc = unsafe {
527                setsockopt(
528                    fd,
529                    SOL_HCI,
530                    HCI_FILTER,
531                    &filter,
532                    std::mem::size_of::<HciFilter>() as u32,
533                )
534            };
535            if rc < 0 {
536                return Err(format!("could not set the HCI filter (errno {})", errno()));
537            }
538
539            let addr = SockAddrHci {
540                family: AF_BLUETOOTH as u16,
541                dev: device,
542                channel: HCI_CHANNEL_RAW,
543            };
544            let len = std::mem::size_of::<SockAddrHci>() as u32;
545            let rc = unsafe { bind(fd, (&raw const addr).cast(), len) };
546            if rc < 0 {
547                return Err(format!(
548                    "could not bind hci{device} (errno {}); is the adapter present and up?",
549                    errno()
550                ));
551            }
552            Ok(socket)
553        }
554
555        fn command(&self, ogf: u16, ocf: u16, params: &[u8]) -> Result<(), String> {
556            // HCI command packet: 0x01, opcode (le16), length, parameters.
557            let opcode = (ogf << 10) | ocf;
558            let mut packet = vec![0x01];
559            packet.extend_from_slice(&opcode.to_le_bytes());
560            packet.push(params.len() as u8);
561            packet.extend_from_slice(params);
562
563            let n = unsafe { write(self.fd, packet.as_ptr(), packet.len()) };
564            if n as usize != packet.len() {
565                return Err(format!(
566                    "HCI command 0x{opcode:04x} failed (errno {})",
567                    errno()
568                ));
569            }
570            Ok(())
571        }
572
573        /// Passive scan, 10 ms window every 10 ms — continuous coverage.
574        pub fn set_scan_parameters(&self) -> Result<(), String> {
575            // type=0 passive, interval=0x0010, window=0x0010, own addr public,
576            // filter policy accept all.
577            self.command(
578                OGF_LE_CTL,
579                OCF_LE_SET_SCAN_PARAMETERS,
580                &[0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x00],
581            )
582        }
583
584        pub fn set_scan_enable(&self, enable: bool) -> Result<(), String> {
585            // enable, filter_duplicates = 0 so RSSI keeps updating.
586            self.command(
587                OGF_LE_CTL,
588                OCF_LE_SET_SCAN_ENABLE,
589                &[u8::from(enable), 0x00],
590            )?;
591            self.scanning.store(enable, Ordering::Release);
592            Ok(())
593        }
594
595        /// Scan until `stop` is set, reporting each advertisement.
596        pub fn scan(
597            &self,
598            stop: Arc<AtomicBool>,
599            mut on_advertisement: impl FnMut(Advertisement),
600        ) -> Result<(), String> {
601            self.set_scan_parameters()?;
602            self.set_scan_enable(true)?;
603
604            let mut buf = [0u8; 260];
605            while !stop.load(Ordering::Acquire) {
606                let n = unsafe { read(self.fd, buf.as_mut_ptr(), buf.len()) };
607                if n < 0 {
608                    if errno() == EINTR {
609                        continue; // EINTR
610                    }
611                    break;
612                }
613                let packet = &buf[..n as usize];
614                // 0x04 event, event code, length, body.
615                if packet.len() < 4 || packet[0] != HCI_EVENT_PKT || packet[1] != EVT_LE_META {
616                    continue;
617                }
618                let body = &packet[3..];
619                let advertisements = match body.first() {
620                    Some(&SUBEVT_LE_ADVERTISING_REPORT) => parse_advertising_report(&body[1..]),
621                    Some(&SUBEVT_LE_EXTENDED_ADVERTISING_REPORT) => {
622                        parse_extended_advertising_report(&body[1..])
623                    }
624                    _ => continue,
625                };
626                for advertisement in advertisements {
627                    on_advertisement(advertisement);
628                }
629            }
630            let _ = self.set_scan_enable(false);
631            Ok(())
632        }
633    }
634}
635
636#[cfg(target_os = "linux")]
637pub use socket::{devices, DeviceInfo, HciSocket};
638
639#[cfg(test)]
640mod tests {
641    use super::*;
642
643    #[test]
644    fn addresses_are_printed_in_written_order() {
645        // The wire carries least-significant first.
646        assert_eq!(
647            format_address(&[0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA]),
648            "AA:BB:CC:DD:EE:FF"
649        );
650    }
651
652    #[test]
653    fn advertising_data_records_parse() {
654        let data = [
655            0x02, 0x01, 0x06, // flags: general discoverable
656            0x03, 0x03, 0x0D, 0x18, // complete 16-bit services: 0x180D
657            0x09, 0x09, b'P', b'o', b'l', b'a', b'r', b' ', b'H', b'1', // complete name
658            0x02, 0x0A, 0xF4, // tx power -12
659        ];
660        let mut advertisement = Advertisement::default();
661        parse_advertising_data(&data, &mut advertisement);
662
663        assert_eq!(advertisement.local_name.as_deref(), Some("Polar H1"));
664        assert_eq!(
665            advertisement.service_uuids,
666            vec!["0000180d-0000-1000-8000-00805f9b34fb"]
667        );
668        assert_eq!(advertisement.tx_power, Some(-12));
669        assert!(advertisement.connectable);
670    }
671
672    #[test]
673    fn a_complete_name_wins_over_a_shortened_one() {
674        let data = [
675            0x03, 0x08, b'P', b'o', // shortened "Po"
676            0x06, 0x09, b'P', b'o', b'l', b'a', b'r', // complete "Polar"
677        ];
678        let mut a = Advertisement::default();
679        parse_advertising_data(&data, &mut a);
680        assert_eq!(a.local_name.as_deref(), Some("Polar"));
681    }
682
683    #[test]
684    fn manufacturer_and_service_data_split_their_identifiers() {
685        let data = [
686            0x05, 0xFF, 0x4C, 0x00, 0x02, 0x15, // Apple, payload 02 15
687            0x05, 0x16, 0x0F, 0x18, 0x5B, 0x01, // battery service data
688        ];
689        let mut a = Advertisement::default();
690        parse_advertising_data(&data, &mut a);
691        assert_eq!(a.manufacturer_data, Some((0x004C, vec![0x02, 0x15])));
692        assert_eq!(a.service_data.len(), 1);
693        assert_eq!(a.service_data[0].0, "0000180f-0000-1000-8000-00805f9b34fb");
694        assert_eq!(a.service_data[0].1, vec![0x5B, 0x01]);
695    }
696
697    #[test]
698    fn a_128_bit_service_uuid_is_reversed() {
699        let mut data = vec![0x11, 0x07];
700        // 6e400001-… on the wire, least-significant first.
701        data.extend_from_slice(&[
702            0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, 0x93, 0xF3, 0xA3, 0xB5, 0x01, 0x00,
703            0x40, 0x6E,
704        ]);
705        let mut a = Advertisement::default();
706        parse_advertising_data(&data, &mut a);
707        assert_eq!(
708            a.service_uuids,
709            vec!["6e400001-b5a3-f393-e0a9-e50e24dcca9e"]
710        );
711    }
712
713    #[test]
714    fn a_zero_length_record_terminates_the_payload() {
715        // Padding after the records must not be decoded as more records.
716        let data = [0x02, 0x01, 0x06, 0x00, 0xFF, 0xFF, 0xFF];
717        let mut a = Advertisement::default();
718        parse_advertising_data(&data, &mut a);
719        assert!(
720            a.manufacturer_data.is_none(),
721            "padding was decoded as a record"
722        );
723    }
724
725    #[test]
726    fn a_record_longer_than_the_payload_is_dropped() {
727        // Reachable from any broken or hostile peer.
728        let data = [0x20, 0x09, b'x'];
729        let mut a = Advertisement::default();
730        parse_advertising_data(&data, &mut a);
731        assert_eq!(a.local_name, None);
732    }
733
734    #[test]
735    fn an_advertising_report_decodes() {
736        let mut body = vec![
737            0x01, // one report
738            0x00, // ADV_IND — connectable
739            0x00, // public address
740            0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, // address, wire order
741            0x05, // data length
742            0x02, 0x01, 0x06, 0x00, 0x00,
743        ];
744        body.push(0xC5); // RSSI -59
745        let reports = parse_advertising_report(&body);
746        assert_eq!(reports.len(), 1);
747        assert_eq!(reports[0].address, "AA:BB:CC:DD:EE:FF");
748        assert_eq!(reports[0].rssi, -59);
749        assert!(reports[0].connectable);
750        assert!(!reports[0].random_address);
751    }
752
753    #[test]
754    fn a_truncated_report_stops_rather_than_over_reading() {
755        // Claims two reports but carries one.
756        let body = [0x02, 0x00, 0x00, 1, 2, 3, 4, 5, 6, 0x00, 0xC5];
757        let reports = parse_advertising_report(&body);
758        assert_eq!(reports.len(), 1);
759        assert!(parse_advertising_report(&[]).is_empty());
760        assert!(parse_advertising_report(&[0x01, 0x00]).is_empty());
761    }
762
763    /// The extended report is a different layout, not a longer one: the data
764    /// length sits at the end of a 24-byte fixed part, and connectability is a
765    /// property bit rather than a PDU-type comparison.
766    #[test]
767    fn extended_advertising_reports_parse() {
768        let mut body = vec![0x01]; // one report
769        body.extend_from_slice(&0x0013u16.to_le_bytes()); // connectable|scannable|legacy
770        body.push(0x00); // public address
771        body.extend_from_slice(&[0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); // address, LSB first
772        body.push(0x01); // primary phy
773        body.push(0x01); // secondary phy
774        body.push(0x00); // sid
775        body.push(0xF4u8); // tx power -12
776        body.push(0xC0u8); // rssi -64
777        body.extend_from_slice(&0u16.to_le_bytes()); // periodic interval
778        body.push(0x00); // direct address type
779        body.extend_from_slice(&[0u8; 6]); // direct address
780        let data = [
781            0x03, 0x03, 0x0D, 0x18, // complete 16-bit services: 0x180D
782            0x06, 0x09, b'P', b'o', b'l', b'a', b'r', // complete name
783        ];
784        body.push(data.len() as u8);
785        body.extend_from_slice(&data);
786
787        let reports = parse_extended_advertising_report(&body);
788        assert_eq!(reports.len(), 1);
789        let a = &reports[0];
790        assert_eq!(a.address, "06:05:04:03:02:01");
791        assert_eq!(a.rssi, -64);
792        assert_eq!(a.tx_power, Some(-12));
793        assert!(a.connectable);
794        assert_eq!(a.local_name.as_deref(), Some("Polar"));
795        assert_eq!(
796            a.service_uuids,
797            vec!["0000180d-0000-1000-8000-00805f9b34fb"]
798        );
799    }
800
801    #[test]
802    fn a_truncated_extended_report_is_dropped_not_guessed() {
803        // One report promised, fixed part cut short.
804        assert!(parse_extended_advertising_report(&[0x01, 0x13, 0x00, 0x00]).is_empty());
805        assert!(parse_extended_advertising_report(&[]).is_empty());
806    }
807
808    #[test]
809    fn a_non_connectable_extended_report_says_so() {
810        let mut body = vec![0x01];
811        body.extend_from_slice(&0x0012u16.to_le_bytes()); // scannable, not connectable
812        body.push(0x01); // random address
813        body.extend_from_slice(&[0u8; 6]);
814        body.extend_from_slice(&[0x01, 0x01, 0x00, 127, 0xC0]);
815        body.extend_from_slice(&0u16.to_le_bytes());
816        body.push(0x00);
817        body.extend_from_slice(&[0u8; 6]);
818        body.push(0);
819        let reports = parse_extended_advertising_report(&body);
820        assert_eq!(reports.len(), 1);
821        assert!(!reports[0].connectable);
822        assert!(reports[0].random_address);
823        // 127 means "unavailable" and must not be reported as a real reading.
824        assert_eq!(reports[0].tx_power, None);
825    }
826}