Skip to main content

webbluetooth_linux/
l2cap.rs

1//! L2CAP connection-oriented channels, as Bluetooth sockets.
2//!
3//! Linux exposes L2CAP directly through the socket API — `AF_BLUETOOTH` with
4//! `BTPROTO_L2CAP` — so this needs neither BlueZ nor D-Bus. That is a much
5//! shorter path than the Apple side, where the same thing arrives as a pair of
6//! runloop-driven `NSStream`s.
7//!
8//! ```text
9//!   socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP)
10//!   connect(&sockaddr_l2 { psm, bdaddr, bdaddr_type })
11//!   read / write
12//! ```
13//!
14//! One detail that silently breaks everything if missed: **a Bluetooth address
15//! goes on the wire least-significant byte first**, so `AA:BB:CC:DD:EE:FF` is
16//! the bytes `FF EE DD CC BB AA`. And an LE channel must name the peer's
17//! address *type* — connecting to a random address as though it were public
18//! simply times out.
19
20use crate::sys::{
21    address_type, bind_le_source, close, connect, errno, parse_address, read, shutdown, socket,
22    write, SockAddrL2, AF_BLUETOOTH, BTPROTO_L2CAP, EINTR, SHUT_RDWR, SOCK_SEQPACKET,
23};
24use std::collections::VecDeque;
25use std::ffi::c_int;
26use std::sync::atomic::{AtomicBool, Ordering};
27use std::sync::{Arc, Mutex};
28
29pub use webbluetooth_core::l2cap::{ChannelSink, Closed, Psm};
30
31struct Socket(c_int);
32
33impl Drop for Socket {
34    fn drop(&mut self) {
35        unsafe { close(self.0) };
36    }
37}
38
39/// An open L2CAP channel.
40pub struct Channel {
41    psm: Psm,
42    peer: String,
43    fd: Arc<Socket>,
44    /// Serialises writes; a partial write must not interleave with another.
45    writing: Mutex<VecDeque<u8>>,
46    closed: Mutex<Option<Closed>>,
47    stopped: Arc<AtomicBool>,
48}
49
50impl Channel {
51    /// Connect to `address` on `psm`.
52    ///
53    /// `address_type` is BlueZ's `AddressType`: `"public"` or `"random"`.
54    pub fn connect(
55        address: &str,
56        peer_address_type: &str,
57        psm: Psm,
58        sink: Arc<dyn ChannelSink>,
59    ) -> Result<Self, String> {
60        let bdaddr = parse_address(address)
61            .ok_or_else(|| format!("{address:?} is not a Bluetooth address"))?;
62
63        let fd = unsafe { socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP) };
64        if fd < 0 {
65            return Err(format!(
66                "could not create an L2CAP socket (errno {})",
67                errno()
68            ));
69        }
70        let socket = Arc::new(Socket(fd));
71
72        if let Err(e) = bind_le_source(fd, 0, 0) {
73            return Err(format!("could not bind an LE L2CAP socket (errno {e})"));
74        }
75
76        let addr = SockAddrL2 {
77            family: AF_BLUETOOTH as u16,
78            psm: psm.to_le(),
79            bdaddr,
80            cid: 0,
81            bdaddr_type: address_type(peer_address_type == "random"),
82        };
83        let rc = unsafe { connect(fd, &addr, std::mem::size_of::<SockAddrL2>() as u32) };
84        if rc < 0 {
85            return Err(format!(
86                "could not open L2CAP PSM {psm} on {address} (errno {})",
87                errno()
88            ));
89        }
90
91        let stopped = Arc::new(AtomicBool::new(false));
92        spawn_reader(socket.clone(), sink, stopped.clone(), psm);
93
94        Ok(Self {
95            psm,
96            peer: address.to_owned(),
97            fd: socket,
98            writing: Mutex::new(VecDeque::new()),
99            closed: Mutex::new(None),
100            stopped,
101        })
102    }
103
104    pub fn psm(&self) -> Psm {
105        self.psm
106    }
107    pub fn peer_id(&self) -> &str {
108        &self.peer
109    }
110
111    /// Write bytes. Blocks only as long as the kernel's socket buffer requires.
112    pub fn send(&self, bytes: &[u8]) -> Result<(), Closed> {
113        if let Some(reason) = self.closed() {
114            return Err(reason);
115        }
116        // Held across the write so two senders cannot interleave a partial one.
117        let _order = self.writing.lock().unwrap();
118        let mut sent = 0;
119        while sent < bytes.len() {
120            let n = unsafe { write(self.fd.0, bytes[sent..].as_ptr(), bytes.len() - sent) };
121            if n > 0 {
122                sent += n as usize;
123                continue;
124            }
125            // EINTR is not a failure; anything else is.
126            if n < 0 && errno() == EINTR {
127                continue;
128            }
129            let reason = Closed::Error(format!("L2CAP write failed (errno {})", errno()));
130            *self.closed.lock().unwrap() = Some(reason.clone());
131            return Err(reason);
132        }
133        Ok(())
134    }
135
136    /// Always zero: writes go straight to the kernel rather than an internal
137    /// queue. Present so both platforms answer the same question.
138    pub fn pending_bytes(&self) -> usize {
139        0
140    }
141
142    pub fn closed(&self) -> Option<Closed> {
143        self.closed.lock().unwrap().clone()
144    }
145
146    pub fn close(&self) {
147        {
148            let mut closed = self.closed.lock().unwrap();
149            if closed.is_none() {
150                *closed = Some(Closed::Locally);
151            }
152        }
153        self.stopped.store(true, Ordering::Release);
154        // Wakes the reader out of its blocking read.
155        unsafe { shutdown(self.fd.0, SHUT_RDWR) };
156    }
157}
158
159impl Drop for Channel {
160    fn drop(&mut self) {
161        self.close();
162    }
163}
164
165impl std::fmt::Debug for Channel {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        f.debug_struct("L2capChannel")
168            .field("psm", &self.psm)
169            .field("peer", &self.peer)
170            .field("closed", &self.closed())
171            .finish()
172    }
173}
174
175fn spawn_reader(
176    socket: Arc<Socket>,
177    sink: Arc<dyn ChannelSink>,
178    stopped: Arc<AtomicBool>,
179    psm: Psm,
180) {
181    std::thread::Builder::new()
182        .name(format!("webbluetooth-l2cap-{psm}"))
183        .spawn(move || {
184            let mut buf = vec![0u8; 4096];
185            let reason = loop {
186                if stopped.load(Ordering::Acquire) {
187                    break Closed::Locally;
188                }
189                let n = unsafe { read(socket.0, buf.as_mut_ptr(), buf.len()) };
190                match n {
191                    0 => break Closed::ByPeer,
192                    n if n > 0 => sink.on_bytes(buf[..n as usize].to_vec()),
193                    // EINTR
194                    _ if errno() == EINTR => continue,
195                    _ => {
196                        if stopped.load(Ordering::Acquire) {
197                            break Closed::Locally;
198                        }
199                        break Closed::Error(format!("L2CAP read failed (errno {})", errno()));
200                    }
201                }
202            };
203            sink.on_closed(reason);
204        })
205        .expect("could not start the L2CAP reader thread");
206}
207
208// ── The portable wrapper ────────────────────────────────────────────────────
209
210/// This platform's channel, wrapped in the portable one.
211///
212/// The wrapper — backlog, async stream, close notification — is
213/// `webbluetooth-core`'s and identical on every platform. Only what is above
214/// this line is Bluetooth-stack-specific.
215pub type L2capChannel = webbluetooth_core::l2cap::L2capChannel<Channel>;
216
217impl webbluetooth_core::l2cap::PlatformChannel for Channel {
218    fn psm(&self) -> Psm {
219        Channel::psm(self)
220    }
221
222    fn peer_id(&self) -> &str {
223        Channel::peer_id(self)
224    }
225
226    fn send(&self, bytes: &[u8]) -> Result<(), Closed> {
227        Channel::send(self, bytes)
228    }
229
230    fn pending_bytes(&self) -> usize {
231        Channel::pending_bytes(self)
232    }
233
234    fn closed(&self) -> Option<Closed> {
235        Channel::closed(self)
236    }
237
238    fn close(&self) {
239        Channel::close(self)
240    }
241}
242
243/// Open a channel to `address` on `psm`.
244///
245/// The Linux path: L2CAP is an ordinary socket here, so a channel is connected
246/// rather than handed over.
247pub fn open(
248    address: &str,
249    address_type: &str,
250    psm: Psm,
251) -> webbluetooth_core::Result<L2capChannel> {
252    let (channel_sink, sink, incoming) = webbluetooth_core::l2cap::sink();
253    let channel = Channel::connect(address, address_type, psm, channel_sink)
254        .map_err(webbluetooth_core::Error::Network)?;
255    Ok(L2capChannel::new(channel, sink, incoming))
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    #[test]
263    fn addresses_are_reversed_onto_the_wire() {
264        // The single easiest thing to get wrong, and it fails as a timeout
265        // rather than an error.
266        assert_eq!(
267            parse_address("AA:BB:CC:DD:EE:FF"),
268            Some([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
269        );
270        assert_eq!(
271            parse_address("00:00:00:00:00:01"),
272            Some([0x01, 0, 0, 0, 0, 0])
273        );
274    }
275
276    #[test]
277    fn malformed_addresses_are_rejected() {
278        assert_eq!(parse_address(""), None);
279        assert_eq!(parse_address("AA:BB:CC:DD:EE"), None);
280        assert_eq!(parse_address("AA:BB:CC:DD:EE:FF:00"), None);
281        assert_eq!(parse_address("ZZ:BB:CC:DD:EE:FF"), None);
282    }
283
284    #[test]
285    fn the_socket_address_matches_the_kernel_layout() {
286        // sockaddr_l2 is packed: 2 + 2 + 6 + 2 + 1 = 13 bytes, no padding.
287        assert_eq!(std::mem::size_of::<SockAddrL2>(), 13);
288    }
289
290    #[test]
291    fn connecting_to_a_bad_address_errors_rather_than_panicking() {
292        struct Discard;
293        impl ChannelSink for Discard {
294            fn on_bytes(&self, _: Vec<u8>) {}
295            fn on_closed(&self, _: Closed) {}
296        }
297        let err = Channel::connect("not-an-address", "public", 0x0080, Arc::new(Discard));
298        assert!(err.is_err());
299    }
300}