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