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_long, 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    const SOL_SOCKET: c_int = 1;
335    const SO_RCVTIMEO: c_int = 20;
336    /// `EAGAIN`, which is also `EWOULDBLOCK`: the receive timeout expired.
337    const EAGAIN: i32 = 11;
338    /// How often a scan with nothing to read looks at its stop flag.
339    const POLL_INTERVAL_US: c_long = 100_000;
340
341    /// `struct timeval`, for `SO_RCVTIMEO`: two C `long`s, so 8 bytes on a
342    /// 32-bit Pi and 16 on 64-bit. Fixed-width fields would hand a 32-bit
343    /// kernel a zero timeout, which means "block for ever".
344    #[repr(C)]
345    struct Timeval {
346        tv_sec: c_long,
347        tv_usec: c_long,
348    }
349
350    // Only the HCI-specific calls; the rest come from `crate::sys`.
351    use crate::sys::{bind, bluetooth_setsockopt};
352    unsafe extern "C" {
353        /// Declared variadic because it is: giving it a concrete third
354        /// parameter would be a different function to the one that exists.
355        fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
356    }
357
358    #[repr(C, packed)]
359    struct SockAddrHci {
360        family: u16,
361        dev: u16,
362        channel: u16,
363    }
364
365    /// `struct hci_filter`. Without one the socket delivers every packet the
366    /// controller produces, including ACL data for other connections.
367    #[repr(C)]
368    struct HciFilter {
369        type_mask: u32,
370        event_mask: [u32; 2],
371        opcode: u16,
372    }
373
374    /// A raw HCI socket bound to one controller.
375    pub struct HciSocket {
376        fd: c_int,
377        scanning: AtomicBool,
378    }
379
380    impl Drop for HciSocket {
381        fn drop(&mut self) {
382            if self.scanning.load(Ordering::Acquire) {
383                let _ = self.set_scan_enable(false);
384            }
385            unsafe { close(self.fd) };
386        }
387    }
388
389    /// One controller, as `HCIGETDEVLIST` and `HCIGETDEVINFO` describe it.
390    #[derive(Debug, Clone, PartialEq, Eq)]
391    pub struct DeviceInfo {
392        /// The controller index: 0 for `hci0`.
393        pub id: u16,
394        /// The kernel's name for it, which is `hci` followed by the index.
395        pub name: String,
396        /// The controller's own address, big-endian as written down.
397        pub address: String,
398        /// Whether the controller is up, which is `HCI_UP` in its flags.
399        pub powered: bool,
400    }
401
402    // The ioctl numbers are built rather than written down. `_IOR(type, nr,
403    // size)` packs a direction, a size, a type letter and a number into one
404    // word; hardcoding the result would be four transcription errors waiting
405    // to happen, and the layout is the same on every architecture this crate
406    // targets (all of them use asm-generic's `ioctl.h`).
407    const IOC_READ: u32 = 2;
408    const fn ior(kind: u8, number: u8, size: u32) -> u32 {
409        (IOC_READ << 30) | (size << 16) | ((kind as u32) << 8) | number as u32
410    }
411    /// `HCIGETDEVLIST` — `_IOR('H', 210, int)`.
412    const HCIGETDEVLIST: u32 = ior(b'H', 210, 4);
413    /// `HCIGETDEVINFO` — `_IOR('H', 211, int)`.
414    const HCIGETDEVINFO: u32 = ior(b'H', 211, 4);
415
416    /// `HCI_UP` is the first entry of the device-flags enum, so bit 0.
417    const HCI_UP: u32 = 1 << 0;
418
419    /// `struct hci_dev_info` is 92 bytes; the buffer is rounded up because the
420    /// kernel writes exactly `sizeof(di)` and a longer one costs nothing.
421    const DEV_INFO_LEN: usize = 128;
422    /// Offsets into `struct hci_dev_info`, from `include/net/bluetooth/hci_sock.h`.
423    const DEV_INFO_NAME: usize = 2;
424    const DEV_INFO_BDADDR: usize = 10;
425    const DEV_INFO_FLAGS: usize = 16;
426
427    /// Every controller the kernel knows about.
428    ///
429    /// This is what `hciconfig` prints. It needs no elevated privilege — the
430    /// ioctls are on an ordinary HCI socket, and reading the list is not a
431    /// privileged operation the way opening a raw controller is.
432    pub fn devices() -> Result<Vec<DeviceInfo>, String> {
433        // A control socket, only to have a descriptor to ioctl on. Which
434        // controller it is bound to does not matter and it is never bound.
435        let fd = unsafe { socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI) };
436        if fd < 0 {
437            return Err(format!(
438                "could not open an HCI control socket (errno {})",
439                errno()
440            ));
441        }
442        struct Fd(c_int);
443        impl Drop for Fd {
444            fn drop(&mut self) {
445                unsafe { close(self.0) };
446            }
447        }
448        let fd = Fd(fd);
449
450        // `struct hci_dev_list_req` is a count followed by that many
451        // `struct hci_dev_req`, which the kernel pads to 8 bytes each. The
452        // request array starts at offset 4, not 2, because `dev_opt` is a
453        // `__u32` and so the struct is 4-aligned.
454        const MAX: u16 = 16;
455        const REQ: usize = 8;
456        let mut buffer = vec![0u8; 4 + REQ * MAX as usize];
457        buffer[0..2].copy_from_slice(&MAX.to_ne_bytes());
458        let rc = unsafe { ioctl(fd.0, HCIGETDEVLIST as _, buffer.as_mut_ptr()) };
459        if rc < 0 {
460            return Err(format!("HCIGETDEVLIST failed (errno {})", errno()));
461        }
462
463        let count = u16::from_ne_bytes([buffer[0], buffer[1]]).min(MAX);
464        let mut out = Vec::with_capacity(count as usize);
465        for i in 0..count as usize {
466            let at = 4 + i * REQ;
467            let id = u16::from_ne_bytes([buffer[at], buffer[at + 1]]);
468            if let Some(info) = device_info(fd.0, id) {
469                out.push(info);
470            }
471        }
472        out.sort_by_key(|d| d.id);
473        Ok(out)
474    }
475
476    /// `HCIGETDEVINFO` for one controller, or `None` if it vanished between
477    /// being listed and being asked about.
478    fn device_info(fd: c_int, id: u16) -> Option<DeviceInfo> {
479        let mut buffer = vec![0u8; DEV_INFO_LEN];
480        buffer[0..2].copy_from_slice(&id.to_ne_bytes());
481        let rc = unsafe { ioctl(fd, HCIGETDEVINFO as _, buffer.as_mut_ptr()) };
482        if rc < 0 {
483            return None;
484        }
485
486        let name = &buffer[DEV_INFO_NAME..DEV_INFO_NAME + 8];
487        let name = name.iter().position(|b| *b == 0).unwrap_or(name.len());
488        let name =
489            String::from_utf8_lossy(&buffer[DEV_INFO_NAME..DEV_INFO_NAME + name]).into_owned();
490
491        let flags = u32::from_ne_bytes([
492            buffer[DEV_INFO_FLAGS],
493            buffer[DEV_INFO_FLAGS + 1],
494            buffer[DEV_INFO_FLAGS + 2],
495            buffer[DEV_INFO_FLAGS + 3],
496        ]);
497
498        Some(DeviceInfo {
499            id,
500            name: if name.is_empty() {
501                format!("hci{id}")
502            } else {
503                name
504            },
505            address: format_address(&buffer[DEV_INFO_BDADDR..DEV_INFO_BDADDR + 6]),
506            powered: flags & HCI_UP != 0,
507        })
508    }
509
510    /// A `bdaddr_t` is little-endian on the wire and written big-endian, so
511    /// the bytes are reversed before formatting — the same convention the
512    /// advertisement parser uses.
513    fn format_address(bytes: &[u8]) -> String {
514        bytes
515            .iter()
516            .rev()
517            .map(|b| format!("{b:02X}"))
518            .collect::<Vec<_>>()
519            .join(":")
520    }
521
522    impl HciSocket {
523        /// Open controller `device` — 0 for `hci0`.
524        pub fn open(device: u16) -> Result<Self, String> {
525            let fd = unsafe { socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI) };
526            if fd < 0 {
527                return Err(format!(
528                    "could not open an HCI socket (errno {}); this needs CAP_NET_RAW",
529                    errno()
530                ));
531            }
532            let socket = Self {
533                fd,
534                scanning: AtomicBool::new(false),
535            };
536
537            // Take only HCI events, and within them only LE Meta.
538            let filter = HciFilter {
539                type_mask: 1 << HCI_EVENT_PKT,
540                event_mask: [0, 1 << (EVT_LE_META - 32)],
541                opcode: 0,
542            };
543            let rc = unsafe {
544                bluetooth_setsockopt(
545                    fd,
546                    SOL_HCI,
547                    HCI_FILTER,
548                    (&raw const filter).cast(),
549                    std::mem::size_of::<HciFilter>() as u32,
550                )
551            };
552            if rc < 0 {
553                return Err(format!("could not set the HCI filter (errno {})", errno()));
554            }
555
556            let addr = SockAddrHci {
557                family: AF_BLUETOOTH as u16,
558                dev: device,
559                channel: HCI_CHANNEL_RAW,
560            };
561            let len = std::mem::size_of::<SockAddrHci>() as u32;
562            let rc = unsafe { bind(fd, (&raw const addr).cast(), len) };
563            if rc < 0 {
564                return Err(format!(
565                    "could not bind hci{device} (errno {}); is the adapter present and up?",
566                    errno()
567                ));
568            }
569            Ok(socket)
570        }
571
572        fn command(&self, ogf: u16, ocf: u16, params: &[u8]) -> Result<(), String> {
573            // HCI command packet: 0x01, opcode (le16), length, parameters.
574            let opcode = (ogf << 10) | ocf;
575            let mut packet = vec![0x01];
576            packet.extend_from_slice(&opcode.to_le_bytes());
577            packet.push(params.len() as u8);
578            packet.extend_from_slice(params);
579
580            let n = unsafe { write(self.fd, packet.as_ptr(), packet.len()) };
581            if n as usize != packet.len() {
582                return Err(format!(
583                    "HCI command 0x{opcode:04x} failed (errno {})",
584                    errno()
585                ));
586            }
587            Ok(())
588        }
589
590        /// Passive scan, 10 ms window every 10 ms — continuous coverage.
591        pub fn set_scan_parameters(&self) -> Result<(), String> {
592            // type=0 passive, interval=0x0010, window=0x0010, own addr public,
593            // filter policy accept all.
594            self.command(
595                OGF_LE_CTL,
596                OCF_LE_SET_SCAN_PARAMETERS,
597                &[0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x00],
598            )
599        }
600
601        pub fn set_scan_enable(&self, enable: bool) -> Result<(), String> {
602            // enable, filter_duplicates = 0 so RSSI keeps updating.
603            self.command(
604                OGF_LE_CTL,
605                OCF_LE_SET_SCAN_ENABLE,
606                &[u8::from(enable), 0x00],
607            )?;
608            self.scanning.store(enable, Ordering::Release);
609            Ok(())
610        }
611
612        /// Scan until `stop` is set, reporting each advertisement.
613        pub fn scan(
614            &self,
615            stop: Arc<AtomicBool>,
616            mut on_advertisement: impl FnMut(Advertisement),
617        ) -> Result<(), String> {
618            // Without a timeout the read below blocks until the next
619            // advertisement, and a stop request waits for it — with the
620            // controller still scanning. A connection started in that window
621            // then has the scan disabled underneath it at an arbitrary moment,
622            // which is a connect that fails with ECONNREFUSED or EINPROGRESS
623            // for no reason visible to the caller.
624            let timeout = Timeval {
625                tv_sec: 0,
626                tv_usec: POLL_INTERVAL_US,
627            };
628            let rc = unsafe {
629                bluetooth_setsockopt(
630                    self.fd,
631                    SOL_SOCKET,
632                    SO_RCVTIMEO,
633                    (&raw const timeout).cast(),
634                    std::mem::size_of::<Timeval>() as u32,
635                )
636            };
637            if rc < 0 {
638                return Err(format!(
639                    "could not set the HCI receive timeout (errno {})",
640                    errno()
641                ));
642            }
643
644            self.set_scan_parameters()?;
645            self.set_scan_enable(true)?;
646
647            let mut buf = [0u8; 260];
648            while !stop.load(Ordering::Acquire) {
649                let n = unsafe { read(self.fd, buf.as_mut_ptr(), buf.len()) };
650                if n < 0 {
651                    match errno() {
652                        EINTR | EAGAIN => continue,
653                        _ => break,
654                    }
655                }
656                let packet = &buf[..n as usize];
657                // 0x04 event, event code, length, body.
658                if packet.len() < 4 || packet[0] != HCI_EVENT_PKT || packet[1] != EVT_LE_META {
659                    continue;
660                }
661                let body = &packet[3..];
662                let advertisements = match body.first() {
663                    Some(&SUBEVT_LE_ADVERTISING_REPORT) => parse_advertising_report(&body[1..]),
664                    Some(&SUBEVT_LE_EXTENDED_ADVERTISING_REPORT) => {
665                        parse_extended_advertising_report(&body[1..])
666                    }
667                    _ => continue,
668                };
669                for advertisement in advertisements {
670                    on_advertisement(advertisement);
671                }
672            }
673            let _ = self.set_scan_enable(false);
674            Ok(())
675        }
676    }
677}
678
679#[cfg(target_os = "linux")]
680pub use socket::{devices, DeviceInfo, HciSocket};
681
682#[cfg(test)]
683mod tests {
684    use super::*;
685
686    #[test]
687    fn addresses_are_printed_in_written_order() {
688        // The wire carries least-significant first.
689        assert_eq!(
690            format_address(&[0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA]),
691            "AA:BB:CC:DD:EE:FF"
692        );
693    }
694
695    #[test]
696    fn advertising_data_records_parse() {
697        let data = [
698            0x02, 0x01, 0x06, // flags: general discoverable
699            0x03, 0x03, 0x0D, 0x18, // complete 16-bit services: 0x180D
700            0x09, 0x09, b'P', b'o', b'l', b'a', b'r', b' ', b'H', b'1', // complete name
701            0x02, 0x0A, 0xF4, // tx power -12
702        ];
703        let mut advertisement = Advertisement::default();
704        parse_advertising_data(&data, &mut advertisement);
705
706        assert_eq!(advertisement.local_name.as_deref(), Some("Polar H1"));
707        assert_eq!(
708            advertisement.service_uuids,
709            vec!["0000180d-0000-1000-8000-00805f9b34fb"]
710        );
711        assert_eq!(advertisement.tx_power, Some(-12));
712        assert!(advertisement.connectable);
713    }
714
715    #[test]
716    fn a_complete_name_wins_over_a_shortened_one() {
717        let data = [
718            0x03, 0x08, b'P', b'o', // shortened "Po"
719            0x06, 0x09, b'P', b'o', b'l', b'a', b'r', // complete "Polar"
720        ];
721        let mut a = Advertisement::default();
722        parse_advertising_data(&data, &mut a);
723        assert_eq!(a.local_name.as_deref(), Some("Polar"));
724    }
725
726    #[test]
727    fn manufacturer_and_service_data_split_their_identifiers() {
728        let data = [
729            0x05, 0xFF, 0x4C, 0x00, 0x02, 0x15, // Apple, payload 02 15
730            0x05, 0x16, 0x0F, 0x18, 0x5B, 0x01, // battery service data
731        ];
732        let mut a = Advertisement::default();
733        parse_advertising_data(&data, &mut a);
734        assert_eq!(a.manufacturer_data, Some((0x004C, vec![0x02, 0x15])));
735        assert_eq!(a.service_data.len(), 1);
736        assert_eq!(a.service_data[0].0, "0000180f-0000-1000-8000-00805f9b34fb");
737        assert_eq!(a.service_data[0].1, vec![0x5B, 0x01]);
738    }
739
740    #[test]
741    fn a_128_bit_service_uuid_is_reversed() {
742        let mut data = vec![0x11, 0x07];
743        // 6e400001-… on the wire, least-significant first.
744        data.extend_from_slice(&[
745            0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, 0x93, 0xF3, 0xA3, 0xB5, 0x01, 0x00,
746            0x40, 0x6E,
747        ]);
748        let mut a = Advertisement::default();
749        parse_advertising_data(&data, &mut a);
750        assert_eq!(
751            a.service_uuids,
752            vec!["6e400001-b5a3-f393-e0a9-e50e24dcca9e"]
753        );
754    }
755
756    #[test]
757    fn a_zero_length_record_terminates_the_payload() {
758        // Padding after the records must not be decoded as more records.
759        let data = [0x02, 0x01, 0x06, 0x00, 0xFF, 0xFF, 0xFF];
760        let mut a = Advertisement::default();
761        parse_advertising_data(&data, &mut a);
762        assert!(
763            a.manufacturer_data.is_none(),
764            "padding was decoded as a record"
765        );
766    }
767
768    #[test]
769    fn a_record_longer_than_the_payload_is_dropped() {
770        // Reachable from any broken or hostile peer.
771        let data = [0x20, 0x09, b'x'];
772        let mut a = Advertisement::default();
773        parse_advertising_data(&data, &mut a);
774        assert_eq!(a.local_name, None);
775    }
776
777    #[test]
778    fn an_advertising_report_decodes() {
779        let mut body = vec![
780            0x01, // one report
781            0x00, // ADV_IND — connectable
782            0x00, // public address
783            0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, // address, wire order
784            0x05, // data length
785            0x02, 0x01, 0x06, 0x00, 0x00,
786        ];
787        body.push(0xC5); // RSSI -59
788        let reports = parse_advertising_report(&body);
789        assert_eq!(reports.len(), 1);
790        assert_eq!(reports[0].address, "AA:BB:CC:DD:EE:FF");
791        assert_eq!(reports[0].rssi, -59);
792        assert!(reports[0].connectable);
793        assert!(!reports[0].random_address);
794    }
795
796    #[test]
797    fn a_truncated_report_stops_rather_than_over_reading() {
798        // Claims two reports but carries one.
799        let body = [0x02, 0x00, 0x00, 1, 2, 3, 4, 5, 6, 0x00, 0xC5];
800        let reports = parse_advertising_report(&body);
801        assert_eq!(reports.len(), 1);
802        assert!(parse_advertising_report(&[]).is_empty());
803        assert!(parse_advertising_report(&[0x01, 0x00]).is_empty());
804    }
805
806    /// The extended report is a different layout, not a longer one: the data
807    /// length sits at the end of a 24-byte fixed part, and connectability is a
808    /// property bit rather than a PDU-type comparison.
809    #[test]
810    fn extended_advertising_reports_parse() {
811        let mut body = vec![0x01]; // one report
812        body.extend_from_slice(&0x0013u16.to_le_bytes()); // connectable|scannable|legacy
813        body.push(0x00); // public address
814        body.extend_from_slice(&[0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); // address, LSB first
815        body.push(0x01); // primary phy
816        body.push(0x01); // secondary phy
817        body.push(0x00); // sid
818        body.push(0xF4u8); // tx power -12
819        body.push(0xC0u8); // rssi -64
820        body.extend_from_slice(&0u16.to_le_bytes()); // periodic interval
821        body.push(0x00); // direct address type
822        body.extend_from_slice(&[0u8; 6]); // direct address
823        let data = [
824            0x03, 0x03, 0x0D, 0x18, // complete 16-bit services: 0x180D
825            0x06, 0x09, b'P', b'o', b'l', b'a', b'r', // complete name
826        ];
827        body.push(data.len() as u8);
828        body.extend_from_slice(&data);
829
830        let reports = parse_extended_advertising_report(&body);
831        assert_eq!(reports.len(), 1);
832        let a = &reports[0];
833        assert_eq!(a.address, "06:05:04:03:02:01");
834        assert_eq!(a.rssi, -64);
835        assert_eq!(a.tx_power, Some(-12));
836        assert!(a.connectable);
837        assert_eq!(a.local_name.as_deref(), Some("Polar"));
838        assert_eq!(
839            a.service_uuids,
840            vec!["0000180d-0000-1000-8000-00805f9b34fb"]
841        );
842    }
843
844    #[test]
845    fn a_truncated_extended_report_is_dropped_not_guessed() {
846        // One report promised, fixed part cut short.
847        assert!(parse_extended_advertising_report(&[0x01, 0x13, 0x00, 0x00]).is_empty());
848        assert!(parse_extended_advertising_report(&[]).is_empty());
849    }
850
851    #[test]
852    fn a_non_connectable_extended_report_says_so() {
853        let mut body = vec![0x01];
854        body.extend_from_slice(&0x0012u16.to_le_bytes()); // scannable, not connectable
855        body.push(0x01); // random address
856        body.extend_from_slice(&[0u8; 6]);
857        body.extend_from_slice(&[0x01, 0x01, 0x00, 127, 0xC0]);
858        body.extend_from_slice(&0u16.to_le_bytes());
859        body.push(0x00);
860        body.extend_from_slice(&[0u8; 6]);
861        body.push(0);
862        let reports = parse_extended_advertising_report(&body);
863        assert_eq!(reports.len(), 1);
864        assert!(!reports[0].connectable);
865        assert!(reports[0].random_address);
866        // 127 means "unavailable" and must not be reported as a real reading.
867        assert_eq!(reports[0].tx_power, None);
868    }
869}