Skip to main content

webbluetooth_linux/
sys.rs

1//! The Bluetooth socket family.
2//!
3//! Both Linux transports here are `AF_BLUETOOTH` sockets, so the address
4//! layout, the address parsing and the libc externs live once rather than once
5//! per transport.
6
7use std::ffi::{c_int, c_void};
8
9pub const AF_BLUETOOTH: c_int = 31;
10pub const SOCK_SEQPACKET: c_int = 5;
11pub const SOCK_STREAM: c_int = 1;
12pub const SOCK_RAW: c_int = 3;
13pub const BTPROTO_L2CAP: c_int = 0;
14pub const BTPROTO_RFCOMM: c_int = 3;
15pub const SOL_BLUETOOTH: c_int = 274;
16pub const BT_SECURITY: c_int = 4;
17/// Only meaningful on the SDP channel; see [`set_classic_security`].
18#[allow(dead_code)]
19pub const BT_SECURITY_SDP: u8 = 0;
20pub const BT_SECURITY_LOW: u8 = 1;
21pub const BT_SECURITY_MEDIUM: u8 = 2;
22pub const BT_SECURITY_HIGH: u8 = 3;
23pub const BT_SECURITY_FIPS: u8 = 4;
24pub const BTPROTO_HCI: c_int = 1;
25pub const BDADDR_LE_PUBLIC: u8 = 1;
26/// `BDADDR_ANY` — let the kernel pick the adapter.
27pub const BDADDR_ANY: [u8; 6] = [0; 6];
28pub const BDADDR_LE_RANDOM: u8 = 2;
29pub const SHUT_RDWR: c_int = 2;
30/// `EINTR` — a syscall interrupted by a signal, which is a retry not a failure.
31pub const EINTR: i32 = 4;
32/// Something else already holds the resource — see `gatt::connect_error`.
33pub const EBUSY: i32 = 16;
34/// How Linux reports the peer closing an RFCOMM channel with a DISC frame.
35pub const ECONNRESET: i32 = 104;
36
37unsafe extern "C" {
38    pub fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int;
39    // Declared with libc's own `void *`, under other names. Newer compilers
40    // check declarations of `read` and `write` against the signatures the
41    // standard library links to, and a `u8` pointer, though ABI-identical, is
42    // reported as suspicious to every crate that builds this one.
43    #[link_name = "read"]
44    fn libc_read(fd: c_int, buf: *mut c_void, count: usize) -> isize;
45    #[link_name = "write"]
46    fn libc_write(fd: c_int, buf: *const c_void, count: usize) -> isize;
47    pub fn close(fd: c_int) -> c_int;
48    pub fn shutdown(fd: c_int, how: c_int) -> c_int;
49    /// `setsockopt`, under a name that says which options this crate sets with
50    /// it. `*const c_void` because the option value differs per level — a
51    /// `bt_security` here, an `hci_filter` in [`crate::hci`] — and two extern
52    /// declarations of one symbol with two signatures is a hard error.
53    #[link_name = "setsockopt"]
54    pub fn bluetooth_setsockopt(
55        fd: c_int,
56        level: c_int,
57        option: c_int,
58        value: *const core::ffi::c_void,
59        length: u32,
60    ) -> c_int;
61    fn __errno_location() -> *mut c_int;
62}
63
64/// `read(2)` into a byte buffer.
65///
66/// # Safety
67/// `buf` must be valid for `count` bytes of writes.
68pub unsafe fn read(fd: c_int, buf: *mut u8, count: usize) -> isize {
69    unsafe { libc_read(fd, buf.cast(), count) }
70}
71
72/// `write(2)` from a byte buffer.
73///
74/// # Safety
75/// `buf` must be valid for `count` bytes of reads.
76pub unsafe fn write(fd: c_int, buf: *const u8, count: usize) -> isize {
77    unsafe { libc_write(fd, buf.cast(), count) }
78}
79
80/// Configure the Linux Bluetooth security level for a Classic socket.
81#[cfg(feature = "classic")]
82pub fn set_classic_security(
83    fd: c_int,
84    security: webbluetooth_core::classic::ClassicSecurity,
85) -> Result<(), i32> {
86    let level = match security {
87        // Not `BT_SECURITY_SDP`, though that is the numerically lowest level:
88        // the kernel reserves it for the SDP channel itself. On any other PSM
89        // it asks for a link with no SSP pairing at all, which an SSP peer —
90        // every controller since Bluetooth 2.1 — answers by refusing the
91        // channel: `ECONNREFUSED` on a cold link, success only if some earlier
92        // connection happened to leave an authenticated link up. `LOW` is the
93        // kernel's own default for these sockets and the least it will
94        // actually connect with.
95        webbluetooth_core::classic::ClassicSecurity::None => BT_SECURITY_LOW,
96        webbluetooth_core::classic::ClassicSecurity::Authentication => BT_SECURITY_LOW,
97        webbluetooth_core::classic::ClassicSecurity::Encryption => BT_SECURITY_MEDIUM,
98        webbluetooth_core::classic::ClassicSecurity::SecureEncryption => BT_SECURITY_FIPS,
99    };
100    let value = [level, 0];
101    let result = unsafe {
102        bluetooth_setsockopt(
103            fd,
104            SOL_BLUETOOTH,
105            BT_SECURITY,
106            value.as_ptr().cast(),
107            value.len() as u32,
108        )
109    };
110    if result == 0 {
111        Ok(())
112    } else {
113        Err(errno())
114    }
115}
116
117/// The current `errno`.
118pub fn errno() -> i32 {
119    unsafe { *__errno_location() }
120}
121
122/// `struct sockaddr_l2` from `bluetooth/l2cap.h`.
123///
124/// Packed, 13 bytes, no trailing padding — a mismatch here is a `connect` that
125/// fails for no visible reason.
126#[repr(C, packed)]
127#[derive(Clone, Copy)]
128pub struct SockAddrL2 {
129    pub family: u16,
130    pub psm: u16,
131    pub bdaddr: [u8; 6],
132    pub cid: u16,
133    pub bdaddr_type: u8,
134}
135
136/// `struct sockaddr_rc` from `bluetooth/rfcomm.h`.
137///
138/// **Not** packed, unlike [`SockAddrL2`]: the kernel's struct is plain, so it
139/// is 2 + 6 + 1 = 9 bytes of fields and 10 with the trailing padding, and
140/// `rfcomm_sock_connect` refuses any length below `sizeof(struct sockaddr_rc)`
141/// with `EINVAL`. Packed, this was 9, so every outbound RFCOMM connection
142/// failed before reaching the radio — while `bind`, which tolerates a short
143/// address, worked, and made the listener look fine.
144#[repr(C)]
145#[derive(Clone, Copy)]
146pub struct SockAddrRc {
147    pub family: u16,
148    pub bdaddr: [u8; 6],
149    pub channel: u8,
150}
151
152unsafe extern "C" {
153    pub fn connect(fd: c_int, addr: *const SockAddrL2, len: u32) -> c_int;
154    pub fn listen(fd: c_int, backlog: c_int) -> c_int;
155    pub fn accept(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
156    /// Takes a `*const c_void` because both socket families here bind with
157    /// their own `sockaddr` shape, and one extern declaration has to serve
158    /// both — two declarations of the same symbol with different pointer
159    /// types do not compile.
160    pub fn bind(fd: c_int, addr: *const core::ffi::c_void, len: u32) -> c_int;
161    pub fn getsockname(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
162    fn poll(fds: *mut PollFd, nfds: core::ffi::c_ulong, timeout: c_int) -> c_int;
163}
164
165/// Parse `AA:BB:CC:DD:EE:FF` into wire order.
166///
167/// **A Bluetooth address goes on the wire least-significant byte first**, so
168/// the result is the written order reversed. Getting this wrong produces a
169/// connection that times out rather than an error, which is why it is one
170/// function with one test rather than a line repeated per transport.
171pub fn parse_address(address: &str) -> Option<[u8; 6]> {
172    let parts: Vec<&str> = address.split(':').collect();
173    if parts.len() != 6 {
174        return None;
175    }
176    let mut out = [0u8; 6];
177    for (i, part) in parts.iter().enumerate() {
178        out[5 - i] = u8::from_str_radix(part, 16).ok()?;
179    }
180    Some(out)
181}
182
183/// Format a wire-order address as it is written.
184pub fn format_address(wire: &[u8; 6]) -> String {
185    let mut out = String::with_capacity(17);
186    for (i, b) in wire.iter().rev().enumerate() {
187        if i > 0 {
188            out.push(':');
189        }
190        out.push_str(&format!("{b:02X}"));
191    }
192    out
193}
194
195#[repr(C)]
196struct PollFd {
197    fd: c_int,
198    events: i16,
199    revents: i16,
200}
201
202pub const POLLIN: i16 = 0x001;
203pub const POLLOUT: i16 = 0x004;
204const POLLERR: i16 = 0x008;
205const POLLHUP: i16 = 0x010;
206
207/// Whether a descriptor became ready, timed out, or failed.
208#[derive(Debug, PartialEq, Eq)]
209pub enum Ready {
210    Yes,
211    TimedOut,
212    /// The peer hung up or the socket errored.
213    Closed,
214}
215
216/// Wait for `fd` to be ready, for at most `timeout_ms`.
217///
218/// Every blocking call on a Bluetooth socket goes through this first.
219/// `read` and `write` on an L2CAP socket can both park in the kernel with no
220/// deadline of their own — a channel suspended pending security will hold a
221/// `write` forever, with `SO_SNDTIMEO` unset — and a caller that has already
222/// decided how long it is willing to wait cannot express that to them.
223pub fn wait_ready(fd: c_int, events: i16, timeout_ms: c_int) -> Result<Ready, i32> {
224    let mut fds = PollFd {
225        fd,
226        events,
227        revents: 0,
228    };
229    loop {
230        let rc = unsafe { poll(&mut fds, 1, timeout_ms) };
231        if rc < 0 {
232            let e = errno();
233            if e == EINTR {
234                continue;
235            }
236            return Err(e);
237        }
238        if rc == 0 {
239            return Ok(Ready::TimedOut);
240        }
241        if fds.revents & (POLLERR | POLLHUP) != 0 {
242            return Ok(Ready::Closed);
243        }
244        return Ok(Ready::Yes);
245    }
246}
247
248/// The address type byte for an LE peer.
249pub fn address_type(random: bool) -> u8 {
250    if random {
251        BDADDR_LE_RANDOM
252    } else {
253        BDADDR_LE_PUBLIC
254    }
255}
256
257/// Bind an L2CAP socket to the local side of an LE link before connecting.
258///
259/// Without this the kernel leaves the channel's source type at `BDADDR_BREDR`,
260/// and `l2cap_chan_connect` refuses a BR/EDR source with an LE destination —
261/// `connect` fails with `EINVAL` and no link is ever attempted. Binding is how
262/// the socket is told it is an LE one; BlueZ's own tools do the same.
263///
264/// `BDADDR_ANY` leaves the choice of adapter to the kernel, which is what we
265/// want: the caller names a peer, not a controller.
266pub fn bind_le_source(fd: c_int, psm: u16, cid: u16) -> Result<(), i32> {
267    let addr = SockAddrL2 {
268        family: AF_BLUETOOTH as u16,
269        psm: psm.to_le(),
270        bdaddr: BDADDR_ANY,
271        cid: cid.to_le(),
272        bdaddr_type: BDADDR_LE_PUBLIC,
273    };
274    let len = core::mem::size_of::<SockAddrL2>() as u32;
275    if unsafe { bind(fd, (&raw const addr).cast(), len) } < 0 {
276        return Err(errno());
277    }
278    Ok(())
279}
280
281#[cfg(test)]
282mod tests {
283
284    #[test]
285    fn the_rfcomm_socket_address_matches_the_kernel_layout() {
286        // Offsets as in `struct sockaddr_rc`, and its padded size: a length
287        // below 10 is refused by `connect` with EINVAL.
288        assert_eq!(std::mem::size_of::<SockAddrRc>(), 10);
289        assert_eq!(std::mem::offset_of!(SockAddrRc, family), 0);
290        assert_eq!(std::mem::offset_of!(SockAddrRc, bdaddr), 2);
291        assert_eq!(std::mem::offset_of!(SockAddrRc, channel), 8);
292    }
293
294    use super::*;
295
296    #[test]
297    fn addresses_are_reversed_onto_the_wire() {
298        assert_eq!(
299            parse_address("AA:BB:CC:DD:EE:FF"),
300            Some([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
301        );
302        assert_eq!(
303            parse_address("00:00:00:00:00:01"),
304            Some([0x01, 0, 0, 0, 0, 0])
305        );
306    }
307
308    #[test]
309    fn formatting_is_the_inverse_of_parsing() {
310        let written = "AA:BB:CC:DD:EE:FF";
311        assert_eq!(format_address(&parse_address(written).unwrap()), written);
312    }
313
314    #[test]
315    fn malformed_addresses_are_rejected() {
316        for bad in [
317            "",
318            "AA:BB:CC:DD:EE",
319            "AA:BB:CC:DD:EE:FF:00",
320            "ZZ:BB:CC:DD:EE:FF",
321        ] {
322            assert_eq!(parse_address(bad), None, "{bad:?} should not parse");
323        }
324    }
325
326    #[test]
327    fn the_socket_address_matches_the_kernel_layout() {
328        assert_eq!(std::mem::size_of::<SockAddrL2>(), 13);
329    }
330}