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