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, PORT_CLOSED};
9use crate::hub::stream::{EventStream, Target, WatchOwner};
10use crate::hub::ExchangeWaiter;
11use serial_codec::framing::Framer;
12use std::collections::{HashMap, HashSet};
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::mpsc;
15use std::sync::{Arc, Condvar, Mutex, OnceLock};
16use std::time::{Duration, Instant};
17
18pub struct DlciChannel {
20 pub path: String,
21 pub exchange_waiter: Mutex<Option<Arc<ExchangeWaiter>>>,
22 watches: Mutex<DlciWatches>,
23 closing: AtomicBool,
25 outbox: Arc<Outbox>,
28}
29
30#[derive(Default)]
32struct DlciWatches {
33 old: Option<DlciWatchSlot>,
34 core: Vec<(u64, DlciWatchSlot)>,
35}
36
37impl DlciWatches {
38 fn each(&mut self, mut f: impl FnMut(&mut DlciWatchSlot)) -> Option<DlciWatchSlot> {
41 self.core.retain(|(_, w)| !w.target.gone());
42 self.core.iter_mut().for_each(|(_, w)| f(w));
43 match self.old.as_mut() {
44 Some(old) if !old.target.gone() => {
45 f(old);
46 None
47 }
48 _ => self.old.take(),
49 }
50 }
51}
52
53struct DlciWatchSlot {
54 target: Target,
55 batch_timeout_ms: u64,
56 flush_at: Instant,
57 framer: Option<Box<dyn Framer>>,
59 buffer: Vec<u8>,
60}
61
62impl DlciWatchSlot {
63 fn new(target: Target, batch_timeout_ms: u64, framer: Option<Box<dyn Framer>>) -> Self {
64 Self {
65 target,
66 batch_timeout_ms,
67 flush_at: Instant::now(),
68 framer,
69 buffer: Vec::new(),
70 }
71 }
72
73 fn take_due(&mut self) -> bool {
74 if self.flush_at.elapsed() >= Duration::from_millis(self.batch_timeout_ms) {
75 self.flush_at = Instant::now();
76 true
77 } else {
78 false
79 }
80 }
81
82 fn push(&mut self, payload: &[u8]) -> Vec<Vec<u8>> {
84 let mut frames = Vec::new();
85 if let Some(f) = self.framer.as_mut() {
86 f.push(payload, Instant::now(), &mut frames);
87 return frames;
88 }
89 self.buffer.extend_from_slice(payload);
90 if self.take_due() {
91 frames.push(std::mem::take(&mut self.buffer));
92 }
93 frames
94 }
95
96 fn poll(&mut self) -> Vec<Vec<u8>> {
98 let mut frames = Vec::new();
99 if let Some(f) = self.framer.as_mut() {
100 f.poll(Instant::now(), &mut frames);
101 } else if self.take_due() && !self.buffer.is_empty() {
102 frames.push(std::mem::take(&mut self.buffer));
103 }
104 frames
105 }
106
107 fn finish(&mut self) -> Vec<Vec<u8>> {
109 let batch = std::mem::take(&mut self.buffer);
110 let rest = self.framer.as_mut().and_then(|f| f.flush());
111 [batch, rest.unwrap_or_default()]
112 .into_iter()
113 .filter(|d| !d.is_empty())
114 .collect()
115 }
116}
117
118impl DlciChannel {
119 fn new(path: String, outbox: Arc<Outbox>) -> Self {
120 Self {
121 path,
122 exchange_waiter: Mutex::new(None),
123 watches: Mutex::new(DlciWatches::default()),
124 closing: AtomicBool::new(false),
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 self.attach_stream(channel, batch_timeout_ms, framer);
142 }
143
144 fn attach_stream(
147 &self,
148 channel: crate::events::EventSink,
149 batch_timeout_ms: u64,
150 framer: Option<Box<dyn Framer>>,
151 ) -> Arc<EventStream> {
152 let stream = self.outbox.stream(channel);
153 let slot = DlciWatchSlot::new(Target::Old(stream.clone()), batch_timeout_ms, framer);
154 let mut guard = crate::sync_util::lock_or_recover(&self.watches);
155 let mut replaced = guard.old.replace(slot);
156 if let Some(old) = replaced.as_mut() {
157 self.end_slot(old, None);
158 }
159 drop(guard);
161 stream
162 }
163
164 fn take_watch(&self, which: impl Fn(&DlciWatchSlot) -> bool) -> Option<DlciWatchSlot> {
166 let mut guard = crate::sync_util::lock_or_recover(&self.watches);
167 if !guard.old.as_ref().is_some_and(which) {
168 return None;
169 }
170 let mut slot = guard.old.take();
171 if let Some(slot) = slot.as_mut() {
172 self.end_slot(slot, None);
173 }
174 slot
175 }
176
177 pub fn detach_watch(&self) {
181 self.take_watch(|_| true);
182 }
183
184 fn attach_core_watch(&self, id: u64, slot: DlciWatchSlot) {
185 crate::sync_util::lock_or_recover(&self.watches)
186 .core
187 .push((id, slot));
188 }
189
190 fn detach_core_watch(&self, id: u64) -> bool {
192 let mut guard = crate::sync_util::lock_or_recover(&self.watches);
193 let Some(i) = guard.core.iter().position(|(c, _)| *c == id) else {
194 return false;
195 };
196 let (_, mut slot) = guard.core.remove(i);
197 self.end_slot(&mut slot, None);
198 drop(guard);
199 true
200 }
201
202 fn end_watches(&self, last: Option<&SerialEvent>) {
204 let ended = {
205 let mut guard = crate::sync_util::lock_or_recover(&self.watches);
206 let mut watches = std::mem::take(&mut *guard);
207 let gone = watches.each(|slot| self.end_slot(slot, last));
208 (watches, gone)
209 };
210 drop(ended);
212 }
213
214 fn end_slot(&self, slot: &mut DlciWatchSlot, last: Option<&SerialEvent>) {
216 let mut events = self.data_events(slot.finish());
217 events.extend(last.cloned());
218 slot.target.end(&mut events);
219 }
220
221 fn fail_exchange(&self, reason: &str) {
223 if let Some(waiter) = crate::sync_util::lock_or_recover(&self.exchange_waiter).as_ref() {
224 waiter.fail_with_reason(reason.to_string());
225 }
226 }
227
228 fn is_closing(&self) -> bool {
229 self.closing.load(Ordering::SeqCst)
230 }
231
232 fn begin_close(&self) {
234 self.closing.store(true, Ordering::SeqCst);
235 self.fail_exchange(PORT_CLOSED);
236 }
237
238 fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
239 *crate::sync_util::lock_or_recover(&self.exchange_waiter) = Some(waiter);
240 if self.is_closing() {
241 self.fail_exchange(PORT_CLOSED);
242 }
243 }
244
245 fn data_events(&self, frames: Vec<Vec<u8>>) -> Vec<SerialEvent> {
246 let event = |data: Vec<u8>| SerialEvent::Data {
247 path: self.path.clone(),
248 size: data.len(),
249 data,
250 };
251 frames.into_iter().map(event).collect()
252 }
253
254 fn each_watch(&self, mut f: impl FnMut(&mut DlciWatchSlot) -> Vec<Vec<u8>>) {
257 let gone = crate::sync_util::lock_or_recover(&self.watches).each(|slot| {
258 let frames = f(slot);
259 slot.target.send(&mut self.data_events(frames));
260 });
261 drop(gone);
262 }
263
264 fn push_stream(&self, payload: &[u8]) {
265 self.each_watch(|slot| slot.push(payload));
266 }
267
268 fn tick(&self) {
270 self.each_watch(DlciWatchSlot::poll);
271 }
272}
273
274impl WatchOwner for DlciChannel {
275 fn stop(&self, stream: &Arc<EventStream>) {
276 drop(self.take_watch(|slot| slot.target.is(stream)));
278 self.outbox.settle(stream);
279 }
280}
281
282fn cmux_param(command: &str, index: usize) -> Option<u64> {
285 let upper = command.to_ascii_uppercase();
286 let at = upper.find("+CMUX=")?;
287 upper[at + "+CMUX=".len()..]
288 .split(',')
289 .nth(index)?
290 .trim()
291 .parse()
292 .ok()
293}
294
295pub fn cmux_n1(command: &str) -> usize {
298 cmux_param(command, 3).map_or(31, |n1| n1 as usize)
299}
300
301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub struct CmuxTimers {
304 pub t1: Duration,
306 pub n2: u32,
308 pub t2: Duration,
310}
311
312impl Default for CmuxTimers {
313 fn default() -> Self {
315 Self {
316 t1: Duration::from_millis(100),
317 n2: 3,
318 t2: Duration::from_millis(300),
319 }
320 }
321}
322
323impl CmuxTimers {
324 pub fn from_command(command: &str) -> Self {
329 let d = Self::default();
330 let tens = |i, min, default| {
331 cmux_param(command, i)
332 .filter(|v| (min..=255).contains(v))
333 .map_or(default, |v| Duration::from_millis(v * 10))
334 };
335 let retransmit = cmux_param(command, 4).is_some() || cmux_param(command, 5).is_some();
336 Self {
337 t1: tens(4, 1, d.t1),
338 n2: if retransmit {
339 cmux_param(command, 5)
340 .filter(|v| *v <= 100)
341 .map_or(d.n2, |v| v as u32)
342 } else {
343 0
344 },
345 t2: tens(6, 2, d.t2),
346 }
347 }
348}
349
350const CR: u8 = 0x02;
352const PN_CMD: u8 = 0x83;
353const PSC_CMD: u8 = 0x43;
354const TEST_CMD: u8 = 0x23;
355const MSC_CMD: u8 = 0xE3;
356const RPN_CMD: u8 = 0x93;
357const RLS_CMD: u8 = 0x53;
358const FCON_CMD: u8 = 0xA3;
359const FCOFF_CMD: u8 = 0x63;
360const CLD_CMD: u8 = 0xC3;
361const CLD_RSP: u8 = 0xC1;
362const NSC_RSP: u8 = 0x11;
364const ECHOED: [u8; 9] = [
366 PN_CMD, PSC_CMD, TEST_CMD, MSC_CMD, RPN_CMD, RLS_CMD, FCON_CMD, FCOFF_CMD, CLD_CMD,
367];
368const V24_READY: u8 = 0x8D;
370const V24_FC: u8 = 0x02;
372
373#[derive(Default)]
376struct TxGate {
377 fc_off: bool,
378 held_dlcis: HashSet<u8>,
379}
380
381pub(crate) type ClosedHook = Box<dyn Fn(&[String], &str, bool) + Send + Sync>;
384
385pub struct CmuxSession {
387 physical_path: String,
388 io: Arc<dyn CmuxPhysicalIo>,
389 deframer: Mutex<Deframer>,
390 channels: Mutex<HashMap<u8, Arc<DlciChannel>>>,
391 pending_open: Mutex<HashMap<u8, mpsc::Sender<bool>>>,
393 pending_cld: Mutex<Option<mpsc::Sender<()>>>,
395 closed: Mutex<HashSet<u8>>,
397 tx: Mutex<TxGate>,
398 tx_cv: Condvar,
399 dead: Mutex<Option<String>>,
401 on_closed: OnceLock<ClosedHook>,
402 timers: CmuxTimers,
403 outbox: Arc<Outbox>,
404}
405
406impl CmuxSession {
407 pub fn new(physical_path: String, io: Arc<dyn CmuxPhysicalIo>) -> Arc<Self> {
410 Self::with_n1(physical_path, io, serial_codec::cmux::TX_N1)
411 }
412
413 pub fn with_n1(physical_path: String, io: Arc<dyn CmuxPhysicalIo>, n1: usize) -> Arc<Self> {
417 let timers = CmuxTimers {
418 n2: 0,
419 ..CmuxTimers::default()
420 };
421 Self::with_timers(physical_path, io, n1, timers)
422 }
423
424 pub fn for_command(
427 physical_path: String,
428 io: Arc<dyn CmuxPhysicalIo>,
429 command: &str,
430 ) -> Arc<Self> {
431 Self::with_timers(
432 physical_path,
433 io,
434 cmux_n1(command),
435 CmuxTimers::from_command(command),
436 )
437 }
438
439 fn with_timers(
440 physical_path: String,
441 io: Arc<dyn CmuxPhysicalIo>,
442 n1: usize,
443 timers: CmuxTimers,
444 ) -> Arc<Self> {
445 Arc::new(Self {
446 physical_path,
447 io,
448 deframer: Mutex::new(Deframer::with_max_info(
449 n1.max(crate::cmux::frame::DEFAULT_MAX_RX_INFO),
450 )),
451 channels: Mutex::new(HashMap::new()),
452 pending_open: Mutex::new(HashMap::new()),
453 pending_cld: Mutex::new(None),
454 closed: Mutex::new(HashSet::new()),
455 tx: Mutex::default(),
456 tx_cv: Condvar::new(),
457 dead: Mutex::new(None),
458 on_closed: OnceLock::new(),
459 timers,
460 outbox: Arc::default(),
461 })
462 }
463
464 pub fn physical_path(&self) -> &str {
465 &self.physical_path
466 }
467
468 pub(crate) fn set_on_closed(&self, hook: ClosedHook) {
470 let _ = self.on_closed.set(hook);
471 }
472
473 fn check_alive(&self) -> Result<(), String> {
475 match crate::sync_util::lock_or_recover(&self.dead).as_ref() {
476 Some(why) => Err(why.clone()),
477 None => Ok(()),
478 }
479 }
480
481 fn end(&self, why: &str) {
482 crate::sync_util::lock_or_recover(&self.dead).get_or_insert_with(|| why.to_string());
483 self.wake_writers();
484 }
485
486 fn wake_writers(&self) {
488 drop(crate::sync_util::lock_or_recover(&self.tx));
489 self.tx_cv.notify_all();
490 }
491
492 pub fn register_dlci(&self, dlci: u8, virtual_path: String) -> Arc<DlciChannel> {
493 let ch = Arc::new(DlciChannel::new(virtual_path, self.outbox.clone()));
494 let replaced = crate::sync_util::lock_or_recover(&self.channels).insert(dlci, ch.clone());
495 if let Some(old) = replaced {
496 old.begin_close();
497 old.end_watches(None);
498 }
499 crate::sync_util::lock_or_recover(&self.closed).remove(&dlci);
500 crate::sync_util::lock_or_recover(&self.tx)
502 .held_dlcis
503 .remove(&dlci);
504 ch
505 }
506
507 pub fn unregister_dlci(&self, dlci: u8) {
508 crate::sync_util::lock_or_recover(&self.closed).remove(&dlci);
509 crate::sync_util::lock_or_recover(&self.tx)
510 .held_dlcis
511 .remove(&dlci);
512 let removed = crate::sync_util::lock_or_recover(&self.channels).remove(&dlci);
513 self.wake_writers();
514 if let Some(ch) = removed {
515 ch.begin_close();
516 ch.end_watches(None);
517 let (tx, rx) = mpsc::channel();
520 crate::sync_util::lock_or_recover(&self.pending_open).insert(dlci, tx);
521 if self
522 .io
523 .write_all(&encode_frame(dlci, true, DISC | PF, &[]))
524 .is_ok()
525 {
526 let _ = rx.recv_timeout(self.timers.t1);
527 }
528 crate::sync_util::lock_or_recover(&self.pending_open).remove(&dlci);
529 }
530 }
531
532 pub fn has_dlci(&self, dlci: u8) -> bool {
533 crate::sync_util::lock_or_recover(&self.channels).contains_key(&dlci)
534 }
535
536 pub fn open_dlci(&self, dlci: u8, timeout: Duration) -> Result<(), String> {
541 self.check_alive()?;
542 let (tx, rx) = mpsc::channel();
543 crate::sync_util::lock_or_recover(&self.pending_open).insert(dlci, tx);
544 let CmuxTimers { t1, n2, .. } = self.timers;
545 let total = timeout.max(t1 * (n2 + 1));
546 let sabm = encode_frame(dlci, true, SABM | PF, &[]);
547 let start = Instant::now();
548 let mut answer = Ok(None);
549 for attempt in 0..=n2 {
550 if let Err(e) = self.io.write_all(&sabm) {
551 answer = Err(e);
552 break;
553 }
554 let wait = if attempt == n2 {
555 total.saturating_sub(start.elapsed())
556 } else {
557 t1
558 };
559 if let Ok(ua) = rx.recv_timeout(wait) {
560 answer = Ok(Some(ua));
561 break;
562 }
563 }
564 crate::sync_util::lock_or_recover(&self.pending_open).remove(&dlci);
565 match answer? {
566 Some(true) => {
567 if dlci != 0 {
568 let msc = [MSC_CMD, 0x05, (dlci << 2) | 0x03, V24_READY];
569 let _ = self.io.write_all(&encode_frame(0, true, UIH, &msc));
570 }
571 Ok(())
572 }
573 Some(false) => Err(format!("modem refused CMUX DLCI {dlci} (DM)")),
574 None => Err(format!(
575 "no UA for CMUX DLCI {dlci} within {} ms",
576 total.as_millis()
577 )),
578 }
579 }
580
581 pub fn close_down(&self) {
584 self.end("CMUX multiplexer is closed");
585 let (tx, rx) = mpsc::channel();
586 *crate::sync_util::lock_or_recover(&self.pending_cld) = Some(tx);
587 let cld = encode_frame(0, true, UIH, &[CLD_CMD, 0x01]);
588 if self.io.write_all(&cld).is_ok() {
589 let _ = rx.recv_timeout(self.timers.t2);
590 }
591 *crate::sync_util::lock_or_recover(&self.pending_cld) = None;
592 }
593
594 fn closed_by_modem(&self, dlci: u8) {
597 let gone: Vec<(u8, Arc<DlciChannel>)> = {
598 let mut channels = crate::sync_util::lock_or_recover(&self.channels);
599 if dlci == 0 {
600 channels.drain().collect()
601 } else {
602 channels
603 .remove(&dlci)
604 .map(|ch| (dlci, ch))
605 .into_iter()
606 .collect()
607 }
608 };
609 if dlci == 0 {
610 self.end("CMUX multiplexer closed by the modem");
611 }
612 let mut paths = Vec::new();
613 for (d, ch) in gone {
614 crate::sync_util::lock_or_recover(&self.closed).insert(d);
615 let reason = format!("CMUX DLCI {d} closed by the modem");
616 ch.fail_exchange(&reason);
617 ch.end_watches(Some(&SerialEvent::Disconnect {
618 path: ch.path.clone(),
619 reason,
620 }));
621 paths.push(ch.path.clone());
622 }
623 self.wake_writers();
624 if let Some(hook) = self.on_closed.get() {
625 let reason = if dlci == 0 {
626 "CMUX multiplexer closed by the modem".to_string()
627 } else {
628 format!("CMUX DLCI {dlci} closed by the modem")
629 };
630 hook(&paths, &reason, dlci == 0);
631 }
632 }
633
634 pub fn tick(&self) {
636 for ch in self.channels() {
637 ch.tick();
638 }
639 self.outbox.deliver();
640 }
641
642 fn channels(&self) -> Vec<Arc<DlciChannel>> {
643 crate::sync_util::lock_or_recover(&self.channels)
644 .values()
645 .cloned()
646 .collect()
647 }
648
649 fn channel(&self, dlci: u8) -> Option<Arc<DlciChannel>> {
650 crate::sync_util::lock_or_recover(&self.channels)
651 .get(&dlci)
652 .cloned()
653 }
654
655 pub fn emit_disconnect(&self, reason: &str) {
659 self.disconnect_queued(reason);
660 self.deliver_queued();
661 }
662
663 pub(crate) fn disconnect_queued(&self, reason: &str) {
665 self.end(reason);
666 let channels = self.channels();
667 for ch in &channels {
668 ch.fail_exchange(reason);
669 }
670 for ch in channels {
671 ch.end_watches(Some(&SerialEvent::Disconnect {
672 path: ch.path.clone(),
673 reason: reason.to_string(),
674 }));
675 }
676 }
677
678 pub(crate) fn deliver_queued(&self) {
680 self.outbox.deliver();
681 }
682
683 pub(crate) fn begin_close(&self, dlci: Option<u8>) {
686 let channels = match dlci {
687 Some(dlci) => self.channel(dlci).into_iter().collect(),
688 None => self.channels(),
689 };
690 channels.iter().for_each(|ch| ch.begin_close());
691 self.wake_writers();
692 }
693
694 #[cfg(feature = "tauri")]
696 pub fn set_watch(
697 &self,
698 dlci: u8,
699 channel: tauri::ipc::Channel<SerialEvent>,
700 batch_timeout_ms: u64,
701 ) {
702 self.set_watch_with(
703 dlci,
704 crate::events::channel_sink(channel),
705 batch_timeout_ms,
706 None,
707 );
708 }
709
710 pub fn set_watch_with(
711 &self,
712 dlci: u8,
713 channel: crate::events::EventSink,
714 batch_timeout_ms: u64,
715 framer: Option<Box<dyn Framer>>,
716 ) {
717 self.attach_stream(dlci, channel, batch_timeout_ms, framer);
718 }
719
720 pub(crate) fn attach_stream(
722 &self,
723 dlci: u8,
724 channel: crate::events::EventSink,
725 batch_timeout_ms: u64,
726 framer: Option<Box<dyn Framer>>,
727 ) -> Option<(Arc<DlciChannel>, Arc<EventStream>)> {
728 let ch = self.channel(dlci)?;
729 let stream = ch.attach_stream(channel, batch_timeout_ms, framer);
730 Some((ch, stream))
731 }
732
733 pub fn clear_watch(&self, dlci: u8) {
737 let slot = self.channel(dlci).and_then(|ch| ch.take_watch(|_| true));
738 if let Some(DlciWatchSlot {
739 target: Target::Old(stream),
740 ..
741 }) = slot
742 {
743 self.outbox.settle(&stream);
744 }
745 }
746
747 pub(crate) fn add_core_watch(
749 &self,
750 dlci: u8,
751 id: u64,
752 target: Target,
753 batch_timeout_ms: u64,
754 framer: Option<Box<dyn Framer>>,
755 ) -> bool {
756 let Some(ch) = self.channel(dlci) else {
757 return false;
758 };
759 ch.attach_core_watch(id, DlciWatchSlot::new(target, batch_timeout_ms, framer));
760 true
761 }
762
763 pub(crate) fn remove_core_watch(&self, dlci: u8, id: u64) -> bool {
765 self.channel(dlci)
766 .is_some_and(|ch| ch.detach_core_watch(id))
767 }
768
769 pub fn set_exchange_waiter(&self, dlci: u8, waiter: Arc<ExchangeWaiter>) {
770 if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
771 ch.set_exchange_waiter(waiter);
772 }
773 }
774
775 pub fn clear_exchange_waiter(&self, dlci: u8) {
776 if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
777 *crate::sync_util::lock_or_recover(&ch.exchange_waiter) = None;
778 }
779 }
780
781 pub fn cancel_active_exchange(&self, dlci: u8) {
783 if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
784 ch.fail_exchange("exchange cancelled");
785 }
786 }
787
788 pub fn send_uih(&self, dlci: u8, payload: &[u8]) -> Result<usize, String> {
792 let frame = encode_uih(dlci, payload);
793 let deadline = Instant::now() + self.io.write_timeout(frame.len());
794 let mut gate = crate::sync_util::lock_or_recover(&self.tx);
796 loop {
797 self.check_alive()?;
798 if crate::sync_util::lock_or_recover(&self.closed).contains(&dlci) {
799 return Err(format!("CMUX DLCI {dlci} closed by the modem"));
800 }
801 match self.channel(dlci) {
802 None => return Err(format!("CMUX DLCI {dlci} is closed")),
803 Some(ch) if ch.is_closing() => return Err(PORT_CLOSED.into()),
804 Some(_) => {}
805 }
806 let held = if gate.fc_off {
807 "CMUX flow control off (FCoff)".to_string()
808 } else if gate.held_dlcis.contains(&dlci) {
809 format!("CMUX DLCI {dlci} flow control off (MSC FC)")
810 } else {
811 break;
812 };
813 let left = deadline.saturating_duration_since(Instant::now());
814 if left.is_zero() {
815 return Err(held);
816 }
817 gate = self
818 .tx_cv
819 .wait_timeout(gate, left)
820 .unwrap_or_else(|e| e.into_inner())
821 .0;
822 }
823 self.io.write_all(&frame)?;
824 drop(gate);
825 Ok(payload.len())
826 }
827
828 pub fn feed_physical_rx(&self, chunk: &[u8]) {
830 let frames = crate::sync_util::lock_or_recover(&self.deframer).feed(chunk);
831 for frame in frames {
832 self.dispatch_frame(frame);
833 }
834 self.outbox.deliver();
835 }
836
837 fn dispatch_frame(&self, frame: DecodedFrame) {
838 match frame.kind {
839 UA | DM => {
840 if let Some(tx) =
841 crate::sync_util::lock_or_recover(&self.pending_open).get(&frame.dlci)
842 {
843 let _ = tx.send(frame.kind == UA);
844 } else if frame.kind == DM {
845 self.closed_by_modem(frame.dlci);
847 }
848 return;
849 }
850 DISC => {
851 let open = frame.dlci == 0 || self.has_dlci(frame.dlci);
853 let reply = if open { UA } else { DM };
854 let _ = self
855 .io
856 .write_all(&encode_frame(frame.dlci, false, reply | PF, &[]));
857 if open {
858 self.closed_by_modem(frame.dlci);
859 }
860 return;
861 }
862 UIH | UI => {}
863 _ => return,
865 }
866 if frame.dlci == 0 {
867 self.handle_control(&frame.payload);
868 return;
869 }
870 let Some(ch) = self.channel(frame.dlci) else {
871 return;
872 };
873 let waiter = crate::sync_util::lock_or_recover(&ch.exchange_waiter).clone();
874 if let Some(waiter) = waiter {
875 waiter.push_bytes(&frame.payload);
876 return;
877 }
878 ch.push_stream(&frame.payload);
879 }
880
881 fn handle_control(&self, payload: &[u8]) {
888 let Some(&type_octet) = payload.first() else {
889 return;
890 };
891 if type_octet & CR == 0 {
892 if type_octet == CLD_RSP {
893 if let Some(tx) = crate::sync_util::lock_or_recover(&self.pending_cld).as_ref() {
894 let _ = tx.send(());
895 }
896 }
897 return;
898 }
899 if type_octet == FCOFF_CMD {
901 crate::sync_util::lock_or_recover(&self.tx).fc_off = true;
902 }
903 if let (MSC_CMD, Some(&address), Some(&v24)) = (type_octet, payload.get(2), payload.get(3))
904 {
905 let dlci = address >> 2;
906 let mut gate = crate::sync_util::lock_or_recover(&self.tx);
907 if v24 & V24_FC != 0 {
908 gate.held_dlcis.insert(dlci);
909 } else {
910 gate.held_dlcis.remove(&dlci);
911 }
912 drop(gate);
913 self.tx_cv.notify_all();
914 }
915 let reply = if ECHOED.contains(&type_octet) {
916 let mut reply = payload.to_vec();
917 reply[0] &= !CR;
918 reply
919 } else {
920 vec![NSC_RSP, 0x03, type_octet]
921 };
922 let _ = self.io.write_all(&encode_frame(0, true, UIH, &reply));
923 match type_octet {
924 FCON_CMD => {
925 crate::sync_util::lock_or_recover(&self.tx).fc_off = false;
926 self.tx_cv.notify_all();
927 }
928 CLD_CMD => self.closed_by_modem(0),
929 _ => {}
930 }
931 }
932}