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