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