Skip to main content

webbluetooth_android/
l2cap.rs

1//! L2CAP channels over `BluetoothSocket`.
2//!
3//! `BluetoothDevice.createL2capChannel(psm)` hands back a socket whose streams
4//! are ordinary `java.io.InputStream` / `OutputStream` — so unlike Apple, where
5//! the streams are runloop-driven, this needs only a reader thread.
6//!
7//! API 29 and newer. Below that the call does not exist and the channel cannot
8//! be opened at all.
9
10#![allow(clippy::not_unsafe_ptr_arg_deref)]
11
12use crate::ble;
13use crate::bluetooth::Ref;
14use crate::runtime::Runtime;
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::sync::{Arc, Mutex};
17
18pub use webbluetooth_core::l2cap::{ChannelSink, Closed, Psm};
19
20struct Shared {
21    socket: Ref,
22    output: Ref,
23    closed: Mutex<Option<Closed>>,
24    stopped: AtomicBool,
25}
26
27/// An open L2CAP channel.
28pub struct Channel {
29    shared: Arc<Shared>,
30    psm: Psm,
31    peer: String,
32    /// Serialises writes, so a partial one cannot interleave with another.
33    writing: Mutex<()>,
34}
35
36impl Channel {
37    /// Take ownership of a connected `BluetoothSocket`.
38    pub fn adopt(
39        socket: crate::jni::JObject,
40        psm: Psm,
41        peer: String,
42        sink: Arc<dyn ChannelSink>,
43    ) -> Result<Self, String> {
44        let runtime = Runtime::get().ok_or("the Android runtime is not started")?;
45        let env = runtime.env().map_err(|e| e.to_string())?;
46
47        // `connect()` blocks while the channel comes up.
48        ble::socket_connect(env, socket).map_err(|e| format!("could not connect: {e}"))?;
49
50        let input = ble::socket_input_stream(env, socket).map_err(|e| e.to_string())?;
51        let output = ble::socket_output_stream(env, socket).map_err(|e| e.to_string())?;
52        let (Some(socket), Some(input), Some(output)) = (
53            Ref::new(env, socket),
54            Ref::new(env, input),
55            Ref::new(env, output),
56        ) else {
57            return Err("the socket had no usable streams".into());
58        };
59
60        let shared = Arc::new(Shared {
61            socket,
62            output,
63            closed: Mutex::new(None),
64            stopped: AtomicBool::new(false),
65        });
66        spawn_reader(shared.clone(), input, sink, psm);
67
68        Ok(Self {
69            shared,
70            psm,
71            peer,
72            writing: Mutex::new(()),
73        })
74    }
75
76    /// Adopt a socket from `BluetoothServerSocket.accept()`.
77    ///
78    /// Already connected, so unlike [`Channel::adopt`] this must not call
79    /// `connect()` — doing so on an accepted socket throws.
80    pub fn adopt_accepted(
81        socket: crate::jni::JObject,
82        psm: Psm,
83        sink: Arc<dyn ChannelSink>,
84    ) -> Result<Self, String> {
85        let runtime = Runtime::get().ok_or("the Android runtime is not started")?;
86        let env = runtime.env().map_err(|e| e.to_string())?;
87
88        let peer = ble::call_object(
89            env,
90            socket,
91            "getRemoteDevice",
92            "()Landroid/bluetooth/BluetoothDevice;",
93            &[],
94        )
95        .ok()
96        .and_then(|d| ble::device_address(env, d))
97        .unwrap_or_default();
98
99        let input = ble::socket_input_stream(env, socket).map_err(|e| e.to_string())?;
100        let output = ble::socket_output_stream(env, socket).map_err(|e| e.to_string())?;
101        let (Some(socket), Some(input), Some(output)) = (
102            Ref::new(env, socket),
103            Ref::new(env, input),
104            Ref::new(env, output),
105        ) else {
106            return Err("the accepted socket had no usable streams".into());
107        };
108
109        let shared = Arc::new(Shared {
110            socket,
111            output,
112            closed: Mutex::new(None),
113            stopped: AtomicBool::new(false),
114        });
115        spawn_reader(shared.clone(), input, sink, psm);
116        Ok(Self {
117            shared,
118            psm,
119            peer,
120            writing: Mutex::new(()),
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    pub fn send(&self, bytes: &[u8]) -> Result<(), Closed> {
132        if let Some(reason) = self.closed() {
133            return Err(reason);
134        }
135        if bytes.is_empty() {
136            return Ok(());
137        }
138        let _order = self.writing.lock().unwrap();
139        let Some(runtime) = Runtime::get() else {
140            return Err(Closed::Error("the Android runtime went away".into()));
141        };
142        let Ok(env) = runtime.env() else {
143            return Err(Closed::Error("could not attach to the VM".into()));
144        };
145        ble::stream_write(env, self.shared.output.as_ptr(), bytes).map_err(|e| {
146            let reason = Closed::Error(format!("write failed: {e}"));
147            *self.shared.closed.lock().unwrap() = Some(reason.clone());
148            reason
149        })
150    }
151
152    /// Always zero: writes go straight to the stream, not an internal queue.
153    pub fn pending_bytes(&self) -> usize {
154        0
155    }
156
157    pub fn closed(&self) -> Option<Closed> {
158        self.shared.closed.lock().unwrap().clone()
159    }
160
161    pub fn close(&self) {
162        {
163            let mut closed = self.shared.closed.lock().unwrap();
164            if closed.is_none() {
165                *closed = Some(Closed::Locally);
166            }
167        }
168        self.shared.stopped.store(true, Ordering::Release);
169        // Closing the socket is what wakes the reader out of its blocking read.
170        if let Some(env) = Runtime::get().and_then(|r| r.env().ok()) {
171            let _ = ble::socket_close(env, self.shared.socket.as_ptr());
172        }
173    }
174}
175
176impl Drop for Channel {
177    fn drop(&mut self) {
178        self.close();
179    }
180}
181
182impl std::fmt::Debug for Channel {
183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        f.debug_struct("L2capChannel")
185            .field("psm", &self.psm)
186            .field("peer", &self.peer)
187            .field("closed", &self.closed())
188            .finish()
189    }
190}
191
192fn spawn_reader(shared: Arc<Shared>, input: Ref, sink: Arc<dyn ChannelSink>, psm: Psm) {
193    std::thread::Builder::new()
194        .name(format!("webbluetooth-l2cap-{psm}"))
195        .spawn(move || {
196            let Some(runtime) = Runtime::get() else {
197                return;
198            };
199            // The reader is our own thread, so it has to attach itself.
200            let Ok(env) = runtime.env() else { return };
201
202            let reason = loop {
203                if shared.stopped.load(Ordering::Acquire) {
204                    break Closed::Locally;
205                }
206                match ble::stream_read(env, input.as_ptr(), 4096) {
207                    Ok(Some(bytes)) if !bytes.is_empty() => sink.on_bytes(bytes),
208                    Ok(Some(_)) => continue,
209                    Ok(None) => break Closed::ByPeer,
210                    Err(e) => {
211                        if shared.stopped.load(Ordering::Acquire) {
212                            break Closed::Locally;
213                        }
214                        break Closed::Error(e.to_string());
215                    }
216                }
217            };
218
219            {
220                let mut closed = shared.closed.lock().unwrap();
221                if closed.is_none() {
222                    *closed = Some(reason.clone());
223                }
224            }
225            sink.on_closed(reason);
226            runtime.vm().detach();
227        })
228        .expect("could not start the L2CAP reader thread");
229}
230
231// ── The portable wrapper ────────────────────────────────────────────────────
232
233/// This platform's channel, wrapped in the portable one.
234///
235/// The wrapper — backlog, async stream, close notification — is
236/// `webbluetooth-core`'s and identical on every platform. Only what is above
237/// this line is Bluetooth-stack-specific.
238pub type L2capChannel = webbluetooth_core::l2cap::L2capChannel<Channel>;
239
240impl webbluetooth_core::l2cap::PlatformChannel for Channel {
241    fn psm(&self) -> Psm {
242        Channel::psm(self)
243    }
244
245    fn peer_id(&self) -> &str {
246        Channel::peer_id(self)
247    }
248
249    fn send(&self, bytes: &[u8]) -> Result<(), Closed> {
250        Channel::send(self, bytes)
251    }
252
253    fn pending_bytes(&self) -> usize {
254        Channel::pending_bytes(self)
255    }
256
257    fn closed(&self) -> Option<Closed> {
258        Channel::closed(self)
259    }
260
261    fn close(&self) {
262        Channel::close(self)
263    }
264}
265
266/// Adopt a connected `BluetoothSocket` — L2CAP arrives here as a socket with
267/// ordinary Java streams.
268pub fn from_socket(socket: crate::jni::JObject) -> webbluetooth_core::Result<L2capChannel> {
269    let (channel_sink, sink, incoming) = webbluetooth_core::l2cap::sink();
270    let channel = Channel::adopt(socket, 0, String::new(), channel_sink)
271        .map_err(webbluetooth_core::Error::Network)?;
272    Ok(L2capChannel::new(channel, sink, incoming))
273}
274
275/// Adopt a socket returned by `BluetoothServerSocket.accept()`, which is
276/// already connected.
277pub fn from_accepted(
278    socket: crate::jni::JObject,
279    psm: Psm,
280) -> webbluetooth_core::Result<L2capChannel> {
281    let (channel_sink, sink, incoming) = webbluetooth_core::l2cap::sink();
282    let channel = Channel::adopt_accepted(socket, psm, channel_sink)
283        .map_err(webbluetooth_core::Error::Network)?;
284    Ok(L2capChannel::new(channel, sink, incoming))
285}