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(test)]
832#[cfg(not(target_os = "android"))]
833mod tests {
834 use super::*;
835 use crate::events::{AtResultFormat, ExchangeCompletionMode, RxPrepareMode};
836 use crate::exchange::options::ResolvedExchangeOptions;
837 use crate::hub::ExchangeWaiter;
838 use std::sync::atomic::AtomicBool;
839
840 fn test_options() -> ResolvedExchangeOptions {
841 ResolvedExchangeOptions {
842 timeout_ms: 3000,
843 max_bytes: 4096,
844 terminators: vec![],
845 idle_ms: None,
846 rx_prepare: RxPrepareMode::None,
847 drain_idle_ms: 50,
848 drain_max_ms: 200,
849 completion_mode: ExchangeCompletionMode::AtFinalLine,
850 result_format: AtResultFormat::Verbose,
851 command: Some("AT".into()),
852 solicited_prefixes: vec![],
853 }
854 }
855
856 #[cfg(unix)]
857 #[test]
858 fn feed_physical_rx_routes_to_exchange_waiter() {
859 use crate::cmux::SerialPortIo;
860 use crate::sync_util::pty_pair_locked;
861 use serialport::SerialPort;
862 let (_pty, port, _master) = pty_pair_locked();
863 let session = CmuxSession::with_n1(
864 "pty".into(),
865 Arc::new(SerialPortIo(Arc::new(Mutex::new(
866 Box::new(port) as Box<dyn SerialPort>
867 )))),
868 31,
869 );
870 session.register_dlci(2, "pty#dlci=2".into());
871 let cancel = Arc::new(AtomicBool::new(false));
872 let waiter = ExchangeWaiter::new(test_options(), cancel);
873 session.set_exchange_waiter(2, waiter.clone());
874 let payload = b"AT\r\r\nOK\r\n";
875 let frame = encode_uih(2, payload);
876 session.feed_physical_rx(&frame);
877 let (raw, matched) = waiter.wait(1000).expect("complete");
878 assert!(String::from_utf8_lossy(&raw).contains("OK"));
879 assert!(matches!(matched, crate::at::parse::ExchangeMatch::Ok));
880 }
881
882 #[test]
883 fn cancel_active_exchange_fails_waiter_quickly() {
884 use crate::cmux::io::CmuxPhysicalIo;
885 struct NoopIo;
886 impl CmuxPhysicalIo for NoopIo {
887 fn write_all(&self, _data: &[u8]) -> Result<(), String> {
888 Ok(())
889 }
890 }
891 let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), 31);
892 session.register_dlci(2, "mock#dlci=2".into());
893 let cancel = Arc::new(AtomicBool::new(false));
894 let waiter = ExchangeWaiter::new(test_options(), cancel);
895 session.set_exchange_waiter(2, waiter.clone());
896 let waiter_bg = waiter.clone();
897 let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
898 let done_bg = done.clone();
899 std::thread::spawn(move || {
900 let _ = waiter_bg.wait(5000);
901 done_bg.store(true, std::sync::atomic::Ordering::SeqCst);
902 });
903 std::thread::sleep(std::time::Duration::from_millis(20));
904 let start = std::time::Instant::now();
905 session.cancel_active_exchange(2);
906 while !done.load(std::sync::atomic::Ordering::SeqCst)
907 && start.elapsed() < std::time::Duration::from_millis(500)
908 {
909 std::thread::sleep(std::time::Duration::from_millis(5));
910 }
911 assert!(done.load(std::sync::atomic::Ordering::SeqCst));
912 assert!(start.elapsed() < std::time::Duration::from_millis(500));
913 }
914
915 #[test]
916 fn dlci_watch_parser_emits_one_event_per_frame() {
917 use crate::cmux::io::CmuxPhysicalIo;
918 use serial_codec::framing::FramerConfig;
919 struct NoopIo;
920 impl CmuxPhysicalIo for NoopIo {
921 fn write_all(&self, _data: &[u8]) -> Result<(), String> {
922 Ok(())
923 }
924 }
925 let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), 31);
926 session.register_dlci(2, "mock#dlci=2".into());
927 let frames = Arc::new(Mutex::new(Vec::new()));
928 let sink = frames.clone();
929 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
930 if let SerialEvent::Data { data, .. } = event {
931 sink.lock().unwrap().push(data);
932 }
933 true
934 });
935 let cfg: FramerConfig =
936 serde_json::from_value(serde_json::json!({"type": "readline"})).unwrap();
937 session.set_watch_with(2, channel, 10_000, Some(cfg.build().unwrap()));
938 session.feed_physical_rx(&encode_uih(2, b"one\ntw"));
939 session.feed_physical_rx(&encode_uih(2, b"o\nthr"));
940 assert_eq!(
941 *frames.lock().unwrap(),
942 vec![b"one".to_vec(), b"two".to_vec()]
943 );
944 session.clear_watch(2);
945 assert_eq!(frames.lock().unwrap().last().unwrap(), b"thr");
946 }
947
948 struct NoopIo;
949 impl crate::cmux::io::CmuxPhysicalIo for NoopIo {
950 fn write_all(&self, _data: &[u8]) -> Result<(), String> {
951 Ok(())
952 }
953 }
954
955 #[test]
958 fn clear_watch_remainder_sink_may_call_back_into_session() {
959 use serial_codec::framing::FramerConfig;
960 let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), 31);
961 session.register_dlci(2, "mock#dlci=2".into());
962 let weak = Arc::downgrade(&session);
963 let (tx, rx) = mpsc::channel();
964 let tx = Mutex::new(tx);
965 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
966 if let SerialEvent::Data { data, .. } = event {
967 let known = weak.upgrade().is_some_and(|s| s.has_dlci(2));
968 let _ = tx.lock().unwrap().send((data, known));
969 }
970 true
971 });
972 let cfg: FramerConfig =
973 serde_json::from_value(serde_json::json!({"type": "readline"})).unwrap();
974 session.set_watch_with(2, channel, 10_000, Some(cfg.build().unwrap()));
975 session.feed_physical_rx(&encode_uih(2, b"partial"));
976 let bg = session.clone();
977 std::thread::spawn(move || bg.clear_watch(2));
978 let (data, known) = rx
979 .recv_timeout(Duration::from_secs(3))
980 .expect("clear_watch deadlocked: sink ran under the channels lock");
981 assert_eq!(data, b"partial");
982 assert!(known);
983 }
984
985 #[test]
986 fn n1_is_the_fourth_cmux_parameter() {
987 assert_eq!(cmux_n1("AT+CMUX=0,0,5,2048"), 2048);
988 assert_eq!(cmux_n1("at+cmux=0,0,5,127,10,3,30,10,2"), 127);
989 assert_eq!(cmux_n1("AT+CMUX=0"), 31);
990 assert_eq!(cmux_n1("AT+CMUX=0,0,,"), 31);
991 assert_eq!(cmux_n1("AT+CMUX=0,0,5, 1600 ,10"), 1600);
992 assert_eq!(cmux_n1("AT"), 31);
993 }
994
995 #[test]
998 fn session_accepts_frames_up_to_negotiated_n1() {
999 let n1 = cmux_n1("AT+CMUX=0,0,5,2048");
1000 let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), n1);
1001 session.register_dlci(1, "mock#dlci=1".into());
1002 let got = Arc::new(Mutex::new(0usize));
1003 let sink = got.clone();
1004 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
1005 if let SerialEvent::Data { size, .. } = event {
1006 *sink.lock().unwrap() += size;
1007 }
1008 true
1009 });
1010 session.set_watch_with(1, channel, 0, None);
1011 let frame = encode_frame(1, true, UIH, &[b'A'; 2000]);
1012 session.feed_physical_rx(&frame);
1013 assert_eq!(*got.lock().unwrap(), 2000, "2000-byte frame dropped");
1014 }
1015
1016 type Log = Arc<Mutex<Vec<DecodedFrame>>>;
1019 type HookLog = Arc<Mutex<Vec<(Vec<String>, bool)>>>;
1020 type Events = Arc<Mutex<Vec<SerialEvent>>>;
1021
1022 struct FakeIo(Mutex<mpsc::Sender<Vec<u8>>>);
1023 impl crate::cmux::io::CmuxPhysicalIo for FakeIo {
1024 fn write_all(&self, data: &[u8]) -> Result<(), String> {
1025 let _ = self.0.lock().unwrap().send(data.to_vec());
1026 Ok(())
1027 }
1028 fn write_timeout(&self, _len: usize) -> Duration {
1030 Duration::from_millis(300)
1031 }
1032 }
1033
1034 fn fake_modem(
1037 command: &str,
1038 mut reply: impl FnMut(&DecodedFrame) -> Vec<u8> + Send + 'static,
1039 ) -> (Arc<CmuxSession>, Log) {
1040 let (tx, rx) = mpsc::channel::<Vec<u8>>();
1041 let session =
1042 CmuxSession::for_command("m".into(), Arc::new(FakeIo(Mutex::new(tx))), command);
1043 let weak = Arc::downgrade(&session);
1044 let log: Log = Arc::default();
1045 let seen = log.clone();
1046 std::thread::spawn(move || {
1047 let mut deframer = Deframer::default();
1048 for bytes in rx {
1049 for f in deframer.feed(&bytes) {
1050 let out = reply(&f);
1051 seen.lock().unwrap().push(f);
1052 if let (false, Some(s)) = (out.is_empty(), weak.upgrade()) {
1053 s.feed_physical_rx(&out);
1054 }
1055 }
1056 }
1057 });
1058 (session, log)
1059 }
1060
1061 fn ua_to_sabm(f: &DecodedFrame) -> Vec<u8> {
1062 if f.kind == SABM {
1063 encode_frame(f.dlci, true, UA | PF, &[])
1064 } else {
1065 Vec::new()
1066 }
1067 }
1068
1069 fn wait_log(
1070 log: &Log,
1071 what: &str,
1072 pred: impl Fn(&[DecodedFrame]) -> bool,
1073 ) -> Vec<DecodedFrame> {
1074 let start = Instant::now();
1075 loop {
1076 let frames = log.lock().unwrap().clone();
1077 if pred(&frames) {
1078 return frames;
1079 }
1080 assert!(
1081 start.elapsed() < Duration::from_secs(3),
1082 "timed out: {what}: {frames:?}"
1083 );
1084 std::thread::sleep(Duration::from_millis(5));
1085 }
1086 }
1087
1088 fn count(frames: &[DecodedFrame], pred: impl Fn(&DecodedFrame) -> bool) -> usize {
1089 frames.iter().filter(|f| pred(f)).count()
1090 }
1091
1092 fn event_sink() -> (crate::events::EventSink, Events) {
1093 let events: Events = Arc::default();
1094 let sink = events.clone();
1095 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
1096 sink.lock().unwrap().push(event);
1097 true
1098 });
1099 (channel, events)
1100 }
1101
1102 fn disconnects(events: &Events) -> Vec<String> {
1103 events
1104 .lock()
1105 .unwrap()
1106 .iter()
1107 .filter_map(|e| match e {
1108 SerialEvent::Disconnect { path, .. } => Some(path.clone()),
1109 _ => None,
1110 })
1111 .collect()
1112 }
1113
1114 #[test]
1115 fn cmux_timers_from_command_parameters() {
1116 let ms = Duration::from_millis;
1117 let default = CmuxTimers::default();
1118 assert_eq!((default.t1, default.n2, default.t2), (ms(100), 3, ms(300)));
1119 let single = CmuxTimers { n2: 0, ..default };
1121 assert_eq!(CmuxTimers::from_command("AT+CMUX=0"), single);
1122 assert_eq!(CmuxTimers::from_command("AT"), single);
1123 let t = CmuxTimers::from_command("AT+CMUX=0,0,5,31,10,2");
1124 assert_eq!((t.t1, t.n2, t.t2), (ms(100), 2, ms(300)));
1125 let t = CmuxTimers::from_command("at+cmux=0,0,5,127,25, 5 ,40,10,2");
1126 assert_eq!((t.t1, t.n2, t.t2), (ms(250), 5, ms(400)));
1127 let t = CmuxTimers::from_command("AT+CMUX=0,0,5,31,0,101,1");
1129 assert_eq!(t, default);
1130 assert_eq!(CmuxTimers::from_command("AT+CMUX=0,0,5,31,,0").n2, 0);
1131 assert_eq!(CmuxTimers::from_command("AT+CMUX=0,0,5,31,10").n2, 3);
1133 let s = CmuxSession::new("p".into(), Arc::new(NoopIo));
1135 assert_eq!(s.timers.n2, 0);
1136 assert_eq!(s.timers.t1, default.t1);
1137 assert_eq!(s.physical_path(), "p");
1138 }
1139
1140 fn data_of(events: &Events) -> Vec<Vec<u8>> {
1141 events
1142 .lock()
1143 .unwrap()
1144 .iter()
1145 .filter_map(|e| match e {
1146 SerialEvent::Data { data, .. } => Some(data.clone()),
1147 _ => None,
1148 })
1149 .collect()
1150 }
1151
1152 #[test]
1153 fn batch_waits_for_its_window_and_empty_ticks_send_nothing() {
1154 let s = CmuxSession::with_n1("m".into(), Arc::new(NoopIo), 31);
1155 s.register_dlci(1, "m#dlci=1".into());
1156 s.register_dlci(2, "m#dlci=2".into());
1157 let (slow, slow_ev) = event_sink();
1158 let (fast, fast_ev) = event_sink();
1159 s.set_watch_with(1, slow, 10_000, None);
1160 s.set_watch_with(2, fast, 0, None);
1161 s.tick();
1162 assert!(fast_ev.lock().unwrap().is_empty(), "empty batch sent");
1163 s.feed_physical_rx(&encode_uih(1, b"held"));
1164 s.feed_physical_rx(&encode_uih(2, b"now"));
1165 s.tick();
1166 assert!(
1167 slow_ev.lock().unwrap().is_empty(),
1168 "batch sent before its window"
1169 );
1170 assert_eq!(data_of(&fast_ev), vec![b"now".to_vec()]);
1171 }
1172
1173 #[test]
1174 fn dead_core_watch_gets_nothing() {
1175 let s = CmuxSession::with_n1("m".into(), Arc::new(NoopIo), 31);
1176 s.register_dlci(1, "m#dlci=1".into());
1177 let (sink, events) = event_sink();
1178 assert!(s.add_core_watch(1, 3, sink, Arc::new(AtomicBool::new(false)), 0, None));
1179 s.feed_physical_rx(&encode_uih(1, b"x"));
1180 s.tick();
1181 assert!(events.lock().unwrap().is_empty());
1182 }
1183
1184 #[test]
1185 fn remove_core_watch_takes_only_that_stream() {
1186 let s = CmuxSession::with_n1("m".into(), Arc::new(NoopIo), 31);
1187 s.register_dlci(1, "m#dlci=1".into());
1188 let (a, a_ev) = event_sink();
1189 let (b, b_ev) = event_sink();
1190 let alive = || Arc::new(AtomicBool::new(true));
1191 assert!(s.add_core_watch(1, 7, a, alive(), 10_000, None));
1192 assert!(s.add_core_watch(1, 8, b, alive(), 10_000, None));
1193 s.feed_physical_rx(&encode_uih(1, b"abc"));
1194 assert!(s.remove_core_watch(1, 8));
1195 assert_eq!(data_of(&b_ev), vec![b"abc".to_vec()], "remainder of 8");
1196 assert!(a_ev.lock().unwrap().is_empty(), "7 is still running");
1197 assert!(s.remove_core_watch(1, 7));
1198 assert_eq!(data_of(&a_ev), vec![b"abc".to_vec()]);
1199 assert!(!s.remove_core_watch(1, 7));
1200 assert!(!s.remove_core_watch(5, 7));
1201 assert!(!s.add_core_watch(5, 9, event_sink().0, alive(), 0, None));
1202 }
1203
1204 #[test]
1205 fn cleared_waiter_leaves_data_to_the_watch() {
1206 let s = CmuxSession::with_n1("m".into(), Arc::new(NoopIo), 31);
1207 s.register_dlci(2, "m#dlci=2".into());
1208 let (sink, events) = event_sink();
1209 s.set_watch_with(2, sink, 0, None);
1210 let waiter = ExchangeWaiter::new(test_options(), Arc::new(AtomicBool::new(false)));
1211 s.set_exchange_waiter(2, waiter.clone());
1212 s.clear_exchange_waiter(2);
1213 s.feed_physical_rx(&encode_uih(2, b"AT\r\r\nOK\r\n"));
1214 assert_eq!(data_of(&events), vec![b"AT\r\r\nOK\r\n".to_vec()]);
1215 assert!(waiter.wait(10).is_err(), "the cleared waiter got the reply");
1216 }
1217
1218 #[test]
1219 fn unregister_sends_disc_and_forgets_the_channel() {
1220 let (s, log) = fake_modem("AT+CMUX=0", |f| {
1221 if f.kind == DISC {
1222 encode_frame(f.dlci, true, UA | PF, &[])
1223 } else {
1224 Vec::new()
1225 }
1226 });
1227 s.register_dlci(1, "m#dlci=1".into());
1228 s.unregister_dlci(1);
1229 assert!(!s.has_dlci(1));
1230 wait_log(&log, "DISC", |f| {
1231 count(f, |f| f.dlci == 1 && f.kind == DISC) == 1
1232 });
1233 }
1234
1235 #[test]
1236 fn closed_hook_names_the_channel_or_the_multiplexer() {
1237 let (s, _log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1238 let reasons: Arc<Mutex<Vec<(String, bool)>>> = Arc::default();
1239 let seen = reasons.clone();
1240 s.set_on_closed(Box::new(
1241 move |_paths: &[String], reason: &str, whole: bool| {
1242 seen.lock().unwrap().push((reason.to_string(), whole));
1243 },
1244 ));
1245 s.register_dlci(1, "m#dlci=1".into());
1246 s.feed_physical_rx(&encode_frame(1, true, DISC | PF, &[]));
1247 s.feed_physical_rx(&encode_frame(0, true, DISC | PF, &[]));
1248 assert_eq!(
1249 reasons.lock().unwrap().as_slice(),
1250 [
1251 ("CMUX DLCI 1 closed by the modem".to_string(), false),
1252 ("CMUX multiplexer closed by the modem".to_string(), true),
1253 ]
1254 );
1255 }
1256
1257 #[test]
1258 fn msc_follows_ua_on_each_data_dlci() {
1259 let (s, log) = fake_modem("AT+CMUX=0", ua_to_sabm);
1260 s.open_dlci(0, Duration::from_secs(1)).unwrap();
1261 s.register_dlci(1, "m#dlci=1".into());
1262 s.open_dlci(1, Duration::from_secs(1)).unwrap();
1263 let ctrl = |f: &DecodedFrame| f.dlci == 0 && f.kind == UIH;
1264 let frames = wait_log(&log, "MSC", |f| count(f, ctrl) >= 1);
1265 let msc: Vec<_> = frames.iter().filter(|f| ctrl(f)).collect();
1266 assert_eq!(msc[0].payload, vec![0xE3, 0x05, 0x07, 0x8D]);
1268 assert!(msc[0].cr, "MSC is our command");
1269 let sabm1 = frames
1270 .iter()
1271 .position(|f| f.dlci == 1 && f.kind == SABM)
1272 .unwrap();
1273 let msc_at = frames.iter().position(ctrl).unwrap();
1274 assert!(sabm1 < msc_at, "MSC after the DLC is established");
1275
1276 s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xE3, 0x05, 0x07, 0x8D]));
1278 s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xE1, 0x05, 0x07, 0x8D]));
1279 wait_log(&log, "MSC response", |f| count(f, ctrl) >= 2);
1280 std::thread::sleep(Duration::from_millis(50));
1281 let frames = log.lock().unwrap().clone();
1282 let ctrl_payloads: Vec<_> = frames
1283 .iter()
1284 .filter(|f| ctrl(f))
1285 .map(|f| f.payload.clone())
1286 .collect();
1287 assert_eq!(
1288 ctrl_payloads,
1289 vec![vec![0xE3, 0x05, 0x07, 0x8D], vec![0xE1, 0x05, 0x07, 0x8D]],
1290 "one MSC of ours (none for DLCI 0), one response to the modem's"
1291 );
1292 }
1293
1294 #[test]
1295 fn sabm_retried_n2_times_with_t1_then_error() {
1296 let (s, log) = fake_modem("AT+CMUX=0,0,5,31,2,2", |_| Vec::new());
1298 s.register_dlci(1, "m#dlci=1".into());
1299 let start = Instant::now();
1300 let err = s.open_dlci(1, Duration::from_millis(1)).unwrap_err();
1301 let took = start.elapsed();
1302 assert!(err.starts_with("no UA for CMUX DLCI 1 within"), "{err}");
1303 assert!(took >= Duration::from_millis(60), "{took:?}");
1304 assert!(took < Duration::from_secs(1), "{took:?}");
1305 let sabm = |f: &DecodedFrame| f.dlci == 1 && f.kind == SABM;
1306 wait_log(&log, "3 SABM", |f| count(f, sabm) == 3);
1307 std::thread::sleep(Duration::from_millis(60));
1308 assert_eq!(
1309 count(&log.lock().unwrap(), sabm),
1310 3,
1311 "no retransmission after the error"
1312 );
1313
1314 let mut seen = 0;
1316 let (s, log) = fake_modem("AT+CMUX=0,0,5,31,2,2", move |f| {
1317 if f.kind != SABM {
1318 return Vec::new();
1319 }
1320 seen += 1;
1321 if seen == 2 {
1322 encode_frame(f.dlci, true, UA | PF, &[])
1323 } else {
1324 Vec::new()
1325 }
1326 });
1327 s.register_dlci(1, "m#dlci=1".into());
1328 s.open_dlci(1, Duration::from_millis(1)).unwrap();
1329 std::thread::sleep(Duration::from_millis(60));
1330 assert_eq!(count(&log.lock().unwrap(), sabm), 2);
1331
1332 let (s, _log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1334 let start = Instant::now();
1335 let err = s.open_dlci(0, Duration::from_millis(200)).unwrap_err();
1336 assert_eq!(err, "no UA for CMUX DLCI 0 within 200 ms");
1337 assert!(start.elapsed() >= Duration::from_millis(200));
1338 }
1339
1340 #[test]
1341 fn modem_disc_closes_only_that_channel() {
1342 let (s, log) = fake_modem("AT+CMUX=0", ua_to_sabm);
1343 s.register_dlci(1, "m#dlci=1".into());
1344 s.register_dlci(2, "m#dlci=2".into());
1345 let (old1, ev_old1) = event_sink();
1346 let (core1, ev_core1) = event_sink();
1347 let (old2, ev_old2) = event_sink();
1348 s.set_watch_with(1, old1, 0, None);
1349 assert!(s.add_core_watch(1, 7, core1, Arc::new(AtomicBool::new(true)), 0, None));
1350 s.set_watch_with(2, old2, 0, None);
1351
1352 s.feed_physical_rx(&encode_frame(1, true, DISC | PF, &[]));
1353 let frames = wait_log(&log, "UA to DISC", |f| {
1354 count(f, |f| f.dlci == 1 && f.kind == UA) == 1
1355 });
1356 let ua = frames.iter().find(|f| f.dlci == 1 && f.kind == UA).unwrap();
1357 assert!(!ua.cr, "UA is our response");
1358 assert_eq!(disconnects(&ev_old1), vec!["m#dlci=1".to_string()]);
1359 assert_eq!(disconnects(&ev_core1), vec!["m#dlci=1".to_string()]);
1360 assert!(disconnects(&ev_old2).is_empty());
1361 assert!(!s.has_dlci(1));
1362 assert!(s.has_dlci(2));
1363 assert_eq!(
1364 s.send_uih(1, b"x").unwrap_err(),
1365 "CMUX DLCI 1 closed by the modem"
1366 );
1367 assert_eq!(s.send_uih(2, b"x"), Ok(1));
1368 s.feed_physical_rx(&encode_uih(1, b"late"));
1370 assert!(!ev_old1
1371 .lock()
1372 .unwrap()
1373 .iter()
1374 .any(|e| matches!(e, SerialEvent::Data { .. })));
1375
1376 s.feed_physical_rx(&encode_frame(2, true, DM | PF, &[]));
1378 assert_eq!(disconnects(&ev_old2), vec!["m#dlci=2".to_string()]);
1379 assert!(!s.has_dlci(2));
1380 s.feed_physical_rx(&encode_frame(5, true, DISC | PF, &[]));
1382 let frames = wait_log(&log, "DM to DISC", |f| {
1383 count(f, |f| f.dlci == 5 && f.kind == DM) == 1
1384 });
1385 assert_eq!(count(&frames, |f| f.kind == UA), 1, "{frames:?}");
1386
1387 s.register_dlci(1, "m#dlci=1".into());
1389 s.open_dlci(1, Duration::from_secs(1)).unwrap();
1390 assert_eq!(s.send_uih(1, b"x"), Ok(1));
1391 }
1392
1393 #[test]
1394 fn fcoff_blocks_writes_until_fcon() {
1395 let (s, log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1396 s.register_dlci(1, "m#dlci=1".into());
1397 let data = |f: &DecodedFrame| f.dlci != 0 && f.kind == UIH;
1398 let ctrl = |f: &DecodedFrame, p: &[u8]| f.dlci == 0 && f.kind == UIH && f.payload == p;
1399
1400 s.feed_physical_rx(&encode_frame(0, true, UIH, &[0x63, 0x01])); wait_log(&log, "FCoff response", |f| {
1402 count(f, |f| ctrl(f, &[0x61, 0x01])) == 1
1403 });
1404 let bg = s.clone();
1405 let writer = std::thread::spawn(move || bg.send_uih(1, b"a"));
1406 std::thread::sleep(Duration::from_millis(100));
1407 assert!(!writer.is_finished(), "write returned during FCoff");
1408 assert_eq!(
1409 count(&log.lock().unwrap(), data),
1410 0,
1411 "data sent during FCoff"
1412 );
1413
1414 s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xA3, 0x01])); assert_eq!(writer.join().unwrap(), Ok(1));
1416 let frames = wait_log(&log, "data after FCon", |f| count(f, data) == 1);
1417 let fcon = frames.iter().position(|f| ctrl(f, &[0xA1, 0x01])).unwrap();
1418 let first = frames.iter().position(data).unwrap();
1419 assert!(fcon < first, "FCon answered first");
1420 }
1421
1422 #[test]
1425 fn fcoff_write_times_out_and_is_not_sent_later() {
1426 let (s, log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1427 s.register_dlci(1, "m#dlci=1".into());
1428 let data = |f: &DecodedFrame| f.dlci != 0 && f.kind == UIH;
1429 s.feed_physical_rx(&encode_frame(0, true, UIH, &[0x63, 0x01])); let t = Instant::now();
1431 let err = s.send_uih(1, b"ATD+123;\r").unwrap_err();
1432 assert_eq!(err, "CMUX flow control off (FCoff)");
1433 assert!(
1434 t.elapsed() >= Duration::from_millis(300),
1435 "{:?}",
1436 t.elapsed()
1437 );
1438 assert!(t.elapsed() < Duration::from_secs(2), "{:?}", t.elapsed());
1439 s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xA3, 0x01])); std::thread::sleep(Duration::from_millis(100));
1441 assert_eq!(
1442 count(&log.lock().unwrap(), data),
1443 0,
1444 "stale data after FCon"
1445 );
1446 }
1447
1448 #[test]
1450 fn fcoff_waiter_fails_when_the_channel_closes() {
1451 let (s, _log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1452 s.register_dlci(1, "m#dlci=1".into());
1453 s.feed_physical_rx(&encode_frame(0, true, UIH, &[0x63, 0x01])); let bg = s.clone();
1455 let t = Instant::now();
1456 let writer = std::thread::spawn(move || bg.send_uih(1, b"a"));
1457 std::thread::sleep(Duration::from_millis(50));
1458 s.feed_physical_rx(&encode_frame(1, true, DISC | PF, &[]));
1459 assert_eq!(
1460 writer.join().unwrap().unwrap_err(),
1461 "CMUX DLCI 1 closed by the modem"
1462 );
1463 assert!(
1464 t.elapsed() < Duration::from_millis(250),
1465 "{:?}",
1466 t.elapsed()
1467 );
1468 }
1469
1470 #[test]
1472 fn msc_fc_bit_holds_only_that_channel() {
1473 let (s, log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1474 s.register_dlci(1, "m#dlci=1".into());
1475 s.register_dlci(2, "m#dlci=2".into());
1476 s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xE3, 0x05, 0x07, 0x8F]));
1478 assert_eq!(s.send_uih(2, b"b"), Ok(1));
1479 let bg = s.clone();
1480 let held = std::thread::spawn(move || bg.send_uih(1, b"a"));
1481 std::thread::sleep(Duration::from_millis(100));
1482 assert!(!held.is_finished(), "DLCI 1 not held by MSC FC");
1483 s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xE3, 0x05, 0x07, 0x8D]));
1484 assert_eq!(held.join().unwrap(), Ok(1));
1485 let data = |f: &DecodedFrame| f.dlci != 0 && f.kind == UIH;
1486 wait_log(&log, "both data frames", |f| count(f, data) == 2);
1487 }
1488
1489 #[test]
1492 fn unknown_control_command_gets_nsc() {
1493 let (s, log) = fake_modem("AT+CMUX=0", |_| Vec::new());
1494 let ctrl = |f: &DecodedFrame, p: &[u8]| f.dlci == 0 && f.kind == UIH && f.payload == p;
1495 s.feed_physical_rx(&encode_frame(0, true, UIH, &[0xF3, 0x01]));
1496 wait_log(&log, "NSC", |f| {
1497 count(f, |f| ctrl(f, &[0x11, 0x03, 0xF3])) == 1
1498 });
1499 s.feed_physical_rx(&encode_frame(0, true, UIH, &[0x23, 0x03, 0x55]));
1500 wait_log(&log, "TEST echo", |f| {
1501 count(f, |f| ctrl(f, &[0x21, 0x03, 0x55])) == 1
1502 });
1503 }
1504
1505 #[test]
1508 fn modem_leaving_mux_kills_the_session() {
1509 for leave in [
1510 encode_frame(0, true, DISC | PF, &[]),
1511 encode_frame(0, true, UIH, &[CLD_CMD, 0x01]),
1512 encode_frame(0, true, DM | PF, &[]),
1513 ] {
1514 let (s, _log) = fake_modem("AT+CMUX=0", ua_to_sabm);
1515 let hook: HookLog = Arc::default();
1516 let seen = hook.clone();
1517 s.set_on_closed(Box::new(
1518 move |paths: &[String], _reason: &str, whole: bool| {
1519 seen.lock().unwrap().push((paths.to_vec(), whole));
1520 },
1521 ));
1522 s.register_dlci(1, "m#dlci=1".into());
1523 let (old, events) = event_sink();
1524 s.set_watch_with(1, old, 0, None);
1525 s.feed_physical_rx(&leave);
1526 assert_eq!(disconnects(&events), vec!["m#dlci=1".to_string()]);
1527 assert_eq!(
1528 hook.lock().unwrap().as_slice(),
1529 [(vec!["m#dlci=1".to_string()], true)]
1530 );
1531 s.register_dlci(2, "m#dlci=2".into());
1532 assert!(s.send_uih(2, b"AT\r").is_err(), "write on a dead mux");
1533 assert!(s.open_dlci(2, Duration::from_millis(100)).is_err());
1534 }
1535 }
1536
1537 #[test]
1539 fn default_command_sends_a_single_sabm() {
1540 let (s, log) = fake_modem("AT+CMUX=0", |f| {
1541 if f.kind == SABM {
1542 std::thread::sleep(Duration::from_millis(250));
1543 }
1544 ua_to_sabm(f)
1545 });
1546 s.register_dlci(1, "m#dlci=1".into());
1547 s.open_dlci(1, Duration::from_secs(2)).unwrap();
1548 std::thread::sleep(Duration::from_millis(100));
1549 assert_eq!(count(&log.lock().unwrap(), |f| f.kind == SABM), 1);
1550 }
1551
1552 #[test]
1553 fn close_down_waits_for_the_cld_response() {
1554 let cld = |f: &DecodedFrame| f.dlci == 0 && f.kind == UIH && f.payload == [0xC3, 0x01];
1555 let (s, _log) = fake_modem("AT+CMUX=0,0,5,31,10,3,50", move |f| {
1557 if cld(f) {
1558 std::thread::sleep(Duration::from_millis(100));
1559 encode_frame(0, true, UIH, &[0xC1, 0x01])
1560 } else {
1561 Vec::new()
1562 }
1563 });
1564 let start = Instant::now();
1565 s.close_down();
1566 let took = start.elapsed();
1567 assert!(
1568 took >= Duration::from_millis(100),
1569 "returned before the response: {took:?}"
1570 );
1571 assert!(
1572 took < Duration::from_millis(450),
1573 "missed the response: {took:?}"
1574 );
1575
1576 let (s, log) = fake_modem("AT+CMUX=0,0,5,31,10,3,5", |_| Vec::new());
1578 let start = Instant::now();
1579 s.close_down();
1580 let took = start.elapsed();
1581 assert!(took >= Duration::from_millis(50), "{took:?}");
1582 assert!(took < Duration::from_secs(1), "{took:?}");
1583 wait_log(&log, "CLD", |f| count(f, cld) == 1);
1584 }
1585}