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