rmux-client 0.10.0

Blocking local client and attach-mode plumbing for the RMUX terminal multiplexer.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use std::io;

use windows_sys::Win32::Foundation::{GetLastError, HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Console::{
    GetConsoleMode, GetStdHandle, SetConsoleMode, WriteConsoleW, ENABLE_VIRTUAL_TERMINAL_INPUT,
    STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
};

use super::console_coordination::{ConsoleIoCoordinator, ATTACH_CONSOLE_IO};
use super::windows_version::{current_windows_version, supports_scoped_vt_input, WindowsVersion};

// Keep each WriteConsoleW request comfortably below the console host's
// internal 64-KiB-class buffers. Large terminal strings (notably OSC 52)
// otherwise turn one transient console allocation limit into a fatal attach
// output error.
const MAX_WRITE_CONSOLE_CODE_UNITS: usize = 16 * 1024;

#[derive(Clone, Copy, Debug)]
pub(super) struct ScopedVtInputPassthrough {
    handles: ConsoleHandles<HANDLE>,
}

impl ScopedVtInputPassthrough {
    /// Enables the bridge only for the Windows builds where it was measured to
    /// make ConPTY expose terminal input-reporting traffic, and only when the
    /// process's actual stdin and stdout are both console handles.
    pub(super) fn for_output(output_handle: HANDLE) -> Option<Self> {
        let handles = ATTACH_CONSOLE_IO
            .synchronized(|| {
                eligible_console_handles(&Win32ConsoleApi, current_windows_version(), output_handle)
            })
            .ok()
            .flatten()?;
        Some(Self { handles })
    }

    pub(super) fn write_wide(&self, wide: &[u16]) -> io::Result<()> {
        let result =
            coordinated_scoped_write(&ATTACH_CONSOLE_IO, &Win32ConsoleApi, self.handles, wide)?;
        result.map_err(scoped_failure_to_io)
    }
}

pub(super) fn write_console_wide(handle: HANDLE, wide: &[u16]) -> io::Result<()> {
    Win32ConsoleApi
        .write_console(handle, wide)
        .map_err(win32_failure_to_io)
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ConsoleHandles<Handle> {
    input: Handle,
    output: Handle,
}

trait ScopedConsoleApi {
    type Handle: Copy + Eq;
    type Error;

    fn std_handle(&self, handle_id: u32) -> Result<Option<Self::Handle>, Self::Error>;
    fn console_mode(&self, handle: Self::Handle) -> Result<u32, Self::Error>;
    fn set_console_mode(&self, handle: Self::Handle, mode: u32) -> Result<(), Self::Error>;
    fn write_console(&self, handle: Self::Handle, wide: &[u16]) -> Result<(), Self::Error>;
}

fn eligible_console_handles<Api>(
    api: &Api,
    version: Option<WindowsVersion>,
    writer_output: Api::Handle,
) -> Option<ConsoleHandles<Api::Handle>>
where
    Api: ScopedConsoleApi,
{
    let version = version?;
    if !supports_scoped_vt_input(version) {
        return None;
    }

    let input = api.std_handle(STD_INPUT_HANDLE).ok().flatten()?;
    let output = api.std_handle(STD_OUTPUT_HANDLE).ok().flatten()?;
    if output != writer_output {
        return None;
    }
    api.console_mode(input).ok()?;
    api.console_mode(output).ok()?;
    Some(ConsoleHandles { input, output })
}

#[derive(Debug, Eq, PartialEq)]
enum ScopedWriteFailure<Error> {
    Snapshot(Error),
    Enable(Error),
    Write(Error),
    Restore(Error),
}

fn coordinated_scoped_write<Api>(
    coordinator: &ConsoleIoCoordinator,
    api: &Api,
    handles: ConsoleHandles<Api::Handle>,
    wide: &[u16],
) -> io::Result<Result<(), ScopedWriteFailure<Api::Error>>>
where
    Api: ScopedConsoleApi,
{
    coordinator.synchronized(|| scoped_write(api, handles, wide))
}

fn scoped_write<Api>(
    api: &Api,
    handles: ConsoleHandles<Api::Handle>,
    wide: &[u16],
) -> Result<(), ScopedWriteFailure<Api::Error>>
where
    Api: ScopedConsoleApi,
{
    let original_mode = api
        .console_mode(handles.input)
        .map_err(ScopedWriteFailure::Snapshot)?;
    if original_mode & ENABLE_VIRTUAL_TERMINAL_INPUT != 0 {
        return api
            .write_console(handles.output, wide)
            .map_err(ScopedWriteFailure::Write);
    }

    api.set_console_mode(handles.input, original_mode | ENABLE_VIRTUAL_TERMINAL_INPUT)
        .map_err(ScopedWriteFailure::Enable)?;
    let restore = InputModeRestore::new(api, handles.input, original_mode);
    let write_result = api.write_console(handles.output, wide);
    let restore_result = restore.restore();

    // A failed restoration is always fatal and takes precedence over a write
    // error because otherwise the input thread could continue in VT mode.
    restore_result.map_err(ScopedWriteFailure::Restore)?;
    write_result.map_err(ScopedWriteFailure::Write)
}

struct InputModeRestore<'a, Api>
where
    Api: ScopedConsoleApi,
{
    api: &'a Api,
    handle: Api::Handle,
    mode: u32,
    armed: bool,
}

impl<'a, Api> InputModeRestore<'a, Api>
where
    Api: ScopedConsoleApi,
{
    const fn new(api: &'a Api, handle: Api::Handle, mode: u32) -> Self {
        Self {
            api,
            handle,
            mode,
            armed: true,
        }
    }

    fn restore(mut self) -> Result<(), Api::Error> {
        let result = self.api.set_console_mode(self.handle, self.mode);
        if result.is_ok() {
            self.armed = false;
        }
        result
    }
}

impl<Api> Drop for InputModeRestore<'_, Api>
where
    Api: ScopedConsoleApi,
{
    fn drop(&mut self) {
        if self.armed {
            let _ = self.api.set_console_mode(self.handle, self.mode);
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Win32ConsoleFailure {
    Os(u32),
    WriteZero,
}

#[derive(Clone, Copy, Debug)]
struct Win32ConsoleApi;

impl ScopedConsoleApi for Win32ConsoleApi {
    type Handle = HANDLE;
    type Error = Win32ConsoleFailure;

    fn std_handle(&self, handle_id: u32) -> Result<Option<Self::Handle>, Self::Error> {
        let handle = unsafe {
            // SAFETY: GetStdHandle accepts the documented STD_* identifiers.
            GetStdHandle(handle_id)
        };
        if handle.is_null() || handle == INVALID_HANDLE_VALUE {
            return Ok(None);
        }
        Ok(Some(handle))
    }

    fn console_mode(&self, handle: Self::Handle) -> Result<u32, Self::Error> {
        let mut mode = 0;
        let ok = unsafe {
            // SAFETY: handle is borrowed and mode points to writable storage.
            GetConsoleMode(handle, &mut mode)
        };
        if ok == 0 {
            return Err(last_win32_failure());
        }
        Ok(mode)
    }

    fn set_console_mode(&self, handle: Self::Handle, mode: u32) -> Result<(), Self::Error> {
        let ok = unsafe {
            // SAFETY: handle was validated as a console input handle and mode
            // is an exact snapshot or that snapshot plus one documented bit.
            SetConsoleMode(handle, mode)
        };
        if ok == 0 {
            return Err(last_win32_failure());
        }
        Ok(())
    }

    fn write_console(&self, handle: Self::Handle, wide: &[u16]) -> Result<(), Self::Error> {
        let mut written = 0;
        while written < wide.len() {
            let chunk_len = console_write_chunk_len(&wide[written..]) as u32;
            let mut chars_written = 0;
            let ok = unsafe {
                // SAFETY: handle is a validated console output handle and the
                // slice contains initialized UTF-16 code units.
                WriteConsoleW(
                    handle,
                    wide[written..].as_ptr().cast(),
                    chunk_len,
                    &mut chars_written,
                    std::ptr::null_mut(),
                )
            };
            if ok == 0 {
                return Err(last_win32_failure());
            }
            if chars_written == 0 {
                return Err(Win32ConsoleFailure::WriteZero);
            }
            written += chars_written as usize;
        }
        Ok(())
    }
}

fn console_write_chunk_len(remaining: &[u16]) -> usize {
    let mut chunk_len = remaining.len().min(MAX_WRITE_CONSOLE_CODE_UNITS);
    if chunk_len < remaining.len()
        && chunk_len > 1
        && (0xD800..=0xDBFF).contains(&remaining[chunk_len - 1])
    {
        chunk_len -= 1;
    }
    chunk_len
}

fn last_win32_failure() -> Win32ConsoleFailure {
    let code = unsafe {
        // SAFETY: GetLastError reads thread-local Win32 error state.
        GetLastError()
    };
    Win32ConsoleFailure::Os(code)
}

fn scoped_failure_to_io(failure: ScopedWriteFailure<Win32ConsoleFailure>) -> io::Error {
    let failure = match failure {
        ScopedWriteFailure::Snapshot(failure)
        | ScopedWriteFailure::Enable(failure)
        | ScopedWriteFailure::Write(failure)
        | ScopedWriteFailure::Restore(failure) => failure,
    };
    win32_failure_to_io(failure)
}

fn win32_failure_to_io(failure: Win32ConsoleFailure) -> io::Error {
    match failure {
        Win32ConsoleFailure::Os(code) => io::Error::from_raw_os_error(code as i32),
        Win32ConsoleFailure::WriteZero => io::Error::new(
            io::ErrorKind::WriteZero,
            "WriteConsoleW wrote zero UTF-16 code units",
        ),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Barrier, Mutex};
    use std::thread;
    use std::time::Duration;

    use windows_sys::Win32::System::Console::{
        ENABLE_MOUSE_INPUT, ENABLE_VIRTUAL_TERMINAL_INPUT, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
    };

    use super::super::windows_version::SCOPED_VT_INPUT_MIN_BUILD;
    use super::{
        console_write_chunk_len, coordinated_scoped_write, eligible_console_handles, scoped_write,
        ConsoleHandles, ConsoleIoCoordinator, ScopedConsoleApi, ScopedWriteFailure, WindowsVersion,
        MAX_WRITE_CONSOLE_CODE_UNITS,
    };

    const INPUT: u8 = 1;
    const OUTPUT: u8 = 2;

    #[test]
    fn console_writes_are_bounded_without_splitting_surrogate_pairs() {
        let short = vec![b'x' as u16; 32];
        assert_eq!(console_write_chunk_len(&short), short.len());

        let oversized = vec![b'x' as u16; MAX_WRITE_CONSOLE_CODE_UNITS + 1];
        assert_eq!(
            console_write_chunk_len(&oversized),
            MAX_WRITE_CONSOLE_CODE_UNITS
        );

        let mut boundary_pair = oversized;
        boundary_pair[MAX_WRITE_CONSOLE_CODE_UNITS - 1] = 0xD83D;
        boundary_pair[MAX_WRITE_CONSOLE_CODE_UNITS] = 0xDE00;
        assert_eq!(
            console_write_chunk_len(&boundary_pair),
            MAX_WRITE_CONSOLE_CODE_UNITS - 1
        );
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    enum Event {
        GetMode(u8),
        SetMode(u8, u32),
        Write(u8),
    }

    #[derive(Debug)]
    struct FakeState {
        input_mode: Result<u32, &'static str>,
        output_mode: Result<u32, &'static str>,
        events: Vec<Event>,
        set_calls: usize,
        fail_set_call: Option<usize>,
        fail_write: bool,
        slow_write: bool,
    }

    #[derive(Clone, Debug)]
    struct FakeApi {
        state: Arc<Mutex<FakeState>>,
        stdin: Option<u8>,
        stdout: Option<u8>,
    }

    impl FakeApi {
        fn new(
            input_mode: Result<u32, &'static str>,
            output_mode: Result<u32, &'static str>,
        ) -> Self {
            Self {
                state: Arc::new(Mutex::new(FakeState {
                    input_mode,
                    output_mode,
                    events: Vec::new(),
                    set_calls: 0,
                    fail_set_call: None,
                    fail_write: false,
                    slow_write: false,
                })),
                stdin: Some(INPUT),
                stdout: Some(OUTPUT),
            }
        }

        fn events(&self) -> Vec<Event> {
            self.state.lock().expect("fake state").events.clone()
        }

        fn clear_events(&self) {
            self.state.lock().expect("fake state").events.clear();
        }
    }

    impl ScopedConsoleApi for FakeApi {
        type Handle = u8;
        type Error = &'static str;

        fn std_handle(&self, handle_id: u32) -> Result<Option<Self::Handle>, Self::Error> {
            match handle_id {
                STD_INPUT_HANDLE => Ok(self.stdin),
                STD_OUTPUT_HANDLE => Ok(self.stdout),
                _ => Ok(None),
            }
        }

        fn console_mode(&self, handle: Self::Handle) -> Result<u32, Self::Error> {
            let mut state = self.state.lock().expect("fake state");
            state.events.push(Event::GetMode(handle));
            match handle {
                INPUT => state.input_mode,
                OUTPUT => state.output_mode,
                _ => Err("unknown handle"),
            }
        }

        fn set_console_mode(&self, handle: Self::Handle, mode: u32) -> Result<(), Self::Error> {
            let mut state = self.state.lock().expect("fake state");
            state.set_calls += 1;
            state.events.push(Event::SetMode(handle, mode));
            if state.fail_set_call == Some(state.set_calls) {
                return Err("set failed");
            }
            if handle == INPUT {
                state.input_mode = Ok(mode);
            }
            Ok(())
        }

        fn write_console(&self, handle: Self::Handle, _wide: &[u16]) -> Result<(), Self::Error> {
            let (fail, slow) = {
                let mut state = self.state.lock().expect("fake state");
                state.events.push(Event::Write(handle));
                (state.fail_write, state.slow_write)
            };
            if slow {
                thread::sleep(Duration::from_millis(15));
            }
            if fail {
                Err("write failed")
            } else {
                Ok(())
            }
        }
    }

    fn version(build: u32) -> WindowsVersion {
        WindowsVersion {
            major: 10,
            minor: 0,
            build,
        }
    }

    #[test]
    fn eligibility_requires_supported_build_and_two_console_handles() {
        let api = FakeApi::new(Ok(ENABLE_MOUSE_INPUT), Ok(0));
        assert_eq!(eligible_console_handles(&api, None, OUTPUT), None);
        assert_eq!(
            eligible_console_handles(&api, Some(version(19_045)), OUTPUT),
            None
        );
        assert!(api.events().is_empty(), "old builds must not probe handles");

        assert_eq!(
            eligible_console_handles(&api, Some(version(SCOPED_VT_INPUT_MIN_BUILD)), OUTPUT,),
            Some(ConsoleHandles {
                input: INPUT,
                output: OUTPUT,
            })
        );

        let pipe_input = FakeApi::new(Err("pipe"), Ok(0));
        assert_eq!(
            eligible_console_handles(
                &pipe_input,
                Some(version(SCOPED_VT_INPUT_MIN_BUILD)),
                OUTPUT,
            ),
            None
        );
        let pipe_output = FakeApi::new(Ok(0), Err("pipe"));
        assert_eq!(
            eligible_console_handles(
                &pipe_output,
                Some(version(SCOPED_VT_INPUT_MIN_BUILD)),
                OUTPUT,
            ),
            None
        );
        assert_eq!(
            eligible_console_handles(&api, Some(version(SCOPED_VT_INPUT_MIN_BUILD)), 9,),
            None
        );
    }

    #[test]
    fn scoped_write_snapshots_enables_writes_and_restores_exactly() {
        let original = ENABLE_MOUSE_INPUT;
        let api = FakeApi::new(Ok(original), Ok(0));
        let handles = ConsoleHandles {
            input: INPUT,
            output: OUTPUT,
        };
        scoped_write(&api, handles, &[0x1b, b'[' as u16]).expect("scoped write");
        assert_eq!(
            api.events(),
            vec![
                Event::GetMode(INPUT),
                Event::SetMode(INPUT, original | ENABLE_VIRTUAL_TERMINAL_INPUT),
                Event::Write(OUTPUT),
                Event::SetMode(INPUT, original),
            ]
        );
        assert_eq!(
            api.state.lock().expect("fake state").input_mode,
            Ok(original)
        );
    }

    #[test]
    fn write_failure_still_restores_the_snapshot() {
        let api = FakeApi::new(Ok(7), Ok(0));
        api.state.lock().expect("fake state").fail_write = true;
        let error = scoped_write(
            &api,
            ConsoleHandles {
                input: INPUT,
                output: OUTPUT,
            },
            &[1],
        )
        .expect_err("write must fail");
        assert_eq!(error, ScopedWriteFailure::Write("write failed"));
        assert_eq!(api.state.lock().expect("fake state").input_mode, Ok(7));
    }

    #[test]
    fn snapshot_failure_never_changes_mode_or_writes() {
        let api = FakeApi::new(Err("snapshot failed"), Ok(0));
        let error = scoped_write(
            &api,
            ConsoleHandles {
                input: INPUT,
                output: OUTPUT,
            },
            &[1],
        )
        .expect_err("snapshot must fail");
        assert_eq!(error, ScopedWriteFailure::Snapshot("snapshot failed"));
        assert_eq!(api.events(), vec![Event::GetMode(INPUT)]);
    }

    #[test]
    fn enable_failure_never_writes_or_attempts_a_restore() {
        let api = FakeApi::new(Ok(11), Ok(0));
        api.state.lock().expect("fake state").fail_set_call = Some(1);
        let error = scoped_write(
            &api,
            ConsoleHandles {
                input: INPUT,
                output: OUTPUT,
            },
            &[1],
        )
        .expect_err("enable must fail");
        assert_eq!(error, ScopedWriteFailure::Enable("set failed"));
        assert_eq!(
            api.events(),
            vec![
                Event::GetMode(INPUT),
                Event::SetMode(INPUT, 11 | ENABLE_VIRTUAL_TERMINAL_INPUT),
            ]
        );
        assert_eq!(api.state.lock().expect("fake state").input_mode, Ok(11));
    }

    #[test]
    fn restoration_failure_is_fatal_even_when_write_also_fails() {
        let api = FakeApi::new(Ok(9), Ok(0));
        {
            let mut state = api.state.lock().expect("fake state");
            state.fail_write = true;
            state.fail_set_call = Some(2);
        }
        let error = scoped_write(
            &api,
            ConsoleHandles {
                input: INPUT,
                output: OUTPUT,
            },
            &[1],
        )
        .expect_err("restore must fail");
        assert_eq!(error, ScopedWriteFailure::Restore("set failed"));
        assert_eq!(
            api.state.lock().expect("fake state").input_mode,
            Ok(9),
            "RAII fallback retries restoration before the fatal error escapes"
        );
    }

    #[test]
    fn already_enabled_input_mode_is_not_rewritten() {
        let api = FakeApi::new(Ok(3 | ENABLE_VIRTUAL_TERMINAL_INPUT), Ok(0));
        scoped_write(
            &api,
            ConsoleHandles {
                input: INPUT,
                output: OUTPUT,
            },
            &[1],
        )
        .expect("write succeeds");
        assert_eq!(
            api.events(),
            vec![Event::GetMode(INPUT), Event::Write(OUTPUT)]
        );
    }

    #[test]
    fn concurrent_scoped_writes_cannot_interleave_mode_windows() {
        let api = FakeApi::new(Ok(5), Ok(0));
        api.state.lock().expect("fake state").slow_write = true;
        let coordinator = Arc::new(ConsoleIoCoordinator::new());
        let start = Arc::new(Barrier::new(3));
        let handles = ConsoleHandles {
            input: INPUT,
            output: OUTPUT,
        };
        let workers = (0..2)
            .map(|_| {
                let api = api.clone();
                let coordinator = Arc::clone(&coordinator);
                let start = Arc::clone(&start);
                thread::spawn(move || {
                    start.wait();
                    coordinated_scoped_write(&coordinator, &api, handles, &[1])
                        .expect("coordinator")
                        .expect("write");
                })
            })
            .collect::<Vec<_>>();
        start.wait();
        for worker in workers {
            worker.join().expect("worker");
        }

        let events = api.events();
        let group = |offset: usize| &events[offset..offset + 4];
        for offset in [0, 4] {
            assert_eq!(group(offset)[0], Event::GetMode(INPUT));
            assert!(matches!(group(offset)[1], Event::SetMode(INPUT, _)));
            assert_eq!(group(offset)[2], Event::Write(OUTPUT));
            assert_eq!(group(offset)[3], Event::SetMode(INPUT, 5));
        }
        api.clear_events();
    }
}