Skip to main content

bluetooth_mesh_stack/
proxy.rs

1//! The GATT bearer: a mesh reached through a node's Mesh Proxy service
2//! rather than on the advertising channels. [`ProxyBearer`] is the client
3//! (a gateway whose radio is busy scanning, or a mesh out of advertising
4//! range but within one connection's); [`ProxyServer`] is a node's side.
5//!
6//! Proxy PDUs (SAR and type, [`crate::bearer::proxy_segments`] and
7//! [`crate::bearer::ProxyRx`]) go to Mesh Proxy Data In as writes without
8//! response and come back as notifications of Data Out. Proxy Configuration
9//! messages set which destinations the proxy forwards to us: on connecting,
10//! an empty reject list, so it forwards everything.
11
12use 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
25/// The Mesh Proxy service and its characteristics (checked against the
26/// SIG's assigned numbers in the tests).
27pub mod uuid {
28    /// Mesh Proxy service.
29    pub const SERVICE: u16 = 0x1828;
30    /// Mesh Proxy Data In (written by the client).
31    pub const DATA_IN: u16 = 0x2add;
32    /// Mesh Proxy Data Out (notified to the client).
33    pub const DATA_OUT: u16 = 0x2ade;
34}
35
36/// A proxy's filter: which destinations it forwards to its client.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum FilterType {
39    /// Only the addresses listed (the proxy's starting state: nothing).
40    Accept,
41    /// All but the addresses listed.
42    Reject,
43}
44
45/// A Proxy Configuration message (opcode and parameters).
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum Config {
48    /// Set Filter Type; the list is emptied.
49    SetFilterType(FilterType),
50    /// Add Addresses to Filter.
51    Add(Vec<u16>),
52    /// Remove Addresses from Filter.
53    Remove(Vec<u16>),
54    /// Filter Status, the proxy's answer to each of the others.
55    Status {
56        /// The filter in force.
57        filter: FilterType,
58        /// How many addresses it lists.
59        list_size: u16,
60    },
61}
62
63impl Config {
64    /// The message's bytes.
65    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    /// Parses one; None for anything malformed or prohibited.
90    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/// Errors connecting to a proxy.
118#[derive(Debug, thiserror::Error)]
119pub enum Error {
120    /// The host failed (connecting, discovery, a write).
121    #[error(transparent)]
122    Host(#[from] bluetooth_host::Error),
123    /// The peer has no Mesh Proxy service, or it lacks a characteristic.
124    #[error("no Mesh Proxy service with Data In and Data Out")]
125    NotAProxy,
126    /// A proxy needs a network: the node is not provisioned yet.
127    #[error("not provisioned")]
128    NotProvisioned,
129}
130
131/// A connection to a node's Mesh Proxy service, as a [`Bearer`].
132pub struct ProxyBearer {
133    conn: Connection,
134    data_in: u16,
135    data_out: u16,
136    /// One message's segments at a time, so two messages never interleave.
137    lock: tokio::sync::Mutex<()>,
138    events: Mutex<Option<broadcast::Receiver<ConnEvent>>>,
139}
140
141impl ProxyBearer {
142    /// Connects to `peer` (a node advertising the Mesh Proxy service),
143    /// exchanges the MTU, and subscribes to Data Out.
144    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    /// The bearer on a connection already made.
156    pub async fn on(conn: Connection) -> Result<Arc<Self>, Error> {
157        // Subscribed before anything is asked, so no notification is missed.
158        let events = conn.events();
159        let gatt = conn.gatt();
160        // A network PDU is at most 29 octets; a larger MTU keeps it in one
161        // write. A peer that refuses is still usable, segmented.
162        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    /// The connection.
190    pub fn connection(&self) -> &Connection {
191        &self.conn
192    }
193
194    /// Writes one message as Proxy PDUs.
195    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    /// Feeds the proxy's messages to `mesh` until the connection closes,
207    /// first asking the proxy to forward everything (an empty reject list).
208    /// Returns the HCI disconnection reason. `mesh` must have been opened on
209    /// this bearer and be provisioned.
210    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                // PB-ADV is the advertising bearer's; a provisioned proxy
256                // has no use for it.
257                _ => 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
270/// A node's Mesh Proxy service, for one client at a time, as a [`Bearer`]:
271/// what the node sends goes to the client (when its filter lets the
272/// destination through) and to `relay` (the advertising bearer); what the
273/// client sends goes to the node and to `relay`, unchanged.
274///
275/// Not yet: forwarding to the client what the node only relays, and Node
276/// Identity advertising. A controller that has one advertising set (legacy
277/// advertising only) cannot advertise the service while a `relay` on the
278/// same host is sending.
279pub 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    /// Adds the Mesh Proxy service to `host`'s GATT server. Open the node's
306    /// [`Mesh`] on the returned bearer, then [`ProxyServer::run`] it.
307    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    /// Advertises the service, connectable, with the primary network's
347    /// Network ID. Returns the advertising set.
348    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        // Flags (general discoverable, no BR/EDR), the service's UUID, and
352        // its Service Data: identification type 0 (Network ID) and the ID.
353        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    /// Serves until the host stops: advertises while no client is
369    /// connected, and takes the client's Proxy PDUs.
370    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                            // A new client hears nothing until it says what.
385                            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                        // What a client sends from, it hears back.
433                        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}