webbluetooth-linux 0.0.5

Linux BLE from pure Rust — D-Bus and the kernel's Bluetooth sockets, spoken directly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! L2CAP connection-oriented channels, as Bluetooth sockets.
//!
//! Linux exposes L2CAP directly through the socket API — `AF_BLUETOOTH` with
//! `BTPROTO_L2CAP` — so this needs neither BlueZ nor D-Bus. That is a much
//! shorter path than the Apple side, where the same thing arrives as a pair of
//! runloop-driven `NSStream`s.
//!
//! ```text
//!   socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP)
//!   connect(&sockaddr_l2 { psm, bdaddr, bdaddr_type })
//!   read / write
//! ```
//!
//! One detail that silently breaks everything if missed: **a Bluetooth address
//! goes on the wire least-significant byte first**, so `AA:BB:CC:DD:EE:FF` is
//! the bytes `FF EE DD CC BB AA`. And an LE channel must name the peer's
//! address *type* — connecting to a random address as though it were public
//! simply times out.
//!
//! And the socket is `SOCK_SEQPACKET`: **each write is one SDU**, which may not
//! exceed the peer's MTU (`BT_SNDMTU`; `EMSGSIZE` otherwise), and each read
//! returns one SDU, cut short if the buffer is smaller. So writes are split at
//! the send MTU and the reader's buffer is at least the receive MTU. The
//! portable channel is a byte stream; SDU boundaries mean nothing to callers.

use crate::sys::{
    address_type, bind_le_source, bluetooth_u16_option, close, connect, errno, parse_address,
    read, shutdown, socket, write, SockAddrL2, AF_BLUETOOTH, BTPROTO_L2CAP, BT_RCVMTU, BT_SNDMTU,
    EINTR, EMSGSIZE, SHUT_RDWR, SOCK_SEQPACKET,
};
use futures_channel::mpsc;
use futures_core::Stream;
use futures_util::StreamExt;
use std::collections::VecDeque;
use std::ffi::c_int;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

pub use webbluetooth_core::l2cap::{ChannelSink, Closed, Psm};

struct Socket(c_int);

impl Drop for Socket {
    fn drop(&mut self) {
        unsafe { close(self.0) };
    }
}

/// An open L2CAP channel.
pub struct Channel {
    psm: Psm,
    peer: String,
    fd: Arc<Socket>,
    /// Serialises writes; a partial write must not interleave with another.
    writing: Mutex<VecDeque<u8>>,
    /// The largest SDU a write may carry (`BT_SNDMTU`), lowered if the kernel
    /// refuses one anyway.
    send_mtu: std::sync::atomic::AtomicUsize,
    /// Shared with the reader thread, which records why the channel ended
    /// before telling anyone — so `closed()` agrees with `on_close()`.
    closed: Arc<Mutex<Option<Closed>>>,
    stopped: Arc<AtomicBool>,
}

impl Channel {
    /// Connect to `address` on `psm`.
    ///
    /// `address_type` is BlueZ's `AddressType`: `"public"` or `"random"`.
    pub fn connect(
        address: &str,
        peer_address_type: &str,
        psm: Psm,
        sink: Arc<dyn ChannelSink>,
    ) -> Result<Self, String> {
        let bdaddr = parse_address(address)
            .ok_or_else(|| format!("{address:?} is not a Bluetooth address"))?;

        let fd = unsafe { socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP) };
        if fd < 0 {
            return Err(format!(
                "could not create an L2CAP socket (errno {})",
                errno()
            ));
        }
        let socket = Arc::new(Socket(fd));

        if let Err(e) = bind_le_source(fd, 0, 0) {
            return Err(format!("could not bind an LE L2CAP socket (errno {e})"));
        }

        let addr = SockAddrL2 {
            family: AF_BLUETOOTH as u16,
            psm: psm.to_le(),
            bdaddr,
            cid: 0,
            bdaddr_type: address_type(peer_address_type == "random"),
        };
        let rc = unsafe { connect(fd, &addr, std::mem::size_of::<SockAddrL2>() as u32) };
        if rc < 0 {
            return Err(format!(
                "could not open L2CAP PSM {psm} on {address} (errno {})",
                errno()
            ));
        }

        let stopped = Arc::new(AtomicBool::new(false));
        let closed = Arc::new(Mutex::new(None));
        spawn_reader(socket.clone(), sink, stopped.clone(), closed.clone(), psm);

