1use 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
17pub struct DlciChannel {
19 pub path: String,
20 pub exchange_waiter: Mutex<Option<Arc<ExchangeWaiter>>>,
21 watches: Mutex<DlciWatches>,
22 outbox: Arc<Outbox>,
25}
26
27#[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 framer: Option<Box<dyn Framer>>,
48 buffer: Vec<u8>,
49 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 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 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 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 #[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 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 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 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 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 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 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
223fn 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
236pub fn cmux_n1(command: &str) -> usize {
239 cmux_param(command, 3).map_or(31, |n1| n1 as usize)
240}
241
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244pub struct CmuxTimers {
245 pub t1: Duration,
247 pub n2: u32,
249 pub t2: Duration,
251}
252
253impl Default for CmuxTimers {
254 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 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
291const 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;
303const NSC_RSP: u8 = 0x11;
305const ECHOED: [u8; 9] = [
307 PN_CMD, PSC_CMD, TEST_CMD, MSC_CMD, RPN_CMD, RLS_CMD, FCON_CMD, FCOFF_CMD, CLD_CMD,
308];
309const V24_READY: u8 = 0x8D;
311const V24_FC: u8 = 0x02;
313
314#[derive(Default)]
317struct TxGate {
318 fc_off: bool,
319 held_dlcis: HashSet<u8>,
320}
321
322pub(crate) type ClosedHook = Box<dyn Fn(&[String], &str, bool) + Send + Sync>;
325
326pub struct CmuxSession {
328 physical_path: String,
329 io: Arc<dyn CmuxPhysicalIo>,
330 deframer: Mutex<Deframer>,
331 channels: Mutex<HashMap<u8, Arc<DlciChannel>>>,
332 pending_open: Mutex<HashMap<u8, mpsc::Sender<bool>>>,
334 pending_cld: Mutex<Option<mpsc::Sender<()>>>,
336 closed: Mutex<HashSet<u8>>,
338 tx: Mutex<TxGate>,
339 tx_cv: Condvar,
340 dead: Mutex<Option<String>>,
342 on_closed: OnceLock<ClosedHook>,
343 timers: CmuxTimers,
344 outbox: Arc<Outbox>,
345}
346
347impl CmuxSession {
348 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 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 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 pub(crate) fn set_on_closed(&self, hook: ClosedHook) {
411 let _ = self.on_closed.set(hook);
412 }
413
414 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 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 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 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 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 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 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 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 #[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 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 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 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 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 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 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 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 self.closed_by_modem(frame.dlci);
743 }
744 return;
745 }
746 DISC => {
747 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 _ => 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 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 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 #[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 #[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 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 fn write_timeout(&self, _len: usize) -> Duration {
1028 Duration::from_millis(300)
1029 }
1030 }
1031
1032 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 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 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 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 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 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 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 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 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 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 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 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])); 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])); 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 #[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])); 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])); 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 #[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])); 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 #[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 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 #[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 #[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 #[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 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 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}