webbluetooth_core/l2cap.rs
1//! L2CAP connection-oriented channels — the portable half.
2//!
3//! The one place Bluetooth stops being request/response. Instead of attributes
4//! you get a bidirectional byte pipe with no 512-byte ceiling and no ATT round
5//! trip per write — the right tool for firmware images, audio, or anything
6//! else that would otherwise be thousands of characteristic writes.
7//!
8//! Neither side is Web Bluetooth; the specification has no L2CAP.
9//!
10//! # What is here and what is not
11//!
12//! A channel is a platform socket: a `CBL2CAPChannel` with two `NSStream`s, an
13//! `AF_BLUETOOTH` file descriptor, a Java `BluetoothSocket`. Opening one is
14//! entirely platform work, so it stays in the platform crates.
15//!
16//! Everything *around* it is the same on all three — a reader callback on some
17//! pump thread, a bounded backlog, an async stream out the other side, a
18//! close reason delivered once — and that was written three times over before
19//! it was written here. [`Closed`] and [`ChannelSink`] were declared in
20//! `webbluetooth-apple`, `webbluetooth-linux` and `webbluetooth-android`
21//! identically, because a shared declaration had nowhere to live.
22//!
23//! So: the platform crate opens the socket and implements [`PlatformChannel`]
24//! on it; [`L2capChannel`] is generic over that, and is the type callers hold.
25//! No dynamic dispatch — each build has exactly one channel type.
26//!
27//! **A chunk is not a message.** L2CAP CoC is a byte stream: what arrives in
28//! one chunk is whatever one read returned. Frame it yourself.
29
30use crate::error::{Error, Result};
31use futures_core::Stream;
32use std::pin::Pin;
33use std::sync::{Arc, Mutex};
34use std::task::{Context, Poll};
35
36/// A PSM — the L2CAP equivalent of a port number.
37pub type Psm = u16;
38
39/// How many packets a channel queues before it has to drop one.
40///
41/// Larger than the advertisement backlog and for the opposite reason: these
42/// are not samples that go stale, they are a stream whose every packet
43/// matters, so the queue absorbs as much of a stall as is reasonable before
44/// anything is lost.
45const L2CAP_BACKLOG: usize = 2048;
46
47/// Why a channel closed.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum Closed {
50 /// The peer closed cleanly.
51 ByPeer,
52 /// This side called [`L2capChannel::close`].
53 Locally,
54 /// The stream reported an error.
55 Error(String),
56}
57
58/// Where a channel's inbound bytes go.
59///
60/// Implemented by [`Sink`] and called on whatever thread the platform reads
61/// on — a CoreBluetooth run loop, a Linux reader thread, a Java pump.
62pub trait ChannelSink: Send + Sync {
63 /// Bytes arrived. Chunk boundaries are read boundaries, not message
64 /// boundaries — L2CAP CoC is a byte stream.
65 fn on_bytes(&self, bytes: Vec<u8>);
66 /// The channel closed. Called exactly once.
67 fn on_closed(&self, reason: Closed);
68}
69
70/// What an open platform socket can do, once somebody has opened one.
71///
72/// Every method here already exists, spelled exactly this way, on
73/// `webbluetooth_apple::l2cap::Channel` and its two siblings; the trait is
74/// what lets one wrapper serve all three.
75pub trait PlatformChannel: Send + Sync + 'static {
76 /// The channel's PSM.
77 fn psm(&self) -> Psm;
78 /// The peer's per-host identifier.
79 fn peer_id(&self) -> &str;
80 /// Queue bytes. Fails only if the channel is closed.
81 fn send(&self, bytes: &[u8]) -> std::result::Result<(), Closed>;
82 /// How many queued bytes have not been written yet.
83 fn pending_bytes(&self) -> usize;
84 /// Why the channel closed, or `None` while it is open.
85 fn closed(&self) -> Option<Closed>;
86 /// Close it.
87 fn close(&self);
88}
89
90/// Bridges the platform's pump-thread callbacks into an async channel.
91pub struct Sink {
92 bytes: crate::backlog::Sender<Vec<u8>>,
93 closed: Mutex<Vec<futures_channel::oneshot::Sender<Closed>>>,
94}
95
96impl ChannelSink for Sink {
97 fn on_bytes(&self, bytes: Vec<u8>) {
98 let _ = self.bytes.send(bytes);
99 }
100
101 fn on_closed(&self, reason: Closed) {
102 // Ending the byte stream is what lets a `while let Some(..)` loop exit.
103 self.bytes.close();
104 for tx in self.closed.lock().unwrap().drain(..) {
105 let _ = tx.send(reason.clone());
106 }
107 }
108}
109
110/// The bridge from a platform's reader callbacks to an async stream.
111///
112/// A platform crate calls this, hands the first value to its own `Channel`
113/// constructor, and passes the rest to [`L2capChannel::new`].
114pub fn sink() -> (Arc<dyn ChannelSink>, Arc<Sink>, Incoming) {
115 // A byte stream being reassembled in order, so the *oldest* are kept: a
116 // contiguous prefix and a known stopping point beat a fresher fragment
117 // with a hole before it. The peer is already sending at link rate and the
118 // reader callback cannot be made to wait, so something has to give when a
119 // consumer falls behind — `lost` says how much.
120 let (tx, rx) = crate::backlog::bounded(L2CAP_BACKLOG, crate::backlog::Overflow::KeepOldest);
121 let sink = Arc::new(Sink {
122 bytes: tx,
123 closed: Mutex::new(Vec::new()),
124 });
125 (sink.clone(), sink, Incoming { rx })
126}
127
128/// An open L2CAP channel. Closes on drop.
129pub struct L2capChannel<C: PlatformChannel> {
130 channel: C,
131 incoming: Mutex<Option<Incoming>>,
132 sink: Arc<Sink>,
133}
134
135impl<C: PlatformChannel> L2capChannel<C> {
136 /// Wrap a platform socket that was opened with [`sink`]'s first value.
137 pub fn new(channel: C, sink: Arc<Sink>, incoming: Incoming) -> Self {
138 Self {
139 channel,
140 incoming: Mutex::new(Some(incoming)),
141 sink,
142 }
143 }
144
145 /// The channel's PSM.
146 pub fn psm(&self) -> Psm {
147 self.channel.psm()
148 }
149
150 /// The peer's per-host identifier.
151 pub fn peer_id(&self) -> &str {
152 self.channel.peer_id()
153 }
154
155 /// Take the inbound byte stream. `None` on a second call — there is one
156 /// stream and consuming it twice would split the bytes between consumers.
157 pub fn take_incoming(&self) -> Option<Incoming> {
158 self.incoming.lock().unwrap().take()
159 }
160
161 /// Queue bytes for sending.
162 ///
163 /// Returns once queued, not once on the air; the pump writes them as the
164 /// peer grants credit. Use [`L2capChannel::flushed`] to wait for the queue
165 /// to drain.
166 pub fn send(&self, bytes: &[u8]) -> Result<()> {
167 self.channel.send(bytes).map_err(closed_error)
168 }
169
170 /// How many queued bytes have not been written yet.
171 pub fn pending_bytes(&self) -> usize {
172 self.channel.pending_bytes()
173 }
174
175 /// Wait until everything queued has been written, or the channel closes.
176 ///
177 /// Polls, because `NSOutputStream` reports space rather than completion.
178 pub async fn flushed(&self) -> Result<()> {
179 while self.pending_bytes() > 0 {
180 if let Some(reason) = self.closed() {
181 return Err(match reason {
182 Closed::ByPeer => Error::Network("the peer closed mid-write".into()),
183 Closed::Locally => Error::InvalidState("the channel was closed".into()),
184 Closed::Error(m) => Error::Network(format!("L2CAP channel failed: {m}")),
185 });
186 }
187 crate::timer::sleep(std::time::Duration::from_millis(5)).await;
188 }
189 Ok(())
190 }
191
192 /// Why the channel closed, or `None` while it is open.
193 pub fn closed(&self) -> Option<Closed> {
194 self.channel.closed()
195 }
196
197 /// Resolve when the channel closes, with the reason.
198 pub async fn on_close(&self) -> Closed {
199 if let Some(reason) = self.closed() {
200 return reason;
201 }
202 let rx = {
203 let (tx, rx) = futures_channel::oneshot::channel();
204 // Re-check under the lock: it may have closed in between.
205 if let Some(reason) = self.closed() {
206 return reason;
207 }
208 self.sink.closed.lock().unwrap().push(tx);
209 rx
210 };
211 rx.await.unwrap_or(Closed::Locally)
212 }
213
214 /// Close the channel.
215 pub fn close(&self) {
216 self.channel.close()
217 }
218}
219
220/// A closed channel, as the error a caller sees.
221fn closed_error(reason: Closed) -> Error {
222 match reason {
223 Closed::ByPeer => Error::Network("the peer closed the L2CAP channel".into()),
224 Closed::Locally => Error::InvalidState("the L2CAP channel is closed".into()),
225 Closed::Error(m) => Error::Network(format!("L2CAP channel failed: {m}")),
226 }
227}
228
229impl<C: PlatformChannel> std::fmt::Debug for L2capChannel<C> {
230 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231 f.debug_struct("L2capChannel")
232 .field("psm", &self.psm())
233 .field("peer_id", &self.peer_id())
234 .field("closed", &self.closed())
235 .finish()
236 }
237}
238
239/// The inbound byte stream of one channel.
240pub struct Incoming {
241 rx: crate::backlog::Receiver<Vec<u8>>,
242}
243
244impl Stream for Incoming {
245 type Item = Vec<u8>;
246
247 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Vec<u8>>> {
248 Pin::new(&mut self.rx).poll_next(cx)
249 }
250}