        Ok(Self {
            psm,
            peer: address.to_owned(),
            send_mtu: send_mtu(fd),
            fd: socket,
            writing: Mutex::new(VecDeque::new()),
            closed,
            stopped,
        })
    }

    /// Adopt an already-connected LE L2CAP socket.
    pub fn adopt_fd(fd: c_int, psm: Psm, peer: String, sink: Arc<dyn ChannelSink>) -> Self {
        let socket = Arc::new(Socket(fd));
        let stopped = Arc::new(AtomicBool::new(false));
        let closed = Arc::new(Mutex::new(None));
        spawn_reader(socket.clone(), sink, stopped.clone(), closed.clone(), psm);
        Self {
            psm,
            peer,
            send_mtu: send_mtu(fd),
            fd: socket,
            writing: Mutex::new(VecDeque::new()),
            closed,
            stopped,
        }
    }

    pub fn psm(&self) -> Psm {
        self.psm
    }
    pub fn peer_id(&self) -> &str {
        &self.peer
    }

    /// Write bytes. Blocks only as long as the kernel's socket buffer requires.
    pub fn send(&self, bytes: &[u8]) -> Result<(), Closed> {
        if let Some(reason) = self.closed() {
            return Err(reason);
        }
        // Held across the write so two senders cannot interleave a partial one.
        let _order = self.writing.lock().unwrap();
        let mut sent = 0;
        while sent < bytes.len() {
            let mtu = self.send_mtu.load(Ordering::Relaxed);
            let len = (bytes.len() - sent).min(mtu);
            let n = unsafe { write(self.fd.0, bytes[sent..].as_ptr(), len) };
            if n > 0 {
                sent += n as usize;
                continue;
            }
            // EINTR is not a failure; anything else is.
            if n < 0 && errno() == EINTR {
                continue;
            }
            // An SDU over the peer's MTU, which the kernel did not report (or
            // which changed): try smaller ones, down to the LE minimum.
            if n < 0 && errno() == EMSGSIZE && mtu > LE_MIN_MTU {
                self.send_mtu.store((mtu / 2).max(LE_MIN_MTU), Ordering::Relaxed);
                continue;
            }
            let reason = Closed::Error(format!("L2CAP write failed (errno {})", errno()));
            *self.closed.lock().unwrap() = Some(reason.clone());
            return Err(reason);
        }
        Ok(())
    }

    /// Always zero: writes go straight to the kernel rather than an internal
    /// queue. Present so both platforms answer the same question.
    pub fn pending_bytes(&self) -> usize {
        0
    }

    pub fn closed(&self) -> Option<Closed> {
        self.closed.lock().unwrap().clone()
    }

    pub fn close(&self) {
        {
            let mut closed = self.closed.lock().unwrap();
            if closed.is_none() {
                *closed = Some(Closed::Locally);
            }
        }
        self.stopped.store(true, Ordering::Release);
        // Wakes the reader out of its blocking read.
        unsafe { shutdown(self.fd.0, SHUT_RDWR) };
    }
}

impl Drop for Channel {
    fn drop(&mut self) {
        self.close();
    }
}

impl std::fmt::Debug for Channel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("L2capChannel")
            .field("psm", &self.psm)
            .field("peer", &self.peer)
            .field("closed", &self.closed())
            .finish()
    }
}

/// The smallest MTU an LE connection-oriented channel may have.
const LE_MIN_MTU: usize = 23;

/// What one write may carry: the kernel's `BT_SNDMTU`, or the LE minimum if it
/// won't say (writes then grow no further, but never fail for size).
fn send_mtu(fd: c_int) -> std::sync::atomic::AtomicUsize {
    let mtu = bluetooth_u16_option(fd, BT_SNDMTU).map_or(LE_MIN_MTU, usize::from);
    std::sync::atomic::AtomicUsize::new(mtu.max(LE_MIN_MTU))
}

