Skip to main content

zigbee_host/
ezsp_adapter.rs

1//! The [`Adapter`] for Silicon Labs EmberZNet NCPs over EZSP.
2//!
3//! Security follows Zigbee 3.0 with hashed trust center link keys: joining
4//! devices use the well-known key (or their install code key) to receive
5//! the network key, then ask the trust center for a link key of their own,
6//! which the NCP derives from a random root key and the device's IEEE
7//! address. The root key is in every backup, so the derived keys survive a
8//! restore without a key table entry per device.
9//!
10//! EmberZNet 6.7 to 6.10 (protocol 8, the last firmware for the EM35x)
11//! predates the security manager: the same keys go through `getKey`, the
12//! key table commands and `addTransientLinkKey` instead. Those key table
13//! entries carry no frame counters, so a restore onto protocol 8 starts its
14//! link keys' counters at zero; with hashed link keys the table is usually
15//! empty anyway.
16
17use std::sync::atomic::{AtomicU16, Ordering};
18use std::sync::{Arc, Mutex};
19use std::time::{Duration, SystemTime, UNIX_EPOCH};
20
21use tokio::io::{AsyncRead, AsyncWrite};
22use tokio::sync::{mpsc, watch};
23use zigbee_ezsp::client::{ClientConfig, Ezsp, EzspEvent, NcpInfo};
24use zigbee_ezsp::ids::{
25    self, aps_option, config, decision, ember_key_type, ext_security, policy, security,
26    tc_decision, value,
27};
28use zigbee_ezsp::types::{InitialSecurityState, KeyStruct, NetworkParameters, SecManContext};
29use zigbee_ezsp::{ApsFrame, Callback, Command, Response, Status};
30use zigbee_primitives::{ExtPanId, Ieee, Key, NodeId};
31
32use crate::adapter::{
33    Adapter, AdapterEvent, AdapterInfo, Aps, Beacon, JoinPolicy, NetworkInfo, NetworkSettings,
34    StartMode, StartOutcome,
35};
36use crate::backup::{
37    self, Backup, BackupDevice, EzspSpecific, Internal, LinkKey, Metadata, NetworkKey,
38    StackSpecific,
39};
40use crate::error::HostError;
41
42/// How long to wait for the network to come up or go down.
43const NETWORK_TIMEOUT: Duration = Duration::from_secs(10);
44/// Silicon Labs' manufacturer code, which the coordinator reports.
45const MANUFACTURER_CODE: u16 = 0x1049;
46/// Every 2.4 GHz channel.
47const ALL_CHANNELS: u32 = 0x07FF_F800;
48/// Default APS options for unicasts.
49const UNICAST_OPTIONS: u16 =
50    aps_option::RETRY | aps_option::ENABLE_ROUTE_DISCOVERY | aps_option::ENABLE_ADDRESS_DISCOVERY;
51
52/// The clusters the host's endpoint 1 serves and uses; devices bind their
53/// reporting clusters to it.
54const ENDPOINT_INPUT_CLUSTERS: &[u16] = &[
55    0x0000, 0x0003, 0x0006, 0x000A, 0x0019, 0x0300, 0x0402, 0x0405, 0x0500, 0x0702, 0x0B04,
56];
57const ENDPOINT_OUTPUT_CLUSTERS: &[u16] = &[
58    0x0000, 0x0001, 0x0003, 0x0004, 0x0005, 0x0006, 0x0008, 0x000F, 0x0012, 0x0020, 0x0101, 0x0102,
59    0x0201, 0x0202, 0x0300, 0x0400, 0x0402, 0x0403, 0x0405, 0x0406, 0x0500, 0x0502, 0x0702, 0x0B04,
60    0x0B05,
61];
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64enum NetState {
65    Unknown,
66    Up,
67    Down,
68}
69
70type ScanResult = Result<(Vec<(u8, i8)>, Vec<Beacon>), HostError>;
71
72struct ScanCollector {
73    results: Vec<(u8, i8)>,
74    beacons: Vec<Beacon>,
75    done: Option<tokio::sync::oneshot::Sender<ScanResult>>,
76}
77
78/// An EmberZNet NCP.
79pub struct EzspAdapter {
80    ezsp: Ezsp,
81    info: NcpInfo,
82    net: watch::Receiver<NetState>,
83    scan: Arc<Mutex<Option<ScanCollector>>>,
84    tag: AtomicU16,
85}
86
87impl std::fmt::Debug for EzspAdapter {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        f.debug_struct("EzspAdapter")
90            .field("info", &self.info)
91            .finish_non_exhaustive()
92    }
93}
94
95fn now_unix() -> u64 {
96    SystemTime::now()
97        .duration_since(UNIX_EPOCH)
98        .map(|d| d.as_secs())
99        .unwrap_or(0)
100}
101
102fn translate(
103    cb: Callback,
104    net: &watch::Sender<NetState>,
105    scan: &Mutex<Option<ScanCollector>>,
106) -> Option<AdapterEvent> {
107    match cb {
108        Callback::StackStatus { status } => {
109            if status.is_network_up() {
110                let _ = net.send(NetState::Up);
111                Some(AdapterEvent::NetworkUp)
112            } else if status.is_network_down() {
113                let _ = net.send(NetState::Down);
114                Some(AdapterEvent::NetworkDown)
115            } else {
116                tracing::debug!(%status, "stack status");
117                None
118            }
119        }
120        Callback::IncomingMessage {
121            kind,
122            aps,
123            info,
124            payload,
125        } => Some(AdapterEvent::Message {
126            source: info.sender,
127            source_ieee: info.sender_ieee,
128            aps: Aps {
129                profile: aps.profile_id,
130                cluster: aps.cluster_id,
131                source_endpoint: aps.source_endpoint,
132                destination_endpoint: aps.destination_endpoint,
133            },
134            broadcast: !matches!(kind, ids::incoming::UNICAST | ids::incoming::UNICAST_REPLY),
135            group: matches!(
136                kind,
137                ids::incoming::MULTICAST | ids::incoming::MULTICAST_LOOPBACK
138            )
139            .then_some(aps.group_id),
140            lqi: info.last_hop_lqi,
141            rssi: Some(info.last_hop_rssi),
142            payload,
143        }),
144        Callback::TrustCenterJoin {
145            node_id,
146            ieee,
147            status,
148            decision,
149            parent,
150        } => match status {
151            ids::device_update::DEVICE_LEFT => Some(AdapterEvent::Left { nwk: node_id, ieee }),
152            _ if decision == ids::join_decision::DENY_JOIN => {
153                tracing::info!(%ieee, "trust center denied a join");
154                None
155            }
156            ids::device_update::UNSECURED_JOIN => Some(AdapterEvent::Joined {
157                nwk: node_id,
158                ieee,
159                parent,
160                rejoin: false,
161            }),
162            _ => Some(AdapterEvent::Joined {
163                nwk: node_id,
164                ieee,
165                parent,
166                rejoin: true,
167            }),
168        },
169        Callback::ZigbeeKeyEstablishment { partner, status } => {
170            use ids::key_status::*;
171            let success = matches!(
172                status,
173                TRUST_CENTER_LINK_KEY_ESTABLISHED
174                    | TC_RESPONDED_TO_KEY_REQUEST
175                    | VERIFY_LINK_KEY_SUCCESS
176            );
177            tracing::debug!(%partner, status, "key establishment");
178            Some(AdapterEvent::KeyExchange {
179                ieee: partner,
180                success,
181            })
182        }
183        Callback::IncomingRouteRecord {
184            source,
185            ieee,
186            last_hop_lqi,
187            last_hop_rssi,
188            relays,
189        } => Some(AdapterEvent::RouteRecord {
190            source,
191            ieee: Some(ieee),
192            relays,
193            lqi: Some(last_hop_lqi),
194            rssi: Some(last_hop_rssi),
195        }),
196        Callback::MessageSent { status, tag, .. } => Some(AdapterEvent::Delivery {
197            tag,
198            delivered: status.is_ok(),
199        }),
200        Callback::EnergyScanResult { channel, max_rssi } => {
201            if let Ok(mut s) = scan.lock() {
202                if let Some(c) = s.as_mut() {
203                    c.results.push((channel, max_rssi));
204                }
205            }
206            None
207        }
208        Callback::NetworkFound {
209            channel,
210            pan_id,
211            extended_pan_id,
212            allowing_join,
213            nwk_update_id,
214            lqi,
215            rssi,
216            ..
217        } => {
218            if let Ok(mut s) = scan.lock() {
219                if let Some(c) = s.as_mut() {
220                    if c.beacons.len() < 256 {
221                        c.beacons.push(Beacon {
222                            channel,
223                            pan_id,
224                            extended_pan_id,
225                            permit_joining: allowing_join,
226                            nwk_update_id,
227                            lqi,
228                            rssi: Some(rssi),
229                        });
230                    }
231                }
232            }
233            None
234        }
235        Callback::ScanComplete { status, channel } => {
236            if let Some(mut c) = scan.lock().ok().and_then(|mut s| s.take()) {
237                let result = if status.is_ok() {
238                    Ok((
239                        std::mem::take(&mut c.results),
240                        std::mem::take(&mut c.beacons),
241                    ))
242                } else {
243                    Err(HostError::Ncp(format!(
244                        "scan failed on channel {channel}: {status}"
245                    )))
246                };
247                if let Some(done) = c.done.take() {
248                    let _ = done.send(result);
249                }
250            }
251            None
252        }
253        Callback::IdConflict { node_id } => {
254            tracing::warn!(node_id, "network address conflict");
255            None
256        }
257        other => {
258            tracing::trace!(?other, "unhandled callback");
259            None
260        }
261    }
262}
263
264impl EzspAdapter {
265    /// Connect to an NCP over `io`. Returns the adapter and its events.
266    pub async fn connect<T>(
267        io: T,
268        config: ClientConfig,
269    ) -> Result<(EzspAdapter, mpsc::UnboundedReceiver<AdapterEvent>), HostError>
270    where
271        T: AsyncRead + AsyncWrite + Send + 'static,
272    {
273        let (ezsp, info, mut ezsp_events) = Ezsp::start(io, config).await?;
274        tracing::info!(protocol = info.protocol.0, firmware = %info.stack_version, "EZSP NCP connected");
275        let (net_tx, net) = watch::channel(NetState::Unknown);
276        let scan: Arc<Mutex<Option<ScanCollector>>> = Arc::new(Mutex::new(None));
277        let (tx, rx) = mpsc::unbounded_channel();
278        let scan_for_task = scan.clone();
279        tokio::spawn(async move {
280            while let Some(event) = ezsp_events.recv().await {
281                let out = match event {
282                    EzspEvent::Callback(cb) => translate(cb, &net_tx, &scan_for_task),
283                    EzspEvent::Down(why) => Some(AdapterEvent::Failed(why)),
284                };
285                if let Some(out) = out {
286                    if tx.send(out).is_err() {
287                        break;
288                    }
289                }
290            }
291        });
292        Ok((
293            EzspAdapter {
294                ezsp,
295                info,
296                net,
297                scan,
298                tag: AtomicU16::new(1),
299            },
300            rx,
301        ))
302    }
303
304    /// The NCP's start-up report.
305    pub fn ncp_info(&self) -> &NcpInfo {
306        &self.info
307    }
308
309    async fn wait_net(&self, want: NetState) -> Result<(), HostError> {
310        let mut net = self.net.clone();
311        let reached = matches!(
312            tokio::time::timeout(NETWORK_TIMEOUT, net.wait_for(|s| *s == want)).await,
313            Ok(Ok(_))
314        );
315        if reached {
316            Ok(())
317        } else {
318            Err(HostError::Ncp(format!(
319                "network did not go {}",
320                if want == NetState::Up { "up" } else { "down" }
321            )))
322        }
323    }
324
325    async fn ok(&self, command: Command) -> Result<(), HostError> {
326        self.ezsp.call_ok(command).await.map_err(HostError::from)
327    }
328
329    /// Configuration that must be set after every NCP reset, before the
330    /// network starts.
331    async fn configure(&self) -> Result<(), HostError> {
332        let required = [
333            (config::STACK_PROFILE, ids::STACK_PROFILE_ZIGBEE_PRO),
334            (config::SECURITY_LEVEL, ids::SECURITY_LEVEL_Z3),
335            (config::SUPPORTED_NETWORKS, 1),
336        ];
337        for (id, v) in required {
338            self.ezsp.set_config(id, v).await?;
339        }
340        // Tuning the firmware may refuse (its build fixes some sizes).
341        let tuning = [
342            (config::MAX_HOPS, 30),
343            (config::INDIRECT_TRANSMISSION_TIMEOUT, 7680),
344            (config::TRUST_CENTER_ADDRESS_CACHE_SIZE, 2),
345            (config::MAX_END_DEVICE_CHILDREN, 32),
346            (config::END_DEVICE_POLL_TIMEOUT, 8),
347            (config::TRANSIENT_KEY_TIMEOUT_S, 300),
348        ];
349        for (id, v) in tuning {
350            if let Err(e) = self.ezsp.set_config(id, v).await {
351                tracing::warn!(config_id = id, value = v, error = %e, "NCP kept its own configuration value");
352            }
353        }
354        self.ezsp
355            .set_policy(
356                policy::BINDING_MODIFICATION,
357                decision::CHECK_BINDING_MODIFICATIONS_ARE_VALID_ENDPOINT_CLUSTERS,
358            )
359            .await?;
360        self.ezsp
361            .set_policy(
362                policy::MESSAGE_CONTENTS_IN_CALLBACK,
363                decision::MESSAGE_TAG_ONLY_IN_CALLBACK,
364            )
365            .await?;
366        self.ezsp
367            .set_policy(
368                policy::TC_KEY_REQUEST,
369                decision::ALLOW_TC_KEY_REQUESTS_AND_SEND_CURRENT_KEY,
370            )
371            .await?;
372        self.ezsp
373            .set_policy(policy::APP_KEY_REQUEST, decision::DENY_APP_KEY_REQUESTS)
374            .await?;
375        self.ezsp
376            .set_policy(policy::TRUST_CENTER, tc_decision::ALLOW_UNSECURED_REJOINS)
377            .await?;
378        self.ok(Command::SetManufacturerCode {
379            code: MANUFACTURER_CODE,
380        })
381        .await?;
382        let endpoint = Command::AddEndpoint {
383            endpoint: 1,
384            profile_id: zigbee_zcl::PROFILE_HOME_AUTOMATION,
385            device_id: 0x0005,
386            device_version: 0,
387            input_clusters: ENDPOINT_INPUT_CLUSTERS.to_vec(),
388            output_clusters: ENDPOINT_OUTPUT_CLUSTERS.to_vec(),
389        };
390        if let Err(e) = self.ok(endpoint).await {
391            // After a soft restart without a reset the endpoint exists.
392            tracing::warn!(error = %e, "adding endpoint 1");
393        }
394        Ok(())
395    }
396
397    async fn network_parameters(&self) -> Result<(u8, NetworkParameters), HostError> {
398        match self.ezsp.call(Command::GetNetworkParameters).await? {
399            Response::GetNetworkParameters {
400                status,
401                node_type,
402                parameters,
403            } if status.is_ok() => Ok((node_type, parameters)),
404            other => Err(HostError::Ncp(format!("getNetworkParameters: {other:?}"))),
405        }
406    }
407
408    /// The network key ([`ids::key_type::NETWORK`]) or the trust center
409    /// root key ([`ids::key_type::TC_LINK`]).
410    async fn export_key(&self, key_type: u8) -> Result<Key, HostError> {
411        if !self.ezsp.version().sec_man() {
412            let legacy = if key_type == ids::key_type::NETWORK {
413                ember_key_type::CURRENT_NETWORK
414            } else {
415                ember_key_type::TRUST_CENTER_LINK
416            };
417            return Ok(self.get_key(legacy).await?.key);
418        }
419        match self
420            .ezsp
421            .call(Command::ExportKey {
422                context: SecManContext::for_key(key_type),
423            })
424            .await?
425        {
426            Response::ExportKey { status, key, .. } if status.is_ok() => Ok(key),
427            other => Err(HostError::Ncp(format!("exportKey({key_type}): {other:?}"))),
428        }
429    }
430
431    /// `getKey`, before protocol 13.
432    async fn get_key(&self, key_type: u8) -> Result<KeyStruct, HostError> {
433        match self.ezsp.call(Command::GetKey { key_type }).await? {
434            Response::GetKey { status, key } if status.is_ok() => Ok(key),
435            other => Err(HostError::Ncp(format!("getKey({key_type}): {other:?}"))),
436        }
437    }
438
439    /// The network key's sequence number and outgoing frame counter.
440    async fn network_key_counters(&self) -> Result<(u8, u32), HostError> {
441        if !self.ezsp.version().sec_man() {
442            let key = self.get_key(ember_key_type::CURRENT_NETWORK).await?;
443            return Ok((key.sequence_number, key.outgoing_frame_counter));
444        }
445        match self.ezsp.call(Command::GetNetworkKeyInfo).await? {
446            Response::GetNetworkKeyInfo { status, info } if status.is_ok() => {
447                Ok((info.network_key_sequence, info.network_key_frame_counter))
448            }
449            other => Err(HostError::Ncp(format!("getNetworkKeyInfo: {other:?}"))),
450        }
451    }
452
453    /// The device link key in key table entry `index`, if there is one.
454    async fn link_key_at(&self, index: u8) -> Option<(Ieee, LinkKey)> {
455        let (status, ieee, key, tx_counter, rx_counter) = if self.ezsp.version().sec_man() {
456            match self
457                .ezsp
458                .call(Command::ExportLinkKeyByIndex { index })
459                .await
460            {
461                Ok(Response::ExportLinkKeyByIndex {
462                    status,
463                    context,
464                    key,
465                    metadata,
466                }) => (
467                    status,
468                    context.ieee,
469                    key,
470                    metadata.outgoing_frame_counter,
471                    metadata.incoming_frame_counter,
472                ),
473                _ => return None,
474            }
475        } else {
476            match self.ezsp.call(Command::GetKeyTableEntry { index }).await {
477                Ok(Response::GetKeyTableEntry { status, key }) => (
478                    status,
479                    key.partner,
480                    key.key,
481                    key.outgoing_frame_counter,
482                    key.incoming_frame_counter,
483                ),
484                _ => return None,
485            }
486        };
487        (status.is_ok() && ieee != Ieee::ZERO && ieee != Ieee::UNSET).then_some((
488            ieee,
489            LinkKey {
490                key,
491                tx_counter,
492                rx_counter,
493            },
494        ))
495    }
496
497    /// Write a device link key into key table entry `index`.
498    async fn import_link_key(&self, index: u8, ieee: Ieee, key: Key) -> Result<(), HostError> {
499        if self.ezsp.version().sec_man() {
500            self.ok(Command::ImportLinkKey { index, ieee, key }).await
501        } else {
502            self.ok(Command::SetKeyTableEntry {
503                index,
504                ieee,
505                link_key: true,
506                key,
507            })
508            .await
509        }
510    }
511
512    /// A transient key for a joining device; [`Ieee::ZERO`] means any device.
513    async fn add_transient_key(&self, ieee: Ieee, key: Key) -> Result<(), HostError> {
514        if self.ezsp.version().sec_man() {
515            self.ok(Command::ImportTransientKey { ieee, key }).await
516        } else {
517            // EmberZNet 6.x spells "any device" as all ones.
518            let ieee = if ieee == Ieee::ZERO {
519                Ieee::UNSET
520            } else {
521                ieee
522            };
523            self.ok(Command::AddTransientLinkKey { ieee, key }).await
524        }
525    }
526
527    async fn eui64(&self) -> Result<Ieee, HostError> {
528        match self.ezsp.call(Command::GetEui64).await? {
529            Response::GetEui64 { ieee } => Ok(ieee),
530            other => Err(HostError::Ncp(format!("getEui64: {other:?}"))),
531        }
532    }
533
534    async fn leave_network(&self) -> Result<(), HostError> {
535        self.ok(Command::LeaveNetwork { options: 0 }).await?;
536        self.wait_net(NetState::Down).await?;
537        tokio::time::sleep(Duration::from_millis(200)).await;
538        Ok(())
539    }
540
541    async fn form(
542        &self,
543        settings: &NetworkSettings,
544        tc_root: Key,
545        restore: Option<&Backup>,
546    ) -> Result<(), HostError> {
547        let mut bitmask = security::TRUST_CENTER_GLOBAL_LINK_KEY
548            | security::HAVE_PRECONFIGURED_KEY
549            | security::HAVE_NETWORK_KEY
550            | security::TRUST_CENTER_USES_HASHED_LINK_KEY
551            | security::REQUIRE_ENCRYPTED_KEY;
552        let mut sequence = 0;
553        if let Some(backup) = restore {
554            bitmask |= security::NO_FRAME_COUNTER_RESET;
555            sequence = backup.network_key.sequence_number;
556            self.ezsp
557                .set_value(
558                    value::NWK_FRAME_COUNTER,
559                    backup.restore_frame_counter().to_le_bytes().to_vec(),
560                )
561                .await?;
562        }
563        self.ok(Command::SetInitialSecurityState {
564            state: InitialSecurityState {
565                bitmask,
566                preconfigured_key: tc_root,
567                network_key: settings.network_key,
568                network_key_sequence: sequence,
569                preconfigured_trust_center: Ieee::ZERO,
570            },
571        })
572        .await?;
573        let ext =
574            ext_security::JOINER_GLOBAL_LINK_KEY | ext_security::NWK_LEAVE_REQUEST_NOT_ALLOWED;
575        self.ezsp
576            .set_value(value::EXTENDED_SECURITY_BITMASK, ext.to_le_bytes().to_vec())
577            .await?;
578        if restore.is_none() {
579            if let Err(e) = self.ok(Command::ClearKeyTable).await {
580                tracing::warn!(error = %e, "clearing the key table");
581            }
582        }
583        let parameters = NetworkParameters {
584            extended_pan_id: settings.extended_pan_id,
585            pan_id: settings.pan_id,
586            radio_tx_power: settings.tx_power.unwrap_or(5),
587            radio_channel: settings.channel,
588            join_method: 0,
589            nwk_manager_id: 0,
590            nwk_update_id: restore.map(|b| b.nwk_update_id).unwrap_or(0),
591            channels: ALL_CHANNELS,
592        };
593        self.ok(Command::FormNetwork { parameters }).await?;
594        self.wait_net(NetState::Up).await?;
595        if let Err(e) = self
596            .ezsp
597            .set_value(value::STACK_TOKEN_WRITING, vec![1])
598            .await
599        {
600            tracing::warn!(error = %e, "enabling stack token writing");
601        }
602        Ok(())
603    }
604
605    async fn restore(&self, backup: &Backup) -> Result<(), HostError> {
606        let ieee = self.eui64().await?;
607        if ieee != backup.coordinator_ieee {
608            // The custom EUI-64 token can be written once; all ones means unset.
609            let token = match self
610                .ezsp
611                .call(Command::GetMfgToken {
612                    token_id: ids::mfg_token::CUSTOM_EUI_64,
613                })
614                .await?
615            {
616                Response::GetMfgToken { data } => data,
617                other => return Err(HostError::Ncp(format!("getMfgToken: {other:?}"))),
618            };
619            if token.len() != 8 || token.iter().any(|b| *b != 0xFF) {
620                return Err(HostError::RestoreRefused(format!(
621                    "this coordinator is {ieee} and its IEEE address token is already written; the backup needs {}",
622                    backup.coordinator_ieee
623                )));
624            }
625            self.ok(Command::SetMfgToken {
626                token_id: ids::mfg_token::CUSTOM_EUI_64,
627                data: backup.coordinator_ieee.to_le_bytes().to_vec(),
628            })
629            .await?;
630            return Err(HostError::RestartRequired);
631        }
632        let key_table = self
633            .ezsp
634            .get_config(config::KEY_TABLE_SIZE)
635            .await
636            .unwrap_or(0);
637        let keys: Vec<(Ieee, &LinkKey)> = backup
638            .devices
639            .iter()
640            .filter_map(|d| d.link_key.as_ref().map(|k| (d.ieee_address, k)))
641            .collect();
642        if keys.len() > usize::from(key_table) {
643            return Err(HostError::RestoreRefused(format!(
644                "{} link keys do not fit the NCP's key table of {key_table}",
645                keys.len()
646            )));
647        }
648        for index in 0..key_table {
649            let result = match keys.get(usize::from(index)) {
650                Some((ieee, link)) => self.import_link_key(index as u8, *ieee, link.key).await,
651                None => {
652                    self.ok(Command::EraseKeyTableEntry { index: index as u8 })
653                        .await
654                }
655            };
656            if let Err(e) = result {
657                tracing::warn!(index, error = %e, "restoring key table entry");
658            }
659        }
660        // A backup from another family has no root key: a new one, with the
661        // devices' own link keys (if the backup has them) in the key table.
662        let tc_root = match backup.stack_specific.as_ref().and_then(|s| s.ezsp.as_ref()) {
663            Some(e) => e.hashed_tclk,
664            None => {
665                tracing::info!(
666                    keys = keys.len(),
667                    "restoring a backup from another coordinator family"
668                );
669                random_key()?
670            }
671        };
672        let settings = NetworkSettings {
673            channel: backup.channel,
674            pan_id: backup.pan_id,
675            extended_pan_id: backup.extended_pan_id,
676            network_key: backup.network_key.key,
677            tx_power: None,
678        };
679        self.form(&settings, tc_root, Some(backup)).await
680    }
681
682    async fn after_up(&self, settings_power: Option<i8>) -> Result<NetworkInfo, HostError> {
683        self.ok(Command::SetConcentrator {
684            on: true,
685            kind: ids::concentrator::HIGH_RAM,
686            min_time: 5,
687            max_time: 60,
688            route_error_threshold: 3,
689            delivery_failure_threshold: 1,
690            max_hops: 0,
691        })
692        .await?;
693        if let Err(e) = self
694            .ezsp
695            .call(Command::SetSourceRouteDiscoveryMode { mode: 2 })
696            .await
697        {
698            tracing::warn!(error = %e, "source route discovery mode");
699        }
700        if let Some(power) = settings_power {
701            if let Err(e) = self.ok(Command::SetRadioPower { power }).await {
702                tracing::warn!(power, error = %e, "setting radio power");
703            }
704        }
705        self.read_network_info().await
706    }
707
708    async fn read_network_info(&self) -> Result<NetworkInfo, HostError> {
709        let (_, p) = self.network_parameters().await?;
710        let nwk = match self.ezsp.call(Command::GetNodeId).await? {
711            Response::GetNodeId { node_id } => node_id,
712            _ => 0,
713        };
714        Ok(NetworkInfo {
715            ieee: self.eui64().await?,
716            nwk,
717            channel: p.radio_channel,
718            pan_id: p.pan_id,
719            extended_pan_id: p.extended_pan_id,
720            nwk_update_id: p.nwk_update_id,
721        })
722    }
723
724    fn next_tag(&self) -> u16 {
725        // Protocol 13 carries one-byte tags.
726        let tag = self.tag.fetch_add(1, Ordering::Relaxed);
727        if self.ezsp.version().sl_status() {
728            tag
729        } else {
730            tag & 0xFF
731        }
732    }
733}
734
735fn describe(p: &NetworkParameters) -> String {
736    format!(
737        "channel {}, PAN {:04x}, extended PAN {}",
738        p.radio_channel, p.pan_id, p.extended_pan_id
739    )
740}
741
742fn random_key() -> Result<Key, HostError> {
743    let mut k = [0u8; 16];
744    getrandom::fill(&mut k).map_err(|e| HostError::Io(format!("random: {e}")))?;
745    Ok(Key(k))
746}
747
748impl Adapter for EzspAdapter {
749    fn info(&self) -> AdapterInfo {
750        let v = self.info.stack_version;
751        AdapterInfo {
752            kind: "ezsp",
753            firmware: format!("{}.{}.{}.{}", v.major, v.minor, v.patch, v.special),
754            protocol: self.info.protocol.0,
755            reports_key_exchange: true,
756        }
757    }
758
759    async fn start(&self, mode: StartMode) -> Result<(StartOutcome, NetworkInfo), HostError> {
760        self.configure().await?;
761        let init = self
762            .ezsp
763            .call(Command::NetworkInit {
764                bitmask: ids::network_init::PARENT_INFO_IN_TOKEN
765                    | ids::network_init::END_DEVICE_REJOIN_ON_REBOOT,
766            })
767            .await?;
768        let status = init.status().unwrap_or(Status::SL_OK);
769        let has_network = status.is_ok();
770        if !has_network && !status.is_not_joined() {
771            return Err(HostError::Ncp(format!("networkInit: {status}")));
772        }
773        if has_network {
774            self.wait_net(NetState::Up).await?;
775        }
776
777        match mode {
778            StartMode::Restore(backup) => {
779                if has_network {
780                    self.leave_network().await?;
781                }
782                self.restore(&backup).await?;
783                Ok((StartOutcome::Restored, self.after_up(None).await?))
784            }
785            StartMode::Normal {
786                settings,
787                replace_other,
788            } => {
789                if has_network {
790                    let (node_type, p) = self.network_parameters().await?;
791                    let key = self.export_key(ids::key_type::NETWORK).await?;
792                    let same = node_type == ids::node_type::COORDINATOR
793                        && p.pan_id == settings.pan_id
794                        && p.extended_pan_id == settings.extended_pan_id
795                        && key == settings.network_key;
796                    if same {
797                        return Ok((
798                            StartOutcome::Resumed,
799                            self.after_up(settings.tx_power).await?,
800                        ));
801                    }
802                    if !replace_other {
803                        return Err(HostError::NetworkMismatch {
804                            found: describe(&p),
805                        });
806                    }
807                    tracing::warn!(found = %describe(&p), "leaving the NCP's other network, as configured");
808                    self.leave_network().await?;
809                }
810                self.form(&settings, random_key()?, None).await?;
811                Ok((
812                    StartOutcome::Formed,
813                    self.after_up(settings.tx_power).await?,
814                ))
815            }
816        }
817    }
818
819    async fn permit_join(&self, seconds: u8, join: &JoinPolicy) -> Result<(), HostError> {
820        if seconds > 0 {
821            if !join.install_code_only {
822                // The well-known key for any device, while open.
823                self.add_transient_key(Ieee::ZERO, Key::ZIGBEE_ALLIANCE_09)
824                    .await?;
825            }
826            let mut decision_bits = tc_decision::ALLOW_JOINS | tc_decision::ALLOW_UNSECURED_REJOINS;
827            if join.install_code_only {
828                decision_bits |= tc_decision::JOINS_USE_INSTALL_CODE_KEY;
829            }
830            self.ezsp
831                .set_policy(policy::TRUST_CENTER, decision_bits)
832                .await?;
833        } else {
834            self.ezsp
835                .set_policy(policy::TRUST_CENTER, tc_decision::ALLOW_UNSECURED_REJOINS)
836                .await?;
837        }
838        self.ok(Command::PermitJoining { duration: seconds })
839            .await?;
840        if seconds == 0 {
841            self.ok(Command::ClearTransientLinkKeys).await?;
842        }
843        Ok(())
844    }
845
846    async fn add_join_key(&self, ieee: Ieee, key: Key) -> Result<(), HostError> {
847        self.add_transient_key(ieee, key).await
848    }
849
850    async fn send_unicast(
851        &self,
852        nwk: NodeId,
853        aps: Aps,
854        payload: Vec<u8>,
855    ) -> Result<u16, HostError> {
856        let tag = self.next_tag();
857        let frame = ApsFrame {
858            profile_id: aps.profile,
859            cluster_id: aps.cluster,
860            source_endpoint: aps.source_endpoint,
861            destination_endpoint: aps.destination_endpoint,
862            options: UNICAST_OPTIONS,
863            group_id: 0,
864            sequence: 0,
865        };
866        match self
867            .ezsp
868            .call(Command::SendUnicast {
869                kind: ids::outgoing::DIRECT,
870                destination: nwk,
871                aps: frame,
872                tag,
873                payload,
874            })
875            .await?
876        {
877            Response::Sent { status, .. } if status.is_ok() => Ok(tag),
878            Response::Sent { status, .. } => Err(HostError::Ncp(format!(
879                "sendUnicast to {nwk:#06x}: {status}"
880            ))),
881            other => Err(HostError::Ncp(format!("sendUnicast: {other:?}"))),
882        }
883    }
884
885    async fn send_broadcast(
886        &self,
887        destination: NodeId,
888        aps: Aps,
889        payload: Vec<u8>,
890    ) -> Result<(), HostError> {
891        let tag = self.next_tag();
892        let frame = ApsFrame {
893            profile_id: aps.profile,
894            cluster_id: aps.cluster,
895            source_endpoint: aps.source_endpoint,
896            destination_endpoint: aps.destination_endpoint,
897            options: aps_option::NONE,
898            group_id: 0,
899            sequence: 0,
900        };
901        let command = Command::SendBroadcast {
902            alias: 0,
903            destination,
904            nwk_sequence: 0,
905            aps: frame,
906            radius: 30,
907            tag,
908            payload,
909        };
910        match self.ezsp.call(command).await? {
911            Response::Sent { status, .. } if status.is_ok() => Ok(()),
912            other => Err(HostError::Ncp(format!("sendBroadcast: {other:?}"))),
913        }
914    }
915
916    async fn network_info(&self) -> Result<NetworkInfo, HostError> {
917        self.read_network_info().await
918    }
919
920    async fn backup(&self) -> Result<Backup, HostError> {
921        let (_, p) = self.network_parameters().await?;
922        let network_key = self.export_key(ids::key_type::NETWORK).await?;
923        let tc_root = self.export_key(ids::key_type::TC_LINK).await?;
924        let (sequence_number, frame_counter) = self.network_key_counters().await?;
925        let key_table = self
926            .ezsp
927            .get_config(config::KEY_TABLE_SIZE)
928            .await
929            .unwrap_or(0);
930        let mut devices = Vec::new();
931        for index in 0..key_table.min(255) {
932            if let Some((ieee, link_key)) = self.link_key_at(index as u8).await {
933                devices.push(BackupDevice {
934                    nwk_address: None,
935                    ieee_address: ieee,
936                    is_child: false,
937                    link_key: Some(link_key),
938                });
939            }
940        }
941        let firmware = self.info().firmware;
942        Ok(Backup {
943            metadata: Metadata {
944                format: backup::FORMAT.into(),
945                version: 1,
946                source: concat!("zigbee-bridge@", env!("CARGO_PKG_VERSION")).into(),
947                internal: Internal {
948                    created_unix: Some(now_unix()),
949                    ezsp_version: Some(self.info.protocol.0),
950                    firmware: Some(firmware),
951                },
952            },
953            stack_specific: Some(StackSpecific {
954                ezsp: Some(EzspSpecific {
955                    hashed_tclk: tc_root,
956                }),
957                zstack: None,
958            }),
959            coordinator_ieee: self.eui64().await?,
960            pan_id: p.pan_id,
961            extended_pan_id: p.extended_pan_id,
962            nwk_update_id: p.nwk_update_id,
963            security_level: 5,
964            channel: p.radio_channel,
965            channel_mask: (11..=26).filter(|c| p.channels & (1 << c) != 0).collect(),
966            network_key: NetworkKey {
967                key: network_key,
968                sequence_number,
969                frame_counter,
970            },
971            devices,
972        })
973    }
974
975    async fn active_scan(&self, channel_mask: u32) -> Result<Vec<Beacon>, HostError> {
976        Ok(self.scan(ids::scan_type::ACTIVE, channel_mask).await?.1)
977    }
978
979    async fn leave(&self) -> Result<(), HostError> {
980        let joined = |r: Response| matches!(r, Response::NetworkState { state } if state != ids::network_status::NO_NETWORK);
981        let mut up = joined(self.ezsp.call(Command::NetworkState).await?);
982        if !up {
983            // Bring up a stored network first, so leaving erases it.
984            let init = self
985                .ezsp
986                .call(Command::NetworkInit {
987                    bitmask: ids::network_init::PARENT_INFO_IN_TOKEN,
988                })
989                .await?;
990            if init.status().is_some_and(|s| s.is_ok()) {
991                self.wait_net(NetState::Up).await?;
992                up = true;
993            }
994        }
995        if up {
996            self.leave_network().await?;
997        }
998        if let Err(e) = self.ok(Command::ClearKeyTable).await {
999            tracing::warn!(error = %e, "clearing the key table");
1000        }
1001        Ok(())
1002    }
1003
1004    async fn energy_scan(&self, channel_mask: u32) -> Result<Vec<(u8, i8)>, HostError> {
1005        Ok(self.scan(ids::scan_type::ENERGY, channel_mask).await?.0)
1006    }
1007}
1008
1009impl EzspAdapter {
1010    async fn scan(&self, scan_type: u8, channel_mask: u32) -> ScanResult {
1011        let (tx, rx) = tokio::sync::oneshot::channel();
1012        if let Ok(mut s) = self.scan.lock() {
1013            if s.is_some() {
1014                return Err(HostError::Invalid("a scan is already running".into()));
1015            }
1016            *s = Some(ScanCollector {
1017                results: Vec::new(),
1018                beacons: Vec::new(),
1019                done: Some(tx),
1020            });
1021        }
1022        let started = self
1023            .ezsp
1024            .call_ok(Command::StartScan {
1025                scan_type,
1026                channel_mask,
1027                duration: 3,
1028            })
1029            .await;
1030        if let Err(e) = started {
1031            if let Ok(mut s) = self.scan.lock() {
1032                *s = None;
1033            }
1034            return Err(e.into());
1035        }
1036        match tokio::time::timeout(Duration::from_secs(30), rx).await {
1037            Ok(Ok(result)) => result,
1038            _ => {
1039                if let Ok(mut s) = self.scan.lock() {
1040                    *s = None;
1041                }
1042                Err(HostError::Ncp("the scan did not complete".into()))
1043            }
1044        }
1045    }
1046}
1047
1048/// A fresh random network: channel `channel`, random PAN ids and network
1049/// key. For a platform that manages keys itself, build
1050/// [`NetworkSettings`] from its own values instead.
1051pub fn random_network(channel: u8) -> Result<NetworkSettings, HostError> {
1052    let mut pan = [0u8; 2];
1053    let mut ext = [0u8; 8];
1054    getrandom::fill(&mut pan).map_err(|e| HostError::Io(format!("random: {e}")))?;
1055    getrandom::fill(&mut ext).map_err(|e| HostError::Io(format!("random: {e}")))?;
1056    // 0x0000 and 0xFFF8 to 0xFFFF are reserved PAN ids.
1057    let pan_id = u16::from_le_bytes(pan) % 0xFFF7 + 1;
1058    Ok(NetworkSettings {
1059        channel,
1060        pan_id,
1061        extended_pan_id: ExtPanId(u64::from_le_bytes(ext)),
1062        network_key: random_key()?,
1063        tx_power: None,
1064    })
1065}