Skip to main content

serialplugin_core/cmux/
session.rs

1//! CMUX session: deframe physical RX, route per DLCI, encode TX.
2
3use crate::cmux::frame::{
4    encode_frame, encode_uih, DecodedFrame, Deframer, DISC, DM, PF, SABM, UA, UI, UIH,
5};
6use crate::cmux::io::CmuxPhysicalIo;
7use crate::events::SerialEvent;
8use crate::hub::shared::Outbox;
9use crate::hub::ExchangeWaiter;
10use serial_codec::framing::Framer;
11use std::collections::{HashMap, HashSet};
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::mpsc;
14use std::sync::{Arc, Condvar, Mutex, OnceLock};
15use std::time::{Duration, Instant};
16
17/// Per-DLCI routing state (virtual channel).
18pub struct DlciChannel {
19    pub path: String,
20    pub exchange_waiter: Mutex<Option<Arc<ExchangeWaiter>>>,
21    watches: Mutex<DlciWatches>,
22    /// The session's outbox: events are queued under `watches`, in production order,
23    /// and delivered by the session once no lock is held.
24    outbox: Arc<Outbox>,
25}
26
27/// The old watch (at most one) and the `watch_core` streams of one channel.
28#[derive(Default)]
29struct DlciWatches {
30    old: Option<DlciWatchSlot>,
31    core: Vec<(u64, DlciWatchSlot)>,
32}
33
34impl DlciWatches {
35    fn each(&mut self, mut f: impl FnMut(&mut DlciWatchSlot)) {
36        self.core.retain(|(_, w)| w.alive());
37        self.old.iter_mut().for_each(&mut f);
38        self.core.iter_mut().for_each(|(_, w)| f(w));
39    }
40}
41
42struct DlciWatchSlot {
43    channel: crate::events::EventSink,
44    batch_timeout_ms: u64,
45    flush_at: Instant,
46    /// Native parser: each frame is one `Data` event, no batching.
47    framer: Option<Box<dyn Framer>>,
48    buffer: Vec<u8>,
49    /// `watch_core` only: cleared once the subscriber is gone.
50    alive: Option<Arc<AtomicBool>>,
51}
52
53impl DlciWatchSlot {
54    fn new(
55        channel: crate::events::EventSink,
56        batch_timeout_ms: u64,
57        framer: Option<Box<dyn Framer>>,
58        alive: Option<Arc<AtomicBool>>,
59    ) -> Self {
60        Self {
61            channel,
62            batch_timeout_ms,
63            flush_at: Instant::now(),
64            framer,
65            buffer: Vec::new(),
66            alive,
67        }
68    }
69
70    fn alive(&self) -> bool {
71        self.alive.as_ref().is_none_or(|a| a.load(Ordering::SeqCst))
72    }
73
74    fn take_due(&mut self) -> bool {
75        if self.flush_at.elapsed() >= Duration::from_millis(self.batch_timeout_ms) {
76            self.flush_at = Instant::now();
77            true
78        } else {
79            false
80        }
81    }
82
83    /// Frames ready after `payload` (parser), or the batch once its timer is due.
84    fn push(&mut self, payload: &[u8]) -> Vec<Vec<u8>> {
85        let mut frames = Vec::new();
86        if let Some(f) = self.framer.as_mut() {
87            f.push(payload, Instant::now(), &mut frames);
88            return frames;
89        }
90        self.buffer.extend_from_slice(payload);
91        if self.take_due() {
92            frames.push(std::mem::take(&mut self.buffer));
93        }
94        frames
95    }
96
97    /// Time-based frames, or a batch whose timeout elapsed with no new data.
98    fn poll(&mut self) -> Vec<Vec<u8>> {
99        let mut frames = Vec::new();
100        if let Some(f) = self.framer.as_mut() {
101            f.poll(Instant::now(), &mut frames);
102        } else if self.take_due() && !self.buffer.is_empty() {
103            frames.push(std::mem::take(&mut self.buffer));
104        }
105        frames
106    }
107
108    /// End of stream: the batch, then the parser remainder.
109    fn finish(&mut self) -> Vec<Vec<u8>> {
110        let batch = std::mem::take(&mut self.buffer);
111        let rest = self.framer.as_mut().and_then(|f| f.flush());
112        [batch, rest.unwrap_or_default()]
113            .into_iter()
114            .filter(|d| !d.is_empty())
115            .collect()
116    }
117}
118
119impl DlciChannel {
120    fn new(path: String, outbox: Arc<Outbox>) -> Self {
121        Self {
122            path,
123            exchange_waiter: Mutex::new(None),
124            watches: Mutex::new(DlciWatches::default()),
125            outbox,
126        }
127    }
128
129    /// 4.0.0 API (feature `tauri`): [`Self::attach_watch_with`] for a Tauri channel, no parser.
130    #[cfg(feature = "tauri")]
131    pub fn attach_watch(&self, channel: tauri::ipc::Channel<SerialEvent>, batch_timeout_ms: u64) {
132        self.attach_watch_with(crate::events::channel_sink(channel), batch_timeout_ms, None);
133    }
134
135    pub fn attach_watch_with(
136        &self,
137        channel: crate::events::EventSink,
138        batch_timeout_ms: u64,
139        framer: Option<Box<dyn Framer>>,
140    ) {
141        crate::sync_util::lock_or_recover(&self.watches).old =
142            Some(DlciWatchSlot::new(channel, batch_timeout_ms, framer, None));
143    }
144
145    /// Stop the watch; a parser's buffered remainder is queued as a last `Data` event
146    /// (after the frames already queued). The session delivers it on its next RX, tick
147    /// or [`CmuxSession::clear_watch`] (which calls this and delivers).
148    pub fn detach_watch(&self) {
149        let mut guard = crate::sync_util::lock_or_recover(&self.watches);
150        if let Some(mut slot) = guard.old.take() {
151            // 4.x: the unflushed batch is dropped, the parser remainder kept.
152            slot.buffer.clear();
153            let rest = slot.finish();
154            self.queue_frames(&slot.channel, rest);
155        }
156    }
157
158    fn attach_core_watch(&self, id: u64, slot: DlciWatchSlot) {
159        crate::sync_util::lock_or_recover(&self.watches)
160            .core
161            .push((id, slot));
162    }
163
164    /// Remove a `watch_core` stream; its batch and remainder are queued last.
165    fn detach_core_watch(&self, id: u64) -> bool {
166        let mut guard = crate::sync_util::lock_or_recover(&self.watches);
167        let Some(i) = guard.core.iter().position(|(c, _)| *c == id) else {
168            return false;
169        };
170        let (_, mut slot) = guard.core.remove(i);
171        let rest = slot.finish();
172        self.queue_frames(&slot.channel, rest);
173        true
174    }
175
176    /// Physical link lost: queue the batch / parser remainder, then `Disconnect`.
177    fn queue_disconnect(&self, reason: &str) {
178        let mut guard = crate::sync_util::lock_or_recover(&self.watches);
179        guard.each(|slot| {
180            let frames = slot.finish();
181            self.queue_frames(&slot.channel, frames);
182            self.outbox.push([(
183                slot.channel.clone(),
184                SerialEvent::Disconnect {
185                    path: self.path.clone(),
186                    reason: reason.to_string(),
187                },
188            )]);
189        });
190    }
191
192    /// Queue `Data` events; called with the `watches` lock held so the order is the
193    /// production order whatever thread queues next.
194    fn queue_frames(&self, channel: &crate::events::EventSink, frames: Vec<Vec<u8>>) {
195        self.outbox.push(frames.into_iter().map(|data| {
196            (
197                channel.clone(),
198                SerialEvent::Data {
199                    path: self.path.clone(),
200                    size: data.len(),
201                    data,
202                },
203            )
204        }));
205    }
206
207    fn push_stream(&self, payload: &[u8]) {
208        crate::sync_util::lock_or_recover(&self.watches).each(|slot| {
209            let frames = slot.push(payload);
210            self.queue_frames(&slot.channel, frames);
211        });
212    }
213
214    /// Parser timers and batches whose timeout elapsed with no new frame.
215    fn tick(&self) {
216        crate::sync_util::lock_or_recover(&self.watches).each(|slot| {
217            let frames = slot.poll();
218            self.queue_frames(&slot.channel, frames);
219        });
220    }
221}
222
223/// Parameter `index` (0-based) of an `AT+CMUX=` command
224/// (27.007 +CMUX: mode, subset, port_speed, N1, T1, N2, T2, T3, k).
225fn cmux_param(command: &str, index: usize) -> Option<u64> {
226    let upper = command.to_ascii_uppercase();
227    let at = upper.find("+CMUX=")?;
228    upper[at + "+CMUX=".len()..]
229        .split(',')
230        .nth(index)?
231        .trim()
232        .parse()
233        .ok()
234}
235
236/// N1 (maximum info bytes per frame) from an `AT+CMUX=` command: the 4th parameter.
237/// 31 (the basic-option default) when absent or empty.
238pub fn cmux_n1(command: &str) -> usize {
239    cmux_param(command, 3).map_or(31, |n1| n1 as usize)
240}
241
242/// 27.010 link timers, from the `AT+CMUX=` parameters (see [`CmuxTimers::from_command`]).
243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244pub struct CmuxTimers {
245    /// T1, acknowledgement timer: how long to wait for UA before resending SABM.
246    pub t1: Duration,
247    /// N2, maximum number of retransmissions.
248    pub n2: u32,
249    /// T2, response timer for control-channel commands (CLD).
250    pub t2: Duration,
251}
252
253impl Default for CmuxTimers {
254    /// The 27.010 defaults: T1 100 ms, N2 3, T2 300 ms.
255    fn default() -> Self {
256        Self {
257            t1: Duration::from_millis(100),
258            n2: 3,
259            t2: Duration::from_millis(300),
260        }
261    }
262}
263
264impl CmuxTimers {
265    /// T1, N2 and T2 are the 5th–7th `+CMUX` parameters (T1/T2 in 10 ms units);
266    /// absent, empty or out of the 27.007 range (T1 1..=255, N2 0..=100, T2 2..=255):
267    /// the default. With neither T1 nor N2 in the command SABM is sent once (N2 = 0)
268    /// and its UA gets the whole open timeout, as in 4.x.
269    pub fn from_command(command: &str) -> Self {
270        let d = Self::default();
271        let tens = |i, min, default| {
272            cmux_param(command, i)
273                .filter(|v| (min..=255).contains(v))
274                .map_or(default, |v| Duration::from_millis(v * 10))
275        };
276        let retransmit = cmux_param(command, 4).is_some() || cmux_param(command, 5).is_some();
277        Self {
278            t1: tens(4, 1, d.t1),
279            n2: if retransmit {
280                cmux_param(command, 5)
281                    .filter(|v| *v <= 100)
282                    .map_or(d.n2, |v| v as u32)
283            } else {
284                0
285            },
286            t2: tens(6, 2, d.t2),
287        }
288    }
289}
290
291// Control-channel message type octets (27.010 §5.4.6.3), C/R and EA bits included.
292const CR: u8 = 0x02;
293const PN_CMD: u8 = 0x83;
294const PSC_CMD: u8 = 0x43;
295const TEST_CMD: u8 = 0x23;
296const MSC_CMD: u8 = 0xE3;
297const RPN_CMD: u8 = 0x93;
298const RLS_CMD: u8 = 0x53;
299const FCON_CMD: u8 = 0xA3;
300const FCOFF_CMD: u8 = 0x63;
301const CLD_CMD: u8 = 0xC3;
302const CLD_RSP: u8 = 0xC1;
303/// Non-supported command response (§5.4.6.3.8).
304const NSC_RSP: u8 = 0x11;
305/// Commands answered by echoing them with C/R cleared.
306const ECHOED: [u8; 9] = [
307    PN_CMD, PSC_CMD, TEST_CMD, MSC_CMD, RPN_CMD, RLS_CMD, FCON_CMD, FCOFF_CMD, CLD_CMD,
308];
309/// MSC V.24 signals we send: EA | RTC | RTR | DV.
310const V24_READY: u8 = 0x8D;
311/// MSC V.24 flow control bit: the sender of the MSC cannot accept frames on that DLC.
312const V24_FC: u8 = 0x02;
313
314/// Flow control from the modem: FCoff stops every DLC, MSC with FC=1 one DLC.
315/// Writes wait (on `CmuxSession::tx_cv`) until it ends or their write timeout.
316#[derive(Default)]
317struct TxGate {
318    fc_off: bool,
319    held_dlcis: HashSet<u8>,
320}
321
322/// The modem closed channels: their virtual paths, the reason, and whether it left
323/// multiplexer mode altogether (DISC / DM on DLCI 0, CLD).
324pub(crate) type ClosedHook = Box<dyn Fn(&[String], &str, bool) + Send + Sync>;
325
326/// Active GSM 07.10 multiplexer on a physical serial port.
327pub struct CmuxSession {
328    physical_path: String,
329    io: Arc<dyn CmuxPhysicalIo>,
330    deframer: Mutex<Deframer>,
331    channels: Mutex<HashMap<u8, Arc<DlciChannel>>>,
332    /// SABM or DISC sent, waiting for UA (true) or DM (false).
333    pending_open: Mutex<HashMap<u8, mpsc::Sender<bool>>>,
334    /// CLD sent, waiting for its response.
335    pending_cld: Mutex<Option<mpsc::Sender<()>>>,
336    /// DLCs the modem closed (DISC / DM): writes fail until the DLCI is registered again.
337    closed: Mutex<HashSet<u8>>,
338    tx: Mutex<TxGate>,
339    tx_cv: Condvar,
340    /// Set when the session ended (closed down, or the modem left multiplexer mode).
341    dead: Mutex<Option<String>>,
342    on_closed: OnceLock<ClosedHook>,
343    timers: CmuxTimers,
344    outbox: Arc<Outbox>,
345}
346
347impl CmuxSession {
348    /// Session with the basic-option default N1 (31, the 4.0.0 behaviour);
349    /// [`Self::with_n1`] for the N1 given to `AT+CMUX`.
350    pub fn new(physical_path: String, io: Arc<dyn CmuxPhysicalIo>) -> Arc<Self> {
351        Self::with_n1(physical_path, io, serial_codec::cmux::TX_N1)
352    }
353
354    /// `n1`: the negotiated maximum frame size (`AT+CMUX` N1, see [`cmux_n1`]).
355    /// Frames up to `max(n1, DEFAULT_MAX_RX_INFO)` info bytes are accepted. One SABM
356    /// per open (4.x).
357    pub fn with_n1(physical_path: String, io: Arc<dyn CmuxPhysicalIo>, n1: usize) -> Arc<Self> {
358        let timers = CmuxTimers {
359            n2: 0,
360            ..CmuxTimers::default()
361        };
362        Self::with_timers(physical_path, io, n1, timers)
363    }
364
365    /// Session for the `AT+CMUX=` command that started it: N1 ([`cmux_n1`]) and the
366    /// T1/N2/T2 timers ([`CmuxTimers::from_command`]).
367    pub fn for_command(
368        physical_path: String,
369        io: Arc<dyn CmuxPhysicalIo>,
370        command: &str,
371    ) -> Arc<Self> {
372        Self::with_timers(
373            physical_path,
374            io,
375            cmux_n1(command),
376            CmuxTimers::from_command(command),
377        )
378    }
379
380    fn with_timers(
381        physical_path: String,
382        io: Arc<dyn CmuxPhysicalIo>,
383        n1: usize,
384        timers: CmuxTimers,
385    ) -> Arc<Self> {
386        Arc::new(Self {
387            physical_path,
388            io,
389            deframer: Mutex::new(Deframer::with_max_info(
390                n1.max(crate::cmux::frame::DEFAULT_MAX_RX_INFO),
391            )),
392            channels: Mutex::new(HashMap::new()),
393            pending_open: Mutex::new(HashMap::new()),
394            pending_cld: Mutex::new(None),
395            closed: Mutex::new(HashSet::new()),
396            tx: Mutex::default(),
397            tx_cv: Condvar::new(),
398            dead: Mutex::new(None),
399            on_closed: OnceLock::new(),
400            timers,
401            outbox: Arc::default(),
402        })
403    }
404
405    pub fn physical_path(&self) -> &str {
406        &self.physical_path
407    }
408
409    /// Run `hook` whenever the modem closes channels (set once, by the manager).
410    pub(crate) fn set_on_closed(&self, hook: ClosedHook) {
411        let _ = self.on_closed.set(hook);
412    }
413
414    /// `Err` once the session ended.
415    fn check_alive(&self) -> Result<(), String> {
416        match crate::sync_util::lock_or_recover(&self.dead).as_ref() {
417            Some(why) => Err(why.clone()),
418            None => Ok(()),
419        }
420    }
421
422    fn end(&self, why: &str) {
423        crate::sync_util::lock_or_recover(&self.dead).get_or_insert_with(|| why.to_string());
424        self.wake_writers();
425    }
426
427    /// Wake writers waiting on flow control (state changed: FCon, a channel closed …).
428    fn wake_writers(&self) {
429        drop(crate::sync_util::lock_or_recover(&self.tx));
430        self.tx_cv.notify_all();
431    }
432
433    pub fn register_dlci(&self, dlci: u8, virtual_path: String) -> Arc<DlciChannel> {
434        let ch = Arc::new(DlciChannel::new(virtual_path, self.outbox.clone()));
435        crate::sync_util::lock_or_recover(&self.channels).insert(dlci, ch.clone());
436        crate::sync_util::lock_or_recover(&self.closed).remove(&dlci);
437        ch
438    }
439
440    pub fn unregister_dlci(&self, dlci: u8) {
441        crate::sync_util::lock_or_recover(&self.closed).remove(&dlci);
442        crate::sync_util::lock_or_recover(&self.tx)
443            .held_dlcis
444            .remove(&dlci);
445        let removed = crate::sync_util::lock_or_recover(&self.channels)
446            .remove(&dlci)
447            .is_some();
448        self.wake_writers();
449        if removed {
450            // Wait (up to T1) for the UA / DM: a CLD sent while the DISC is still in
451            // progress is answered by the M26 only after ~0.5 s, past T2.
452            let (tx, rx) = mpsc::channel();
453            crate::sync_util::lock_or_recover(&self.pending_open).insert(dlci, tx);
454            if self
455                .io
456                .write_all(&encode_frame(dlci, true, DISC | PF, &[]))
457                .is_ok()
458            {
459                let _ = rx.recv_timeout(self.timers.t1);
460            }
461            crate::sync_util::lock_or_recover(&self.pending_open).remove(&dlci);
462        }
463    }
464
465    pub fn has_dlci(&self, dlci: u8) -> bool {
466        crate::sync_util::lock_or_recover(&self.channels).contains_key(&dlci)
467    }
468
469    /// Establish a DLC: send SABM and wait for the modem's UA (DM = refused). SABM is
470    /// resent every T1, at most N2 times; the last try waits out `timeout` (at least T1).
471    /// A data DLC gets an MSC (V.24 signals ready) once established.
472    /// DLCI 0 (the control channel) must be opened first.
473    pub fn open_dlci(&self, dlci: u8, timeout: Duration) -> Result<(), String> {
474        self.check_alive()?;
475        let (tx, rx) = mpsc::channel();
476        crate::sync_util::lock_or_recover(&self.pending_open).insert(dlci, tx);
477        let CmuxTimers { t1, n2, .. } = self.timers;
478        let total = timeout.max(t1 * (n2 + 1));
479        let sabm = encode_frame(dlci, true, SABM | PF, &[]);
480        let start = Instant::now();
481        let mut answer = Ok(None);
482        for attempt in 0..=n2 {
483            if let Err(e) = self.io.write_all(&sabm) {
484                answer = Err(e);
485                break;
486            }
487            let wait = if attempt == n2 {
488                total.saturating_sub(start.elapsed())
489            } else {
490                t1
491            };
492            if let Ok(ua) = rx.recv_timeout(wait) {
493                answer = Ok(Some(ua));
494                break;
495            }
496        }
497        crate::sync_util::lock_or_recover(&self.pending_open).remove(&dlci);
498        match answer? {
499            Some(true) => {
500                if dlci != 0 {
501                    let msc = [MSC_CMD, 0x05, (dlci << 2) | 0x03, V24_READY];
502                    let _ = self.io.write_all(&encode_frame(0, true, UIH, &msc));
503                }
504                Ok(())
505            }
506            Some(false) => Err(format!("modem refused CMUX DLCI {dlci} (DM)")),
507            None => Err(format!(
508                "no UA for CMUX DLCI {dlci} within {} ms",
509                total.as_millis()
510            )),
511        }
512    }
513
514    /// Ask the modem to leave multiplexer mode: CLD on the control channel, then wait
515    /// up to T2 for its response. Channel writes fail from here on.
516    pub fn close_down(&self) {
517        self.end("CMUX multiplexer is closed");
518        let (tx, rx) = mpsc::channel();
519        *crate::sync_util::lock_or_recover(&self.pending_cld) = Some(tx);
520        let cld = encode_frame(0, true, UIH, &[CLD_CMD, 0x01]);
521        if self.io.write_all(&cld).is_ok() {
522            let _ = rx.recv_timeout(self.timers.t2);
523        }
524        *crate::sync_util::lock_or_recover(&self.pending_cld) = None;
525    }
526
527    /// The modem closed `dlci` (DISC / DM; 0: the whole multiplexer): its watches get
528    /// their remainder and `Disconnect`, an exchange in flight fails, held data is dropped.
529    fn closed_by_modem(&self, dlci: u8) {
530        let gone: Vec<(u8, Arc<DlciChannel>)> = {
531            let mut channels = crate::sync_util::lock_or_recover(&self.channels);
532            if dlci == 0 {
533                channels.drain().collect()
534            } else {
535                channels
536                    .remove(&dlci)
537                    .map(|ch| (dlci, ch))
538                    .into_iter()
539                    .collect()
540            }
541        };
542        if dlci == 0 {
543            self.end("CMUX multiplexer closed by the modem");
544        }
545        let mut paths = Vec::new();
546        for (d, ch) in gone {
547            crate::sync_util::lock_or_recover(&self.closed).insert(d);
548            let reason = format!("CMUX DLCI {d} closed by the modem");
549            if let Some(waiter) = crate::sync_util::lock_or_recover(&ch.exchange_waiter).as_ref() {
550                waiter.fail_with_reason(reason.clone());
551            }
552            ch.queue_disconnect(&reason);
553            paths.push(ch.path.clone());
554        }
555        self.wake_writers();
556        if let Some(hook) = self.on_closed.get() {
557            let reason = if dlci == 0 {
558                "CMUX multiplexer closed by the modem".to_string()
559            } else {
560                format!("CMUX DLCI {dlci} closed by the modem")
561            };
562            hook(&paths, &reason, dlci == 0);
563        }
564    }
565
566    /// Batch-timeout flush for virtual-channel watches (called from the hub tick).
567    pub fn tick(&self) {
568        let channels: Vec<_> = crate::sync_util::lock_or_recover(&self.channels)
569            .values()
570            .cloned()
571            .collect();
572        for ch in channels {
573            ch.tick();
574        }
575        self.outbox.deliver();
576    }
577
578    fn channel(&self, dlci: u8) -> Option<Arc<DlciChannel>> {
579        crate::sync_util::lock_or_recover(&self.channels)
580            .get(&dlci)
581            .cloned()
582    }
583
584    /// Physical link lost: every channel watch gets its remainder, then `Disconnect`
585    /// with the channel's virtual path.
586    pub fn emit_disconnect(&self, reason: &str) {
587        let channels: Vec<_> = crate::sync_util::lock_or_recover(&self.channels)
588            .values()
589            .cloned()
590            .collect();
591        for ch in channels {
592            ch.queue_disconnect(reason);
593        }
594        self.outbox.deliver();
595    }
596
597    /// 4.0.0 API (feature `tauri`): [`Self::set_watch_with`] for a Tauri channel, no parser.
598    #[cfg(feature = "tauri")]
599    pub fn set_watch(
600        &self,
601        dlci: u8,
602        channel: tauri::ipc::Channel<SerialEvent>,
603        batch_timeout_ms: u64,
604    ) {
605        self.set_watch_with(
606            dlci,
607            crate::events::channel_sink(channel),
608            batch_timeout_ms,
609            None,
610        );
611    }
612
613    pub fn set_watch_with(
614        &self,
615        dlci: u8,
616        channel: crate::events::EventSink,
617        batch_timeout_ms: u64,
618        framer: Option<Box<dyn Framer>>,
619    ) {
620        if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
621            ch.attach_watch_with(channel, batch_timeout_ms, framer);
622        }
623    }
624
625    /// Stop the channel watch; its parser remainder is the last `Data`. The sink runs
626    /// here, so call with no manager lock held.
627    pub fn clear_watch(&self, dlci: u8) {
628        if let Some(ch) = self.channel(dlci) {
629            ch.detach_watch();
630        }
631        self.outbox.deliver();
632    }
633
634    /// Add a `watch_core` stream on `dlci` (its own batch / parser). `false`: no channel.
635    pub(crate) fn add_core_watch(
636        &self,
637        dlci: u8,
638        id: u64,
639        sink: crate::events::EventSink,
640        alive: Arc<AtomicBool>,
641        batch_timeout_ms: u64,
642        framer: Option<Box<dyn Framer>>,
643    ) -> bool {
644        let Some(ch) = self.channel(dlci) else {
645            return false;
646        };
647        ch.attach_core_watch(
648            id,
649            DlciWatchSlot::new(sink, batch_timeout_ms, framer, Some(alive)),
650        );
651        true
652    }
653
654    /// Remove a `watch_core` stream; its remainder is delivered here (no lock held).
655    pub(crate) fn remove_core_watch(&self, dlci: u8, id: u64) -> bool {
656        let removed = self
657            .channel(dlci)
658            .is_some_and(|ch| ch.detach_core_watch(id));
659        self.outbox.deliver();
660        removed
661    }
662
663    pub fn set_exchange_waiter(&self, dlci: u8, waiter: Arc<ExchangeWaiter>) {
664        if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
665            *crate::sync_util::lock_or_recover(&ch.exchange_waiter) = Some(waiter);
666        }
667    }
668
669    pub fn clear_exchange_waiter(&self, dlci: u8) {
670        if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
671            *crate::sync_util::lock_or_recover(&ch.exchange_waiter) = None;
672        }
673    }
674
675    /// Fail the in-flight exchange waiter on `dlci` (used by `cancel_exchange`).
676    pub fn cancel_active_exchange(&self, dlci: u8) {
677        if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
678            if let Some(waiter) = crate::sync_util::lock_or_recover(&ch.exchange_waiter).as_ref() {
679                waiter.fail_with_reason("exchange cancelled".into());
680            }
681        }
682    }
683
684    /// Send `payload` on `dlci` as UIH frames. While the modem holds flow control off
685    /// (FCoff, or MSC with FC=1 for this DLC) the write waits for it to end, at most the
686    /// write timeout of the frames, then fails; nothing is queued to go out later.
687    pub fn send_uih(&self, dlci: u8, payload: &[u8]) -> Result<usize, String> {
688        let frame = encode_uih(dlci, payload);
689        let deadline = Instant::now() + self.io.write_timeout(frame.len());
690        // Written under the gate lock: no data frame follows our FCoff response.
691        let mut gate = crate::sync_util::lock_or_recover(&self.tx);
692        let mut waited = false;
693        loop {
694            self.check_alive()?;
695            if crate::sync_util::lock_or_recover(&self.closed).contains(&dlci) {
696                return Err(format!("CMUX DLCI {dlci} closed by the modem"));
697            }
698            if waited && !self.has_dlci(dlci) {
699                return Err(format!("CMUX DLCI {dlci} is closed"));
700            }
701            let held = if gate.fc_off {
702                "CMUX flow control off (FCoff)".to_string()
703            } else if gate.held_dlcis.contains(&dlci) {
704                format!("CMUX DLCI {dlci} flow control off (MSC FC)")
705            } else {
706                break;
707            };
708            let left = deadline.saturating_duration_since(Instant::now());
709            if left.is_zero() {
710                return Err(held);
711            }
712            gate = self
713                .tx_cv
714                .wait_timeout(gate, left)
715                .unwrap_or_else(|e| e.into_inner())
716                .0;
717            waited = true;
718        }
719        self.io.write_all(&frame)?;
720        drop(gate);
721        Ok(payload.len())
722    }
723
724    /// Feed raw bytes from the physical RX hub thread.
725    pub fn feed_physical_rx(&self, chunk: &[u8]) {
726        let frames = crate::sync_util::lock_or_recover(&self.deframer).feed(chunk);
727        for frame in frames {
728            self.dispatch_frame(frame);
729        }
730        self.outbox.deliver();
731    }
732
733    fn dispatch_frame(&self, frame: DecodedFrame) {
734        match frame.kind {
735            UA | DM => {
736                if let Some(tx) =
737                    crate::sync_util::lock_or_recover(&self.pending_open).get(&frame.dlci)
738                {
739                    let _ = tx.send(frame.kind == UA);
740                } else if frame.kind == DM {
741                    // DM on an established DLC: the modem has closed it.
742                    self.closed_by_modem(frame.dlci);
743                }
744                return;
745            }
746            DISC => {
747                // UA when the DLC is open (DLCI 0: the whole multiplexer), else DM.
748                let open = frame.dlci == 0 || self.has_dlci(frame.dlci);
749                let reply = if open { UA } else { DM };
750                let _ = self
751                    .io
752                    .write_all(&encode_frame(frame.dlci, false, reply | PF, &[]));
753                if open {
754                    self.closed_by_modem(frame.dlci);
755                }
756                return;
757            }
758            UIH | UI => {}
759            // SABM from the modem: we are the initiator, nothing to accept.
760            _ => return,
761        }
762        if frame.dlci == 0 {
763            self.handle_control(&frame.payload);
764            return;
765        }
766        let Some(ch) = self.channel(frame.dlci) else {
767            return;
768        };
769        let waiter = crate::sync_util::lock_or_recover(&ch.exchange_waiter).clone();
770        if let Some(waiter) = waiter {
771            waiter.push_bytes(&frame.payload);
772            return;
773        }
774        ch.push_stream(&frame.payload);
775    }
776
777    /// Control-channel message from the modem. The commands we know (PN, PSC, TEST,
778    /// MSC, RPN, RLS, FCon/FCoff, CLD) are acknowledged by echoing them back with the
779    /// type octet's C/R bit cleared, as 27.010 §5.4.6 requires; any other command gets
780    /// NSC (§5.4.6.3.8). FCoff holds UIH data on every DLC until FCon, an MSC with FC
781    /// set holds that DLC until an MSC without it; CLD from the modem closes every
782    /// channel. Of the responses only CLD's is waited for.
783    fn handle_control(&self, payload: &[u8]) {
784        let Some(&type_octet) = payload.first() else {
785            return;
786        };
787        if type_octet & CR == 0 {
788            if type_octet == CLD_RSP {
789                if let Some(tx) = crate::sync_util::lock_or_recover(&self.pending_cld).as_ref() {
790                    let _ = tx.send(());
791                }
792            }
793            return;
794        }
795        // Gate first: no data frame may follow the FCoff response.
796        if type_octet == FCOFF_CMD {
797            crate::sync_util::lock_or_recover(&self.tx).fc_off = true;
798        }
799        if let (MSC_CMD, Some(&address), Some(&v24)) = (type_octet, payload.get(2), payload.get(3))
800        {
801            let dlci = address >> 2;
802            let mut gate = crate::sync_util::lock_or_recover(&self.tx);
803            if v24 & V24_FC != 0 {
804                gate.held_dlcis.insert(dlci);
805            } else {
806                gate.held_dlcis.remove(&dlci);
807            }
808            drop(gate);
809            self.tx_cv.notify_all();
810        }
811        let reply = if ECHOED.contains(&type_octet) {
812            let mut reply = payload.to_vec();
813            reply[0] &= !CR;
814            reply
815        } else {
816            vec![NSC_RSP, 0x03, type_octet]
817        };
818        let _ = self.io.write_all(&encode_frame(0, true, UIH, &reply));
819        match type_octet {
820            FCON_CMD => {
821                crate::sync_util::lock_or_recover(&self.tx).fc_off = false;
822                self.tx_cv.notify_all();
823            }
824            CLD_CMD => self.closed_by_modem(0),
825            _ => {}
826        }
827    }
828}
829
830#[cfg(all(test, not(target_os = "android")))]
831mod tests {
832    use super::*;
833    use crate::events::{AtResultFormat, ExchangeCompletionMode, RxPrepareMode};
834    use crate::exchange::options::ResolvedExchangeOptions;
835    use crate::hub::ExchangeWaiter;
836    use std::sync::atomic::AtomicBool;
837
838    fn test_options() -> ResolvedExchangeOptions {
839        ResolvedExchangeOptions {
840            timeout_ms: 3000,
841            max_bytes: 4096,
842            terminators: vec![],
843            idle_ms: None,
844            rx_prepare: RxPrepareMode::None,
845            drain_idle_ms: 50,
846            drain_max_ms: 200,
847            completion_mode: ExchangeCompletionMode::AtFinalLine,
848            result_format: AtResultFormat::Verbose,
849            command: Some("AT".into()),
850            solicited_prefixes: vec![],
851        }
852    }
853
854    #[cfg(unix)]
855    #[test]
856    fn feed_physical_rx_routes_to_exchange_waiter() {
857        use crate::cmux::SerialPortIo;
858        use crate::sync_util::pty_pair_locked;
859        use serialport::SerialPort;
860        let (_pty, port, _master) = pty_pair_locked();
861        let session = CmuxSession::with_n1(
862            "pty".into(),
863            Arc::new(SerialPortIo(Arc::new(Mutex::new(
864                Box::new(port) as Box<dyn SerialPort>
865            )))),
866            31,
867        );
868        session.register_dlci(2, "pty#dlci=2".into());
869        let cancel = Arc::new(AtomicBool::new(false));
870        let waiter = ExchangeWaiter::new(test_options(), cancel);
871        session.set_exchange_waiter(2, waiter.clone());
872        let payload = b"AT\r\r\nOK\r\n";
873        let frame = encode_uih(2, payload);
874        session.feed_physical_rx(&frame);
875        let (raw, matched) = waiter.wait(1000).expect("complete");
876        assert!(String::from_utf8_lossy(&raw).contains("OK"));
877        assert!(matches!(matched, crate::at::parse::ExchangeMatch::Ok));
878    }
879
880    #[test]
881    fn cancel_active_exchange_fails_waiter_quickly() {
882        use crate::cmux::io::CmuxPhysicalIo;
883        struct NoopIo;
884        impl CmuxPhysicalIo for NoopIo {
885            fn write_all(&self, _data: &[u8]) -> Result<(), String> {
886                Ok(())
887            }
888        }
889        let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), 31);
890        session.register_dlci(2, "mock#dlci=2".into());
891        let cancel = Arc::new(AtomicBool::new(false));
892        let waiter = ExchangeWaiter::new(test_options(), cancel);
893        session.set_exchange_waiter(2, waiter.clone());
894        let waiter_bg = waiter.clone();
895        let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
896        let done_bg = done.clone();
897        std::thread::spawn(move || {
898            let _ = waiter_bg.wait(5000);
899            done_bg.store(true, std::sync::atomic::Ordering::SeqCst);
900        });
901        std::thread::sleep(std::time::Duration::from_millis(20));
902        let start = std::time::Instant::now();
903        session.cancel_active_exchange(2);
904        while !done.load(std::sync::atomic::Ordering::SeqCst)
905            && start.elapsed() < std::time::Duration::from_millis(500)
906        {
907            std::thread::sleep(std::time::Duration::from_millis(5));
908        }
909        assert!(done.load(std::sync::atomic::Ordering::SeqCst));
910        assert!(start.elapsed() < std::time::Duration::from_millis(500));
911    }
912
913    #[test]
914    fn dlci_watch_parser_emits_one_event_per_frame() {
915        use crate::cmux::io::CmuxPhysicalIo;
916        use serial_codec::framing::FramerConfig;
917        struct NoopIo;
918        impl CmuxPhysicalIo for NoopIo {
919            fn write_all(&self, _data: &[u8]) -> Result<(), String> {
920                Ok(())
921            }
922        }
923        let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), 31);
924        session.register_dlci(2, "mock#dlci=2".into());
925        let frames = Arc::new(Mutex::new(Vec::new()));
926        let sink = frames.clone();
927        let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
928            if let SerialEvent::Data { data, .. } = event {
929                sink.lock().unwrap().push(data);
930            }
931            true
932        });
933        let cfg: FramerConfig =
934            serde_json::from_value(serde_json::json!({"type": "readline"})).unwrap();
935        session.set_watch_with(2, channel, 10_000, Some(cfg.build().unwrap()));
936        session.feed_physical_rx(&encode_uih(2, b"one\ntw"));
937        session.feed_physical_rx(&encode_uih(2, b"o\nthr"));
938        assert_eq!(
939            *frames.lock().unwrap(),
940            vec![b"one".to_vec(), b"two".to_vec()]
941        );
942        session.clear_watch(2);
943        assert_eq!(frames.lock().unwrap().last().unwrap(), b"thr");
944    }
945
946    struct NoopIo;
947    impl crate::cmux::io::CmuxPhysicalIo for NoopIo {
948        fn write_all(&self, _data: &[u8]) -> Result<(), String> {
949            Ok(())
950        }
951    }
952
953    /// The remainder sink ran under the session's `channels` lock (and the manager's
954    /// `mux` lock), so a sink calling back into the session deadlocked.
955    #[test]
956    fn clear_watch_remainder_sink_may_call_back_into_session() {
957        use serial_codec::framing::FramerConfig;
958        let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), 31);
959        session.register_dlci(2, "mock#dlci=2".into());
960        let weak = Arc::downgrade(&session);
961        let (tx, rx) = mpsc::channel();
962        let tx = Mutex::new(tx);
963        let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
964            if let SerialEvent::Data { data, .. } = event {
965                let known = weak.upgrade().is_some_and(|s| s.has_dlci(2));
966                let _ = tx.lock().unwrap().send((data, known));
967            }
968            true
969        });
970        let cfg: FramerConfig =
971            serde_json::from_value(serde_json::json!({"type": "readline"})).unwrap();
972        session.set_watch_with(2, channel, 10_000, Some(cfg.build().unwrap()));
973        session.feed_physical_rx(&encode_uih(2, b"partial"));
974        let bg = session.clone();
975        std::thread::spawn(move || bg.clear_watch(2));
976        let (data, known) = rx
977            .recv_timeout(Duration::from_secs(3))
978            .expect("clear_watch deadlocked: sink ran under the channels lock");
979        assert_eq!(data, b"partial");
980        assert!(known);
981    }
982
983    #[test]
984    fn n1_is_the_fourth_cmux_parameter() {
985        assert_eq!(cmux_n1("AT+CMUX=0,0,5,2048"), 2048);
986        assert_eq!(cmux_n1("at+cmux=0,0,5,127,10,3,30,10,2"), 127);
987        assert_eq!(cmux_n1("AT+CMUX=0"), 31);
988        assert_eq!(cmux_n1("AT+CMUX=0,0,,"), 31);
989        assert_eq!(cmux_n1("AT+CMUX=0,0,5, 1600 ,10"), 1600);
990        assert_eq!(cmux_n1("AT"), 31);
991    }
992
993    /// Audit p4: the session always used the 1509-byte default deframer, so with
994    /// `AT+CMUX=…,N1=2048` every larger modem frame was dropped as corrupt.
995    #[test]
996    fn session_accepts_frames_up_to_negotiated_n1() {
997        let n1 = cmux_n1("AT+CMUX=0,0,5,2048");
998        let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), n1);
999        session.register_dlci(1, "mock#dlci=1".into());
1000        let got = Arc::new(Mutex::new(0usize));
1001        let sink = got.clone();
1002        let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
1003            if let SerialEvent::Data { size, .. } = event {
1004                *sink.lock().unwrap() += size;
1005            }
1006            true
1007        });
1008        session.set_watch_with(1, channel, 0, None);
1009        let frame = encode_frame(1, true, UIH, &[b'A'; 2000]);
1010        session.feed_physical_rx(&frame);
1011        assert_eq!(*got.lock().unwrap(), 2000, "2000-byte frame dropped");
1012    }
1013
1014    // ------------------------------------------------ fake 27.010 modem (item 11)
1015
1016    type Log = Arc<Mutex<Vec<DecodedFrame>>>;
1017    type HookLog = Arc<Mutex<Vec<(Vec<String>, bool)>>>;
1018    type Events = Arc<Mutex<Vec<SerialEvent>>>;
1019
1020    struct FakeIo(Mutex<mpsc::Sender<Vec<u8>>>);
1021    impl crate::cmux::io::CmuxPhysicalIo for FakeIo {
1022        fn write_all(&self, data: &[u8]) -> Result<(), String> {
1023            let _ = self.0.lock().unwrap().send(data.to_vec());
1024            Ok(())
1025        }
1026        /// Short, so FCoff tests time out quickly.
1027        fn write_timeout(&self, _len: usize) -> Duration {
1028            Duration::from_millis(300)
1029        }
1030    }
1031
1032    /// Fake modem on its own thread: logs every frame the session writes, and feeds
1033    /// `reply(frame)` back as physical RX.
1034    fn fake_modem(
1035        command: &str,
1036        mut reply: impl FnMut(&DecodedFrame) -> Vec<u8> + Send + 'static,
1037    ) -> (Arc<CmuxSession>, Log) {
1038        let (tx, rx) = mpsc::channel::<Vec<u8>>();
1039        let session =
1040            CmuxSession::for_command("m".into(), Arc::new(FakeIo(Mutex::new(tx))), command);
1041        let weak = Arc::downgrade(&session);
1042        let log: Log = Arc::default();
1043        let seen = log.clone();
1044        std::thread::spawn(move || {
1045            let mut deframer = Deframer::default();
1046            for bytes in rx {
1047                for f in deframer.feed(&bytes) {
1048                    let out = reply(&f);
1049                    seen.lock().unwrap().push(f);
1050                    if let (false, Some(s)) = (out.is_empty(), weak.upgrade()) {
1051                        s.feed_physical_rx(&out);
1052                    }
1053                }
1054            }
1055        });
1056        (session, log)
1057    }
1058
1059    fn ua_to_sabm(f: &DecodedFrame) -> Vec<u8> {
1060        if f.kind == SABM {
1061            encode_frame(f.dlci, true, UA | PF, &[])
1062        } else {
1063            Vec::new()
1064        }
1065    }
1066
1067    fn wait_log(
1068        log: &Log,
1069        what: &str,
1070        pred: impl Fn(&[DecodedFrame]) -> bool,
1071    ) -> Vec<DecodedFrame> {
1072        let start = Instant::now();
1073        loop {
1074            let frames = log.lock().unwrap().clone();
1075            if pred(&frames) {
1076                return frames;
1077            }
1078            assert!(
1079                start.elapsed() < Duration::from_secs(3),
1080                "timed out: {what}: {frames:?}"
1081            );
1082            std::thread::sleep(Duration::from_millis(5));
1083        }
1084    }
1085
1086    fn count(frames: &[DecodedFrame], pred: impl Fn(&DecodedFrame) -> bool) -> usize {
1087        frames.iter().filter(|f| pred(f)).count()
1088    }
1089
1090    fn event_sink() -> (crate::events::EventSink, Events) {
1091        let events: Events = Arc::default();
1092        let sink = events.clone();
1093        let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
1094            sink.lock().unwrap().push(event);
1095            true
1096        });
1097        (channel, events)
1098    }
1099
1100    fn disconnects(events: &Events) -> Vec<String> {
1101        events
1102            .lock()
1103            .unwrap()
1104            .iter()
1105            .filter_map(|e| match e {
1106                SerialEvent::Disconnect { path, .. } => Some(path.clone()),
1107                _ => None,
1108            })
1109            .collect()
1110    }
1111
1112    #[test]
1113    fn cmux_timers_from_command_parameters() {
1114        let ms = Duration::from_millis;
1115        let default = CmuxTimers::default();
1116        assert_eq!((default.t1, default.n2, default.t2), (ms(100), 3, ms(300)));
1117        // No T1 / N2 in the command: one SABM, as in 4.x.
1118        let single = CmuxTimers { n2: 0, ..default };
1119        assert_eq!(CmuxTimers::from_command("AT+CMUX=0"), single);
1120        assert_eq!(CmuxTimers::from_command("AT"), single);
1121        let t = CmuxTimers::from_command("AT+CMUX=0,0,5,31,10,2");
1122        assert_eq!((t.t1, t.n2, t.t2), (ms(100), 2, ms(300)));
1123        let t = CmuxTimers::from_command("at+cmux=0,0,5,127,25, 5 ,40,10,2");
1124        assert_eq!((t.t1, t.n2, t.t2), (ms(250), 5, ms(400)));
1125        // Out of the 27.007 ranges (T1 1..=255, N2 0..=100, T2 2..=255): the default.
1126        let t = CmuxTimers::from_command("AT+CMUX=0,0,5,31,0,101,1");
1127        assert_eq!(t, default);
1128        assert_eq!(CmuxTimers::from_command("AT+CMUX=0,0,5,31,,0").n2, 0);
1129    }
1130
1131    #[test]
1132    fn msc_follows_ua_on_each_data_dlci() {
1133        let (s, log) = fake_modem("AT+CMUX=0", ua_to_sabm);
1134        s.open_dlci(0, Duration::from_secs(1)).unwrap();
1135        s.register_dlci(1, "m#dlci=1".into());
1136        s.open_dlci(1, Duration::from_secs(1)).unwrap();
1137        let ctrl = |f: &DecodedFrame| f.dlci == 0 && f.kind == UIH;
1138        let frames = wait_log(&log, "MSC", |f| count(f, ctrl) >= 1);
1139        let msc: Vec<_> = frames.iter().filter(|f| ctrl(f)).collect();
1140        // MSC command, length 2, DLCI 1 address octet, V.24: EA|RTC|RTR|DV.
1141        assert_eq!(msc[0].payload, vec![0xE3, 0x05, 0x07, 0x8D]);
1142        assert!(msc[0].cr, "MSC is our command");
1143        let sabm1 = frames
1144            .iter()
1145            .position(|f| f.dlci == 1 && f.kind == SABM)
1146            .unwrap();
1147        let msc_at = frames.iter().position(ctrl).unwrap();
1148        assert!(sabm1 < msc_at, "MSC after the DLC is established");
1149
1150        // The modem's MSC command is answered (C/R cleared); its response to ours is not.
1151        s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xE3, 0x05, 0x07, 0x8D]));
1152        s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xE1, 0x05, 0x07, 0x8D]));
1153        wait_log(&log, "MSC response", |f| count(f, ctrl) >= 2);
1154        std::thread::sleep(Duration::from_millis(50));
1155        let frames = log.lock().unwrap().clone();
1156        let ctrl_payloads: Vec<_> = frames
1157            .iter()
1158            .filter(|f| ctrl(f))
1159            .map(|f| f.payload.clone())
1160            .collect();
1161        assert_eq!(
1162            ctrl_payloads,
1163            vec![vec![0xE3, 0x05, 0x07, 0x8D], vec![0xE1, 0x05, 0x07, 0x8D]],
1164            "one MSC of ours (none for DLCI 0), one response to the modem's"
1165        );
1166    }
1167
1168    #[test]
1169    fn sabm_retried_n2_times_with_t1_then_error() {
1170        // T1 = 2 (20 ms), N2 = 2: three SABMs in all, then the error.
1171        let (s, log) = fake_modem("AT+CMUX=0,0,5,31,2,2", |_| Vec::new());
1172        s.register_dlci(1, "m#dlci=1".into());
1173        let start = Instant::now();
1174        let err = s.open_dlci(1, Duration::from_millis(1)).unwrap_err();
1175        let took = start.elapsed();
1176        assert!(err.starts_with("no UA for CMUX DLCI 1 within"), "{err}");
1177        assert!(took >= Duration::from_millis(60), "{took:?}");
1178        assert!(took < Duration::from_secs(1), "{took:?}");
1179        let sabm = |f: &DecodedFrame| f.dlci == 1 && f.kind == SABM;
1180        wait_log(&log, "3 SABM", |f| count(f, sabm) == 3);
1181        std::thread::sleep(Duration::from_millis(60));
1182        assert_eq!(
1183            count(&log.lock().unwrap(), sabm),
1184            3,
1185            "no retransmission after the error"
1186        );
1187
1188        // A modem that only answers the second SABM: open succeeds after one retry.
1189        let mut seen = 0;
1190        let (s, log) = fake_modem("AT+CMUX=0,0,5,31,2,2", move |f| {
1191            if f.kind != SABM {
1192                return Vec::new();
1193            }
1194            seen += 1;
1195            if seen == 2 {
1196                encode_frame(f.dlci, true, UA | PF, &[])
1197            } else {
1198                Vec::new()
1199            }
1200        });
1201        s.register_dlci(1, "m#dlci=1".into());
1202        s.open_dlci(1, Duration::from_millis(1)).unwrap();
1203        std::thread::sleep(Duration::from_millis(60));
1204        assert_eq!(count(&log.lock().unwrap(), sabm), 2);
1205
1206        // Without T1/N2 in the command the 4.x wait (the caller's timeout) still holds.
1207        let (s, _log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1208        let start = Instant::now();
1209        let err = s.open_dlci(0, Duration::from_millis(700)).unwrap_err();
1210        assert_eq!(err, "no UA for CMUX DLCI 0 within 700 ms");
1211        assert!(start.elapsed() >= Duration::from_millis(700));
1212    }
1213
1214    #[test]
1215    fn modem_disc_closes_only_that_channel() {
1216        let (s, log) = fake_modem("AT+CMUX=0", ua_to_sabm);
1217        s.register_dlci(1, "m#dlci=1".into());
1218        s.register_dlci(2, "m#dlci=2".into());
1219        let (old1, ev_old1) = event_sink();
1220        let (core1, ev_core1) = event_sink();
1221        let (old2, ev_old2) = event_sink();
1222        s.set_watch_with(1, old1, 0, None);
1223        assert!(s.add_core_watch(1, 7, core1, Arc::new(AtomicBool::new(true)), 0, None));
1224        s.set_watch_with(2, old2, 0, None);
1225
1226        s.feed_physical_rx(&encode_frame(1, true, DISC | PF, &[]));
1227        let frames = wait_log(&log, "UA to DISC", |f| {
1228            count(f, |f| f.dlci == 1 && f.kind == UA) == 1
1229        });
1230        let ua = frames.iter().find(|f| f.dlci == 1 && f.kind == UA).unwrap();
1231        assert!(!ua.cr, "UA is our response");
1232        assert_eq!(disconnects(&ev_old1), vec!["m#dlci=1".to_string()]);
1233        assert_eq!(disconnects(&ev_core1), vec!["m#dlci=1".to_string()]);
1234        assert!(disconnects(&ev_old2).is_empty());
1235        assert!(!s.has_dlci(1));
1236        assert!(s.has_dlci(2));
1237        assert_eq!(
1238            s.send_uih(1, b"x").unwrap_err(),
1239            "CMUX DLCI 1 closed by the modem"
1240        );
1241        assert_eq!(s.send_uih(2, b"x"), Ok(1));
1242        // Data for the closed channel goes nowhere.
1243        s.feed_physical_rx(&encode_uih(1, b"late"));
1244        assert!(!ev_old1
1245            .lock()
1246            .unwrap()
1247            .iter()
1248            .any(|e| matches!(e, SerialEvent::Data { .. })));
1249
1250        // DM on an open DLC: closed too, but no UA.
1251        s.feed_physical_rx(&encode_frame(2, true, DM | PF, &[]));
1252        assert_eq!(disconnects(&ev_old2), vec!["m#dlci=2".to_string()]);
1253        assert!(!s.has_dlci(2));
1254        // DISC on a DLC that is not open is answered with DM.
1255        s.feed_physical_rx(&encode_frame(5, true, DISC | PF, &[]));
1256        let frames = wait_log(&log, "DM to DISC", |f| {
1257            count(f, |f| f.dlci == 5 && f.kind == DM) == 1
1258        });
1259        assert_eq!(count(&frames, |f| f.kind == UA), 1, "{frames:?}");
1260
1261        // Re-opening the channel clears the closed state.
1262        s.register_dlci(1, "m#dlci=1".into());
1263        s.open_dlci(1, Duration::from_secs(1)).unwrap();
1264        assert_eq!(s.send_uih(1, b"x"), Ok(1));
1265    }
1266
1267    #[test]
1268    fn fcoff_blocks_writes_until_fcon() {
1269        let (s, log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1270        s.register_dlci(1, "m#dlci=1".into());
1271        let data = |f: &DecodedFrame| f.dlci != 0 && f.kind == UIH;
1272        let ctrl = |f: &DecodedFrame, p: &[u8]| f.dlci == 0 && f.kind == UIH && f.payload == p;
1273
1274        s.feed_physical_rx(&encode_frame(0, true, UIH, &[0x63, 0x01])); // FCoff
1275        wait_log(&log, "FCoff response", |f| {
1276            count(f, |f| ctrl(f, &[0x61, 0x01])) == 1
1277        });
1278        let bg = s.clone();
1279        let writer = std::thread::spawn(move || bg.send_uih(1, b"a"));
1280        std::thread::sleep(Duration::from_millis(100));
1281        assert!(!writer.is_finished(), "write returned during FCoff");
1282        assert_eq!(
1283            count(&log.lock().unwrap(), data),
1284            0,
1285            "data sent during FCoff"
1286        );
1287
1288        s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xA3, 0x01])); // FCon
1289        assert_eq!(writer.join().unwrap(), Ok(1));
1290        let frames = wait_log(&log, "data after FCon", |f| count(f, data) == 1);
1291        let fcon = frames.iter().position(|f| ctrl(f, &[0xA1, 0x01])).unwrap();
1292        let first = frames.iter().position(data).unwrap();
1293        assert!(fcon < first, "FCon answered first");
1294    }
1295
1296    /// FCoff for longer than the write timeout: the write fails, and nothing stale
1297    /// goes out on a later FCon (27.010 §5.4.6.3.5/6: the sender stops).
1298    #[test]
1299    fn fcoff_write_times_out_and_is_not_sent_later() {
1300        let (s, log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1301        s.register_dlci(1, "m#dlci=1".into());
1302        let data = |f: &DecodedFrame| f.dlci != 0 && f.kind == UIH;
1303        s.feed_physical_rx(&encode_frame(0, true, UIH, &[0x63, 0x01])); // FCoff
1304        let t = Instant::now();
1305        let err = s.send_uih(1, b"ATD+123;\r").unwrap_err();
1306        assert_eq!(err, "CMUX flow control off (FCoff)");
1307        assert!(
1308            t.elapsed() >= Duration::from_millis(300),
1309            "{:?}",
1310            t.elapsed()
1311        );
1312        assert!(t.elapsed() < Duration::from_secs(2), "{:?}", t.elapsed());
1313        s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xA3, 0x01])); // FCon
1314        std::thread::sleep(Duration::from_millis(100));
1315        assert_eq!(
1316            count(&log.lock().unwrap(), data),
1317            0,
1318            "stale data after FCon"
1319        );
1320    }
1321
1322    /// A write waiting on FCoff fails as soon as its channel goes away.
1323    #[test]
1324    fn fcoff_waiter_fails_when_the_channel_closes() {
1325        let (s, _log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1326        s.register_dlci(1, "m#dlci=1".into());
1327        s.feed_physical_rx(&encode_frame(0, true, UIH, &[0x63, 0x01])); // FCoff
1328        let bg = s.clone();
1329        let t = Instant::now();
1330        let writer = std::thread::spawn(move || bg.send_uih(1, b"a"));
1331        std::thread::sleep(Duration::from_millis(50));
1332        s.feed_physical_rx(&encode_frame(1, true, DISC | PF, &[]));
1333        assert_eq!(
1334            writer.join().unwrap().unwrap_err(),
1335            "CMUX DLCI 1 closed by the modem"
1336        );
1337        assert!(
1338            t.elapsed() < Duration::from_millis(250),
1339            "{:?}",
1340            t.elapsed()
1341        );
1342    }
1343
1344    /// MSC with FC=1 from the modem holds only that DLC; FC=0 releases it.
1345    #[test]
1346    fn msc_fc_bit_holds_only_that_channel() {
1347        let (s, log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1348        s.register_dlci(1, "m#dlci=1".into());
1349        s.register_dlci(2, "m#dlci=2".into());
1350        // MSC command: DLCI 1, V.24 EA|FC|RTC|RTR|DV.
1351        s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xE3, 0x05, 0x07, 0x8F]));
1352        assert_eq!(s.send_uih(2, b"b"), Ok(1));
1353        let bg = s.clone();
1354        let held = std::thread::spawn(move || bg.send_uih(1, b"a"));
1355        std::thread::sleep(Duration::from_millis(100));
1356        assert!(!held.is_finished(), "DLCI 1 not held by MSC FC");
1357        s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xE3, 0x05, 0x07, 0x8D]));
1358        assert_eq!(held.join().unwrap(), Ok(1));
1359        let data = |f: &DecodedFrame| f.dlci != 0 && f.kind == UIH;
1360        wait_log(&log, "both data frames", |f| count(f, data) == 2);
1361    }
1362
1363    /// 27.010 §5.4.6.3.8: an unknown control command is answered with NSC; the known
1364    /// ones are still echoed.
1365    #[test]
1366    fn unknown_control_command_gets_nsc() {
1367        let (s, log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1368        let ctrl = |f: &DecodedFrame, p: &[u8]| f.dlci == 0 && f.kind == UIH && f.payload == p;
1369        s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xF3, 0x01]));
1370        wait_log(&log, "NSC", |f| {
1371            count(f, |f| ctrl(f, &[0x11, 0x03, 0xF3])) == 1
1372        });
1373        s.feed_physical_rx(&encode_frame(0, true, UIH, &[0x23, 0x03, 0x55]));
1374        wait_log(&log, "TEST echo", |f| {
1375            count(f, |f| ctrl(f, &[0x21, 0x03, 0x55])) == 1
1376        });
1377    }
1378
1379    /// DISC on DLCI 0, CLD or an unsolicited DM on DLCI 0: the modem left multiplexer
1380    /// mode. Writes and opens fail, channels get `Disconnect`, the manager hook runs.
1381    #[test]
1382    fn modem_leaving_mux_kills_the_session() {
1383        for leave in [
1384            encode_frame(0, true, DISC | PF, &[]),
1385            encode_frame(0, true, UIH, &[CLD_CMD, 0x01]),
1386            encode_frame(0, true, DM | PF, &[]),
1387        ] {
1388            let (s, _log) = fake_modem("AT+CMUX=0", ua_to_sabm);
1389            let hook: HookLog = Arc::default();
1390            let seen = hook.clone();
1391            s.set_on_closed(Box::new(
1392                move |paths: &[String], _reason: &str, whole: bool| {
1393                    seen.lock().unwrap().push((paths.to_vec(), whole));
1394                },
1395            ));
1396            s.register_dlci(1, "m#dlci=1".into());
1397            let (old, events) = event_sink();
1398            s.set_watch_with(1, old, 0, None);
1399            s.feed_physical_rx(&leave);
1400            assert_eq!(disconnects(&events), vec!["m#dlci=1".to_string()]);
1401            assert_eq!(
1402                hook.lock().unwrap().as_slice(),
1403                [(vec!["m#dlci=1".to_string()], true)]
1404            );
1405            s.register_dlci(2, "m#dlci=2".into());
1406            assert!(s.send_uih(2, b"AT\r").is_err(), "write on a dead mux");
1407            assert!(s.open_dlci(2, Duration::from_millis(100)).is_err());
1408        }
1409    }
1410
1411    /// `AT+CMUX` without T1 / N2: one SABM, the whole timeout for its UA (4.x).
1412    #[test]
1413    fn default_command_sends_a_single_sabm() {
1414        let (s, log) = fake_modem("AT+CMUX=0", |f| {
1415            if f.kind == SABM {
1416                std::thread::sleep(Duration::from_millis(250));
1417            }
1418            ua_to_sabm(f)
1419        });
1420        s.register_dlci(1, "m#dlci=1".into());
1421        s.open_dlci(1, Duration::from_secs(2)).unwrap();
1422        std::thread::sleep(Duration::from_millis(100));
1423        assert_eq!(count(&log.lock().unwrap(), |f| f.kind == SABM), 1);
1424    }
1425
1426    #[test]
1427    fn close_down_waits_for_the_cld_response() {
1428        let cld = |f: &DecodedFrame| f.dlci == 0 && f.kind == UIH && f.payload == [0xC3, 0x01];
1429        // T2 = 50 (500 ms); the modem answers after 100 ms.
1430        let (s, _log) = fake_modem("AT+CMUX=0,0,5,31,10,3,50", move |f| {
1431            if cld(f) {
1432                std::thread::sleep(Duration::from_millis(100));
1433                encode_frame(0, true, UIH, &[0xC1, 0x01])
1434            } else {
1435                Vec::new()
1436            }
1437        });
1438        let start = Instant::now();
1439        s.close_down();
1440        let took = start.elapsed();
1441        assert!(
1442            took >= Duration::from_millis(100),
1443            "returned before the response: {took:?}"
1444        );
1445        assert!(
1446            took < Duration::from_millis(450),
1447            "missed the response: {took:?}"
1448        );
1449
1450        // No response: close_down gives up after T2 (5 = 50 ms).
1451        let (s, log) = fake_modem("AT+CMUX=0,0,5,31,10,3,5", |_| Vec::new());
1452        let start = Instant::now();
1453        s.close_down();
1454        let took = start.elapsed();
1455        assert!(took >= Duration::from_millis(50), "{took:?}");
1456        assert!(took < Duration::from_secs(1), "{took:?}");
1457        wait_log(&log, "CLD", |f| count(f, cld) == 1);
1458    }
1459}