fn spawn_reader(
    socket: Arc<Socket>,
    sink: Arc<dyn ChannelSink>,
    stopped: Arc<AtomicBool>,
    closed: Arc<Mutex<Option<Closed>>>,
    psm: Psm,
) {
    std::thread::Builder::new()
        .name(format!("webbluetooth-l2cap-{psm}"))
        .spawn(move || {
            // One read is one SDU, truncated if the buffer is smaller.
            let rcv = bluetooth_u16_option(socket.0, BT_RCVMTU).map_or(0, usize::from);
            let mut buf = vec![0u8; rcv.max(4096)];
            let reason = loop {
                if stopped.load(Ordering::Acquire) {
                    break Closed::Locally;
                }
                let n = unsafe { read(socket.0, buf.as_mut_ptr(), buf.len()) };
                match n {
                    0 => break Closed::ByPeer,
                    n if n > 0 => sink.on_bytes(buf[..n as usize].to_vec()),
                    // EINTR
                    _ if errno() == EINTR => continue,
                    _ => {
                        if stopped.load(Ordering::Acquire) {
                            break Closed::Locally;
                        }
                        break Closed::Error(format!("L2CAP read failed (errno {})", errno()));
                    }
                }
            };
            // First reason wins: a local close already recorded stays.
            let reason = closed.lock().unwrap().get_or_insert(reason).clone();
            sink.on_closed(reason);
        })
        .expect("could not start the L2CAP reader thread");
}

// ── The portable wrapper ────────────────────────────────────────────────────

/// This platform's channel, wrapped in the portable one.
///
/// The wrapper — backlog, async stream, close notification — is
/// `webbluetooth-core`'s and identical on every platform. Only what is above
/// this line is Bluetooth-stack-specific.
pub type L2capChannel = webbluetooth_core::l2cap::L2capChannel<Channel>;

/// Listener for inbound LE L2CAP connection-oriented channels.
pub struct L2capListener {
    socket: Arc<Socket>,
    incoming: mpsc::UnboundedReceiver<webbluetooth_core::Result<L2capChannel>>,
}

/// Handle used to stop a listener whose stream is being routed elsewhere.
pub struct L2capListenerHandle {
    socket: Arc<Socket>,
}

impl Drop for L2capListenerHandle {
    fn drop(&mut self) {
        unsafe { shutdown(self.socket.0, SHUT_RDWR) };
    }
}

impl L2capListener {
    /// Route accepted channels to a callback on a dedicated thread.
    pub fn spawn<F>(self, callback: F) -> webbluetooth_core::Result<L2capListenerHandle>
    where
        F: Fn(webbluetooth_core::Result<L2capChannel>) + Send + 'static,
    {
        let handle = L2capListenerHandle {
            socket: self.socket.clone(),
        };
        let name = "webbluetooth-l2cap-le-router";
        std::thread::Builder::new()
            .name(name.into())
            .spawn(move || {
                futures_executor::block_on(async move {
                    let mut listener = self;
                    while let Some(channel) = listener.next().await {
                        callback(channel);
                    }
                });
            })
            .map_err(|error| webbluetooth_core::Error::Network(error.to_string()))?;
        Ok(handle)
    }
}

impl Stream for L2capListener {
    type Item = webbluetooth_core::Result<L2capChannel>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.incoming).poll_next(cx)
    }
}

impl Drop for L2capListener {
    fn drop(&mut self) {
        unsafe { shutdown(self.socket.0, SHUT_RDWR) };
    }
}

