1use std::collections::{HashMap, HashSet};
13use std::sync::{Arc, Mutex, OnceLock};
14
15use bluetooth_host::adv::Uuid;
16use bluetooth_host::gatt::server::{Access, CharacteristicDef, ServiceDef};
17use bluetooth_host::{
18 Address, AdvertisingParams, ConnEvent, ConnectParams, Connection, Host, HostEvent,
19};
20use tokio::sync::broadcast;
21
22use crate::bearer::{proxy, proxy_segments, ProxyRx};
23use crate::runtime::{ad, Bearer, BoxFuture, Mesh};
24
25pub mod uuid {
28 pub const SERVICE: u16 = 0x1828;
30 pub const DATA_IN: u16 = 0x2add;
32 pub const DATA_OUT: u16 = 0x2ade;
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum FilterType {
39 Accept,
41 Reject,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum Config {
48 SetFilterType(FilterType),
50 Add(Vec<u16>),
52 Remove(Vec<u16>),
54 Status {
56 filter: FilterType,
58 list_size: u16,
60 },
61}
62
63impl Config {
64 pub fn bytes(&self) -> Vec<u8> {
66 let ft = |f: &FilterType| match f {
67 FilterType::Accept => 0x00,
68 FilterType::Reject => 0x01,
69 };
70 let addrs = |op: u8, a: &[u16]| {
71 let mut v = vec![op];
72 for x in a {
73 v.extend_from_slice(&x.to_be_bytes());
74 }
75 v
76 };
77 match self {
78 Config::SetFilterType(f) => vec![0x00, ft(f)],
79 Config::Add(a) => addrs(0x01, a),
80 Config::Remove(a) => addrs(0x02, a),
81 Config::Status { filter, list_size } => {
82 let mut v = vec![0x03, ft(filter)];
83 v.extend_from_slice(&list_size.to_be_bytes());
84 v
85 }
86 }
87 }
88
89 pub fn parse(d: &[u8]) -> Option<Config> {
91 let ft = |b: u8| match b {
92 0x00 => Some(FilterType::Accept),
93 0x01 => Some(FilterType::Reject),
94 _ => None,
95 };
96 let addrs = |a: &[u8]| -> Option<Vec<u16>> {
97 a.len().is_multiple_of(2).then(|| {
98 a.chunks(2)
99 .map(|c| u16::from_be_bytes([c[0], c[1]]))
100 .collect()
101 })
102 };
103 let (&op, p) = d.split_first()?;
104 match (op, p.len()) {
105 (0x00, 1) => Some(Config::SetFilterType(ft(p[0])?)),
106 (0x01, _) => Some(Config::Add(addrs(p)?)),
107 (0x02, _) => Some(Config::Remove(addrs(p)?)),
108 (0x03, 3) => Some(Config::Status {
109 filter: ft(p[0])?,
110 list_size: u16::from_be_bytes([p[1], p[2]]),
111 }),
112 _ => None,
113 }
114 }
115}
116
117#[derive(Debug, thiserror::Error)]
119pub enum Error {
120 #[error(transparent)]
122 Host(#[from] bluetooth_host::Error),
123 #[error("no Mesh Proxy service with Data In and Data Out")]
125 NotAProxy,
126 #[error("not provisioned")]
128 NotProvisioned,
129}
130
131pub struct ProxyBearer {
133 conn: Connection,
134 data_in: u16,
135 data_out: u16,
136 lock: tokio::sync::Mutex<()>,
138 events: Mutex<Option<broadcast::Receiver<ConnEvent>>>,
139}
140
141impl ProxyBearer {
142 pub async fn connect(host: &Host, peer: Address) -> Result<Arc<Self>, Error> {
145 let conn = host.connect(peer, &ConnectParams::default()).await?;
146 match Self::on(conn.clone()).await {
147 Ok(b) => Ok(b),
148 Err(e) => {
149 let _ = conn.disconnect().await;
150 Err(e)
151 }
152 }
153 }
154
155 pub async fn on(conn: Connection) -> Result<Arc<Self>, Error> {
157 let events = conn.events();
159 let gatt = conn.gatt();
160 let _ = gatt.exchange_mtu(69).await;
163 let service = gatt
164 .services_by_uuid(Uuid::Uuid16(uuid::SERVICE))
165 .await?
166 .into_iter()
167 .next()
168 .ok_or(Error::NotAProxy)?;
169 let chars = gatt.characteristics(&service).await?;
170 let find = |u: u16| {
171 chars
172 .iter()
173 .find(|c| c.uuid == Uuid::Uuid16(u))
174 .cloned()
175 .ok_or(Error::NotAProxy)
176 };
177 let (data_in, mut data_out) = (find(uuid::DATA_IN)?, find(uuid::DATA_OUT)?);
178 data_out.descriptors = gatt.descriptors(&data_out).await?;
179 gatt.subscribe(&data_out, true, false).await?;
180 Ok(Arc::new(ProxyBearer {
181 data_in: data_in.value_handle,
182 data_out: data_out.value_handle,
183 conn,
184 lock: tokio::sync::Mutex::new(()),
185 events: Mutex::new(Some(events)),
186 }))
187 }
188
189 pub fn connection(&self) -> &Connection {
191 &self.conn
192 }
193
194 pub async fn write(&self, kind: u8, msg: &[u8]) -> Result<(), bluetooth_host::Error> {
196 let _one = self.lock.lock().await;
197 for p in proxy_segments(kind, msg, self.conn.att_mtu()) {
198 self.conn
199 .gatt()
200 .write_without_response(self.data_in, &p)
201 .await?;
202 }
203 Ok(())
204 }
205
206 pub async fn run(self: &Arc<Self>, mesh: Mesh) -> u8 {
211 let Some(mut events) = self.events.lock().unwrap_or_else(|e| e.into_inner()).take() else {
212 tracing::warn!("ProxyBearer::run called twice");
213 return 0;
214 };
215 match mesh.proxy_configuration(&Config::SetFilterType(FilterType::Reject)) {
216 Some(m) => {
217 if let Err(e) = self.write(proxy::CONFIGURATION, &m).await {
218 tracing::warn!("mesh proxy: setting the filter: {e}");
219 }
220 }
221 None => tracing::warn!("mesh proxy: not provisioned; the proxy forwards nothing"),
222 }
223 let mut rx = ProxyRx::default();
224 loop {
225 match events.recv().await {
226 Ok(ConnEvent::Notification { handle, value, .. }) if handle == self.data_out => {
227 let Some((kind, msg)) = rx.add(&value) else {
228 continue;
229 };
230 match kind {
231 proxy::NETWORK => mesh.receive(ad::MESSAGE, &msg),
232 proxy::BEACON => mesh.receive(ad::BEACON, &msg),
233 proxy::CONFIGURATION => {
234 if let Some(c) = mesh.open_proxy_configuration(&msg) {
235 tracing::debug!("mesh proxy: {c:?}");
236 }
237 }
238 _ => {}
239 }
240 }
241 Ok(ConnEvent::Disconnected(reason)) => return reason,
242 Err(broadcast::error::RecvError::Closed) => return 0,
243 _ => {}
244 }
245 }
246 }
247}
248
249impl Bearer for ProxyBearer {
250 fn send(&self, ad_type: u8, data: Vec<u8>) -> BoxFuture<'_, ()> {
251 Box::pin(async move {
252 let kind = match ad_type {
253 ad::MESSAGE => proxy::NETWORK,
254 ad::BEACON => proxy::BEACON,
255 _ => return,
258 };
259 if let Err(e) = self.write(kind, &data).await {
260 tracing::warn!("mesh proxy: {e}");
261 }
262 })
263 }
264}
265
266fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
267 m.lock().unwrap_or_else(|e| e.into_inner())
268}
269
270pub struct ProxyServer {
280 host: Host,
281 data_in: u16,
282 data_out: u16,
283 relay: Option<Arc<dyn Bearer>>,
284 mesh: OnceLock<Mesh>,
285 client: Mutex<Option<Client>>,
286 lock: tokio::sync::Mutex<()>,
287}
288
289struct Client {
290 conn: Connection,
291 filter: FilterType,
292 list: HashSet<u16>,
293}
294
295impl Client {
296 fn passes(&self, dst: u16) -> bool {
297 match self.filter {
298 FilterType::Accept => self.list.contains(&dst),
299 FilterType::Reject => !self.list.contains(&dst),
300 }
301 }
302}
303
304impl ProxyServer {
305 pub async fn new(host: Host, relay: Option<Arc<dyn Bearer>>) -> Result<Arc<Self>, Error> {
308 let def = ServiceDef {
309 uuid: Uuid::Uuid16(uuid::SERVICE),
310 primary: true,
311 characteristics: vec![
312 CharacteristicDef {
313 uuid: Uuid::Uuid16(uuid::DATA_IN),
314 properties: vec!["write_without_response".into()],
315 read: Access::Never,
316 write: Access::Open,
317 value: Vec::new(),
318 max_len: 66,
319 description: None,
320 descriptors: Vec::new(),
321 },
322 CharacteristicDef {
323 uuid: Uuid::Uuid16(uuid::DATA_OUT),
324 properties: vec!["notify".into()],
325 read: Access::Never,
326 write: Access::Never,
327 value: Vec::new(),
328 max_len: 66,
329 description: None,
330 descriptors: Vec::new(),
331 },
332 ],
333 };
334 let h = host.gatt_server().add(&def).await?;
335 Ok(Arc::new(ProxyServer {
336 data_in: h.characteristics[0].1,
337 data_out: h.characteristics[1].1,
338 host,
339 relay,
340 mesh: OnceLock::new(),
341 client: Mutex::new(None),
342 lock: tokio::sync::Mutex::new(()),
343 }))
344 }
345
346 pub async fn advertise(&self, mesh: &Mesh) -> Result<u8, Error> {
349 let id = mesh.network_id().ok_or(Error::NotProvisioned)?;
350 let [lo, hi] = uuid::SERVICE.to_le_bytes();
351 let mut ad = vec![
354 0x02, 0x01, 0x06, 0x03, 0x03, lo, hi, 0x0c, 0x16, lo, hi, 0x00,
355 ];
356 ad.extend_from_slice(&id);
357 let p = AdvertisingParams {
358 legacy: Some(true),
359 connectable: true,
360 scannable: true,
361 interval_min_ms: 100,
362 interval_max_ms: 150,
363 ..Default::default()
364 };
365 Ok(self.host.advertise(&p, &ad, &[]).await?)
366 }
367
368 pub async fn run(self: &Arc<Self>, mesh: Mesh) {
371 let _ = self.mesh.set(mesh.clone());
372 let mut events = self.host.events();
373 let mut rx: HashMap<u16, ProxyRx> = HashMap::new();
374 if let Err(e) = self.advertise(&mesh).await {
375 tracing::warn!("mesh proxy: advertising: {e}");
376 }
377 loop {
378 match events.recv().await {
379 Ok(HostEvent::Connected(conn)) => {
380 let mut c = lock(&self.client);
381 if c.is_none() {
382 *c = Some(Client {
383 conn,
384 filter: FilterType::Accept,
386 list: HashSet::new(),
387 });
388 }
389 }
390 Ok(HostEvent::Disconnected { handle, .. }) => {
391 rx.remove(&handle);
392 let gone = {
393 let mut c = lock(&self.client);
394 let ours = c.as_ref().is_some_and(|c| c.conn.handle() == handle);
395 if ours {
396 *c = None;
397 }
398 ours
399 };
400 if gone {
401 if let Err(e) = self.advertise(&mesh).await {
402 tracing::warn!("mesh proxy: advertising: {e}");
403 }
404 }
405 }
406 Ok(HostEvent::GattWrite {
407 handle,
408 attribute,
409 value,
410 }) if attribute == self.data_in => {
411 let ours = lock(&self.client)
412 .as_ref()
413 .is_some_and(|c| c.conn.handle() == handle);
414 if !ours {
415 continue;
416 }
417 if let Some((kind, msg)) = rx.entry(handle).or_default().add(&value) {
418 self.client_sent(&mesh, kind, msg).await;
419 }
420 }
421 Ok(HostEvent::Stopped(_)) | Err(broadcast::error::RecvError::Closed) => return,
422 _ => {}
423 }
424 }
425 }
426
427 async fn client_sent(&self, mesh: &Mesh, kind: u8, msg: Vec<u8>) {
428 match kind {
429 proxy::NETWORK => {
430 if let Some(pdu) = mesh.open_network(&msg) {
431 if let Some(c) = lock(&self.client).as_mut() {
432 if c.filter == FilterType::Accept {
434 c.list.insert(pdu.src);
435 }
436 }
437 }
438 mesh.receive(ad::MESSAGE, &msg);
439 if let Some(r) = &self.relay {
440 r.send(ad::MESSAGE, msg).await;
441 }
442 }
443 proxy::BEACON => mesh.receive(ad::BEACON, &msg),
444 proxy::CONFIGURATION => {
445 let Some(cfg) = mesh.open_proxy_configuration(&msg) else {
446 return;
447 };
448 let status = {
449 let mut g = lock(&self.client);
450 let Some(c) = g.as_mut() else { return };
451 match cfg {
452 Config::SetFilterType(f) => {
453 c.filter = f;
454 c.list.clear();
455 }
456 Config::Add(a) => c.list.extend(a),
457 Config::Remove(a) => {
458 for x in a {
459 c.list.remove(&x);
460 }
461 }
462 Config::Status { .. } => return,
463 }
464 Config::Status {
465 filter: c.filter,
466 list_size: u16::try_from(c.list.len()).unwrap_or(u16::MAX),
467 }
468 };
469 if let Some(m) = mesh.proxy_configuration(&status) {
470 self.to_client(proxy::CONFIGURATION, &m).await;
471 }
472 }
473 _ => {}
474 }
475 }
476
477 async fn to_client(&self, kind: u8, msg: &[u8]) {
478 let Some(mtu) = lock(&self.client).as_ref().map(|c| c.conn.att_mtu()) else {
479 return;
480 };
481 let _one = self.lock.lock().await;
482 for p in proxy_segments(kind, msg, mtu) {
483 if let Err(e) = self.host.gatt_server().notify(self.data_out, &p).await {
484 tracing::debug!("mesh proxy: {e}");
485 return;
486 }
487 }
488 }
489}
490
491impl Bearer for ProxyServer {
492 fn send(&self, ad_type: u8, data: Vec<u8>) -> BoxFuture<'_, ()> {
493 Box::pin(async move {
494 let to_client = match ad_type {
495 ad::MESSAGE => self
496 .mesh
497 .get()
498 .and_then(|m| m.open_network(&data))
499 .is_some_and(|pdu| {
500 lock(&self.client)
501 .as_ref()
502 .is_some_and(|c| c.passes(pdu.dst))
503 }),
504 ad::BEACON => true,
505 _ => false,
506 };
507 if to_client {
508 let kind = if ad_type == ad::BEACON {
509 proxy::BEACON
510 } else {
511 proxy::NETWORK
512 };
513 self.to_client(kind, &data).await;
514 }
515 if let Some(r) = &self.relay {
516 r.send(ad_type, data).await;
517 }
518 })
519 }
520}
521
522#[cfg(test)]
523mod tests {
524 use super::*;
525
526 #[test]
527 fn uuids_are_the_sigs() {
528 let name = |u: Option<bluetooth_numbers::Uuid16>| u.map(|u| u.name);
529 assert_eq!(
530 name(bluetooth_numbers::service(uuid::SERVICE)),
531 Some("Mesh Proxy")
532 );
533 assert_eq!(
534 name(bluetooth_numbers::characteristic(uuid::DATA_IN)),
535 Some("Mesh Proxy Data In")
536 );
537 assert_eq!(
538 name(bluetooth_numbers::characteristic(uuid::DATA_OUT)),
539 Some("Mesh Proxy Data Out")
540 );
541 }
542
543 #[test]
544 fn configuration_messages() {
545 for c in [
546 Config::SetFilterType(FilterType::Reject),
547 Config::SetFilterType(FilterType::Accept),
548 Config::Add(vec![0x0001, 0xc000]),
549 Config::Remove(vec![]),
550 Config::Status {
551 filter: FilterType::Accept,
552 list_size: 2,
553 },
554 ] {
555 assert_eq!(Config::parse(&c.bytes()), Some(c));
556 }
557 assert_eq!(
558 Config::SetFilterType(FilterType::Reject).bytes(),
559 [0x00, 0x01]
560 );
561 assert_eq!(Config::Add(vec![0x1234]).bytes(), [0x01, 0x12, 0x34]);
562 assert_eq!(Config::parse(&[0x00, 0x02]), None, "prohibited filter type");
563 assert_eq!(Config::parse(&[0x01, 0x12]), None, "half an address");
564 assert_eq!(Config::parse(&[0x03, 0x00, 0x01]), None, "short status");
565 assert_eq!(Config::parse(&[0x04]), None);
566 assert_eq!(Config::parse(&[]), None);
567 }
568}