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;
12use std::sync::mpsc;
13use std::sync::{Arc, Mutex};
14use std::time::{Duration, Instant};
15
16pub struct DlciChannel {
18 pub path: String,
19 pub exchange_waiter: Mutex<Option<Arc<ExchangeWaiter>>>,
20 watch: Mutex<Option<DlciWatchSlot>>,
21 stream_buffer: Mutex<Vec<u8>>,
22 outbox: Arc<Outbox>,
25}
26
27struct DlciWatchSlot {
28 channel: crate::events::EventSink,
29 batch_timeout_ms: u64,
30 flush_at: Instant,
31 framer: Option<Box<dyn Framer>>,
33}
34
35impl DlciChannel {
36 fn new(path: String, outbox: Arc<Outbox>) -> Self {
37 Self {
38 path,
39 exchange_waiter: Mutex::new(None),
40 watch: Mutex::new(None),
41 stream_buffer: Mutex::new(Vec::new()),
42 outbox,
43 }
44 }
45
46 #[cfg(feature = "tauri")]
48 pub fn attach_watch(&self, channel: tauri::ipc::Channel<SerialEvent>, batch_timeout_ms: u64) {
49 self.attach_watch_with(crate::events::channel_sink(channel), batch_timeout_ms, None);
50 }
51
52 pub fn attach_watch_with(
53 &self,
54 channel: crate::events::EventSink,
55 batch_timeout_ms: u64,
56 framer: Option<Box<dyn Framer>>,
57 ) {
58 *crate::sync_util::lock_or_recover(&self.watch) = Some(DlciWatchSlot {
59 channel,
60 batch_timeout_ms,
61 flush_at: Instant::now(),
62 framer,
63 });
64 }
65
66 pub fn detach_watch(&self) {
70 let mut guard = crate::sync_util::lock_or_recover(&self.watch);
71 crate::sync_util::lock_or_recover(&self.stream_buffer).clear();
72 if let Some(mut slot) = guard.take() {
73 if let Some(rest) = slot.framer.as_mut().and_then(|f| f.flush()) {
74 self.queue_frames(&slot.channel, vec![rest]);
75 }
76 }
77 }
78
79 fn queue_disconnect(&self, reason: &str) {
81 let mut guard = crate::sync_util::lock_or_recover(&self.watch);
82 let Some(slot) = guard.as_mut() else {
83 return;
84 };
85 let batch = std::mem::take(&mut *crate::sync_util::lock_or_recover(&self.stream_buffer));
86 let rest = slot.framer.as_mut().and_then(|f| f.flush());
87 let frames: Vec<_> = [batch, rest.unwrap_or_default()]
88 .into_iter()
89 .filter(|d| !d.is_empty())
90 .collect();
91 self.queue_frames(&slot.channel, frames);
92 self.outbox.push([(
93 slot.channel.clone(),
94 SerialEvent::Disconnect {
95 path: self.path.clone(),
96 reason: reason.to_string(),
97 },
98 )]);
99 }
100
101 fn queue_frames(&self, channel: &crate::events::EventSink, frames: Vec<Vec<u8>>) {
104 self.outbox.push(frames.into_iter().map(|data| {
105 (
106 channel.clone(),
107 SerialEvent::Data {
108 path: self.path.clone(),
109 size: data.len(),
110 data,
111 },
112 )
113 }));
114 }
115
116 fn with_framer(&self, run: impl FnOnce(&mut dyn Framer, &mut Vec<Vec<u8>>)) -> bool {
119 let mut guard = crate::sync_util::lock_or_recover(&self.watch);
120 let Some(slot) = guard.as_mut() else {
121 return false;
122 };
123 let Some(f) = slot.framer.as_mut() else {
124 return false;
125 };
126 let mut frames = Vec::new();
127 run(f.as_mut(), &mut frames);
128 self.queue_frames(&slot.channel, frames);
129 true
130 }
131
132 fn push_stream(&self, payload: &[u8]) {
133 if self.with_framer(|f, out| f.push(payload, Instant::now(), out)) {
134 return;
135 }
136 let due = {
137 let mut guard = crate::sync_util::lock_or_recover(&self.watch);
138 let Some(slot) = guard.as_mut() else {
139 return;
140 };
141 crate::sync_util::lock_or_recover(&self.stream_buffer).extend_from_slice(payload);
142 slot.take_due()
143 };
144 if due {
146 self.flush_stream_buffer();
147 }
148 }
149
150 fn tick(&self) {
152 if self.with_framer(|f, out| f.poll(Instant::now(), out)) {
153 return;
154 }
155 let due = crate::sync_util::lock_or_recover(&self.watch)
156 .as_mut()
157 .is_some_and(DlciWatchSlot::take_due);
158 if due {
159 self.flush_stream_buffer();
160 }
161 }
162
163 fn flush_stream_buffer(&self) {
164 let guard = crate::sync_util::lock_or_recover(&self.watch);
165 let data = std::mem::take(&mut *crate::sync_util::lock_or_recover(&self.stream_buffer));
166 if let (Some(slot), false) = (guard.as_ref(), data.is_empty()) {
167 self.queue_frames(&slot.channel, vec![data]);
168 }
169 }
170}
171
172impl DlciWatchSlot {
173 fn take_due(&mut self) -> bool {
174 if self.flush_at.elapsed() >= Duration::from_millis(self.batch_timeout_ms) {
175 self.flush_at = Instant::now();
176 true
177 } else {
178 false
179 }
180 }
181}
182
183pub fn cmux_n1(command: &str) -> usize {
187 const DEFAULT_N1: usize = 31;
188 let upper = command.to_ascii_uppercase();
189 let Some(at) = upper.find("+CMUX=") else {
190 return DEFAULT_N1;
191 };
192 upper[at + "+CMUX=".len()..]
193 .split(',')
194 .nth(3)
195 .and_then(|n1| n1.trim().parse().ok())
196 .unwrap_or(DEFAULT_N1)
197}
198
199pub struct CmuxSession {
201 physical_path: String,
202 io: Arc<dyn CmuxPhysicalIo>,
203 deframer: Mutex<Deframer>,
204 channels: Mutex<HashMap<u8, Arc<DlciChannel>>>,
205 pending_open: Mutex<HashMap<u8, mpsc::Sender<bool>>>,
207 outbox: Arc<Outbox>,
208}
209
210impl CmuxSession {
211 pub fn new(physical_path: String, io: Arc<dyn CmuxPhysicalIo>) -> Arc<Self> {
214 Self::with_n1(physical_path, io, serial_codec::cmux::TX_N1)
215 }
216
217 pub fn with_n1(physical_path: String, io: Arc<dyn CmuxPhysicalIo>, n1: usize) -> Arc<Self> {
220 Arc::new(Self {
221 physical_path,
222 io,
223 deframer: Mutex::new(Deframer::with_max_info(
224 n1.max(crate::cmux::frame::DEFAULT_MAX_RX_INFO),
225 )),
226 channels: Mutex::new(HashMap::new()),
227 pending_open: Mutex::new(HashMap::new()),
228 outbox: Arc::default(),
229 })
230 }
231
232 pub fn physical_path(&self) -> &str {
233 &self.physical_path
234 }
235
236 pub fn register_dlci(&self, dlci: u8, virtual_path: String) -> Arc<DlciChannel> {
237 let ch = Arc::new(DlciChannel::new(virtual_path, self.outbox.clone()));
238 crate::sync_util::lock_or_recover(&self.channels).insert(dlci, ch.clone());
239 ch
240 }
241
242 pub fn unregister_dlci(&self, dlci: u8) {
243 if crate::sync_util::lock_or_recover(&self.channels)
244 .remove(&dlci)
245 .is_some()
246 {
247 let _ = self.io.write_all(&encode_frame(dlci, true, DISC | PF, &[]));
248 }
249 }
250
251 pub fn has_dlci(&self, dlci: u8) -> bool {
252 crate::sync_util::lock_or_recover(&self.channels).contains_key(&dlci)
253 }
254
255 pub fn open_dlci(&self, dlci: u8, timeout: Duration) -> Result<(), String> {
258 let (tx, rx) = mpsc::channel();
259 crate::sync_util::lock_or_recover(&self.pending_open).insert(dlci, tx);
260 let sent = self.io.write_all(&encode_frame(dlci, true, SABM | PF, &[]));
261 let result = sent.and_then(|()| match rx.recv_timeout(timeout) {
262 Ok(true) => Ok(()),
263 Ok(false) => Err(format!("modem refused CMUX DLCI {dlci} (DM)")),
264 Err(_) => Err(format!(
265 "no UA for CMUX DLCI {dlci} within {} ms",
266 timeout.as_millis()
267 )),
268 });
269 crate::sync_util::lock_or_recover(&self.pending_open).remove(&dlci);
270 result
271 }
272
273 pub fn close_down(&self) {
275 let _ = self
277 .io
278 .write_all(&encode_frame(0, true, UIH, &[0xC3, 0x01]));
279 }
280
281 pub fn tick(&self) {
283 let channels: Vec<_> = crate::sync_util::lock_or_recover(&self.channels)
284 .values()
285 .cloned()
286 .collect();
287 for ch in channels {
288 ch.tick();
289 }
290 self.outbox.deliver();
291 }
292
293 fn channel(&self, dlci: u8) -> Option<Arc<DlciChannel>> {
294 crate::sync_util::lock_or_recover(&self.channels)
295 .get(&dlci)
296 .cloned()
297 }
298
299 pub fn emit_disconnect(&self, reason: &str) {
302 let channels: Vec<_> = crate::sync_util::lock_or_recover(&self.channels)
303 .values()
304 .cloned()
305 .collect();
306 for ch in channels {
307 ch.queue_disconnect(reason);
308 }
309 self.outbox.deliver();
310 }
311
312 #[cfg(feature = "tauri")]
314 pub fn set_watch(
315 &self,
316 dlci: u8,
317 channel: tauri::ipc::Channel<SerialEvent>,
318 batch_timeout_ms: u64,
319 ) {
320 self.set_watch_with(
321 dlci,
322 crate::events::channel_sink(channel),
323 batch_timeout_ms,
324 None,
325 );
326 }
327
328 pub fn set_watch_with(
329 &self,
330 dlci: u8,
331 channel: crate::events::EventSink,
332 batch_timeout_ms: u64,
333 framer: Option<Box<dyn Framer>>,
334 ) {
335 if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
336 ch.attach_watch_with(channel, batch_timeout_ms, framer);
337 }
338 }
339
340 pub fn clear_watch(&self, dlci: u8) {
343 if let Some(ch) = self.channel(dlci) {
344 ch.detach_watch();
345 }
346 self.outbox.deliver();
347 }
348
349 pub fn set_exchange_waiter(&self, dlci: u8, waiter: Arc<ExchangeWaiter>) {
350 if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
351 *crate::sync_util::lock_or_recover(&ch.exchange_waiter) = Some(waiter);
352 }
353 }
354
355 pub fn clear_exchange_waiter(&self, dlci: u8) {
356 if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
357 *crate::sync_util::lock_or_recover(&ch.exchange_waiter) = None;
358 }
359 }
360
361 pub fn cancel_active_exchange(&self, dlci: u8) {
363 if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
364 if let Some(waiter) = crate::sync_util::lock_or_recover(&ch.exchange_waiter).as_ref() {
365 waiter.fail_with_reason("exchange cancelled".into());
366 }
367 }
368 }
369
370 pub fn send_uih(&self, dlci: u8, payload: &[u8]) -> Result<usize, String> {
371 let frame = encode_uih(dlci, payload);
372 self.io.write_all(&frame)?;
373 Ok(payload.len())
374 }
375
376 pub fn feed_physical_rx(&self, chunk: &[u8]) {
378 let frames = crate::sync_util::lock_or_recover(&self.deframer).feed(chunk);
379 for frame in frames {
380 self.dispatch_frame(frame);
381 }
382 self.outbox.deliver();
383 }
384
385 fn dispatch_frame(&self, frame: DecodedFrame) {
386 match frame.kind {
387 UA | DM => {
388 if let Some(tx) =
389 crate::sync_util::lock_or_recover(&self.pending_open).get(&frame.dlci)
390 {
391 let _ = tx.send(frame.kind == UA);
392 }
393 return;
394 }
395 UIH | UI => {}
396 _ => return,
398 }
399 if frame.dlci == 0 {
400 self.handle_control(&frame.payload);
401 return;
402 }
403 let Some(ch) = self.channel(frame.dlci) else {
404 return;
405 };
406 let waiter = crate::sync_util::lock_or_recover(&ch.exchange_waiter).clone();
407 if let Some(waiter) = waiter {
408 waiter.push_bytes(&frame.payload);
409 return;
410 }
411 ch.push_stream(&frame.payload);
412 }
413
414 fn handle_control(&self, payload: &[u8]) {
418 let Some(&type_octet) = payload.first() else {
419 return;
420 };
421 if type_octet & 0x02 == 0 {
422 return;
423 }
424 let mut reply = payload.to_vec();
425 reply[0] &= !0x02;
426 let _ = self.io.write_all(&encode_frame(0, true, UIH, &reply));
427 }
428}
429
430#[cfg(all(test, not(target_os = "android")))]
431mod tests {
432 use super::*;
433 use crate::events::{AtResultFormat, ExchangeCompletionMode, RxPrepareMode};
434 use crate::exchange::options::ResolvedExchangeOptions;
435 use crate::hub::ExchangeWaiter;
436 use std::sync::atomic::AtomicBool;
437
438 fn test_options() -> ResolvedExchangeOptions {
439 ResolvedExchangeOptions {
440 timeout_ms: 3000,
441 max_bytes: 4096,
442 terminators: vec![],
443 idle_ms: None,
444 rx_prepare: RxPrepareMode::None,
445 drain_idle_ms: 50,
446 drain_max_ms: 200,
447 completion_mode: ExchangeCompletionMode::AtFinalLine,
448 result_format: AtResultFormat::Verbose,
449 command: Some("AT".into()),
450 solicited_prefixes: vec![],
451 }
452 }
453
454 #[cfg(unix)]
455 #[test]
456 fn feed_physical_rx_routes_to_exchange_waiter() {
457 use crate::cmux::SerialPortIo;
458 use crate::sync_util::pty_pair_locked;
459 use serialport::SerialPort;
460 let (_pty, port, _master) = pty_pair_locked();
461 let session = CmuxSession::with_n1(
462 "pty".into(),
463 Arc::new(SerialPortIo(Arc::new(Mutex::new(
464 Box::new(port) as Box<dyn SerialPort>
465 )))),
466 31,
467 );
468 session.register_dlci(2, "pty#dlci=2".into());
469 let cancel = Arc::new(AtomicBool::new(false));
470 let waiter = ExchangeWaiter::new(test_options(), cancel);
471 session.set_exchange_waiter(2, waiter.clone());
472 let payload = b"AT\r\r\nOK\r\n";
473 let frame = encode_uih(2, payload);
474 session.feed_physical_rx(&frame);
475 let (raw, matched) = waiter.wait(1000).expect("complete");
476 assert!(String::from_utf8_lossy(&raw).contains("OK"));
477 assert!(matches!(matched, crate::at::parse::ExchangeMatch::Ok));
478 }
479
480 #[test]
481 fn cancel_active_exchange_fails_waiter_quickly() {
482 use crate::cmux::io::CmuxPhysicalIo;
483 struct NoopIo;
484 impl CmuxPhysicalIo for NoopIo {
485 fn write_all(&self, _data: &[u8]) -> Result<(), String> {
486 Ok(())
487 }
488 }
489 let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), 31);
490 session.register_dlci(2, "mock#dlci=2".into());
491 let cancel = Arc::new(AtomicBool::new(false));
492 let waiter = ExchangeWaiter::new(test_options(), cancel);
493 session.set_exchange_waiter(2, waiter.clone());
494 let waiter_bg = waiter.clone();
495 let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
496 let done_bg = done.clone();
497 std::thread::spawn(move || {
498 let _ = waiter_bg.wait(5000);
499 done_bg.store(true, std::sync::atomic::Ordering::SeqCst);
500 });
501 std::thread::sleep(std::time::Duration::from_millis(20));
502 let start = std::time::Instant::now();
503 session.cancel_active_exchange(2);
504 while !done.load(std::sync::atomic::Ordering::SeqCst)
505 && start.elapsed() < std::time::Duration::from_millis(500)
506 {
507 std::thread::sleep(std::time::Duration::from_millis(5));
508 }
509 assert!(done.load(std::sync::atomic::Ordering::SeqCst));
510 assert!(start.elapsed() < std::time::Duration::from_millis(500));
511 }
512
513 #[test]
514 fn dlci_watch_parser_emits_one_event_per_frame() {
515 use crate::cmux::io::CmuxPhysicalIo;
516 use serial_codec::framing::FramerConfig;
517 struct NoopIo;
518 impl CmuxPhysicalIo for NoopIo {
519 fn write_all(&self, _data: &[u8]) -> Result<(), String> {
520 Ok(())
521 }
522 }
523 let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), 31);
524 session.register_dlci(2, "mock#dlci=2".into());
525 let frames = Arc::new(Mutex::new(Vec::new()));
526 let sink = frames.clone();
527 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
528 if let SerialEvent::Data { data, .. } = event {
529 sink.lock().unwrap().push(data);
530 }
531 true
532 });
533 let cfg: FramerConfig =
534 serde_json::from_value(serde_json::json!({"type": "readline"})).unwrap();
535 session.set_watch_with(2, channel, 10_000, Some(cfg.build().unwrap()));
536 session.feed_physical_rx(&encode_uih(2, b"one\ntw"));
537 session.feed_physical_rx(&encode_uih(2, b"o\nthr"));
538 assert_eq!(
539 *frames.lock().unwrap(),
540 vec![b"one".to_vec(), b"two".to_vec()]
541 );
542 session.clear_watch(2);
543 assert_eq!(frames.lock().unwrap().last().unwrap(), b"thr");
544 }
545
546 struct NoopIo;
547 impl crate::cmux::io::CmuxPhysicalIo for NoopIo {
548 fn write_all(&self, _data: &[u8]) -> Result<(), String> {
549 Ok(())
550 }
551 }
552
553 #[test]
556 fn clear_watch_remainder_sink_may_call_back_into_session() {
557 use serial_codec::framing::FramerConfig;
558 let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), 31);
559 session.register_dlci(2, "mock#dlci=2".into());
560 let weak = Arc::downgrade(&session);
561 let (tx, rx) = mpsc::channel();
562 let tx = Mutex::new(tx);
563 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
564 if let SerialEvent::Data { data, .. } = event {
565 let known = weak.upgrade().is_some_and(|s| s.has_dlci(2));
566 let _ = tx.lock().unwrap().send((data, known));
567 }
568 true
569 });
570 let cfg: FramerConfig =
571 serde_json::from_value(serde_json::json!({"type": "readline"})).unwrap();
572 session.set_watch_with(2, channel, 10_000, Some(cfg.build().unwrap()));
573 session.feed_physical_rx(&encode_uih(2, b"partial"));
574 let bg = session.clone();
575 std::thread::spawn(move || bg.clear_watch(2));
576 let (data, known) = rx
577 .recv_timeout(Duration::from_secs(3))
578 .expect("clear_watch deadlocked: sink ran under the channels lock");
579 assert_eq!(data, b"partial");
580 assert!(known);
581 }
582
583 #[test]
584 fn n1_is_the_fourth_cmux_parameter() {
585 assert_eq!(cmux_n1("AT+CMUX=0,0,5,2048"), 2048);
586 assert_eq!(cmux_n1("at+cmux=0,0,5,127,10,3,30,10,2"), 127);
587 assert_eq!(cmux_n1("AT+CMUX=0"), 31);
588 assert_eq!(cmux_n1("AT+CMUX=0,0,,"), 31);
589 assert_eq!(cmux_n1("AT+CMUX=0,0,5, 1600 ,10"), 1600);
590 assert_eq!(cmux_n1("AT"), 31);
591 }
592
593 #[test]
596 fn session_accepts_frames_up_to_negotiated_n1() {
597 let n1 = cmux_n1("AT+CMUX=0,0,5,2048");
598 let session = CmuxSession::with_n1("mock".into(), Arc::new(NoopIo), n1);
599 session.register_dlci(1, "mock#dlci=1".into());
600 let got = Arc::new(Mutex::new(0usize));
601 let sink = got.clone();
602 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
603 if let SerialEvent::Data { size, .. } = event {
604 *sink.lock().unwrap() += size;
605 }
606 true
607 });
608 session.set_watch_with(1, channel, 0, None);
609 let frame = encode_frame(1, true, UIH, &[b'A'; 2000]);
610 session.feed_physical_rx(&frame);
611 assert_eq!(*got.lock().unwrap(), 2000, "2000-byte frame dropped");
612 }
613}