/// Bind and listen on an LE L2CAP PSM. Pass zero to let the kernel allocate it
/// (from the dynamic range, 0x80–0xFF). With `encryption_required`, a channel
/// only opens on an encrypted link; the security level is set on the listener
/// and accepted sockets inherit it.
pub fn listen(
    psm: Psm,
    encryption_required: bool,
) -> webbluetooth_core::Result<(Psm, L2capListener)> {
    let fd = unsafe { socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP) };
    if fd < 0 {
        return Err(webbluetooth_core::Error::Network(format!(
            "could not create LE L2CAP listener (errno {})",
            errno()
        )));
    }
    let socket = Arc::new(Socket(fd));
    if let Err(code) = crate::sys::set_le_security(fd, encryption_required) {
        return Err(webbluetooth_core::Error::Network(format!(
            "could not set the LE L2CAP listener's security (errno {code})"
        )));
    }
    let address = SockAddrL2 {
        family: AF_BLUETOOTH as u16,
        psm: psm.to_le(),
        bdaddr: crate::sys::BDADDR_ANY,
        cid: 0,
        bdaddr_type: crate::sys::BDADDR_LE_PUBLIC,
    };
    if unsafe {
        crate::sys::bind(
            fd,
            (&raw const address).cast(),
            std::mem::size_of::<SockAddrL2>() as u32,
        )
    } < 0
        || unsafe { crate::sys::listen(fd, 8) } < 0
    {
        return Err(webbluetooth_core::Error::Network(format!(
            "could not bind LE L2CAP PSM {psm} (errno {})",
            errno()
        )));
    }
    let mut bound = SockAddrL2 {
        family: 0,
        psm: 0,
        bdaddr: [0; 6],
        cid: 0,
        bdaddr_type: 0,
    };
    let mut length = std::mem::size_of::<SockAddrL2>() as u32;
    if unsafe { crate::sys::getsockname(fd, (&raw mut bound).cast(), &mut length) } < 0 {
        return Err(webbluetooth_core::Error::Network(format!(
            "could not query LE L2CAP PSM (errno {})",
            errno()
        )));
    }
    let bound_psm = u16::from_le(bound.psm);
    let (tx, rx) = mpsc::unbounded();
    let listener_fd = socket.clone();
    let accept_fd = listener_fd.clone();
    std::thread::Builder::new()
        .name(format!("webbluetooth-l2cap-le-listener-{bound_psm:04x}"))
        .spawn(move || loop {
            let mut peer = SockAddrL2 {
                family: 0,
                psm: 0,
                bdaddr: [0; 6],
                cid: 0,
                bdaddr_type: 0,
            };
            let mut length = std::mem::size_of::<SockAddrL2>() as u32;
            let accepted =
                unsafe { crate::sys::accept(accept_fd.0, (&raw mut peer).cast(), &mut length) };
            if accepted < 0 {
                break;
            }
            let (channel_sink, sink, incoming) = webbluetooth_core::l2cap::sink();
            let peer_id = peer
                .bdaddr
                .iter()
                .rev()
                .map(|byte| format!("{byte:02X}"))
                .collect::<Vec<_>>()
                .join(":");
            let channel = Channel::adopt_fd(accepted, bound_psm, peer_id, channel_sink);
            if tx
                .unbounded_send(Ok(L2capChannel::new(channel, sink, incoming)))
                .is_err()
            {
                break;
            }
        })
        .map_err(|error| webbluetooth_core::Error::Network(error.to_string()))?;
    Ok((
        bound_psm,
        L2capListener {
            socket,
            incoming: rx,
        },
    ))
}

impl webbluetooth_core::l2cap::PlatformChannel for Channel {
    fn psm(&self) -> Psm {
        Channel::psm(self)
    }

    fn peer_id(&self) -> &str {
        Channel::peer_id(self)
    }

    fn send(&self, bytes: &[u8]) -> Result<(), Closed> {
        Channel::send(self, bytes)
    }

    fn pending_bytes(&self) -> usize {
        Channel::pending_bytes(self)
    }

    fn closed(&self) -> Option<Closed> {
        Channel::closed(self)
    }

    fn close(&self) {
        Channel::close(self)
    }
}

/// Open a channel to `address` on `psm`.
///
/// The Linux path: L2CAP is an ordinary socket here, so a channel is connected
/// rather than handed over.
pub fn open(
    address: &str,
    address_type: &str,
    psm: Psm,
) -> webbluetooth_core::Result<L2capChannel> {
    let (channel_sink, sink, incoming) = webbluetooth_core::l2cap::sink();
    let channel = Channel::connect(address, address_type, psm, channel_sink)
        .map_err(webbluetooth_core::Error::Network)?;
    Ok(L2capChannel::new(channel, sink, incoming))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn addresses_are_reversed_onto_the_wire() {
        // The single easiest thing to get wrong, and it fails as a timeout
        // rather than an error.
        assert_eq!(
            parse_address("AA:BB:CC:DD:EE:FF"),
            Some([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
        );
        assert_eq!(
            parse_address("00:00:00:00:00:01"),
            Some([0x01, 0, 0, 0, 0, 0])
        );
    }

    #[test]
    fn malformed_addresses_are_rejected() {
        assert_eq!(parse_address(""), None);
        assert_eq!(parse_address("AA:BB:CC:DD:EE"), None);
        assert_eq!(parse_address("AA:BB:CC:DD:EE:FF:00"), None);
        assert_eq!(parse_address("ZZ:BB:CC:DD:EE:FF"), None);
    }

    #[test]
    fn the_socket_address_matches_the_kernel_layout() {
        // sockaddr_l2 is packed: 2 + 2 + 6 + 2 + 1 = 13 bytes, no padding.
        assert_eq!(std::mem::size_of::<SockAddrL2>(), 13);
    }

    #[test]
    fn connecting_to_a_bad_address_errors_rather_than_panicking() {
        struct Discard;
        impl ChannelSink for Discard {
            fn on_bytes(&self, _: Vec<u8>) {}
            fn on_closed(&self, _: Closed) {}
        }
        let err = Channel::connect("not-an-address", "public", 0x0080, Arc::new(Discard));
        assert!(err.is_err());
    }
}