Skip to main content

matc/
controller.rs

1use std::{collections::HashMap, sync::Arc, time::Duration};
2
3pub use crate::active_connection::RequestTimeout;
4use crate::{
5    active_connection::{ActiveConnection, Exchange},
6    cert_matter, certmanager, commission, fabric, im,
7    messages::{self, Message},
8    retransmit, session, sigma, spake2p,
9    tlv::TlvItemValue,
10    transport::{self, ConnectionTrait},
11    util::cryptoutil,
12};
13use anyhow::{Context, Result};
14use tokio::sync::mpsc;
15use byteorder::{LittleEndian, WriteBytesExt};
16
17pub struct Controller {
18    certmanager: Arc<dyn certmanager::CertManager>,
19    #[allow(dead_code)]
20    transport: Arc<transport::Transport>,
21    fabric: fabric::Fabric,
22    /// In-memory CASE session resumption records keyed by peer node ID.
23    resumption: Arc<tokio::sync::Mutex<HashMap<u64, sigma::ResumptionRecord>>>,
24}
25
26pub struct Connection {
27    active: ActiveConnection,
28}
29//trait IsSync: Sync {}
30//impl IsSync for Controller {}
31
32const CA_ID: u64 = 1;
33
34#[derive(Debug, Clone, Copy)]
35pub struct SigmaBusy {
36    pub wait_ms: Option<u32>,
37}
38impl std::fmt::Display for SigmaBusy {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self.wait_ms {
41            Some(ms) => write!(f, "responder BUSY (min wait {} ms)", ms),
42            None => write!(f, "responder BUSY"),
43        }
44    }
45}
46impl std::error::Error for SigmaBusy {}
47
48impl Controller {
49    pub fn new(
50        certmanager: &Arc<dyn certmanager::CertManager>,
51        transport: &Arc<transport::Transport>,
52        fabric_id: u64,
53    ) -> Result<Arc<Self>> {
54        let fabric = fabric::Fabric::new(
55            fabric_id,
56            CA_ID,
57            &certmanager.get_ca_public_key()?,
58            &certmanager.get_ipk_epoch_key(),
59        );
60        Ok(Arc::new(Self {
61            certmanager: certmanager.clone(),
62            transport: transport.clone(),
63            fabric,
64            resumption: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
65        }))
66    }
67
68    /// commission device
69    /// - authenticate using pin
70    /// - push CA certificate to device
71    /// - sign device's certificate
72    /// - set controller id - user which can control device
73    /// - return authenticated connection which can be used to send additional commands
74    pub async fn commission(
75        &self,
76        connection: &Arc<dyn ConnectionTrait>,
77        pin: u32,
78        node_id: u64,
79        controller_id: u64,
80    ) -> Result<Connection> {
81        let mut session = auth_spake(connection.as_ref(), pin).await?;
82        let session = commission::commission(
83            connection.as_ref(),
84            &mut session,
85            &self.fabric,
86            self.certmanager.as_ref(),
87            node_id,
88            controller_id,
89        )
90        .await?;
91        Ok(Connection {
92            active: ActiveConnection::new(connection.clone(), session),
93        })
94    }
95
96    /// create authenticated connection to control device
97    pub async fn auth_sigma(
98        &self,
99        connection: &Arc<dyn ConnectionTrait>,
100        node_id: u64,
101        controller_id: u64,
102    ) -> Result<Connection> {
103        let (session, resumption) = auth_sigma(
104            connection.as_ref(),
105            &self.fabric,
106            self.certmanager.as_ref(),
107            node_id,
108            controller_id,
109        )
110        .await?;
111        if let Some(record) = resumption {
112            self.resumption.lock().await.insert(node_id, record);
113        }
114        Ok(Connection {
115            active: ActiveConnection::new(connection.clone(), session),
116        })
117    }
118
119    /// Run auth_sigma with automatic BUSY retry.
120    /// Attempts a CASE session resumption first; falls back to full SIGMA on failure.
121    /// Returns only the Session so that both initial connect and in-place reauth can use it.
122    pub async fn auth_sigma_with_busy_retry(
123        &self,
124        connection: &Arc<dyn ConnectionTrait>,
125        node_id: u64,
126        controller_id: u64,
127    ) -> Result<session::Session> {
128        if let Some(ses) = self.try_auth_sigma_resume(connection, node_id, controller_id).await? {
129            return Ok(ses);
130        }
131
132        const MAX_BUSY_RETRIES: u32 = 5;
133        const DEFAULT_BUSY_WAIT: Duration = Duration::from_millis(3000);
134        const MAX_BUSY_WAIT: Duration = Duration::from_secs(60);
135
136        let mut busy_retries = 0u32;
137        loop {
138            match auth_sigma(connection.as_ref(), &self.fabric, self.certmanager.as_ref(), node_id, controller_id).await {
139                Ok((ses, resumption)) => {
140                    if let Some(record) = resumption {
141                        self.resumption.lock().await.insert(node_id, record);
142                    }
143                    return Ok(ses);
144                }
145                Err(e) => {
146                    if let Some(busy) = e.downcast_ref::<SigmaBusy>() {
147                        if busy_retries < MAX_BUSY_RETRIES {
148                            let wait = busy.wait_ms
149                                .map(|ms| Duration::from_millis(ms.into()))
150                                .unwrap_or(DEFAULT_BUSY_WAIT)
151                                .min(MAX_BUSY_WAIT);
152                            log::info!(
153                                "CASE responder BUSY, waiting {:?} before retry ({}/{})",
154                                wait, busy_retries + 1, MAX_BUSY_RETRIES
155                            );
156                            tokio::time::sleep(wait).await;
157                            busy_retries += 1;
158                            continue;
159                        }
160                        return Err(e).context(format!(
161                            "still BUSY after {} retries", MAX_BUSY_RETRIES
162                        ));
163                    }
164                    return Err(e);
165                }
166            }
167        }
168    }
169
170    async fn try_auth_sigma_resume(
171        &self,
172        connection: &Arc<dyn ConnectionTrait>,
173        node_id: u64,
174        controller_id: u64,
175    ) -> Result<Option<session::Session>> {
176        let record = {
177            let map = self.resumption.lock().await;
178            map.get(&node_id).cloned()
179        };
180        let record = match record {
181            Some(r) => r,
182            None => return Ok(None),
183        };
184
185        let exchange: u16 = rand::random();
186        let session = session::Session::new();
187        let mut retrctx = retransmit::RetrContext::new(connection.as_ref(), &session);
188        retrctx.subscribe_exchange(exchange);
189
190        let mut ctx = sigma::SigmaContext::new(node_id);
191        let ca_pubkey = self.certmanager.get_ca_key()?.public_key().to_sec1_bytes();
192        sigma::sigma1_resume(&self.fabric, &mut ctx, &ca_pubkey, &record)?;
193        let s1 = messages::sigma1(exchange, &ctx.sigma1_payload)?;
194
195        log::debug!("CASE resume: send Sigma1Resume exchange:{}", exchange);
196        retrctx.send(&s1).await?;
197
198        let sigma2 = retrctx.get_next_message().await?;
199
200        // Responder sent a status report instead of Sigma2 / Sigma2Resume - this includes
201        // Fall back to full SIGMA in all cases.
202        if sigma2.protocol_header.protocol_id == messages::ProtocolMessageHeader::PROTOCOL_ID_SECURE_CHANNEL
203            && sigma2.protocol_header.opcode == messages::ProtocolMessageHeader::OPCODE_STATUS
204        {
205            log::debug!(
206                "CASE resume: responder rejected with status report, falling back to full SIGMA (exchange:{} {:?})",
207                exchange,
208                sigma2.status_report_info
209            );
210            return Ok(None);
211        }
212
213        if !sigma::is_sigma2_resume(&sigma2.payload) {
214            // Responder gracefully fell back to full Sigma2 - evict the stale record so
215            // the next reconnect does a fresh full SIGMA.
216            log::debug!("CASE resume: responder sent full Sigma2, falling back");
217            self.resumption.lock().await.remove(&node_id);
218            return Ok(None);
219        }
220
221        let parsed = match sigma::parse_sigma2_resume(&sigma2.payload) {
222            Ok(p) => p,
223            Err(e) => {
224                log::debug!("CASE resume: malformed Sigma2Resume ({:?}), falling back to full SIGMA", e);
225                self.resumption.lock().await.remove(&node_id);
226                return Ok(None);
227            }
228        };
229
230        if let Err(e) = sigma::verify_sigma2_resume_mic(
231            &record.shared_secret,
232            &ctx.initiator_random,
233            &parsed.new_resumption_id,
234            &parsed.sigma2_resume_mic,
235        ) {
236            log::debug!("CASE resume: MIC verification failed: {:?}, falling back to full SIGMA", e);
237            self.resumption.lock().await.remove(&node_id);
238            return Ok(None);
239        }
240
241        let sr = messages::status_report_success(exchange)?;
242        if let Err(e) = retrctx.send(&sr).await {
243            log::debug!("CASE resume: failed to send StatusReport ({:?}), falling back to full SIGMA", e);
244            self.resumption.lock().await.remove(&node_id);
245            return Ok(None);
246        }
247
248        let keypack = sigma::derive_resumed_session_keys(
249            &record.shared_secret,
250            &ctx.initiator_random,
251            &record.resumption_id,
252        )?;
253
254        let mut ses = session::Session::new();
255        ses.session_id = parsed.responder_session_id;
256        ses.my_session_id = ctx.session_id;
257        ses.set_decrypt_key(&keypack[16..32]);
258        ses.set_encrypt_key(&keypack[..16]);
259
260        let mut local_node = Vec::new();
261        local_node.write_u64::<LittleEndian>(controller_id)?;
262        ses.local_node = Some(local_node);
263
264        let mut remote_node = Vec::new();
265        remote_node.write_u64::<LittleEndian>(node_id)?;
266        ses.remote_node = Some(remote_node);
267
268        // Rotate the resumption ID to the one the responder issued for the next round.
269        {
270            let mut map = self.resumption.lock().await;
271            if let Some(entry) = map.get_mut(&node_id) {
272                entry.resumption_id = parsed.new_resumption_id;
273            }
274        }
275
276        log::info!("CASE session resumed for node_id={}", node_id);
277        Ok(Some(ses))
278    }
279
280    /// Commission a device that is advertising over BLE.
281    ///
282    /// 1. Scans for a commissionable BLE device with the given `discriminator`.
283    /// 2. Runs PASE over BTP (BLE transport protocol).
284    /// 3. Pushes the CA cert, signs the device cert (AddNOC).
285    /// 4. Sends ArmFailSafe + SetRegulatoryConfig.
286    /// 5. Optionally provisions network credentials (Wi-Fi / Thread).
287    /// 6. Drops the BLE connection.
288    /// 7. Discovers the device on the IP network via mDNS.
289    /// 8. Establishes CASE + sends CommissioningComplete over UDP.
290    /// 9. Returns an authenticated [`Connection`] ready for commands.
291    ///
292    /// Requires the `ble` Cargo feature.
293    #[cfg(feature = "ble")]
294    pub async fn commission_ble(
295        &self,
296        discriminator: u16,
297        short_discriminator: bool,
298        pin: u32,
299        node_id: u64,
300        controller_id: u64,
301        network_creds: commission::NetworkCreds,
302        mdns: &std::sync::Arc<crate::mdns2::MdnsService>,
303    ) -> Result<Connection> {
304        use crate::btp::BtpConnection;
305
306        // 1. BLE scan + GATT connect + BTP handshake
307        let peripheral = crate::ble::find_by_discriminator(discriminator, short_discriminator, std::time::Duration::from_secs(30))
308            .await
309            .context("BLE scan")?;
310        log::debug!("BLE device found: z2");
311        let btp_conn = BtpConnection::connect(peripheral).await.context("BTP connect")?;
312
313        // 2. PASE
314        let mut pase_session = auth_spake(btp_conn.as_ref(), pin).await.context("PASE over BLE")?;
315
316        // 3. BLE-side commissioning phase
317        commission::commission_ble_phase(
318            btp_conn.as_ref(),
319            &mut pase_session,
320            &self.fabric,
321            self.certmanager.as_ref(),
322            node_id,
323            controller_id,
324            &network_creds,
325        )
326        .await
327        .context("BLE commissioning phase")?;
328        tokio::time::sleep(std::time::Duration::from_secs(5)).await; // wait for device to finish BLE-side commissioning before dropping connection
329
330        // 4. Drop BTP (BLE connection closes when btp_conn is dropped)
331        drop(btp_conn);
332
333        // 5 + 6. Rediscover via operational mDNS and commission over UDP
334        for attempt in 0..5 {
335            let addresses = match self.discover_operational_addresses(node_id, mdns).await {
336                Ok(a) => a,
337                Err(e) => {
338                    log::debug!("mDNS discovery failed (attempt {}/{}): {:?}", attempt + 1, 5, e);
339                    continue;
340                }
341            };
342            for address in &addresses {
343                log::debug!("Trying to commission over UDP at {}... (attempt {}/{})", address, attempt + 1, 5);
344                let udp_conn = self.transport.create_connection(&address).await;
345                let ses = commission::commissioning_complete_udp(
346                    udp_conn.as_ref(),
347                    self.certmanager.as_ref(),
348                    node_id,
349                    controller_id,
350                    &self.fabric,
351                )
352                .await;
353                if let Ok(ses) = ses {
354                    return Ok(Connection {
355                        active: ActiveConnection::new(udp_conn, ses),
356                    });
357                } else {
358                    log::debug!("Failed to commission over UDP at {}: {:?}", address, ses.err());
359                }
360            }
361        }
362        Err(anyhow::anyhow!("failed to commission device over UDP at any discovered address"))
363    }
364
365    #[cfg(feature = "ble")]
366    async fn discover_operational_addresses(
367        &self,
368        node_id: u64,
369        mdns: &std::sync::Arc<crate::mdns2::MdnsService>,
370    ) -> Result<Vec<String>> {
371        use crate::discover;
372
373        let ca_pubkey = self.certmanager.get_ca_public_key()?;
374        let fabric_tmp = fabric::Fabric::new(self.fabric.id, 0, &ca_pubkey, &self.certmanager.get_ipk_epoch_key());
375        let compressed = fabric_tmp.compressed().context("compressed fabric ID")?;
376        let instance = format!("{}-{:016X}", hex::encode_upper(&compressed), node_id);
377        let expected_target = format!("{}._matter._tcp.local.", instance);
378
379        log::debug!("Discovering operational device via mDNS with target {}", expected_target);
380        let (_, info) = discover::discover_one(
381            mdns,
382            "_matter._tcp.local",
383            "_matter._tcp.local.",
384            std::time::Duration::from_secs(120),
385            move |target, _| target == expected_target,
386        ).await.context(format!("operational mDNS timeout for {}", instance))?;
387        log::debug!("Operational mDNS discovered device: {:?}", info);
388
389        let port = info.port.unwrap_or(5540);
390        let addresses: Vec<String> = info
391            .ips
392            .iter()
393            .map(|ip| crate::discover::addr_string(ip, port, info.scope_id))
394            .collect();
395        log::info!("Device discovered at {}", addresses.join(", "));
396        Ok(addresses)
397    }
398}
399
400/// Everything needed to invoke one command, passed to [Connection::invoke].
401///
402/// New options are added here as fields rather than as parameters of
403/// [Connection::invoke], so existing call sites keep working. Construct it either
404/// with `..Default::default()`, which stays source compatible when a field is
405/// added, or with [InvokeRequest::new] and the setters, which additionally cannot
406/// leave a required field at zero:
407///
408/// ```no_run
409/// # use matc::controller::{Connection, InvokeRequest};
410/// # use std::time::Duration;
411/// # async fn f(conn: &Connection, payload: &[u8]) -> anyhow::Result<()> {
412/// conn.invoke(InvokeRequest {
413///     endpoint: 0,
414///     cluster: 0x31,
415///     command: 0,
416///     payload,
417///     response_timeout: Some(Duration::from_secs(60)),
418///     ..Default::default()
419/// })
420/// .await?;
421///
422/// conn.invoke(
423///     InvokeRequest::new(0, 0x31, 0)
424///         .payload(payload)
425///         .response_timeout(Duration::from_secs(60)),
426/// )
427/// .await?;
428/// # Ok(())
429/// # }
430/// ```
431#[derive(Debug, Clone, Copy, Default)]
432pub struct InvokeRequest<'a> {
433    pub endpoint: u16,
434    pub cluster: u32,
435    pub command: u32,
436    /// TLV encoded command fields, empty for commands without arguments.
437    pub payload: &'a [u8],
438    /// Deadline for each message of this transaction. `None` uses the
439    /// connection setting ([Connection::set_response_timeout]), which in turn
440    /// falls back to the MRP-derived default.
441    pub response_timeout: Option<Duration>,
442    /// Run the command as a timed interaction: a TimedRequest with this timeout
443    /// in milliseconds is sent first and its status checked.
444    pub timed_ms: Option<u16>,
445}
446
447impl<'a> InvokeRequest<'a> {
448    pub fn new(endpoint: u16, cluster: u32, command: u32) -> Self {
449        Self {
450            endpoint,
451            cluster,
452            command,
453            ..Default::default()
454        }
455    }
456
457    pub fn payload(self, payload: &'a [u8]) -> Self {
458        Self { payload, ..self }
459    }
460
461    pub fn response_timeout(self, timeout: Duration) -> Self {
462        Self {
463            response_timeout: Some(timeout),
464            ..self
465        }
466    }
467
468    pub fn timed(self, timeout_ms: u16) -> Self {
469        Self {
470            timed_ms: Some(timeout_ms),
471            ..self
472        }
473    }
474}
475
476/// Authenticated virtual connection can be used to send commands to device.
477///
478/// Every message awaited by the methods below is bounded: if the device goes
479/// silent the call fails with [RequestTimeout] instead of hanging. The deadline
480/// restarts on each received message, so multi-message transactions (chunked
481/// reports, subscribe priming) are not cut short while they make progress. It
482/// defaults to the peer's worst-case MRP transmission time plus a processing
483/// allowance. Precedence of the overrides, narrowest first:
484/// [InvokeRequest::response_timeout], then [Connection::set_response_timeout],
485/// then the MRP-derived default.
486impl Connection {
487    /// Build a Connection from a transport-layer connection and an established session.
488    pub(crate) fn from_parts(conn: Arc<dyn ConnectionTrait>, session: session::Session) -> Self {
489        Self { active: ActiveConnection::new(conn, session) }
490    }
491
492    /// Read attribute from device and return parsed matter protocol response.
493    pub async fn read_request(
494        &self,
495        endpoint: u16,
496        cluster: u32,
497        attr: u32,
498    ) -> Result<Message> {
499        let exchange: u16 = rand::random();
500        let msg = messages::im_read_request(endpoint, cluster, attr, exchange)?;
501        self.active.request(exchange, &msg).await
502    }
503
504    /// Read attribute from device and return tlv with attribute value.
505    /// Reassembles chunked reports (MoreChunkedMessages) transparently.
506    pub async fn read_request2(
507        &self,
508        endpoint: u16,
509        cluster: u32,
510        attr: u32,
511    ) -> Result<TlvItemValue> {
512        let exchange: u16 = rand::random();
513        let msg = messages::im_read_request(endpoint, cluster, attr, exchange)?;
514        let mut ex = self.active.open_exchange(exchange);
515        ex.send(&msg).await?;
516        let report = self.collect_reports(&mut ex).await?;
517        let first = report
518            .attribute_reports
519            .into_iter()
520            .next()
521            .context("report data contains no attribute reports")?;
522        match first.data {
523            im::AttributeData::Value(v) => Ok(v),
524            im::AttributeData::Status { status, .. } => {
525                Err(anyhow::anyhow!("report data with status {}", status))
526            }
527        }
528    }
529
530    /// Receive ReportData chunks on the exchange until the last chunk,
531    /// sending the IM StatusResponse between chunks as required, and return
532    /// the merged report. The final StatusResponse is only sent when the
533    /// device did not set SuppressResponse (e.g. subscribe priming reports).
534    async fn collect_reports(&self, exchange: &mut Exchange<'_>) -> Result<im::ReportData> {
535        let mut merged: Option<im::ReportData> = None;
536        loop {
537            let msg = exchange.recv().await?;
538            if let Some(status) = &msg.status_report_info {
539                return Err(anyhow::anyhow!(
540                    "status report while waiting for report data: {:?}",
541                    status
542                ));
543            }
544            if msg.protocol_header.protocol_id
545                != messages::ProtocolMessageHeader::PROTOCOL_ID_INTERACTION
546                || msg.protocol_header.opcode
547                    != messages::ProtocolMessageHeader::INTERACTION_OPCODE_REPORT_DATA
548            {
549                return Err(anyhow::anyhow!(
550                    "response is not expected report_data {:?}",
551                    msg.protocol_header
552                ));
553            }
554            let report = im::ReportData::parse(&msg.tlv)?;
555            let more = report.more_chunks;
556            let respond = more || !report.suppress_response;
557            match merged.as_mut() {
558                Some(m) => m.merge(report),
559                None => merged = Some(report),
560            }
561            if respond {
562                let flags = messages::im_status_flags_for(msg.protocol_header.exchange_flags);
563                let resp = messages::im_status_response(
564                    exchange.id,
565                    flags,
566                    msg.message_header.message_counter,
567                )?;
568                exchange.send(&resp).await?;
569            }
570            if !more {
571                return merged.context("no report data received");
572            }
573        }
574    }
575
576    /// Invoke command described by [InvokeRequest]. All other invoke methods are
577    /// thin wrappers around this one.
578    ///
579    /// `response_timeout` applies to every message of the transaction and takes
580    /// precedence over [Connection::set_response_timeout]; use it for commands that
581    /// are expected to run long (ScanNetworks, ConnectNetwork, OTA) instead of
582    /// stretching the deadline of the whole connection.
583    pub async fn invoke(&self, req: InvokeRequest<'_>) -> Result<Message> {
584        let exchange: u16 = rand::random();
585        log::debug!(
586            "invoke exch:{} endpoint:{} cluster:{} command:{} timed:{:?}",
587            exchange,
588            req.endpoint,
589            req.cluster,
590            req.command,
591            req.timed_ms
592        );
593        let mut ex = self.active.open_exchange_with(exchange, req.response_timeout);
594
595        if let Some(timeout) = req.timed_ms {
596            let tr = messages::im_timed_request(exchange, timeout)?;
597            ex.send(&tr).await?;
598            let result = ex.recv().await?;
599            if result.protocol_header.protocol_id
600                != messages::ProtocolMessageHeader::PROTOCOL_ID_INTERACTION
601                || result.protocol_header.opcode
602                    != messages::ProtocolMessageHeader::INTERACTION_OPCODE_STATUS_RESP
603            {
604                return Err(anyhow::anyhow!(
605                    "invoke: unexpected response to timed request {:?}",
606                    result
607                ));
608            }
609            let status = result
610                .tlv
611                .get_int(&[0])
612                .context("invoke: status not found in timed request response")?;
613            if status != 0 {
614                return Err(anyhow::anyhow!(
615                    "invoke: unexpected status {} for timed request",
616                    status
617                ));
618            }
619        }
620
621        let msg = messages::im_invoke_request(
622            req.endpoint,
623            req.cluster,
624            req.command,
625            exchange,
626            req.payload,
627            req.timed_ms.is_some(),
628        )?;
629        ex.send(&msg).await?;
630        ex.recv().await
631    }
632
633    /// Invoke command
634    pub async fn invoke_request(
635        &self,
636        endpoint: u16,
637        cluster: u32,
638        command: u32,
639        payload: &[u8],
640    ) -> Result<Message> {
641        self.invoke(InvokeRequest::new(endpoint, cluster, command).payload(payload))
642            .await
643    }
644
645    /// Invoke command and return result TLV
646    pub async fn invoke_request2(
647        &self,
648        endpoint: u16,
649        cluster: u32,
650        command: u32,
651        payload: &[u8],
652    ) -> Result<TlvItemValue> {
653        let res = self.invoke_request(endpoint, cluster, command, payload).await?;
654        let o = res.tlv.get(&[1, 0, 1, 1]).context("result not found")?;
655        Ok(o.clone())
656    }
657
658    /// Write attribute value and check the status in the write response.
659    pub async fn write_request(
660        &self,
661        endpoint: u16,
662        cluster: u32,
663        attr: u32,
664        payload: &[u8],
665    ) -> Result<()> {
666        let exchange: u16 = rand::random();
667        log::debug!(
668            "write_request exch:{} endpoint:{} cluster:{} attr:{}",
669            exchange,
670            endpoint,
671            cluster,
672            attr,
673        );
674
675        let msg = messages::im_write_request(endpoint, cluster, attr, exchange, payload)?;
676        let res = self.active.request(exchange, &msg).await?;
677        if res.status_report_info.is_some() {
678            return Err(anyhow::anyhow!(
679                "write_request failed with status {:?}",
680                res.status_report_info
681            ))
682        };
683        if res.protocol_header.protocol_id
684            == messages::ProtocolMessageHeader::PROTOCOL_ID_INTERACTION
685            && res.protocol_header.opcode
686                == messages::ProtocolMessageHeader::INTERACTION_OPCODE_STATUS_RESP
687        {
688            let stat = res
689                .tlv
690                .get_int(&[0])
691                .context("status not found in status response")?;
692            res.tlv.dump(1);
693            return Err(anyhow::anyhow!(
694                "response is not expected status_resp 0x{:x}",
695                stat
696            ))
697        };
698        if res.protocol_header.protocol_id
699            != messages::ProtocolMessageHeader::PROTOCOL_ID_INTERACTION
700            || res.protocol_header.opcode
701                != messages::ProtocolMessageHeader::INTERACTION_OPCODE_WRITE_RESP
702        {
703            return Err(anyhow::anyhow!(
704                "response is not expected write_resp {:?}",
705                res.protocol_header
706            ))
707        };
708        let stat = res.tlv.get_int(&[0, 0, 1, 0]).context("status not found in write response")?;
709        if stat != 0 {
710            return Err(anyhow::anyhow!("write failed with status 0x{:x}", stat));
711        }
712        Ok(())
713    }
714
715    /// Subscribe to attribute changes. `None` path fields act as wildcards.
716    /// Set `keep_subscriptions = true` when adding a second subscription on the same
717    /// connection so the device does not cancel the first one.
718    ///
719    /// Handles the full subscribe transaction (chunked priming report, IM
720    /// StatusResponse acks, SubscribeResponse) and returns a [Subscription]
721    /// delivering decoded updates; updates are acked automatically by the
722    /// background read loop.
723    pub async fn subscribe_attrs(
724        &self,
725        endpoint: Option<u16>,
726        cluster: Option<u32>,
727        attr: Option<u32>,
728        keep_subscriptions: bool,
729    ) -> Result<Subscription> {
730        let exchange: u16 = rand::random();
731        log::debug!(
732            "subscribe_attrs exch:{} endpoint:{:?} cluster:{:?} attr:{:?} keep:{}",
733            exchange, endpoint, cluster, attr, keep_subscriptions
734        );
735        let msg = messages::im_subscribe_request_attr(endpoint, cluster, attr, exchange, keep_subscriptions)?;
736        self.subscribe_internal(exchange, &msg).await
737    }
738
739    /// Subscribe to events. `None` path fields act as wildcards.
740    /// See [Connection::subscribe_attrs] for transaction details.
741    pub async fn subscribe_events(
742        &self,
743        endpoint: Option<u16>,
744        cluster: Option<u32>,
745        event: Option<u32>,
746        keep_subscriptions: bool,
747    ) -> Result<Subscription> {
748        let exchange: u16 = rand::random();
749        log::debug!(
750            "subscribe_events exch:{} endpoint:{:?} cluster:{:?} event:{:?} keep:{}",
751            exchange, endpoint, cluster, event, keep_subscriptions
752        );
753        let msg = messages::im_subscribe_request_event(endpoint, cluster, event, exchange, keep_subscriptions)?;
754        self.subscribe_internal(exchange, &msg).await
755    }
756
757    async fn subscribe_internal(&self, exchange_id: u16, msg: &[u8]) -> Result<Subscription> {
758        let mut exchange = self.active.open_exchange(exchange_id);
759        exchange.send(msg).await?;
760        let priming = self.collect_reports(&mut exchange).await?;
761        let subscription_id = priming
762            .subscription_id
763            .context("priming report missing subscription id")?;
764
765        // Register before awaiting the SubscribeResponse so no update can be
766        // missed; the device cannot report before the transaction completes.
767        let rx = self.active.register_subscription(subscription_id);
768        let registry = self.active.subscriptions_handle();
769
770        let response = async {
771            let resp = exchange.recv().await?;
772            if resp.protocol_header.protocol_id
773                != messages::ProtocolMessageHeader::PROTOCOL_ID_INTERACTION
774                || resp.protocol_header.opcode
775                    != messages::ProtocolMessageHeader::INTERACTION_OPCODE_SUBSCRIBE_RESP
776            {
777                anyhow::bail!(
778                    "response is not expected subscribe_resp {:?}",
779                    resp.protocol_header
780                );
781            }
782            let sr = im::SubscribeResponse::parse(&resp.tlv)?;
783            if sr.subscription_id != subscription_id {
784                anyhow::bail!(
785                    "subscribe response id {} does not match priming report id {}",
786                    sr.subscription_id,
787                    subscription_id
788                );
789            }
790            Ok(sr)
791        }
792        .await;
793
794        match response {
795            Ok(sr) => Ok(Subscription {
796                subscription_id,
797                max_interval: sr.max_interval,
798                priming_attribute_reports: priming.attribute_reports,
799                priming_event_reports: priming.event_reports,
800                rx,
801                registry,
802            }),
803            Err(e) => {
804                registry.lock().unwrap().remove(&subscription_id);
805                Err(e)
806            }
807        }
808    }
809
810    /// Cancel all subscriptions on this session by sending a SubscribeRequest with
811    /// `KeepSubscriptions = false` and no paths. The device drops all prior subscriptions.
812    pub async fn im_unsubscribe_all(&self) -> Result<Message> {
813        let exchange: u16 = rand::random();
814        log::debug!("im_unsubscribe_all exch:{}", exchange);
815        let msg = messages::im_unsubscribe_all(exchange)?;
816        self.active.request(exchange, &msg).await
817    }
818
819    /// Enable or disable automatic IM StatusResponse replies to unsolicited
820    /// ReportData (enabled by default). Disable only when acking reports
821    /// manually via the raw message API.
822    pub fn set_auto_status_response(&self, enabled: bool) {
823        self.active.set_auto_status_response(enabled);
824    }
825
826    /// Override how long to wait for each message of a request/response
827    /// transaction. `None` restores the default, which is derived from the
828    /// peer's advertised MRP intervals (worst-case time to exhaust all MRP
829    /// transmissions plus an allowance for device-side processing).
830    ///
831    /// The deadline applies per awaited message, not per transaction: it
832    /// restarts whenever the device sends something, so chunked reports and
833    /// subscribe transactions are not cut short while they progress.
834    ///
835    /// This is connection wide and stays in effect until changed. To wait longer
836    /// for one slow command only, set [InvokeRequest::response_timeout] instead -
837    /// it takes precedence and cannot leak into other requests.
838    pub fn set_response_timeout(&self, timeout: Option<Duration>) {
839        self.active.set_response_timeout(timeout);
840    }
841
842    /// Invoke command with timed interaction
843    pub async fn invoke_request_timed(
844        &self,
845        endpoint: u16,
846        cluster: u32,
847        command: u32,
848        payload: &[u8],
849        timeout: u16,
850    ) -> Result<Message> {
851        self.invoke(
852            InvokeRequest::new(endpoint, cluster, command)
853                .payload(payload)
854                .timed(timeout),
855        )
856        .await
857    }
858
859    /// Receive next unsolicited raw message not handled elsewhere (subscription
860    /// reports are delivered decoded via [Subscription]; only reports with an
861    /// unknown subscription id and other unsolicited messages end up here).
862    /// Returns None when connection is closed. Messages may be dropped when
863    /// nobody drains this channel.
864    pub async fn recv_event(&self) -> Option<Message> {
865        self.active.recv_event().await
866    }
867
868    /// Try receive event without blocking.
869    pub fn try_recv_event(&self) -> Option<Message> {
870        self.active.try_recv_event()
871    }
872
873    /// Re-run CASE over the existing transport channel without tearing it down.
874    /// Stops the active read loop, runs auth_sigma (with BUSY retry), swaps the session,
875    /// and restarts the read loop -- all on the same underlying UDP channel registration.
876    pub async fn reauth(
877        &self,
878        controller: &Controller,
879        node_id: u64,
880        controller_id: u64,
881    ) -> Result<()> {
882        self.active.pause_read_loop().await;
883        let new_session = controller
884            .auth_sigma_with_busy_retry(&self.active.transport_conn, node_id, controller_id)
885            .await?;
886        self.active.reauth_with_session(new_session).await
887    }
888}
889
890/// Active subscription created by [Connection::subscribe_attrs] or
891/// [Connection::subscribe_events]. Decoded updates are delivered via [Subscription::next];
892/// the background read loop acks them automatically. Dropping the handle stops
893/// delivery (the device-side subscription stays active until it expires or is
894/// cancelled via [Connection::im_unsubscribe_all]).
895pub struct Subscription {
896    pub subscription_id: u32,
897    /// Maximum reporting interval in seconds granted by the device.
898    pub max_interval: u16,
899    /// Attribute reports from the priming report (current values at subscribe time).
900    pub priming_attribute_reports: Vec<im::AttributeReport>,
901    /// Event reports from the priming report.
902    pub priming_event_reports: Vec<im::EventReport>,
903    rx: mpsc::Receiver<im::ReportUpdate>,
904    registry: Arc<std::sync::Mutex<HashMap<u32, mpsc::Sender<im::ReportUpdate>>>>,
905}
906
907impl Subscription {
908    /// Receive the next decoded update. Returns None when the connection is
909    /// closed or re-authenticated (the subscription is then gone; resubscribe).
910    pub async fn next(&mut self) -> Option<im::ReportUpdate> {
911        self.rx.recv().await
912    }
913}
914
915impl Drop for Subscription {
916    fn drop(&mut self) {
917        self.registry.lock().unwrap().remove(&self.subscription_id);
918    }
919}
920
921pub fn pin_to_passcode(pin: u32) -> Result<Vec<u8>> {
922    let mut out = Vec::new();
923    out.write_u32::<LittleEndian>(pin)?;
924    Ok(out)
925}
926
927pub(crate) async fn auth_spake(connection: &dyn ConnectionTrait, pin: u32) -> Result<session::Session> {
928    let exchange = rand::random();
929    log::debug!("start auth_spake");
930    let mut session = session::Session::new();
931    session.my_session_id = 1;
932    let mut retrctx = retransmit::RetrContext::new(connection, &session);
933    // send pbkdf
934    log::debug!("send pbkdf request");
935    let pbkdf_req_protocol_message = messages::pbkdf_req(exchange)?;
936    retrctx.send(&pbkdf_req_protocol_message).await?;
937
938    // get pbkdf response
939    let pbkdf_response = retrctx.get_next_message().await?;
940    if pbkdf_response.protocol_header.protocol_id
941        != messages::ProtocolMessageHeader::PROTOCOL_ID_SECURE_CHANNEL
942        || pbkdf_response.protocol_header.opcode
943            != messages::ProtocolMessageHeader::OPCODE_PBKDF_RESP
944    {
945        return Err(anyhow::anyhow!("pbkdf response not received"));
946    }
947
948    let iterations = pbkdf_response
949        .tlv
950        .get_int(&[4, 1])
951        .context("pbkdf_response - iterations missing")?;
952    let salt = pbkdf_response
953        .tlv
954        .get_octet_string(&[4, 2])
955        .context("pbkdf_response - salt missing")?;
956    let p_session = pbkdf_response
957        .tlv
958        .get_int(&[3])
959        .context("pbkdf_response - session missing")?;
960
961    // send pake1
962    let engine = spake2p::Engine::new()?;
963    let mut ctx = engine.start(&pin_to_passcode(pin)?, salt, iterations as u32)?;
964    log::debug!("send pake1 request");
965    let pake1_protocol_message = messages::pake1(exchange, ctx.x.as_bytes(), -1)?;
966    retrctx.send(&pake1_protocol_message).await?;
967
968    // receive pake2
969    let pake2 = retrctx.get_next_message().await?;
970    if pake2.protocol_header.protocol_id
971        != messages::ProtocolMessageHeader::PROTOCOL_ID_SECURE_CHANNEL
972        || pake2.protocol_header.opcode != messages::ProtocolMessageHeader::OPCODE_PASE_PAKE2
973    {
974        return Err(anyhow::anyhow!("pake2 not received"));
975    }
976    let pake2_pb = pake2
977        .tlv
978        .get_octet_string(&[1])
979        .context("pake2 pb tlv missing")?;
980    ctx.y = p256::EncodedPoint::from_bytes(pake2_pb)?;
981
982    let pake2_cb = pake2
983        .tlv
984        .get_octet_string(&[2])
985        .context("pake2 cb tlv missing")?;
986
987    // send pake3
988    let mut hash_seed = "CHIP PAKE V1 Commissioning".as_bytes().to_vec();
989    hash_seed.extend_from_slice(&pbkdf_req_protocol_message[6..]);
990    hash_seed.extend_from_slice(&pbkdf_response.payload);
991    engine.finish(&mut ctx, &hash_seed, pake2_cb)?;
992    let pake3_protocol_message = messages::pake3(
993        exchange,
994        &ctx.ca.context("ca value not present in context")?,
995        -1,
996    )?;
997    log::debug!("send pake3 request");
998    retrctx.send(&pake3_protocol_message).await?;
999
1000    let pake3_resp = retrctx.get_next_message().await?;
1001    match &pake3_resp.status_report_info {
1002        Some(s) => {
1003            if !s.is_ok() {
1004                return Err(anyhow::anyhow!("pake3 resp not ok), got {:?}", pake3_resp));
1005            }
1006        }
1007        None => {
1008            return Err(anyhow::anyhow!(
1009                "expecting status report (pake3 resp), got {:?}",
1010                pake3_resp
1011            ))
1012        }
1013    }
1014
1015    session.set_encrypt_key(&ctx.encrypt_key.context("encrypt key missing")?);
1016    session.set_decrypt_key(&ctx.decrypt_key.context("decrypt key missing")?);
1017    session.session_id = p_session as u16;
1018    log::debug!("auth_spake ok; session: {}", session.session_id);
1019    Ok(session)
1020}
1021
1022pub(crate) async fn auth_sigma(
1023    connection: &dyn ConnectionTrait,
1024    fabric: &fabric::Fabric,
1025    cm: &dyn certmanager::CertManager,
1026    node_id: u64,
1027    controller_id: u64,
1028) -> Result<(session::Session, Option<sigma::ResumptionRecord>)> {
1029    log::debug!("auth_sigma");
1030    let exchange = rand::random();
1031    let session = session::Session::new();
1032    let mut retrctx = retransmit::RetrContext::new(connection, &session);
1033    retrctx.subscribe_exchange(exchange);
1034    let mut ctx = sigma::SigmaContext::new(node_id);
1035    let ca_pubkey = cm.get_ca_key()?.public_key().to_sec1_bytes();
1036    sigma::sigma1(fabric, &mut ctx, &ca_pubkey)?;
1037    let s1 = messages::sigma1(exchange, &ctx.sigma1_payload)?;
1038
1039    log::debug!("send sigma1 {}", exchange);
1040    retrctx.send(&s1).await?;
1041
1042    // receive sigma2
1043    log::debug!("receive sigma2 {}", exchange);
1044    let sigma2 = retrctx.get_next_message().await?;
1045    log::debug!("sigma2 received {:?}", sigma2);
1046    if sigma2.protocol_header.protocol_id == messages::ProtocolMessageHeader::PROTOCOL_ID_SECURE_CHANNEL
1047        && sigma2.protocol_header.opcode == messages::ProtocolMessageHeader::OPCODE_STATUS
1048    {
1049        let sri = sigma2.status_report_info.context("status report info missing")?;
1050        if sri.is_busy() {
1051            return Err(anyhow::Error::new(SigmaBusy { wait_ms: sri.minimum_wait_time_ms() }));
1052        }
1053        return Err(anyhow::anyhow!("sigma2 not received, status: {}", sri));
1054    }
1055    ctx.sigma2_payload = sigma2.payload;
1056    ctx.responder_session = sigma2
1057        .tlv
1058        .get_int(&[2])
1059        .context("responder session tlv missing in sigma2")? as u16;
1060    ctx.responder_public = sigma2
1061        .tlv
1062        .get_octet_string(&[3])
1063        .context("responder public tlv missing in sigma2")?
1064        .to_vec();
1065
1066    log::debug!("verify sigma2 {}", exchange);
1067    let resumption_id =
1068        sigma::verify_sigma2(fabric, &ctx, &ca_pubkey).context("sigma2 verification failed")?;
1069
1070    let controller_private = cm.get_user_key(controller_id)?;
1071    let controller_x509 = cm.get_user_cert(controller_id)?;
1072    let controller_matter_cert =
1073        cert_matter::convert_x509_bytes_to_matter(&controller_x509, &ca_pubkey)?;
1074
1075    // send sigma3
1076    log::debug!("send sigma3 {} with piggyback ack for {}", exchange, sigma2.message_header.message_counter);
1077    sigma::sigma3(
1078        fabric,
1079        &mut ctx,
1080        &controller_private.to_sec1_der()?,
1081        &controller_matter_cert,
1082    )?;
1083    let sigma3 = messages::sigma3(exchange, &ctx.sigma3_payload, sigma2.message_header.message_counter)?;
1084    retrctx.send(&sigma3).await?;
1085
1086    log::debug!("receive result {}", exchange);
1087    let status = retrctx.get_next_message().await?;
1088    if !status
1089        .status_report_info
1090        .as_ref()
1091        .context("sigma3 status resp not received")?
1092        .is_ok()
1093    {
1094        return Err(anyhow::anyhow!(format!(
1095            "response to sigma3 does not contain status ok {:?}",
1096            status
1097        )));
1098    }
1099
1100    //session keys
1101    let mut th = ctx.sigma1_payload.clone();
1102    th.extend_from_slice(&ctx.sigma2_payload);
1103
1104    let mut transcript = th;
1105    transcript.extend_from_slice(&ctx.sigma3_payload);
1106    let transcript_hash = cryptoutil::sha256(&transcript);
1107    let mut salt = fabric.signed_ipk()?;
1108    salt.extend_from_slice(&transcript_hash);
1109    let shared = ctx.shared.context("shared secret not in context")?;
1110    let shared_bytes: [u8; 32] = shared.raw_secret_bytes().as_slice()
1111        .try_into()
1112        .map_err(|_| anyhow::anyhow!("shared secret wrong length"))?;
1113    let keypack = cryptoutil::hkdf_sha256(
1114        &salt,
1115        &shared_bytes,
1116        "SessionKeys".as_bytes(),
1117        16 * 3,
1118    )?;
1119    let mut ses = session::Session::new();
1120    ses.session_id = ctx.responder_session;
1121    ses.my_session_id = ctx.session_id;
1122    ses.set_decrypt_key(&keypack[16..32]);
1123    ses.set_encrypt_key(&keypack[..16]);
1124
1125    let mut local_node = Vec::new();
1126    local_node.write_u64::<LittleEndian>(controller_id)?;
1127    ses.local_node = Some(local_node);
1128
1129    let mut remote_node = Vec::new();
1130    remote_node.write_u64::<LittleEndian>(node_id)?;
1131    ses.remote_node = Some(remote_node);
1132
1133    let resumption = resumption_id
1134        .map(|id| sigma::ResumptionRecord { resumption_id: id, shared_secret: shared_bytes });
1135
1136    if resumption.is_none() {
1137        log::debug!("auth_sigma: responder did not include a NewResumptionID - resumption unavailable for node {}", node_id);
1138    }
1139
1140    Ok((ses, resumption))
1141}
1142
1143#[cfg(test)]
1144mod tests {
1145    use super::*;
1146    use crate::messages::ProtocolMessageHeader;
1147    use crate::tlv;
1148    use std::time::Duration;
1149
1150    // Loopback transport: the test acts as the device on the other end.
1151    struct MockConn {
1152        inbound: tokio::sync::Mutex<mpsc::Receiver<Vec<u8>>>,
1153        outbound: mpsc::UnboundedSender<Vec<u8>>,
1154        reliable: bool,
1155        mrp: std::sync::Mutex<crate::mrp::MrpParameters>,
1156    }
1157
1158    #[async_trait::async_trait]
1159    impl ConnectionTrait for MockConn {
1160        async fn send(&self, data: &[u8]) -> Result<()> {
1161            self.outbound
1162                .send(data.to_vec())
1163                .map_err(|_| anyhow::anyhow!("mock closed"))
1164        }
1165        async fn receive(&self, timeout: Duration) -> Result<Vec<u8>> {
1166            let mut rx = self.inbound.lock().await;
1167            match tokio::time::timeout(timeout, rx.recv()).await {
1168                Ok(Some(d)) => Ok(d),
1169                Ok(None) => Err(anyhow::anyhow!("mock closed")),
1170                Err(_) => Err(anyhow::anyhow!("timeout")),
1171            }
1172        }
1173        fn is_reliable(&self) -> bool {
1174            self.reliable
1175        }
1176        fn mrp_params(&self) -> crate::mrp::MrpParameters {
1177            *self.mrp.lock().unwrap()
1178        }
1179        fn set_mrp_params(&self, params: crate::mrp::MrpParameters) {
1180            *self.mrp.lock().unwrap() = params;
1181        }
1182    }
1183
1184    struct MockDevice {
1185        rx: mpsc::UnboundedReceiver<Vec<u8>>,
1186        tx: mpsc::Sender<Vec<u8>>,
1187        session: session::Session,
1188    }
1189
1190    impl MockDevice {
1191        async fn recv(&mut self) -> Message {
1192            let data = tokio::time::timeout(Duration::from_secs(2), self.rx.recv())
1193                .await
1194                .expect("timeout waiting for controller message")
1195                .expect("mock closed");
1196            Message::decode(&data).unwrap()
1197        }
1198
1199        async fn expect_status_response(&mut self, want_flags: u8, want_ack: u32) {
1200            let msg = self.recv().await;
1201            assert_eq!(
1202                msg.protocol_header.protocol_id,
1203                ProtocolMessageHeader::PROTOCOL_ID_INTERACTION
1204            );
1205            assert_eq!(
1206                msg.protocol_header.opcode,
1207                ProtocolMessageHeader::INTERACTION_OPCODE_STATUS_RESP
1208            );
1209            assert_eq!(
1210                msg.protocol_header.exchange_flags,
1211                ProtocolMessageHeader::FLAG_RELIABILITY | want_flags
1212            );
1213            assert_eq!(msg.protocol_header.ack_counter, want_ack);
1214            assert_eq!(msg.tlv.get_int(&[0]), Some(0));
1215        }
1216
1217        async fn expect_silence(&mut self) {
1218            assert!(
1219                tokio::time::timeout(Duration::from_millis(200), self.rx.recv())
1220                    .await
1221                    .is_err(),
1222                "unexpected message from controller"
1223            );
1224        }
1225
1226        async fn send(&self, payload: &[u8]) -> u32 {
1227            let encoded = self.session.encode_message(payload).unwrap();
1228            let (header, _) = messages::MessageHeader::decode(&encoded).unwrap();
1229            self.tx.send(encoded).await.unwrap();
1230            header.message_counter
1231        }
1232
1233        async fn recv_within(&mut self, d: Duration) -> Option<Message> {
1234            match tokio::time::timeout(d, self.rx.recv()).await {
1235                Ok(Some(data)) => Some(Message::decode(&data).unwrap()),
1236                _ => None,
1237            }
1238        }
1239    }
1240
1241    fn mock_pair() -> (Connection, MockDevice) {
1242        mock_pair_with(true, Default::default())
1243    }
1244
1245    fn mock_pair_unreliable(mrp: crate::mrp::MrpParameters) -> (Connection, MockDevice) {
1246        mock_pair_with(false, mrp)
1247    }
1248
1249    fn mock_pair_with(reliable: bool, mrp: crate::mrp::MrpParameters) -> (Connection, MockDevice) {
1250        let (to_ctrl_tx, to_ctrl_rx) = mpsc::channel(32);
1251        let (to_dev_tx, to_dev_rx) = mpsc::unbounded_channel();
1252        let mock = Arc::new(MockConn {
1253            inbound: tokio::sync::Mutex::new(to_ctrl_rx),
1254            outbound: to_dev_tx,
1255            reliable,
1256            mrp: std::sync::Mutex::new(mrp),
1257        });
1258        let conn = Connection::from_parts(mock, session::Session::new());
1259        let device = MockDevice {
1260            rx: to_dev_rx,
1261            tx: to_ctrl_tx,
1262            session: session::Session::new(),
1263        };
1264        (conn, device)
1265    }
1266
1267    fn report_data(
1268        exchange: u16,
1269        flags: u8,
1270        sub_id: Option<u32>,
1271        values: &[(u16, bool)],
1272        more: bool,
1273        suppress: bool,
1274    ) -> Vec<u8> {
1275        let b = ProtocolMessageHeader {
1276            exchange_flags: flags,
1277            opcode: ProtocolMessageHeader::INTERACTION_OPCODE_REPORT_DATA,
1278            exchange_id: exchange,
1279            protocol_id: ProtocolMessageHeader::PROTOCOL_ID_INTERACTION,
1280            ack_counter: 0,
1281        }
1282        .encode()
1283        .unwrap();
1284        let mut t = tlv::TlvBuffer::from_vec(b);
1285        t.write_anon_struct().unwrap();
1286        if let Some(id) = sub_id {
1287            t.write_uint32(0, id).unwrap();
1288        }
1289        t.write_array(1).unwrap();
1290        for (endpoint, value) in values {
1291            t.write_anon_struct().unwrap();
1292            t.write_struct(1).unwrap();
1293            t.write_uint32(0, 0).unwrap();
1294            t.write_list(1).unwrap();
1295            t.write_uint16(2, *endpoint).unwrap();
1296            t.write_uint32(3, 6).unwrap();
1297            t.write_uint32(4, 0).unwrap();
1298            t.write_struct_end().unwrap();
1299            t.write_bool(2, *value).unwrap();
1300            t.write_struct_end().unwrap();
1301            t.write_struct_end().unwrap();
1302        }
1303        t.write_struct_end().unwrap();
1304        if more {
1305            t.write_bool(3, true).unwrap();
1306        }
1307        if suppress {
1308            t.write_bool(4, true).unwrap();
1309        }
1310        t.write_struct_end().unwrap();
1311        t.data
1312    }
1313
1314    fn status_response(exchange: u16, flags: u8) -> Vec<u8> {
1315        let b = ProtocolMessageHeader {
1316            exchange_flags: flags,
1317            opcode: ProtocolMessageHeader::INTERACTION_OPCODE_STATUS_RESP,
1318            exchange_id: exchange,
1319            protocol_id: ProtocolMessageHeader::PROTOCOL_ID_INTERACTION,
1320            ack_counter: 0,
1321        }
1322        .encode()
1323        .unwrap();
1324        let mut t = tlv::TlvBuffer::from_vec(b);
1325        t.write_anon_struct().unwrap();
1326        t.write_uint8(0, 0).unwrap();
1327        t.write_struct_end().unwrap();
1328        t.data
1329    }
1330
1331    fn subscribe_response(exchange: u16, sub_id: u32, max_interval: u16) -> Vec<u8> {
1332        let b = ProtocolMessageHeader {
1333            exchange_flags: 0,
1334            opcode: ProtocolMessageHeader::INTERACTION_OPCODE_SUBSCRIBE_RESP,
1335            exchange_id: exchange,
1336            protocol_id: ProtocolMessageHeader::PROTOCOL_ID_INTERACTION,
1337            ack_counter: 0,
1338        }
1339        .encode()
1340        .unwrap();
1341        let mut t = tlv::TlvBuffer::from_vec(b);
1342        t.write_anon_struct().unwrap();
1343        t.write_uint32(0, sub_id).unwrap();
1344        t.write_uint16(2, max_interval).unwrap();
1345        t.write_struct_end().unwrap();
1346        t.data
1347    }
1348
1349    const FLAGS_RESPONDER: u8 = 0;
1350    const FLAGS_DEVICE_INITIATED: u8 = ProtocolMessageHeader::FLAG_INITIATOR;
1351    const ACK_AND_INITIATOR: u8 =
1352        ProtocolMessageHeader::FLAG_INITIATOR | ProtocolMessageHeader::FLAG_ACK;
1353
1354    #[tokio::test]
1355    async fn test_read_request2_single_chunk() {
1356        let (conn, mut device) = mock_pair();
1357        let task = tokio::spawn(async move {
1358            let req = device.recv().await;
1359            assert_eq!(
1360                req.protocol_header.opcode,
1361                ProtocolMessageHeader::INTERACTION_OPCODE_READ_REQ
1362            );
1363            let exchange = req.protocol_header.exchange_id;
1364            device
1365                .send(&report_data(exchange, FLAGS_RESPONDER, None, &[(1, true)], false, true))
1366                .await;
1367            device.expect_silence().await;
1368        });
1369        let val = conn.read_request2(1, 6, 0).await.unwrap();
1370        assert_eq!(val, TlvItemValue::Bool(true));
1371        task.await.unwrap();
1372    }
1373
1374    #[tokio::test]
1375    async fn test_read_request2_chunked() {
1376        let (conn, mut device) = mock_pair();
1377        let task = tokio::spawn(async move {
1378            let req = device.recv().await;
1379            let exchange = req.protocol_header.exchange_id;
1380            let counter = device
1381                .send(&report_data(exchange, FLAGS_RESPONDER, None, &[(1, true)], true, false))
1382                .await;
1383            device.expect_status_response(ACK_AND_INITIATOR, counter).await;
1384            device
1385                .send(&report_data(exchange, FLAGS_RESPONDER, None, &[(2, false)], false, true))
1386                .await;
1387            device.expect_silence().await;
1388        });
1389        let val = conn.read_request2(1, 6, 0).await.unwrap();
1390        assert_eq!(val, TlvItemValue::Bool(true));
1391        task.await.unwrap();
1392    }
1393
1394    #[tokio::test]
1395    async fn test_subscribe_and_updates() {
1396        let (conn, mut device) = mock_pair();
1397        let task = tokio::spawn(async move {
1398            let req = device.recv().await;
1399            assert_eq!(
1400                req.protocol_header.opcode,
1401                ProtocolMessageHeader::INTERACTION_OPCODE_SUBSCRIBE_REQ
1402            );
1403            let exchange = req.protocol_header.exchange_id;
1404            let counter = device
1405                .send(&report_data(exchange, FLAGS_RESPONDER, Some(7), &[(1, true)], true, false))
1406                .await;
1407            device.expect_status_response(ACK_AND_INITIATOR, counter).await;
1408            let counter = device
1409                .send(&report_data(exchange, FLAGS_RESPONDER, Some(7), &[(2, false)], false, false))
1410                .await;
1411            device.expect_status_response(ACK_AND_INITIATOR, counter).await;
1412            device.send(&subscribe_response(exchange, 7, 60)).await;
1413
1414            // device-initiated update on a fresh exchange
1415            let counter = device
1416                .send(&report_data(0x4001, FLAGS_DEVICE_INITIATED, Some(7), &[(1, false)], false, false))
1417                .await;
1418            device
1419                .expect_status_response(ProtocolMessageHeader::FLAG_ACK, counter)
1420                .await;
1421            device
1422        });
1423
1424        let mut sub = conn.subscribe_attrs(Some(1), Some(6), Some(0), false).await.unwrap();
1425        assert_eq!(sub.subscription_id, 7);
1426        assert_eq!(sub.max_interval, 60);
1427        assert_eq!(sub.priming_attribute_reports.len(), 2);
1428        assert_eq!(sub.priming_attribute_reports[0].path.endpoint, Some(1));
1429        assert_eq!(sub.priming_attribute_reports[1].path.endpoint, Some(2));
1430
1431        let update = sub.next().await.unwrap();
1432        assert_eq!(update.subscription_id, 7);
1433        assert_eq!(update.attribute_reports.len(), 1);
1434        assert_eq!(
1435            update.attribute_reports[0].data,
1436            im::AttributeData::Value(TlvItemValue::Bool(false))
1437        );
1438        task.await.unwrap();
1439    }
1440
1441    #[tokio::test]
1442    async fn test_chunked_unsolicited_report() {
1443        let (conn, mut device) = mock_pair();
1444        let task = tokio::spawn(async move {
1445            let req = device.recv().await;
1446            let exchange = req.protocol_header.exchange_id;
1447            let counter = device
1448                .send(&report_data(exchange, FLAGS_RESPONDER, Some(9), &[(1, true)], false, false))
1449                .await;
1450            device.expect_status_response(ACK_AND_INITIATOR, counter).await;
1451            device.send(&subscribe_response(exchange, 9, 60)).await;
1452
1453            // chunked device-initiated update
1454            let counter = device
1455                .send(&report_data(0x4002, FLAGS_DEVICE_INITIATED, Some(9), &[(1, false)], true, false))
1456                .await;
1457            device
1458                .expect_status_response(ProtocolMessageHeader::FLAG_ACK, counter)
1459                .await;
1460            let counter = device
1461                .send(&report_data(0x4002, FLAGS_DEVICE_INITIATED, Some(9), &[(2, true)], false, false))
1462                .await;
1463            device
1464                .expect_status_response(ProtocolMessageHeader::FLAG_ACK, counter)
1465                .await;
1466        });
1467
1468        let mut sub = conn.subscribe_attrs(Some(1), Some(6), Some(0), false).await.unwrap();
1469        let update = sub.next().await.unwrap();
1470        assert_eq!(update.attribute_reports.len(), 2);
1471        assert_eq!(update.attribute_reports[0].path.endpoint, Some(1));
1472        assert_eq!(update.attribute_reports[1].path.endpoint, Some(2));
1473        task.await.unwrap();
1474    }
1475
1476    #[tokio::test]
1477    async fn test_unregistered_subscription_id() {
1478        let (conn, mut device) = mock_pair();
1479
1480        let counter = device
1481            .send(&report_data(0x4003, FLAGS_DEVICE_INITIATED, Some(99), &[(1, true)], false, false))
1482            .await;
1483        device
1484            .expect_status_response(ProtocolMessageHeader::FLAG_ACK, counter)
1485            .await;
1486        let raw = conn.recv_event().await.unwrap();
1487        assert_eq!(
1488            raw.protocol_header.opcode,
1489            ProtocolMessageHeader::INTERACTION_OPCODE_REPORT_DATA
1490        );
1491
1492        conn.set_auto_status_response(false);
1493        device
1494            .send(&report_data(0x4004, FLAGS_DEVICE_INITIATED, Some(99), &[(1, true)], false, false))
1495            .await;
1496        device.expect_silence().await;
1497        let raw = conn.recv_event().await.unwrap();
1498        assert_eq!(raw.protocol_header.exchange_id, 0x4004);
1499    }
1500
1501    #[tokio::test]
1502    async fn test_duplicate_message_dropped() {
1503        let (conn, mut device) = mock_pair();
1504
1505        let payload =
1506            report_data(0x4005, FLAGS_DEVICE_INITIATED, Some(99), &[(1, true)], false, false);
1507        let encoded = device.session.encode_message(&payload).unwrap();
1508        let (header, _) = messages::MessageHeader::decode(&encoded).unwrap();
1509        device.tx.send(encoded.clone()).await.unwrap();
1510        device
1511            .expect_status_response(ProtocolMessageHeader::FLAG_ACK, header.message_counter)
1512            .await;
1513        let raw = conn.recv_event().await.unwrap();
1514        assert_eq!(raw.protocol_header.exchange_id, 0x4005);
1515
1516        // replayed frame must be dropped: no status response, no event
1517        device.tx.send(encoded).await.unwrap();
1518        device.expect_silence().await;
1519        assert!(conn.try_recv_event().is_none());
1520    }
1521
1522    #[tokio::test]
1523    async fn test_initiator_flag_not_misrouted() {
1524        let (conn, mut device) = mock_pair();
1525        let task = tokio::spawn(async move {
1526            let req = device.recv().await;
1527            let exchange = req.protocol_header.exchange_id;
1528            // device-initiated report colliding with the pending exchange id
1529            // must not resolve the pending read request
1530            let counter = device
1531                .send(&report_data(exchange, FLAGS_DEVICE_INITIATED, None, &[(5, false)], false, false))
1532                .await;
1533            device
1534                .expect_status_response(ProtocolMessageHeader::FLAG_ACK, counter)
1535                .await;
1536            device
1537                .send(&report_data(exchange, FLAGS_RESPONDER, None, &[(1, true)], false, true))
1538                .await;
1539        });
1540        let val = conn.read_request2(1, 6, 0).await.unwrap();
1541        assert_eq!(val, TlvItemValue::Bool(true));
1542        task.await.unwrap();
1543    }
1544
1545    #[tokio::test(start_paused = true)]
1546    async fn test_retransmit_schedule_and_give_up() {
1547        let mrp = crate::mrp::MrpParameters::from_txt_ms(Some(5000), None, None);
1548        let (conn, mut device) = mock_pair_unreliable(mrp);
1549        let req = tokio::spawn(async move { conn.read_request2(1, 6, 0).await });
1550
1551        let mut times = Vec::new();
1552        let mut counters = Vec::new();
1553        for i in 0..crate::mrp::MRP_MAX_TRANSMISSIONS {
1554            let msg = device
1555                .recv_within(Duration::from_secs(30))
1556                .await
1557                .unwrap_or_else(|| panic!("missing transmission {}", i));
1558            times.push(tokio::time::Instant::now());
1559            counters.push(msg.message_header.message_counter);
1560        }
1561        assert!(counters.iter().all(|c| *c == counters[0]));
1562
1563        // gap n follows backoff: 5s * 1.1 * 1.6^max(0, n-1) plus up to 25% jitter
1564        for (n, w) in times.windows(2).enumerate() {
1565            let gap = (w[1] - w[0]).as_secs_f64();
1566            let lower = 5.0 * 1.1 * 1.6f64.powi(n.saturating_sub(1) as i32);
1567            let upper = lower * 1.25;
1568            assert!(
1569                gap >= lower - 0.01 && gap <= upper + 0.1,
1570                "gap {} = {} not in [{}, {}]",
1571                n, gap, lower, upper
1572            );
1573        }
1574
1575        // after the final backoff period the exchange is dropped and the request fails
1576        let res = req.await.unwrap();
1577        assert!(res.is_err(), "request should fail after give-up");
1578        assert!(
1579            device.recv_within(Duration::from_secs(120)).await.is_none(),
1580            "no transmissions expected after give-up"
1581        );
1582    }
1583
1584    #[tokio::test(start_paused = true)]
1585    async fn test_retransmit_stops_after_ack() {
1586        let (conn, mut device) = mock_pair_unreliable(Default::default());
1587        let _req = tokio::spawn(async move { conn.read_request2(1, 6, 0).await });
1588
1589        let msg = device.recv_within(Duration::from_secs(5)).await.expect("request");
1590        let retr = device.recv_within(Duration::from_secs(5)).await.expect("retransmit");
1591        assert_eq!(
1592            msg.message_header.message_counter,
1593            retr.message_header.message_counter
1594        );
1595
1596        device
1597            .send(&messages::ack(
1598                msg.protocol_header.exchange_id,
1599                msg.message_header.message_counter as i64,
1600            ).unwrap())
1601            .await;
1602        assert!(
1603            device.recv_within(Duration::from_secs(60)).await.is_none(),
1604            "no retransmissions expected after ack"
1605        );
1606    }
1607
1608    #[tokio::test(start_paused = true)]
1609    async fn test_retransmit_not_starved_by_inbound_traffic() {
1610        let (conn, mut device) = mock_pair_unreliable(Default::default());
1611        let _req = tokio::spawn(async move { conn.read_request2(1, 6, 0).await });
1612
1613        let first = device.recv_within(Duration::from_secs(2)).await.expect("request");
1614        let counter = first.message_header.message_counter;
1615
1616        // keep the read loop busy with inbound messages so it never hits a
1617        // receive timeout; the retransmit (due at ~550-690ms) must still fire
1618        let mut seen_retransmit = false;
1619        for _ in 0..10 {
1620            device.send(&messages::ack(0x7777, 999_999).unwrap()).await;
1621            tokio::time::sleep(Duration::from_millis(100)).await;
1622            while let Ok(data) = device.rx.try_recv() {
1623                let m = Message::decode(&data).unwrap();
1624                if m.message_header.message_counter == counter {
1625                    seen_retransmit = true;
1626                }
1627            }
1628        }
1629        assert!(seen_retransmit, "retransmit starved by continuous inbound traffic");
1630    }
1631
1632    /// Default deadline with spec MRP defaults: worst case transmission time
1633    /// (7.051 s at 500 ms base) plus the 2 s processing allowance.
1634    const DEFAULT_DEADLINE: Duration = Duration::from_millis(9051);
1635
1636    #[tokio::test(start_paused = true)]
1637    async fn test_request_times_out() {
1638        // reliable transport: no MRP give-up, so only the response deadline
1639        // can end the wait
1640        let (conn, _device) = mock_pair();
1641        let start = tokio::time::Instant::now();
1642
1643        let err = conn.read_request(1, 6, 0).await.unwrap_err();
1644
1645        let timeout = err
1646            .downcast_ref::<RequestTimeout>()
1647            .unwrap_or_else(|| panic!("expected RequestTimeout, got: {}", err));
1648        assert_eq!(timeout.waited, DEFAULT_DEADLINE);
1649        assert_eq!(start.elapsed(), DEFAULT_DEADLINE);
1650    }
1651
1652    #[tokio::test(start_paused = true)]
1653    async fn test_chunked_report_resets_idle_timer() {
1654        let (conn, mut device) = mock_pair();
1655        // each gap is below the deadline, their sum is not
1656        let gap = DEFAULT_DEADLINE.mul_f64(0.8);
1657        let task = tokio::spawn(async move {
1658            let req = device.recv().await;
1659            let exchange = req.protocol_header.exchange_id;
1660            tokio::time::sleep(gap).await;
1661            let counter = device
1662                .send(&report_data(exchange, FLAGS_RESPONDER, None, &[(1, true)], true, false))
1663                .await;
1664            device.expect_status_response(ACK_AND_INITIATOR, counter).await;
1665            tokio::time::sleep(gap).await;
1666            device
1667                .send(&report_data(exchange, FLAGS_RESPONDER, None, &[(2, false)], false, true))
1668                .await;
1669        });
1670
1671        let start = tokio::time::Instant::now();
1672        let val = conn.read_request2(1, 6, 0).await.unwrap();
1673
1674        assert_eq!(val, TlvItemValue::Bool(true));
1675        assert!(start.elapsed() > DEFAULT_DEADLINE, "test did not outlast the deadline");
1676        task.await.unwrap();
1677    }
1678
1679    #[tokio::test(start_paused = true)]
1680    async fn test_response_timeout_override() {
1681        let (conn, _device) = mock_pair();
1682        conn.set_response_timeout(Some(Duration::from_secs(1)));
1683        let start = tokio::time::Instant::now();
1684
1685        let err = conn.read_request(1, 6, 0).await.unwrap_err();
1686
1687        assert!(err.downcast_ref::<RequestTimeout>().is_some(), "got: {}", err);
1688        assert_eq!(start.elapsed(), Duration::from_secs(1));
1689
1690        conn.set_response_timeout(None);
1691        let start = tokio::time::Instant::now();
1692        let _ = conn.read_request(1, 6, 0).await;
1693        assert_eq!(start.elapsed(), DEFAULT_DEADLINE, "None must restore the default");
1694    }
1695
1696    #[tokio::test(start_paused = true)]
1697    async fn test_sleepy_peer_gets_longer_deadline() {
1698        let sleepy = crate::mrp::MrpParameters {
1699            session_idle_interval: Duration::from_secs(30),
1700            ..Default::default()
1701        };
1702        let (conn, _device) = mock_pair_unreliable(sleepy);
1703
1704        // a peer this slow must still be waited for well past the default
1705        let res = tokio::time::timeout(
1706            DEFAULT_DEADLINE * 4,
1707            conn.read_request(1, 6, 0),
1708        )
1709        .await;
1710
1711        assert!(res.is_err(), "sleepy peer request gave up too early");
1712    }
1713
1714    #[tokio::test(start_paused = true)]
1715    async fn test_invoke_per_request_timeout() {
1716        let (conn, _device) = mock_pair();
1717        let start = tokio::time::Instant::now();
1718
1719        let err = conn
1720            .invoke(InvokeRequest::new(1, 6, 1).response_timeout(Duration::from_secs(1)))
1721            .await
1722            .unwrap_err();
1723
1724        let timeout = err
1725            .downcast_ref::<RequestTimeout>()
1726            .unwrap_or_else(|| panic!("expected RequestTimeout, got: {}", err));
1727        assert_eq!(timeout.waited, Duration::from_secs(1));
1728        assert_eq!(start.elapsed(), Duration::from_secs(1));
1729    }
1730
1731    /// The per-request deadline wins over the connection wide one in both directions.
1732    #[tokio::test(start_paused = true)]
1733    async fn test_invoke_timeout_precedence() {
1734        let (conn, _device) = mock_pair();
1735
1736        conn.set_response_timeout(Some(Duration::from_secs(30)));
1737        let start = tokio::time::Instant::now();
1738        let _ = conn
1739            .invoke(InvokeRequest::new(1, 6, 1).response_timeout(Duration::from_secs(1)))
1740            .await;
1741        assert_eq!(start.elapsed(), Duration::from_secs(1));
1742
1743        conn.set_response_timeout(Some(Duration::from_secs(1)));
1744        let start = tokio::time::Instant::now();
1745        let _ = conn
1746            .invoke(InvokeRequest::new(1, 6, 1).response_timeout(Duration::from_secs(30)))
1747            .await;
1748        assert_eq!(start.elapsed(), Duration::from_secs(30));
1749    }
1750
1751    #[tokio::test(start_paused = true)]
1752    async fn test_invoke_without_timeout_uses_connection_default() {
1753        let (conn, _device) = mock_pair();
1754        let start = tokio::time::Instant::now();
1755
1756        let _ = conn.invoke(InvokeRequest::new(1, 6, 1)).await;
1757        assert_eq!(start.elapsed(), DEFAULT_DEADLINE);
1758
1759        conn.set_response_timeout(Some(Duration::from_secs(2)));
1760        let start = tokio::time::Instant::now();
1761        let _ = conn.invoke(InvokeRequest::new(1, 6, 1)).await;
1762        assert_eq!(start.elapsed(), Duration::from_secs(2));
1763    }
1764
1765    #[tokio::test]
1766    async fn test_invoke_timed_sends_timed_request_first() {
1767        let (conn, mut device) = mock_pair();
1768        let task = tokio::spawn(async move {
1769            let tr = device.recv().await;
1770            assert_eq!(
1771                tr.protocol_header.opcode,
1772                ProtocolMessageHeader::INTERACTION_OPCODE_TIMED_REQ
1773            );
1774            assert_eq!(tr.tlv.get_int(&[0]), Some(1000));
1775            let exchange = tr.protocol_header.exchange_id;
1776            device.send(&status_response(exchange, FLAGS_RESPONDER)).await;
1777
1778            let inv = device.recv().await;
1779            assert_eq!(
1780                inv.protocol_header.opcode,
1781                ProtocolMessageHeader::INTERACTION_OPCODE_INVOKE_REQ
1782            );
1783            assert_eq!(inv.protocol_header.exchange_id, exchange, "timed interaction must stay on one exchange");
1784            assert_eq!(inv.tlv.get_bool(&[1]), Some(true), "invoke not marked as timed");
1785            device.send(&status_response(exchange, FLAGS_RESPONDER)).await;
1786        });
1787
1788        conn.invoke(InvokeRequest::new(1, 6, 1).timed(1000)).await.unwrap();
1789        task.await.unwrap();
1790    }
1791}