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//!
20//! And the socket is `SOCK_SEQPACKET`: **each write is one SDU**, which may not
21//! exceed the peer's MTU (`BT_SNDMTU`; `EMSGSIZE` otherwise), and each read
22//! returns one SDU, cut short if the buffer is smaller. So writes are split at
23//! the send MTU and the reader's buffer is at least the receive MTU. The
24//! portable channel is a byte stream; SDU boundaries mean nothing to callers.
25
26use crate::sys::{
27    address_type, bind_le_source, bluetooth_u16_option, close, connect, errno, parse_address,
28    read, shutdown, socket, write, SockAddrL2, AF_BLUETOOTH, BTPROTO_L2CAP, BT_RCVMTU, BT_SNDMTU,
29    EINTR, EMSGSIZE, SHUT_RDWR, SOCK_SEQPACKET,
30};
31use futures_channel::mpsc;
32use futures_core::Stream;
33use futures_util::StreamExt;
34use std::collections::VecDeque;
35use std::ffi::c_int;
36use std::pin::Pin;
37use std::sync::atomic::{AtomicBool, Ordering};
38use std::sync::{Arc, Mutex};
39use std::task::{Context, Poll};
40
41pub use webbluetooth_core::l2cap::{ChannelSink, Closed, Psm};
42
43struct Socket(c_int);
44
45impl Drop for Socket {
46    fn drop(&mut self) {
47        unsafe { close(self.0) };
48    }
49}
50
51/// An open L2CAP channel.
52pub struct Channel {
53    psm: Psm,
54    peer: String,
55    fd: Arc<Socket>,
56    /// Serialises writes; a partial write must not interleave with another.
57    writing: Mutex<VecDeque<u8>>,
58    /// The largest SDU a write may carry (`BT_SNDMTU`), lowered if the kernel
59    /// refuses one anyway.
60    send_mtu: std::sync::atomic::AtomicUsize,
61    /// Shared with the reader thread, which records why the channel ended
62    /// before telling anyone — so `closed()` agrees with `on_close()`.
63    closed: Arc<Mutex<Option<Closed>>>,
64    stopped: Arc<AtomicBool>,
65}
66
67impl Channel {
68    /// Connect to `address` on `psm`.
69    ///
70    /// `address_type` is BlueZ's `AddressType`: `"public"` or `"random"`.
71    pub fn connect(
72        address: &str,
73        peer_address_type: &str,
74        psm: Psm,
75        sink: Arc<dyn ChannelSink>,
76    ) -> Result<Self, String> {
77        let bdaddr = parse_address(address)
78            .ok_or_else(|| format!("{address:?} is not a Bluetooth address"))?;
79
80        let fd = unsafe { socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP) };
81        if fd < 0 {
82            return Err(format!(
83                "could not create an L2CAP socket (errno {})",
84                errno()
85            ));
86        }
87        let socket = Arc::new(Socket(fd));
88
89        if let Err(e) = bind_le_source(fd, 0, 0) {
90            return Err(format!("could not bind an LE L2CAP socket (errno {e})"));
91        }
92
93        let addr = SockAddrL2 {
94            family: AF_BLUETOOTH as u16,
95            psm: psm.to_le(),
96            bdaddr,
97            cid: 0,
98            bdaddr_type: address_type(peer_address_type == "random"),
99        };
100        let rc = unsafe { connect(fd, &addr, std::mem::size_of::<SockAddrL2>() as u32) };
101        if rc < 0 {
102            return Err(format!(
103                "could not open L2CAP PSM {psm} on {address} (errno {})",
104                errno()
105            ));
106        }
107
108        let stopped = Arc::new(AtomicBool::new(false));
109        let closed = Arc::new(Mutex::new(None));
110        spawn_reader(socket.clone(), sink, stopped.clone(), closed.clone(), psm);
111
112        Ok(Self {
113            psm,
114            peer: address.to_owned(),
115            send_mtu: send_mtu(fd),
116            fd: socket,
117            writing: Mutex::new(VecDeque::new()),
118            closed,
119            stopped,
120        })
121    }
122
123    /// Adopt an already-connected LE L2CAP socket.
124    pub fn adopt_fd(fd: c_int, psm: Psm, peer: String, sink: Arc<dyn ChannelSink>) -> Self {
125        let socket = Arc::new(Socket(fd));
126        let stopped = Arc::new(AtomicBool::new(false));
127        let closed = Arc::new(Mutex::new(None));
128        spawn_reader(socket.clone(), sink, stopped.clone(), closed.clone(), psm);
129        Self {
130            psm,
131            peer,
132            send_mtu: send_mtu(fd),
133            fd: socket,
134            writing: Mutex::new(VecDeque::new()),
135            closed,
136            stopped,
137        }
138    }
139
140    pub fn psm(&self) -> Psm {
141        self.psm
142    }
143    pub fn peer_id(&self) -> &str {
144        &self.peer
145    }
146
147    /// Write bytes. Blocks only as long as the kernel's socket buffer requires.
148    pub fn send(&self, bytes: &[u8]) -> Result<(), Closed> {
149        if let Some(reason) = self.closed() {
150            return Err(reason);
151        }
152        // Held across the write so two senders cannot interleave a partial one.
153        let _order = self.writing.lock().unwrap();
154        let mut sent = 0;
155        while sent < bytes.len() {
156            let mtu = self.send_mtu.load(Ordering::Relaxed);
157            let len = (bytes.len() - sent).min(mtu);
158            let n = unsafe { write(self.fd.0, bytes[sent..].as_ptr(), len) };
159            if n > 0 {
160                sent += n as usize;
161                continue;
162            }
163            // EINTR is not a failure; anything else is.
164            if n < 0 && errno() == EINTR {
165                continue;
166            }
167            // An SDU over the peer's MTU, which the kernel did not report (or
168            // which changed): try smaller ones, down to the LE minimum.
169            if n < 0 && errno() == EMSGSIZE && mtu > LE_MIN_MTU {
170                self.send_mtu.store((mtu / 2).max(LE_MIN_MTU), Ordering::Relaxed);
171                continue;
172            }
173            let reason = Closed::Error(format!("L2CAP write failed (errno {})", errno()));
174            *self.closed.lock().unwrap() = Some(reason.clone());
175            return Err(reason);
176        }
177        Ok(())
178    }
179
180    /// Always zero: writes go straight to the kernel rather than an internal
181    /// queue. Present so both platforms answer the same question.
182    pub fn pending_bytes(&self) -> usize {
183        0
184    }
185
186    pub fn closed(&self) -> Option<Closed> {
187        self.closed.lock().unwrap().clone()
188    }
189
190    pub fn close(&self) {
191        {
192            let mut closed = self.closed.lock().unwrap();
193            if closed.is_none() {
194                *closed = Some(Closed::Locally);
195            }
196        }
197        self.stopped.store(true, Ordering::Release);
198        // Wakes the reader out of its blocking read.
199        unsafe { shutdown(self.fd.0, SHUT_RDWR) };
200    }
201}
202
203impl Drop for Channel {
204    fn drop(&mut self) {
205        self.close();
206    }
207}
208
209impl std::fmt::Debug for Channel {
210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211        f.debug_struct("L2capChannel")
212            .field("psm", &self.psm)
213            .field("peer", &self.peer)
214            .field("closed", &self.closed())
215            .finish()
216    }
217}
218
219/// The smallest MTU an LE connection-oriented channel may have.
220const LE_MIN_MTU: usize = 23;
221
222/// What one write may carry: the kernel's `BT_SNDMTU`, or the LE minimum if it
223/// won't say (writes then grow no further, but never fail for size).
224fn send_mtu(fd: c_int) -> std::sync::atomic::AtomicUsize {
225    let mtu = bluetooth_u16_option(fd, BT_SNDMTU).map_or(LE_MIN_MTU, usize::from);
226    std::sync::atomic::AtomicUsize::new(mtu.max(LE_MIN_MTU))
227}
228
229fn spawn_reader(
230    socket: Arc<Socket>,
231    sink: Arc<dyn ChannelSink>,
232    stopped: Arc<AtomicBool>,
233    closed: Arc<Mutex<Option<Closed>>>,
234    psm: Psm,
235) {
236    std::thread::Builder::new()
237        .name(format!("webbluetooth-l2cap-{psm}"))
238        .spawn(move || {
239            // One read is one SDU, truncated if the buffer is smaller.
240            let rcv = bluetooth_u16_option(socket.0, BT_RCVMTU).map_or(0, usize::from);
241            let mut buf = vec![0u8; rcv.max(4096)];
242            let reason = loop {
243                if stopped.load(Ordering::Acquire) {
244                    break Closed::Locally;
245                }
246                let n = unsafe { read(socket.0, buf.as_mut_ptr(), buf.len()) };
247                match n {
248                    0 => break Closed::ByPeer,
249                    n if n > 0 => sink.on_bytes(buf[..n as usize].to_vec()),
250                    // EINTR
251                    _ if errno() == EINTR => continue,
252                    _ => {
253                        if stopped.load(Ordering::Acquire) {
254                            break Closed::Locally;
255                        }
256                        break Closed::Error(format!("L2CAP read failed (errno {})", errno()));
257                    }
258                }
259            };
260            // First reason wins: a local close already recorded stays.
261            let reason = closed.lock().unwrap().get_or_insert(reason).clone();
262            sink.on_closed(reason);
263        })
264        .expect("could not start the L2CAP reader thread");
265}
266
267// ── The portable wrapper ────────────────────────────────────────────────────
268
269/// This platform's channel, wrapped in the portable one.
270///
271/// The wrapper — backlog, async stream, close notification — is
272/// `webbluetooth-core`'s and identical on every platform. Only what is above
273/// this line is Bluetooth-stack-specific.
274pub type L2capChannel = webbluetooth_core::l2cap::L2capChannel<Channel>;
275
276/// Listener for inbound LE L2CAP connection-oriented channels.
277pub struct L2capListener {
278    socket: Arc<Socket>,
279    incoming: mpsc::UnboundedReceiver<webbluetooth_core::Result<L2capChannel>>,
280}
281
282/// Handle used to stop a listener whose stream is being routed elsewhere.
283pub struct L2capListenerHandle {
284    socket: Arc<Socket>,
285}
286
287impl Drop for L2capListenerHandle {
288    fn drop(&mut self) {
289        unsafe { shutdown(self.socket.0, SHUT_RDWR) };
290    }
291}
292
293impl L2capListener {
294    /// Route accepted channels to a callback on a dedicated thread.
295    pub fn spawn<F>(self, callback: F) -> webbluetooth_core::Result<L2capListenerHandle>
296    where
297        F: Fn(webbluetooth_core::Result<L2capChannel>) + Send + 'static,
298    {
299        let handle = L2capListenerHandle {
300            socket: self.socket.clone(),
301        };
302        let name = "webbluetooth-l2cap-le-router";
303        std::thread::Builder::new()
304            .name(name.into())
305            .spawn(move || {
306                futures_executor::block_on(async move {
307                    let mut listener = self;
308                    while let Some(channel) = listener.next().await {
309                        callback(channel);
310                    }
311                });
312            })
313            .map_err(|error| webbluetooth_core::Error::Network(error.to_string()))?;
314        Ok(handle)
315    }
316}
317
318impl Stream for L2capListener {
319    type Item = webbluetooth_core::Result<L2capChannel>;
320
321    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
322        Pin::new(&mut self.incoming).poll_next(cx)
323    }
324}
325
326impl Drop for L2capListener {
327    fn drop(&mut self) {
328        unsafe { shutdown(self.socket.0, SHUT_RDWR) };
329    }
330}
331
332/// Bind and listen on an LE L2CAP PSM. Pass zero to let the kernel allocate it
333/// (from the dynamic range, 0x80–0xFF). With `encryption_required`, a channel
334/// only opens on an encrypted link; the security level is set on the listener
335/// and accepted sockets inherit it.
336pub fn listen(
337    psm: Psm,
338    encryption_required: bool,
339) -> webbluetooth_core::Result<(Psm, L2capListener)> {
340    let fd = unsafe { socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP) };
341    if fd < 0 {
342        return Err(webbluetooth_core::Error::Network(format!(
343            "could not create LE L2CAP listener (errno {})",
344            errno()
345        )));
346    }
347    let socket = Arc::new(Socket(fd));
348    if let Err(code) = crate::sys::set_le_security(fd, encryption_required) {
349        return Err(webbluetooth_core::Error::Network(format!(
350            "could not set the LE L2CAP listener's security (errno {code})"
351        )));
352    }
353    let address = SockAddrL2 {
354        family: AF_BLUETOOTH as u16,
355        psm: psm.to_le(),
356        bdaddr: crate::sys::BDADDR_ANY,
357        cid: 0,
358        bdaddr_type: crate::sys::BDADDR_LE_PUBLIC,
359    };
360    if unsafe {
361        crate::sys::bind(
362            fd,
363            (&raw const address).cast(),
364            std::mem::size_of::<SockAddrL2>() as u32,
365        )
366    } < 0
367        || unsafe { crate::sys::listen(fd, 8) } < 0
368    {
369        return Err(webbluetooth_core::Error::Network(format!(
370            "could not bind LE L2CAP PSM {psm} (errno {})",
371            errno()
372        )));
373    }
374    let mut bound = SockAddrL2 {
375        family: 0,
376        psm: 0,
377        bdaddr: [0; 6],
378        cid: 0,
379        bdaddr_type: 0,
380    };
381    let mut length = std::mem::size_of::<SockAddrL2>() as u32;
382    if unsafe { crate::sys::getsockname(fd, (&raw mut bound).cast(), &mut length) } < 0 {
383        return Err(webbluetooth_core::Error::Network(format!(
384            "could not query LE L2CAP PSM (errno {})",
385            errno()
386        )));
387    }
388    let bound_psm = u16::from_le(bound.psm);
389    let (tx, rx) = mpsc::unbounded();
390    let listener_fd = socket.clone();
391    let accept_fd = listener_fd.clone();
392    std::thread::Builder::new()
393        .name(format!("webbluetooth-l2cap-le-listener-{bound_psm:04x}"))
394        .spawn(move || loop {
395            let mut peer = SockAddrL2 {
396                family: 0,
397                psm: 0,
398                bdaddr: [0; 6],
399                cid: 0,
400                bdaddr_type: 0,
401            };
402            let mut length = std::mem::size_of::<SockAddrL2>() as u32;
403            let accepted =
404                unsafe { crate::sys::accept(accept_fd.0, (&raw mut peer).cast(), &mut length) };
405            if accepted < 0 {
406                break;
407            }
408            let (channel_sink, sink, incoming) = webbluetooth_core::l2cap::sink();
409            let peer_id = peer
410                .bdaddr
411                .iter()
412                .rev()
413                .map(|byte| format!("{byte:02X}"))
414                .collect::<Vec<_>>()
415                .join(":");
416            let channel = Channel::adopt_fd(accepted, bound_psm, peer_id, channel_sink);
417            if tx
418                .unbounded_send(Ok(L2capChannel::new(channel, sink, incoming)))
419                .is_err()
420            {
421                break;
422            }
423        })
424        .map_err(|error| webbluetooth_core::Error::Network(error.to_string()))?;
425    Ok((
426        bound_psm,
427        L2capListener {
428            socket,
429            incoming: rx,
430        },
431    ))
432}
433
434impl webbluetooth_core::l2cap::PlatformChannel for Channel {
435    fn psm(&self) -> Psm {
436        Channel::psm(self)
437    }
438
439    fn peer_id(&self) -> &str {
440        Channel::peer_id(self)
441    }
442
443    fn send(&self, bytes: &[u8]) -> Result<(), Closed> {
444        Channel::send(self, bytes)
445    }
446
447    fn pending_bytes(&self) -> usize {
448        Channel::pending_bytes(self)
449    }
450
451    fn closed(&self) -> Option<Closed> {
452        Channel::closed(self)
453    }
454
455    fn close(&self) {
456        Channel::close(self)
457    }
458}
459
460/// Open a channel to `address` on `psm`.
461///
462/// The Linux path: L2CAP is an ordinary socket here, so a channel is connected
463/// rather than handed over.
464pub fn open(
465    address: &str,
466    address_type: &str,
467    psm: Psm,
468) -> webbluetooth_core::Result<L2capChannel> {
469    let (channel_sink, sink, incoming) = webbluetooth_core::l2cap::sink();
470    let channel = Channel::connect(address, address_type, psm, channel_sink)
471        .map_err(webbluetooth_core::Error::Network)?;
472    Ok(L2capChannel::new(channel, sink, incoming))
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478
479    #[test]
480    fn addresses_are_reversed_onto_the_wire() {
481        // The single easiest thing to get wrong, and it fails as a timeout
482        // rather than an error.
483        assert_eq!(
484            parse_address("AA:BB:CC:DD:EE:FF"),
485            Some([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
486        );
487        assert_eq!(
488            parse_address("00:00:00:00:00:01"),
489            Some([0x01, 0, 0, 0, 0, 0])
490        );
491    }
492
493    #[test]
494    fn malformed_addresses_are_rejected() {
495        assert_eq!(parse_address(""), None);
496        assert_eq!(parse_address("AA:BB:CC:DD:EE"), None);
497        assert_eq!(parse_address("AA:BB:CC:DD:EE:FF:00"), None);
498        assert_eq!(parse_address("ZZ:BB:CC:DD:EE:FF"), None);
499    }
500
501    #[test]
502    fn the_socket_address_matches_the_kernel_layout() {
503        // sockaddr_l2 is packed: 2 + 2 + 6 + 2 + 1 = 13 bytes, no padding.
504        assert_eq!(std::mem::size_of::<SockAddrL2>(), 13);
505    }
506
507    #[test]
508    fn connecting_to_a_bad_address_errors_rather_than_panicking() {
509        struct Discard;
510        impl ChannelSink for Discard {
511            fn on_bytes(&self, _: Vec<u8>) {}
512            fn on_closed(&self, _: Closed) {}
513        }
514        let err = Channel::connect("not-an-address", "public", 0x0080, Arc::new(Discard));
515        assert!(err.is_err());
516    }
517}