Skip to main content

bluetooth_mesh_stack/
runtime.rs

1//! A Mesh node or provisioner on a bearer: PB-ADV provisioning on both
2//! sides, the network and transport layers with segmentation and
3//! acknowledgments, and the foundation models a provisioner configures
4//! (Configuration Server) plus a Generic OnOff Server on the node side.
5//!
6//! The radio is a [`Bearer`]: [`HostBearer`] advertises and scans through
7//! `bluetooth-host`; tests use an in-memory one.
8
9use std::collections::HashMap;
10use std::future::Future;
11use std::path::PathBuf;
12use std::pin::Pin;
13use std::sync::{Arc, Mutex};
14use std::time::Duration;
15
16use serde::{Deserialize, Serialize};
17use tokio::sync::{broadcast, oneshot};
18
19use crate::access::{self, op, Composition, ModelId, Opcode};
20use crate::bearer::{Beacon, Generic, PbAdv, TransactionRx};
21use crate::crypto::{self, Key};
22use crate::network::{self, NetworkKey, NetworkPdu};
23use crate::provisioning::{self, Auth, Capabilities, ProvisioningData, Step};
24use crate::transport::{self, AccessKey, Lower, Meta, Reassembled, Reassembly};
25
26/// AD types Mesh uses.
27pub mod ad {
28    /// PB-ADV.
29    pub const PB_ADV: u8 = 0x29;
30    /// Mesh Message (a Network PDU).
31    pub const MESSAGE: u8 = 0x2a;
32    /// Mesh Beacon.
33    pub const BEACON: u8 = 0x2b;
34}
35
36/// A boxed future.
37pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
38
39/// Puts one AD structure of Mesh on the air.
40pub trait Bearer: Send + Sync {
41    /// Sends `data` as one AD structure of `ad_type`.
42    fn send(&self, ad_type: u8, data: Vec<u8>) -> BoxFuture<'_, ()>;
43}
44
45/// The advertising bearer through `bluetooth-host`: each PDU is sent as a
46/// short burst of non-connectable advertising, one at a time.
47pub struct HostBearer {
48    host: bluetooth_host::Host,
49    lock: tokio::sync::Mutex<()>,
50}
51
52impl HostBearer {
53    /// A bearer on a host (which must be scanning for [`run_host_bearer`] to hear anything).
54    pub fn new(host: bluetooth_host::Host) -> Arc<Self> {
55        Arc::new(HostBearer {
56            host,
57            lock: tokio::sync::Mutex::new(()),
58        })
59    }
60}
61
62impl Bearer for HostBearer {
63    fn send(&self, ad_type: u8, data: Vec<u8>) -> BoxFuture<'_, ()> {
64        Box::pin(async move {
65            let _one = self.lock.lock().await;
66            let mut adv = vec![(data.len() + 1) as u8, ad_type];
67            adv.extend_from_slice(&data);
68            let p = bluetooth_host::AdvertisingParams {
69                legacy: Some(true),
70                interval_min_ms: 20,
71                interval_max_ms: 30,
72                ..Default::default()
73            };
74            match self.host.advertise(&p, &adv, &[]).await {
75                Ok(set) => {
76                    // About three advertising events.
77                    tokio::time::sleep(Duration::from_millis(80)).await;
78                    let _ = self.host.stop_advertising(set).await;
79                }
80                Err(e) => tracing::warn!("mesh advertising: {e}"),
81            }
82        })
83    }
84}
85
86/// Feeds a host's advertisements to a mesh until the host stops.
87pub async fn run_host_bearer(host: bluetooth_host::Host, mesh: Mesh) {
88    let mut events = host.events();
89    loop {
90        match events.recv().await {
91            Ok(bluetooth_host::HostEvent::Advertisement(r)) => {
92                for s in bluetooth_adv::AdStructures::new(&r.data).flatten() {
93                    if matches!(s.ad_type, ad::PB_ADV | ad::MESSAGE | ad::BEACON) {
94                        mesh.receive(s.ad_type, s.data);
95                    }
96                }
97            }
98            Ok(bluetooth_host::HostEvent::Stopped(_))
99            | Err(broadcast::error::RecvError::Closed) => return,
100            _ => {}
101        }
102    }
103}
104
105/// A node the provisioner provisioned.
106#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
107pub struct NodeRecord {
108    /// Its Device UUID.
109    #[serde(with = "hexa")]
110    pub uuid: [u8; 16],
111    /// Its primary element's address.
112    pub address: u16,
113    /// Its elements.
114    pub elements: u8,
115    /// Its device key.
116    #[serde(with = "hexa")]
117    pub device_key: Key,
118}
119
120/// What a mesh instance keeps.
121#[derive(Debug, Clone, Default, Serialize, Deserialize)]
122pub struct Store {
123    /// The IV index.
124    pub iv_index: u32,
125    /// The next sequence number (persisted ahead in blocks).
126    pub seq: u32,
127    /// Our primary element address (0 while unprovisioned).
128    pub address: u16,
129    /// Network keys: index, key.
130    pub net_keys: Vec<(u16, HexKey)>,
131    /// Application keys: index, bound network key index, key.
132    pub app_keys: Vec<(u16, u16, HexKey)>,
133    /// Our device key (node role).
134    pub device_key: Option<HexKey>,
135    /// Provisioned nodes (provisioner role).
136    pub nodes: Vec<NodeRecord>,
137    /// Model to application key bindings (node role): element, model, app index.
138    pub bindings: Vec<(u16, u16, u16)>,
139    /// The Generic OnOff Server's state (node role).
140    pub onoff: bool,
141}
142
143/// A key, kept as hex in the store.
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
145pub struct HexKey(#[serde(with = "hexa")] pub Key);
146
147mod hexa {
148    pub fn serialize<S: serde::Serializer>(v: &[u8; 16], s: S) -> Result<S::Ok, S::Error> {
149        s.serialize_str(&hex::encode(v))
150    }
151    pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result<[u8; 16], D::Error> {
152        let s = <String as serde::Deserialize>::deserialize(d)?;
153        hex::decode(s)
154            .ok()
155            .and_then(|v| v.try_into().ok())
156            .ok_or_else(|| serde::de::Error::custom("want 32 hex digits"))
157    }
158}
159
160/// Sequence numbers reserved per store write.
161const SEQ_BLOCK: u32 = 256;
162/// Default TTL of what we send.
163const TTL: u8 = 7;
164
165/// Something that happened in the mesh.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub enum MeshEvent {
168    /// An unprovisioned device's beacon.
169    Unprovisioned {
170        /// Its UUID.
171        uuid: [u8; 16],
172        /// OOB information.
173        oob_info: u16,
174    },
175    /// We were provisioned (node role).
176    Provisioned {
177        /// Our address.
178        address: u16,
179    },
180    /// An access message addressed to us.
181    Message {
182        /// Source.
183        src: u16,
184        /// Destination (us, or a group).
185        dst: u16,
186        /// Opcode.
187        opcode: Opcode,
188        /// Parameters.
189        params: Vec<u8>,
190    },
191}
192
193/// Mesh errors.
194#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
195pub enum Error {
196    /// No answer in time.
197    #[error("timed out: {0}")]
198    Timeout(&'static str),
199    /// Provisioning failed with this error code.
200    #[error("provisioning failed: error {0:#04x}")]
201    Provisioning(u8),
202    /// Not possible in this state.
203    #[error("{0}")]
204    State(&'static str),
205}
206
207struct PbLink {
208    id: u32,
209    /// Next transaction number we send.
210    tx: u8,
211    /// The transaction acknowledged by the peer last.
212    acked: Option<u8>,
213    /// Transactions received whole: a repeat is acknowledged again, never
214    /// handled twice (numbers are not reused on a link).
215    seen: std::collections::HashSet<u8>,
216    rx: TransactionRx,
217    /// Provisioning PDUs received, for the provisioning task.
218    inbox: Vec<Vec<u8>>,
219    opened: bool,
220    wake: Arc<tokio::sync::Notify>,
221}
222
223struct Waiter {
224    src: u16,
225    opcode: Opcode,
226    tx: oneshot::Sender<Vec<u8>>,
227}
228
229struct Inner {
230    bearer: Arc<dyn Bearer>,
231    dir: Option<PathBuf>,
232    store: Mutex<Store>,
233    reserved: Mutex<u32>,
234    uuid: [u8; 16],
235    cache: Mutex<network::Cache>,
236    reassembly: Mutex<Reassembly>,
237    /// Segmented messages awaiting acknowledgment, by (destination, SeqZero):
238    /// the union of the blocks acknowledged so far.
239    acks: Mutex<HashMap<(u16, u16), tokio::sync::watch::Sender<u32>>>,
240    waiters: Mutex<Vec<Waiter>>,
241    link: Mutex<Option<PbLink>>,
242    device: Mutex<Option<provisioning::Device>>,
243    events: broadcast::Sender<MeshEvent>,
244}
245
246/// A mesh instance (provisioner, node, or both).
247#[derive(Clone)]
248pub struct Mesh {
249    inner: Arc<Inner>,
250}
251
252fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
253    m.lock().unwrap_or_else(|e| e.into_inner())
254}
255
256impl Mesh {
257    /// Opens (or creates) a mesh instance with its store in `dir`, and a
258    /// Device UUID for when it is a node waiting to be provisioned.
259    pub fn open(
260        bearer: Arc<dyn Bearer>,
261        dir: Option<PathBuf>,
262        uuid: [u8; 16],
263    ) -> std::io::Result<Mesh> {
264        let store = match dir.as_ref().map(|d| d.join("mesh.json")) {
265            Some(p) if p.exists() => serde_json::from_slice(&std::fs::read(&p)?)
266                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?,
267            _ => Store::default(),
268        };
269        let reserved = store.seq;
270        Ok(Mesh {
271            inner: Arc::new(Inner {
272                bearer,
273                dir,
274                store: Mutex::new(store),
275                reserved: Mutex::new(reserved),
276                uuid,
277                cache: Mutex::new(network::Cache::new(1024)),
278                reassembly: Mutex::new(Reassembly::default()),
279                acks: Mutex::new(HashMap::new()),
280                waiters: Mutex::new(Vec::new()),
281                link: Mutex::new(None),
282                device: Mutex::new(None),
283                events: broadcast::channel(256).0,
284            }),
285        })
286    }
287
288    /// Events, from now on.
289    pub fn events(&self) -> broadcast::Receiver<MeshEvent> {
290        self.inner.events.subscribe()
291    }
292
293    /// A copy of the store.
294    pub fn store(&self) -> Store {
295        lock(&self.inner.store).clone()
296    }
297
298    /// Writes the store. The sequence number written is the reserved one,
299    /// never the live one, so after a crash a node never reuses a number
300    /// its peers' replay protection has already seen.
301    fn save(&self) {
302        let Some(d) = &self.inner.dir else { return };
303        let mut s = lock(&self.inner.store).clone();
304        s.seq = s.seq.max(*lock(&self.inner.reserved));
305        let r = std::fs::create_dir_all(d).and_then(|_| {
306            let tmp = d.join("mesh.json.tmp");
307            std::fs::write(&tmp, serde_json::to_vec_pretty(&s).unwrap_or_default())?;
308            std::fs::rename(tmp, d.join("mesh.json"))
309        });
310        if let Err(e) = r {
311            tracing::error!("saving the mesh store: {e}");
312        }
313    }
314
315    fn next_seq(&self) -> u32 {
316        let (seq, write) = {
317            let mut s = lock(&self.inner.store);
318            let seq = s.seq;
319            s.seq += 1;
320            let mut r = lock(&self.inner.reserved);
321            let write = s.seq >= *r;
322            if write {
323                *r = s.seq + SEQ_BLOCK;
324            }
325            (seq, write)
326        };
327        if write {
328            self.save();
329        }
330        seq
331    }
332
333    fn net_keys(&self) -> Vec<NetworkKey> {
334        lock(&self.inner.store)
335            .net_keys
336            .iter()
337            .map(|(i, k)| NetworkKey::new(*i, k.0))
338            .collect()
339    }
340
341    // ------------------------------------------------------------ provisioner
342
343    /// Starts a new network with us as its provisioner at address 0x0001:
344    /// a fresh network key (index 0) and application key (index 0).
345    pub fn create_network(&self) {
346        let mut k = [0u8; 16];
347        let mut a = [0u8; 16];
348        bluetooth_host::crypto::random_bytes(&mut k);
349        bluetooth_host::crypto::random_bytes(&mut a);
350        {
351            let mut s = lock(&self.inner.store);
352            s.net_keys = vec![(0, HexKey(k))];
353            s.app_keys = vec![(0, 0, HexKey(a))];
354            s.address = 0x0001;
355        }
356        self.save();
357    }
358
359    fn next_address(&self, elements: u8) -> u16 {
360        let s = lock(&self.inner.store);
361        let mut a = s.address.max(1) + 1;
362        for n in &s.nodes {
363            a = a.max(n.address + u16::from(n.elements));
364        }
365        let _ = elements;
366        a
367    }
368
369    /// Provisions the device with this UUID over PB-ADV; returns its record.
370    pub async fn provision(&self, uuid: [u8; 16], auth: Auth) -> Result<NodeRecord, Error> {
371        let (net_key, iv_index) = {
372            let s = lock(&self.inner.store);
373            let k = s
374                .net_keys
375                .first()
376                .ok_or(Error::State("no network: create one first"))?
377                .1;
378            (k.0, s.iv_index)
379        };
380        let mut id = [0u8; 4];
381        bluetooth_host::crypto::random_bytes(&mut id);
382        let link_id = u32::from_be_bytes(id);
383        let wake = Arc::new(tokio::sync::Notify::new());
384        *lock(&self.inner.link) = Some(PbLink {
385            id: link_id,
386            tx: 0,
387            acked: None,
388            seen: std::collections::HashSet::new(),
389            rx: TransactionRx::default(),
390            inbox: Vec::new(),
391            opened: false,
392            wake: wake.clone(),
393        });
394        let r = self
395            .provision_on(link_id, uuid, auth, net_key, iv_index, &wake)
396            .await;
397        for _ in 0..3 {
398            self.send_pb(link_id, 0, Generic::LinkClose(u8::from(r.is_err()) * 2))
399                .await;
400        }
401        *lock(&self.inner.link) = None;
402        r
403    }
404
405    async fn send_pb(&self, link: u32, transaction: u8, pdu: Generic) {
406        let p = PbAdv {
407            link,
408            transaction,
409            pdu,
410        };
411        self.inner.bearer.send(ad::PB_ADV, p.bytes()).await;
412    }
413
414    async fn provision_on(
415        &self,
416        link: u32,
417        uuid: [u8; 16],
418        auth: Auth,
419        net_key: Key,
420        iv_index: u32,
421        wake: &tokio::sync::Notify,
422    ) -> Result<NodeRecord, Error> {
423        // Open the link.
424        let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
425        loop {
426            self.send_pb(link, 0, Generic::LinkOpen(uuid)).await;
427            if lock(&self.inner.link).as_ref().is_some_and(|l| l.opened) {
428                break;
429            }
430            if tokio::time::Instant::now() > deadline {
431                return Err(Error::Timeout("the device to open the link"));
432            }
433            let _ = tokio::time::timeout(Duration::from_millis(300), wake.notified()).await;
434        }
435        let address = self.next_address(1);
436        let data = ProvisioningData {
437            net_key,
438            key_index: 0,
439            flags: 0,
440            iv_index,
441            address,
442        };
443        let (mut p, invite) = provisioning::Provisioner::start(0, auth, data);
444        let mut outgoing = vec![invite];
445        loop {
446            for pdu in outgoing.drain(..) {
447                self.send_transaction(&pdu, wake).await?;
448            }
449            let pdu = self.next_pdu(wake).await?;
450            match p.receive(&pdu) {
451                Step::Send(v) => outgoing = v,
452                Step::Show(_) => {
453                    return Err(Error::State(
454                        "output and input OOB need a person; use Static or None",
455                    ))
456                }
457                Step::Done { device_key, .. } => {
458                    let elements = p.capabilities().map(|c| c.elements).unwrap_or(1);
459                    let rec = NodeRecord {
460                        uuid,
461                        address,
462                        elements,
463                        device_key,
464                    };
465                    lock(&self.inner.store).nodes.push(rec.clone());
466                    self.save();
467                    return Ok(rec);
468                }
469                Step::Failed { code, send } => {
470                    if let Some(f) = send {
471                        let _ = self.send_transaction(&f, wake).await;
472                    }
473                    return Err(Error::Provisioning(code));
474                }
475            }
476        }
477    }
478
479    /// Sends one provisioning PDU as a transaction, repeating it until it is acknowledged.
480    async fn send_transaction(&self, pdu: &[u8], wake: &tokio::sync::Notify) -> Result<(), Error> {
481        let (link, tn) = {
482            let mut l = lock(&self.inner.link);
483            let l = l.as_mut().ok_or(Error::State("no link"))?;
484            let tn = l.tx;
485            l.tx = l.tx.wrapping_add(1) & 0x7f | (tn & 0x80);
486            (l.id, tn)
487        };
488        let segments = PbAdv::transaction(link, tn, pdu);
489        let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
490        loop {
491            for s in &segments {
492                self.inner.bearer.send(ad::PB_ADV, s.bytes()).await;
493            }
494            if lock(&self.inner.link)
495                .as_ref()
496                .is_some_and(|l| l.acked == Some(tn))
497            {
498                return Ok(());
499            }
500            if tokio::time::Instant::now() > deadline {
501                return Err(Error::Timeout(
502                    "a provisioning transaction's acknowledgment",
503                ));
504            }
505            // Wait the whole interval before sending again, however often
506            // something else wakes us.
507            let resend = tokio::time::Instant::now() + Duration::from_millis(400);
508            while tokio::time::Instant::now() < resend {
509                let _ = tokio::time::timeout_at(resend, wake.notified()).await;
510                if lock(&self.inner.link)
511                    .as_ref()
512                    .is_some_and(|l| l.acked == Some(tn))
513                {
514                    return Ok(());
515                }
516            }
517            if lock(&self.inner.link)
518                .as_ref()
519                .is_some_and(|l| l.acked == Some(tn))
520            {
521                return Ok(());
522            }
523        }
524    }
525
526    async fn next_pdu(&self, wake: &tokio::sync::Notify) -> Result<Vec<u8>, Error> {
527        let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
528        loop {
529            if let Some(p) = lock(&self.inner.link)
530                .as_mut()
531                .and_then(|l| (!l.inbox.is_empty()).then(|| l.inbox.remove(0)))
532            {
533                return Ok(p);
534            }
535            if tokio::time::timeout_at(deadline, wake.notified())
536                .await
537                .is_err()
538            {
539                return Err(Error::Timeout("the device's next provisioning PDU"));
540            }
541        }
542    }
543
544    /// Configures a provisioned node: reads its composition, gives it the
545    /// application key, and binds it to every Generic OnOff and Level Server.
546    pub async fn configure(&self, node: &NodeRecord) -> Result<Composition, Error> {
547        let key = AccessKey::Device(&node.device_key);
548        let c = self
549            .request(
550                node.address,
551                key,
552                &access::message(op::COMPOSITION_GET, &[0]),
553                op::COMPOSITION_STATUS,
554            )
555            .await?;
556        let comp = Composition::parse(&c).ok_or(Error::State("malformed composition data"))?;
557        let (app_index, app) = {
558            let s = lock(&self.inner.store);
559            let (i, _, k) = s
560                .app_keys
561                .first()
562                .copied()
563                .ok_or(Error::State("no application key"))?;
564            (i, k.0)
565        };
566        let st = self
567            .request(
568                node.address,
569                key,
570                &access::appkey_add(0, app_index, &app),
571                op::APPKEY_STATUS,
572            )
573            .await?;
574        if st.first() != Some(&0) {
575            return Err(Error::State("the node refused the application key"));
576        }
577        for (i, e) in comp.elements.iter().enumerate() {
578            for m in &e.models {
579                if matches!(m, ModelId::Sig(0x1000) | ModelId::Sig(0x1002)) {
580                    let addr = node.address + i as u16;
581                    let st = self
582                        .request(
583                            node.address,
584                            key,
585                            &access::model_app_bind(addr, app_index, *m),
586                            op::MODEL_APP_STATUS,
587                        )
588                        .await?;
589                    if st.first() != Some(&0) {
590                        return Err(Error::State("the node refused a model binding"));
591                    }
592                }
593            }
594        }
595        Ok(comp)
596    }
597
598    /// Sends an acknowledged access message and waits for the reply's parameters.
599    pub async fn request(
600        &self,
601        dst: u16,
602        key: AccessKey<'_>,
603        payload: &[u8],
604        reply: Opcode,
605    ) -> Result<Vec<u8>, Error> {
606        for _ in 0..3 {
607            let (tx, rx) = oneshot::channel();
608            lock(&self.inner.waiters).push(Waiter {
609                src: dst,
610                opcode: reply,
611                tx,
612            });
613            self.send_access(dst, key, payload).await?;
614            if let Ok(Ok(p)) = tokio::time::timeout(Duration::from_secs(5), rx).await {
615                return Ok(p);
616            }
617        }
618        Err(Error::Timeout("the node's reply"))
619    }
620
621    /// The application key with this index, and its AID.
622    pub fn app_key(&self, index: u16) -> Option<(Key, u8)> {
623        lock(&self.inner.store)
624            .app_keys
625            .iter()
626            .find(|(i, ..)| *i == index)
627            .map(|(_, _, k)| (k.0, crypto::k4(&k.0)))
628    }
629
630    /// Sets a Generic OnOff Server and returns its present state.
631    pub async fn onoff_set(&self, dst: u16, on: bool, tid: u8) -> Result<bool, Error> {
632        let (k, aid) = self.app_key(0).ok_or(Error::State("no application key"))?;
633        let p = self
634            .request(
635                dst,
636                AccessKey::App(&k, aid),
637                &access::onoff_set(on, tid, true),
638                op::ONOFF_STATUS,
639            )
640            .await?;
641        match access::generic_status(op::ONOFF_STATUS, &p) {
642            Some(access::GenericStatus::OnOff(present, _)) => Ok(present),
643            _ => Err(Error::State("malformed Generic OnOff Status")),
644        }
645    }
646
647    /// Sends an access message (segmented and acknowledged as needed).
648    pub async fn send_access(
649        &self,
650        dst: u16,
651        key: AccessKey<'_>,
652        payload: &[u8],
653    ) -> Result<(), Error> {
654        let (src, iv) = {
655            let s = lock(&self.inner.store);
656            (s.address, s.iv_index)
657        };
658        if src == 0 {
659            return Err(Error::State("not provisioned"));
660        }
661        let net = self
662            .net_keys()
663            .into_iter()
664            .next()
665            .ok_or(Error::State("no network key"))?;
666        let seq = self.next_seq();
667        let segmented = payload.len() + 4 > transport::MAX_UNSEGMENTED_ACCESS;
668        let upper = transport::encrypt_access(
669            key,
670            &Meta {
671                seq,
672                src,
673                dst,
674                iv_index: iv,
675                label: None,
676            },
677            payload,
678            false,
679        );
680        let aid = match key {
681            AccessKey::App(_, aid) => Some(aid),
682            AccessKey::Device(_) => None,
683        };
684        let segs = transport::segment_access(aid, false, seq, &upper, segmented)
685            .ok_or(Error::State("message too long"))?;
686        // The first segment carries SeqAuth's own number; every other
687        // transmission, retransmissions included, takes a new one.
688        let mut first = Some(seq);
689        let mut send = |which: u32| {
690            let mut out = Vec::new();
691            for (i, s) in segs.iter().enumerate() {
692                if which & (1 << i) == 0 {
693                    continue;
694                }
695                let pdu = NetworkPdu {
696                    ctl: false,
697                    ttl: TTL,
698                    seq: first.take().unwrap_or_else(|| self.next_seq()),
699                    src,
700                    dst,
701                    transport: s.clone(),
702                };
703                if let Ok(w) = network::encode(&net, iv, &pdu) {
704                    out.push(w);
705                }
706            }
707            out
708        };
709        if !segmented || dst & 0x8000 != 0 {
710            for w in send(u32::MAX) {
711                self.inner.bearer.send(ad::MESSAGE, w).await;
712            }
713            return Ok(());
714        }
715        // Segmented to a unicast address: resend what is not acknowledged.
716        let all = (1u32 << segs.len()) - 1;
717        let key = (dst, (seq & 0x1fff) as u16);
718        let (tx, mut rx) = tokio::sync::watch::channel(0u32);
719        lock(&self.inner.acks).insert(key, tx);
720        let mut result = Err(Error::Timeout("the segment acknowledgments"));
721        for _ in 0..4 {
722            let missing = all & !*rx.borrow();
723            for w in send(missing) {
724                self.inner.bearer.send(ad::MESSAGE, w).await;
725            }
726            let done =
727                tokio::time::timeout(Duration::from_millis(800), rx.wait_for(|b| b & all == all))
728                    .await;
729            if matches!(done, Ok(Ok(_))) {
730                result = Ok(());
731                break;
732            }
733        }
734        lock(&self.inner.acks).remove(&key);
735        result
736    }
737
738    // ------------------------------------------------------------ node
739
740    /// Starts as a node waiting to be provisioned: sends unprovisioned
741    /// device beacons until provisioned (then sends nothing).
742    pub async fn wait_for_provisioning(&self, caps: Capabilities, static_oob: Option<Key>) {
743        *lock(&self.inner.device) = Some(provisioning::Device::new(caps, static_oob));
744        while lock(&self.inner.store).address == 0 {
745            let mut b = vec![0x00];
746            b.extend_from_slice(&self.inner.uuid);
747            b.extend_from_slice(&[0, 0]);
748            self.inner.bearer.send(ad::BEACON, b).await;
749            tokio::time::sleep(Duration::from_millis(300)).await;
750        }
751    }
752
753    fn composition(&self) -> Vec<u8> {
754        // CID 0xFFFF (none assigned), PID 0, VID 0, CRPL 32, no features;
755        // one element: Configuration Server and Generic OnOff Server.
756        let mut d = vec![0x00, 0xff, 0xff, 0, 0, 0, 0, 32, 0, 0, 0];
757        d.extend_from_slice(&[0, 0, 2, 0, 0x00, 0x00, 0x00, 0x10]);
758        d
759    }
760
761    // ------------------------------------------------------------ proxy
762
763    /// A Proxy Configuration message from us, for the proxy we are connected
764    /// to: a control message, TTL 0, to the unassigned address, with the
765    /// proxy nonce and our primary network key. None until provisioned.
766    pub fn proxy_configuration(&self, msg: &crate::proxy::Config) -> Option<Vec<u8>> {
767        let (iv, src) = {
768            let s = lock(&self.inner.store);
769            (s.iv_index, s.address)
770        };
771        let net = self.net_keys().into_iter().next()?;
772        if src == 0 {
773            return None;
774        }
775        let pdu = NetworkPdu {
776            ctl: true,
777            ttl: 0,
778            seq: self.next_seq(),
779            src,
780            dst: 0,
781            transport: msg.bytes(),
782        };
783        network::encode_proxy(&net, iv, &pdu).ok()
784    }
785
786    /// The primary network's Network ID (what a proxy advertises).
787    pub fn network_id(&self) -> Option<[u8; 8]> {
788        let s = lock(&self.inner.store);
789        (s.address != 0)
790            .then(|| s.net_keys.first().map(|(_, k)| crypto::k3(&k.0)))
791            .flatten()
792    }
793
794    /// A Network PDU opened with our keys, without taking it (no replay
795    /// cache, no delivery): for a proxy deciding where it goes.
796    pub fn open_network(&self, data: &[u8]) -> Option<NetworkPdu> {
797        let iv = lock(&self.inner.store).iv_index;
798        network::decode(&self.net_keys(), iv, data).map(|(_, _, p)| p)
799    }
800
801    /// A Proxy Configuration message from the proxy (or its client), opened.
802    pub fn open_proxy_configuration(&self, data: &[u8]) -> Option<crate::proxy::Config> {
803        let iv = lock(&self.inner.store).iv_index;
804        let (_, _, pdu) = network::decode_proxy(&self.net_keys(), iv, data)?;
805        (pdu.ctl && pdu.ttl == 0 && pdu.dst == 0)
806            .then(|| crate::proxy::Config::parse(&pdu.transport))
807            .flatten()
808    }
809
810    // ------------------------------------------------------------ receiving
811
812    /// Takes one Mesh AD structure heard on the air.
813    pub fn receive(&self, ad_type: u8, data: &[u8]) {
814        match ad_type {
815            ad::BEACON => {
816                if let Some(Beacon::Unprovisioned { uuid, oob_info, .. }) = Beacon::parse(data) {
817                    let _ = self
818                        .inner
819                        .events
820                        .send(MeshEvent::Unprovisioned { uuid, oob_info });
821                }
822            }
823            ad::PB_ADV => {
824                if let Some(p) = PbAdv::parse(data) {
825                    self.on_pb_adv(p);
826                }
827            }
828            ad::MESSAGE => self.on_network(data),
829            _ => {}
830        }
831    }
832
833    fn on_pb_adv(&self, p: PbAdv) {
834        // The device side: a link opened to our UUID.
835        if let Generic::LinkOpen(uuid) = &p.pdu {
836            let waiting =
837                lock(&self.inner.device).is_some() && lock(&self.inner.store).address == 0;
838            if *uuid == self.inner.uuid && waiting {
839                let mut l = lock(&self.inner.link);
840                if l.as_ref().is_none_or(|l| l.id != p.link) {
841                    *l = Some(PbLink {
842                        id: p.link,
843                        tx: 0x80,
844                        acked: None,
845                        seen: std::collections::HashSet::new(),
846                        rx: TransactionRx::default(),
847                        inbox: Vec::new(),
848                        opened: true,
849                        wake: Arc::new(tokio::sync::Notify::new()),
850                    });
851                }
852                drop(l);
853                let me = self.clone();
854                let link = p.link;
855                tokio::spawn(async move { me.send_pb(link, 0, Generic::LinkAck).await });
856            }
857            return;
858        }
859        let mut guard = lock(&self.inner.link);
860        let Some(l) = guard.as_mut().filter(|l| l.id == p.link) else {
861            return;
862        };
863        match &p.pdu {
864            Generic::LinkAck => {
865                l.opened = true;
866                l.wake.notify_one();
867            }
868            Generic::Ack => {
869                l.acked = Some(p.transaction);
870                l.wake.notify_one();
871            }
872            Generic::LinkClose(_) => {
873                l.opened = false;
874                l.wake.notify_one();
875            }
876            Generic::Start { .. } | Generic::Continuation { .. } => {
877                if l.seen.contains(&p.transaction) {
878                    // A repeat of what we already have: acknowledge again.
879                    let me = self.clone();
880                    let (link, tn) = (l.id, p.transaction);
881                    tokio::spawn(async move { me.send_pb(link, tn, Generic::Ack).await });
882                    return;
883                }
884                if let Some(pdu) = l.rx.add(&p) {
885                    l.seen.insert(p.transaction);
886                    let (link, tn) = (l.id, p.transaction);
887                    let device_side =
888                        lock(&self.inner.device).is_some() && lock(&self.inner.store).address == 0;
889                    if device_side {
890                        drop(guard);
891                        self.device_pdu(link, tn, pdu);
892                    } else {
893                        l.inbox.push(pdu);
894                        l.wake.notify_one();
895                        let me = self.clone();
896                        tokio::spawn(async move { me.send_pb(link, tn, Generic::Ack).await });
897                    }
898                }
899            }
900            Generic::LinkOpen(_) => {}
901        }
902    }
903
904    /// The device side answers one provisioning PDU.
905    fn device_pdu(&self, link: u32, tn: u8, pdu: Vec<u8>) {
906        let step = match lock(&self.inner.device).as_mut() {
907            Some(d) => d.receive(&pdu),
908            None => return,
909        };
910        let me = self.clone();
911        tokio::spawn(async move {
912            me.send_pb(link, tn, Generic::Ack).await;
913            let wake = lock(&me.inner.link).as_ref().map(|l| l.wake.clone());
914            let Some(wake) = wake else { return };
915            match step {
916                Step::Send(v) => {
917                    for p in v {
918                        if me.send_transaction(&p, &wake).await.is_err() {
919                            return;
920                        }
921                    }
922                }
923                Step::Done { device_key, data } => {
924                    let _ = me
925                        .send_transaction(&[provisioning::pdu::COMPLETE], &wake)
926                        .await;
927                    if let Some(d) = data {
928                        {
929                            let mut s = lock(&me.inner.store);
930                            s.net_keys = vec![(d.key_index, HexKey(d.net_key))];
931                            s.iv_index = d.iv_index;
932                            s.address = d.address;
933                            s.device_key = Some(HexKey(device_key));
934                        }
935                        me.save();
936                        *lock(&me.inner.device) = None;
937                        let _ = me
938                            .inner
939                            .events
940                            .send(MeshEvent::Provisioned { address: d.address });
941                    }
942                }
943                Step::Failed { send, .. } => {
944                    if let Some(f) = send {
945                        let _ = me.send_transaction(&f, &wake).await;
946                    }
947                }
948                Step::Show(n) => tracing::info!("provisioning: show {n}"),
949            }
950        });
951    }
952
953    fn on_network(&self, data: &[u8]) {
954        let (iv, me_addr) = {
955            let s = lock(&self.inner.store);
956            (s.iv_index, s.address)
957        };
958        if me_addr == 0 {
959            return;
960        }
961        let keys = self.net_keys();
962        let Some((_, iv, pdu)) = network::decode(&keys, iv, data) else {
963            return;
964        };
965        if pdu.src == me_addr || !lock(&self.inner.cache).insert(pdu.src, pdu.seq) {
966            return;
967        }
968        let for_us = pdu.dst == me_addr || pdu.dst == 0xffff || (pdu.dst & 0xc000) == 0xc000;
969        if !for_us {
970            return;
971        }
972        let Some(lower) = transport::parse(pdu.ctl, &pdu.transport) else {
973            return;
974        };
975        match lower {
976            Lower::Ack {
977                seq_zero, block, ..
978            } => {
979                if let Some(tx) = lock(&self.inner.acks).get(&(pdu.src, seq_zero)) {
980                    tx.send_modify(|b| *b |= block);
981                }
982            }
983            Lower::Access { aid, upper } => {
984                self.on_upper(pdu.src, pdu.dst, pdu.seq, iv, aid, false, &upper)
985            }
986            seg @ Lower::Segment { .. } => {
987                let Lower::Segment { seq_zero, .. } = seg else {
988                    return;
989                };
990                let r = lock(&self.inner.reassembly).add(pdu.src, &seg);
991                let (block, done) = match r {
992                    Some(Reassembled::Partial { block }) => (block, None),
993                    Some(Reassembled::Complete {
994                        aid,
995                        big_mic,
996                        upper,
997                        block,
998                    }) => (block, Some((aid, big_mic, upper))),
999                    None => return,
1000                };
1001                // SeqAuth: the first segment's sequence number.
1002                let seq_auth = (pdu.seq & !0x1fff) | u32::from(seq_zero);
1003                let seq_auth = if seq_auth > pdu.seq {
1004                    seq_auth.wrapping_sub(0x2000)
1005                } else {
1006                    seq_auth
1007                };
1008                if pdu.dst & 0x8000 == 0 {
1009                    let me = self.clone();
1010                    let src = pdu.src;
1011                    tokio::spawn(async move { me.send_ack(src, seq_zero, block).await });
1012                }
1013                if let Some((aid, big_mic, upper)) = done {
1014                    self.on_upper(
1015                        pdu.src,
1016                        pdu.dst,
1017                        seq_auth & 0x00ff_ffff,
1018                        iv,
1019                        aid,
1020                        big_mic,
1021                        &upper,
1022                    );
1023                }
1024            }
1025            Lower::Control { .. } => {}
1026        }
1027    }
1028
1029    async fn send_ack(&self, dst: u16, seq_zero: u16, block: u32) {
1030        let (src, iv) = {
1031            let s = lock(&self.inner.store);
1032            (s.address, s.iv_index)
1033        };
1034        let Some(net) = self.net_keys().into_iter().next() else {
1035            return;
1036        };
1037        let pdu = NetworkPdu {
1038            ctl: true,
1039            ttl: TTL,
1040            seq: self.next_seq(),
1041            src,
1042            dst,
1043            transport: transport::ack(seq_zero, block),
1044        };
1045        if let Ok(w) = network::encode(&net, iv, &pdu) {
1046            self.inner.bearer.send(ad::MESSAGE, w).await;
1047        }
1048    }
1049
1050    #[allow(clippy::too_many_arguments)]
1051    fn on_upper(
1052        &self,
1053        src: u16,
1054        dst: u16,
1055        seq: u32,
1056        iv: u32,
1057        aid: Option<u8>,
1058        big_mic: bool,
1059        upper: &[u8],
1060    ) {
1061        let meta = Meta {
1062            seq,
1063            src,
1064            dst,
1065            iv_index: iv,
1066            label: None,
1067        };
1068        let plain = match aid {
1069            None => {
1070                // The device key: ours (node), or the source node's (provisioner).
1071                let s = lock(&self.inner.store);
1072                let mut keys: Vec<Key> = s.device_key.iter().map(|k| k.0).collect();
1073                keys.extend(
1074                    s.nodes
1075                        .iter()
1076                        .filter(|n| n.address == src)
1077                        .map(|n| n.device_key),
1078                );
1079                drop(s);
1080                keys.iter().find_map(|k| {
1081                    transport::decrypt_access(AccessKey::Device(k), &meta, upper, big_mic)
1082                })
1083            }
1084            Some(aid) => {
1085                let keys: Vec<Key> = lock(&self.inner.store)
1086                    .app_keys
1087                    .iter()
1088                    .map(|(_, _, k)| k.0)
1089                    .filter(|k| crypto::k4(k) == aid)
1090                    .collect();
1091                keys.iter().find_map(|k| {
1092                    transport::decrypt_access(AccessKey::App(k, aid), &meta, upper, big_mic)
1093                })
1094            }
1095        };
1096        let Some(plain) = plain else { return };
1097        let Some((opcode, params)) = access::split(&plain) else {
1098            return;
1099        };
1100        let params = params.to_vec();
1101        {
1102            let mut w = lock(&self.inner.waiters);
1103            if let Some(i) = w.iter().position(|x| x.src == src && x.opcode == opcode) {
1104                let x = w.remove(i);
1105                let _ = x.tx.send(params);
1106                return;
1107            }
1108        }
1109        if self.serve(src, aid, opcode, &params) {
1110            return;
1111        }
1112        let _ = self.inner.events.send(MeshEvent::Message {
1113            src,
1114            dst,
1115            opcode,
1116            params,
1117        });
1118    }
1119
1120    /// The node's servers: Configuration (device key) and Generic OnOff (bound application key).
1121    fn serve(&self, src: u16, aid: Option<u8>, opcode: Opcode, p: &[u8]) -> bool {
1122        let Some(dev) = lock(&self.inner.store).device_key.map(|k| k.0) else {
1123            return false;
1124        };
1125        let reply: Option<(Option<u16>, Vec<u8>)> = match (aid, opcode) {
1126            (None, op::COMPOSITION_GET) => {
1127                let mut d = vec![0u8];
1128                d.extend(self.composition()[1..].iter());
1129                Some((None, access::message(op::COMPOSITION_STATUS, &d)))
1130            }
1131            (None, op::APPKEY_ADD) if p.len() == 19 => {
1132                let v = u32::from(p[0]) | (u32::from(p[1]) << 8) | (u32::from(p[2]) << 16);
1133                let (net, app) = ((v & 0xfff) as u16, (v >> 12) as u16);
1134                let mut k = [0u8; 16];
1135                k.copy_from_slice(&p[3..]);
1136                {
1137                    let mut s = lock(&self.inner.store);
1138                    s.app_keys.retain(|(i, ..)| *i != app);
1139                    s.app_keys.push((app, net, HexKey(k)));
1140                }
1141                self.save();
1142                let mut st = vec![0u8];
1143                st.extend_from_slice(&p[..3]);
1144                Some((None, access::message(op::APPKEY_STATUS, &st)))
1145            }
1146            (None, op::MODEL_APP_BIND) if p.len() == 6 => {
1147                let element = u16::from_le_bytes([p[0], p[1]]);
1148                let app = u16::from_le_bytes([p[2], p[3]]);
1149                let model = u16::from_le_bytes([p[4], p[5]]);
1150                let known = lock(&self.inner.store)
1151                    .app_keys
1152                    .iter()
1153                    .any(|(i, ..)| *i == app);
1154                let status = if known { 0 } else { 0x03 }; // Invalid AppKey Index
1155                if known {
1156                    lock(&self.inner.store).bindings.push((element, model, app));
1157                    self.save();
1158                }
1159                let mut st = vec![status];
1160                st.extend_from_slice(p);
1161                Some((None, access::message(op::MODEL_APP_STATUS, &st)))
1162            }
1163            (Some(aid), op::ONOFF_GET | op::ONOFF_SET | op::ONOFF_SET_UNACK) => {
1164                let bound: Vec<u16> = lock(&self.inner.store)
1165                    .bindings
1166                    .iter()
1167                    .filter(|(_, m, _)| *m == 0x1000)
1168                    .map(|(_, _, a)| *a)
1169                    .collect();
1170                let Some(app) = bound
1171                    .into_iter()
1172                    .find(|a| self.app_key(*a).is_some_and(|(_, x)| x == aid))
1173                else {
1174                    return true;
1175                };
1176                if opcode != op::ONOFF_GET {
1177                    if let Some(&on) = p.first() {
1178                        lock(&self.inner.store).onoff = on == 1;
1179                        self.save();
1180                    }
1181                }
1182                if opcode == op::ONOFF_SET_UNACK {
1183                    return true;
1184                }
1185                let on = lock(&self.inner.store).onoff;
1186                Some((
1187                    Some(app),
1188                    access::message(op::ONOFF_STATUS, &[u8::from(on)]),
1189                ))
1190            }
1191            _ => None,
1192        };
1193        let Some((app, msg)) = reply else {
1194            return false;
1195        };
1196        let me = self.clone();
1197        tokio::spawn(async move {
1198            let r = match app {
1199                None => me.send_access(src, AccessKey::Device(&dev), &msg).await,
1200                Some(a) => match me.app_key(a) {
1201                    Some((k, aid)) => me.send_access(src, AccessKey::App(&k, aid), &msg).await,
1202                    None => Ok(()),
1203                },
1204            };
1205            if let Err(e) = r {
1206                tracing::debug!("mesh reply to {src:#06x}: {e}");
1207            }
1208        });
1209        true
1210    }
1211}
1212
1213#[cfg(test)]
1214mod tests {
1215    use super::*;
1216
1217    /// A radio in memory: everything sent reaches every other mesh.
1218    struct Air {
1219        meshes: Mutex<Vec<(usize, Mesh)>>,
1220    }
1221
1222    struct Radio {
1223        air: Arc<Air>,
1224        me: usize,
1225    }
1226
1227    impl Bearer for Radio {
1228        fn send(&self, ad_type: u8, data: Vec<u8>) -> BoxFuture<'_, ()> {
1229            Box::pin(async move {
1230                let others: Vec<Mesh> = lock(&self.air.meshes)
1231                    .iter()
1232                    .filter(|(i, _)| *i != self.me)
1233                    .map(|(_, m)| m.clone())
1234                    .collect();
1235                for m in others {
1236                    m.receive(ad_type, &data);
1237                }
1238                tokio::time::sleep(Duration::from_millis(2)).await;
1239            })
1240        }
1241    }
1242
1243    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1244    async fn provision_configure_and_control_a_node() {
1245        let air = Arc::new(Air {
1246            meshes: Mutex::new(Vec::new()),
1247        });
1248        let dir = tempfile::tempdir().unwrap();
1249        let prov = Mesh::open(
1250            Arc::new(Radio {
1251                air: air.clone(),
1252                me: 0,
1253            }),
1254            Some(dir.path().join("p")),
1255            [0; 16],
1256        )
1257        .unwrap();
1258        let uuid = [0x42; 16];
1259        let node = Mesh::open(
1260            Arc::new(Radio {
1261                air: air.clone(),
1262                me: 1,
1263            }),
1264            Some(dir.path().join("n")),
1265            uuid,
1266        )
1267        .unwrap();
1268        lock(&air.meshes).extend([(0, prov.clone()), (1, node.clone())]);
1269
1270        prov.create_network();
1271        let mut events = prov.events();
1272        let caps = Capabilities {
1273            elements: 1,
1274            algorithms: 1,
1275            public_key_oob: false,
1276            static_oob: true,
1277            output_oob: (0, 0),
1278            input_oob: (0, 0),
1279        };
1280        let n2 = node.clone();
1281        tokio::spawn(async move { n2.wait_for_provisioning(caps, Some([0x5a; 16])).await });
1282        // The node's beacon is heard.
1283        let seen = tokio::time::timeout(Duration::from_secs(5), async {
1284            loop {
1285                if let Ok(MeshEvent::Unprovisioned { uuid: u, .. }) = events.recv().await {
1286                    break u;
1287                }
1288            }
1289        })
1290        .await
1291        .unwrap();
1292        assert_eq!(seen, uuid);
1293
1294        let rec = prov
1295            .provision(uuid, Auth::Static([0x5a; 16]))
1296            .await
1297            .unwrap();
1298        assert_eq!(rec.address, 0x0002);
1299        tokio::time::sleep(Duration::from_millis(200)).await;
1300        assert_eq!(node.store().address, 0x0002);
1301        assert_eq!(node.store().device_key.unwrap().0, rec.device_key);
1302
1303        let comp = prov.configure(&rec).await.unwrap();
1304        assert_eq!(
1305            comp.elements[0].models,
1306            vec![ModelId::Sig(0), ModelId::Sig(0x1000)]
1307        );
1308        assert!(prov.onoff_set(rec.address, true, 1).await.unwrap());
1309        assert!(node.store().onoff);
1310        assert!(!prov.onoff_set(rec.address, false, 2).await.unwrap());
1311
1312        // Both survive a restart from their stores.
1313        let again = Mesh::open(
1314            Arc::new(Radio { air, me: 2 }),
1315            Some(dir.path().join("n")),
1316            uuid,
1317        )
1318        .unwrap();
1319        assert_eq!(again.store().address, 0x0002);
1320        assert!(again.store().seq >= node.store().seq);
1321    }
1322}