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;
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;
17pub const BT_SECURITY_SDP: u8 = 0;
18pub const BT_SECURITY_LOW: u8 = 1;
19pub const BT_SECURITY_MEDIUM: u8 = 2;
20pub const BT_SECURITY_HIGH: u8 = 3;
21pub const BT_SECURITY_FIPS: u8 = 4;
22pub const BTPROTO_HCI: c_int = 1;
23pub const BDADDR_LE_PUBLIC: u8 = 1;
24/// `BDADDR_ANY` — let the kernel pick the adapter.
25pub const BDADDR_ANY: [u8; 6] = [0; 6];
26pub const BDADDR_LE_RANDOM: u8 = 2;
27pub const SHUT_RDWR: c_int = 2;
28/// `EINTR` — a syscall interrupted by a signal, which is a retry not a failure.
29pub const EINTR: i32 = 4;
30
31unsafe extern "C" {
32    pub fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int;
33    pub fn read(fd: c_int, buf: *mut u8, count: usize) -> isize;
34    pub fn write(fd: c_int, buf: *const u8, count: usize) -> isize;
35    pub fn close(fd: c_int) -> c_int;
36    pub fn shutdown(fd: c_int, how: c_int) -> c_int;
37    /// `setsockopt`, under a name that says which options this crate sets with
38    /// it. `*const c_void` because the option value differs per level — a
39    /// `bt_security` here, an `hci_filter` in [`crate::hci`] — and two extern
40    /// declarations of one symbol with two signatures is a hard error.
41    #[link_name = "setsockopt"]
42    pub fn bluetooth_setsockopt(
43        fd: c_int,
44        level: c_int,
45        option: c_int,
46        value: *const core::ffi::c_void,
47        length: u32,
48    ) -> c_int;
49    fn __errno_location() -> *mut c_int;
50}
51
52/// Configure the Linux Bluetooth security level for a Classic socket.
53#[cfg(feature = "classic")]
54pub fn set_classic_security(
55    fd: c_int,
56    security: webbluetooth_core::classic::ClassicSecurity,
57) -> Result<(), i32> {
58    let level = match security {
59        webbluetooth_core::classic::ClassicSecurity::None => BT_SECURITY_SDP,
60        webbluetooth_core::classic::ClassicSecurity::Authentication => BT_SECURITY_LOW,
61        webbluetooth_core::classic::ClassicSecurity::Encryption => BT_SECURITY_MEDIUM,
62        webbluetooth_core::classic::ClassicSecurity::SecureEncryption => BT_SECURITY_FIPS,
63    };
64    let value = [level, 0];
65    let result = unsafe {
66        bluetooth_setsockopt(
67            fd,
68            SOL_BLUETOOTH,
69            BT_SECURITY,
70            value.as_ptr().cast(),
71            value.len() as u32,
72        )
73    };
74    if result == 0 {
75        Ok(())
76    } else {
77        Err(errno())
78    }
79}
80
81/// The current `errno`.
82pub fn errno() -> i32 {
83    unsafe { *__errno_location() }
84}
85
86/// `struct sockaddr_l2` from `bluetooth/l2cap.h`.
87///
88/// Packed, 13 bytes, no trailing padding — a mismatch here is a `connect` that
89/// fails for no visible reason.
90#[repr(C, packed)]
91#[derive(Clone, Copy)]
92pub struct SockAddrL2 {
93    pub family: u16,
94    pub psm: u16,
95    pub bdaddr: [u8; 6],
96    pub cid: u16,
97    pub bdaddr_type: u8,
98}
99
100/// `struct sockaddr_rc` from `bluetooth/rfcomm.h`.
101#[repr(C, packed)]
102#[derive(Clone, Copy)]
103pub struct SockAddrRc {
104    pub family: u16,
105    pub bdaddr: [u8; 6],
106    pub channel: u8,
107}
108
109unsafe extern "C" {
110    pub fn connect(fd: c_int, addr: *const SockAddrL2, len: u32) -> c_int;
111    pub fn listen(fd: c_int, backlog: c_int) -> c_int;
112    pub fn accept(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
113    /// Takes a `*const c_void` because both socket families here bind with
114    /// their own `sockaddr` shape, and one extern declaration has to serve
115    /// both — two declarations of the same symbol with different pointer
116    /// types do not compile.
117    pub fn bind(fd: c_int, addr: *const core::ffi::c_void, len: u32) -> c_int;
118    pub fn getsockname(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
119    fn poll(fds: *mut PollFd, nfds: core::ffi::c_ulong, timeout: c_int) -> c_int;
120}
121
122/// Parse `AA:BB:CC:DD:EE:FF` into wire order.
123///
124/// **A Bluetooth address goes on the wire least-significant byte first**, so
125/// the result is the written order reversed. Getting this wrong produces a
126/// connection that times out rather than an error, which is why it is one
127/// function with one test rather than a line repeated per transport.
128pub fn parse_address(address: &str) -> Option<[u8; 6]> {
129    let parts: Vec<&str> = address.split(':').collect();
130    if parts.len() != 6 {
131        return None;
132    }
133    let mut out = [0u8; 6];
134    for (i, part) in parts.iter().enumerate() {
135        out[5 - i] = u8::from_str_radix(part, 16).ok()?;
136    }
137    Some(out)
138}
139
140/// Format a wire-order address as it is written.
141pub fn format_address(wire: &[u8; 6]) -> String {
142    let mut out = String::with_capacity(17);
143    for (i, b) in wire.iter().rev().enumerate() {
144        if i > 0 {
145            out.push(':');
146        }
147        out.push_str(&format!("{b:02X}"));
148    }
149    out
150}
151
152#[repr(C)]
153struct PollFd {
154    fd: c_int,
155    events: i16,
156    revents: i16,
157}
158
159pub const POLLIN: i16 = 0x001;
160pub const POLLOUT: i16 = 0x004;
161const POLLERR: i16 = 0x008;
162const POLLHUP: i16 = 0x010;
163
164/// Whether a descriptor became ready, timed out, or failed.
165#[derive(Debug, PartialEq, Eq)]
166pub enum Ready {
167    Yes,
168    TimedOut,
169    /// The peer hung up or the socket errored.
170    Closed,
171}
172
173/// Wait for `fd` to be ready, for at most `timeout_ms`.
174///
175/// Every blocking call on a Bluetooth socket goes through this first.
176/// `read` and `write` on an L2CAP socket can both park in the kernel with no
177/// deadline of their own — a channel suspended pending security will hold a
178/// `write` forever, with `SO_SNDTIMEO` unset — and a caller that has already
179/// decided how long it is willing to wait cannot express that to them.
180pub fn wait_ready(fd: c_int, events: i16, timeout_ms: c_int) -> Result<Ready, i32> {
181    let mut fds = PollFd {
182        fd,
183        events,
184        revents: 0,
185    };
186    loop {
187        let rc = unsafe { poll(&mut fds, 1, timeout_ms) };
188        if rc < 0 {
189            let e = errno();
190            if e == EINTR {
191                continue;
192            }
193            return Err(e);
194        }
195        if rc == 0 {
196            return Ok(Ready::TimedOut);
197        }
198        if fds.revents & (POLLERR | POLLHUP) != 0 {
199            return Ok(Ready::Closed);
200        }
201        return Ok(Ready::Yes);
202    }
203}
204
205/// The address type byte for an LE peer.
206pub fn address_type(random: bool) -> u8 {
207    if random {
208        BDADDR_LE_RANDOM
209    } else {
210        BDADDR_LE_PUBLIC
211    }
212}
213
214/// Bind an L2CAP socket to the local side of an LE link before connecting.
215///
216/// Without this the kernel leaves the channel's source type at `BDADDR_BREDR`,
217/// and `l2cap_chan_connect` refuses a BR/EDR source with an LE destination —
218/// `connect` fails with `EINVAL` and no link is ever attempted. Binding is how
219/// the socket is told it is an LE one; BlueZ's own tools do the same.
220///
221/// `BDADDR_ANY` leaves the choice of adapter to the kernel, which is what we
222/// want: the caller names a peer, not a controller.
223pub fn bind_le_source(fd: c_int, psm: u16, cid: u16) -> Result<(), i32> {
224    let addr = SockAddrL2 {
225        family: AF_BLUETOOTH as u16,
226        psm: psm.to_le(),
227        bdaddr: BDADDR_ANY,
228        cid: cid.to_le(),
229        bdaddr_type: BDADDR_LE_PUBLIC,
230    };
231    let len = core::mem::size_of::<SockAddrL2>() as u32;
232    if unsafe { bind(fd, (&raw const addr).cast(), len) } < 0 {
233        return Err(errno());
234    }
235    Ok(())
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn addresses_are_reversed_onto_the_wire() {
244        assert_eq!(
245            parse_address("AA:BB:CC:DD:EE:FF"),
246            Some([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
247        );
248        assert_eq!(
249            parse_address("00:00:00:00:00:01"),
250            Some([0x01, 0, 0, 0, 0, 0])
251        );
252    }
253
254    #[test]
255    fn formatting_is_the_inverse_of_parsing() {
256        let written = "AA:BB:CC:DD:EE:FF";
257        assert_eq!(format_address(&parse_address(written).unwrap()), written);
258    }
259
260    #[test]
261    fn malformed_addresses_are_rejected() {
262        for bad in [
263            "",
264            "AA:BB:CC:DD:EE",
265            "AA:BB:CC:DD:EE:FF:00",
266            "ZZ:BB:CC:DD:EE:FF",
267        ] {
268            assert_eq!(parse_address(bad), None, "{bad:?} should not parse");
269        }
270    }
271
272    #[test]
273    fn the_socket_address_matches_the_kernel_layout() {
274        assert_eq!(std::mem::size_of::<SockAddrL2>(), 13);
275    }
276}