rmux-server 0.10.0

Tokio daemon and request dispatcher 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
//! Fragmentation-safe WebShare policy boundary.
//!
//! Visual OSC commands on the allowlist survive. Clipboard OSC 52, unknown
//! OSC commands, and every APC/DCS/PM/SOS string (including Kitty graphics and
//! SIXEL) are dropped rather than delegated to browser-terminal behavior.
//!
//! RMUX decodes UTF-8 only in Ground. Encoded C1 code points are therefore
//! zero-width text for the pane owner, while xterm.js would reinterpret them as
//! terminal controls. This boundary removes those nonprinting code points and
//! replaces malformed Ground UTF-8 with U+FFFD before xterm.js sees it.

use super::WebShareConnectRole;

const MAX_BUFFERED_OSC_BYTES: usize = 1024 * 1024;
const HYPERLINK_CLOSE_ST: &[u8] = b"\x1b]8;;\x1b\\";
const UTF8_REPLACEMENT: &[u8] = "\u{fffd}".as_bytes();

#[derive(Debug)]
pub(crate) struct WebTerminalSanitizer {
    role: WebShareConnectRole,
    state: State,
    pending_utf8: Option<PendingUtf8>,
}

#[derive(Debug, Default)]
enum State {
    #[default]
    Ground,
    Escape,
    Osc {
        bytes: Vec<u8>,
        escaped: bool,
    },
    DiscardString(DiscardString),
    Dcs(DcsState),
}

#[derive(Debug)]
struct DiscardString {
    escaped: bool,
    terminator: StringTerminator,
    completion: DiscardCompletion,
}

impl DiscardString {
    const fn new(terminator: StringTerminator) -> Self {
        Self {
            escaped: false,
            terminator,
            completion: DiscardCompletion::Drop,
        }
    }

    const fn with_escape(
        terminator: StringTerminator,
        escaped: bool,
        completion: DiscardCompletion,
    ) -> Self {
        Self {
            escaped,
            terminator,
            completion,
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum DiscardCompletion {
    Drop,
    CloseHyperlink,
}

#[derive(Debug, Clone, Copy)]
enum StringTerminator {
    St,
    StOrBel,
}

#[derive(Debug)]
enum DcsState {
    Entry,
    Parameter,
    Intermediate,
    Ignore,
    Passthrough,
    PassthroughEscape,
}

#[derive(Debug)]
struct PendingUtf8 {
    bytes: [u8; 4],
    len: u8,
    expected: u8,
}

impl PendingUtf8 {
    fn start(byte: u8) -> Option<Self> {
        let expected = match byte {
            0xc0..=0xdf => 2,
            0xe0..=0xef => 3,
            0xf0..=0xf7 => 4,
            _ => return None,
        };
        let mut bytes = [0; 4];
        bytes[0] = byte;
        Some(Self {
            bytes,
            len: 1,
            expected,
        })
    }

    fn push_continuation(&mut self, byte: u8) -> bool {
        if byte & 0xc0 != 0x80 {
            return false;
        }
        self.bytes[usize::from(self.len)] = byte;
        self.len += 1;
        true
    }

    const fn is_complete(&self) -> bool {
        self.len == self.expected
    }

    fn bytes(&self) -> &[u8] {
        &self.bytes[..usize::from(self.len)]
    }
}

impl Default for WebTerminalSanitizer {
    fn default() -> Self {
        Self::for_role(WebShareConnectRole::Operator)
    }
}

impl WebTerminalSanitizer {
    pub(crate) fn for_role(role: WebShareConnectRole) -> Self {
        Self {
            role,
            state: State::Ground,
            pending_utf8: None,
        }
    }

    pub(crate) fn push(&mut self, input: &[u8], output: &mut Vec<u8>) {
        for byte in input.iter().copied() {
            self.push_byte(byte, output);
        }
    }

    pub(crate) fn reset(&mut self) {
        self.state = State::Ground;
        self.pending_utf8 = None;
    }

    fn push_byte(&mut self, byte: u8, output: &mut Vec<u8>) {
        if let Some(mut pending) = self.pending_utf8.take() {
            if pending.push_continuation(byte) {
                if pending.is_complete() {
                    forward_ground_utf8(&pending, output);
                } else {
                    self.pending_utf8 = Some(pending);
                }
                return;
            }
            output.extend_from_slice(UTF8_REPLACEMENT);
        }

        if matches!(self.state, State::Ground) && byte >= 0x80 {
            if let Some(pending) = PendingUtf8::start(byte) {
                self.pending_utf8 = Some(pending);
            } else {
                output.extend_from_slice(UTF8_REPLACEMENT);
            }
            return;
        }

        self.process_byte(byte, output);
    }

    fn process_byte(&mut self, byte: u8, output: &mut Vec<u8>) {
        let state = std::mem::take(&mut self.state);
        self.state = match state {
            State::Ground => ground(byte, output),
            State::Escape => escape_sequence(byte, output),
            State::Osc { mut bytes, escaped } => {
                if escaped && byte != b'\\' {
                    close_rejected_hyperlink(&bytes, self.role, output);
                    escape_sequence(byte, output)
                } else if escaped || byte == 0x07 {
                    bytes.push(byte);
                    complete_osc(&bytes, self.role, output);
                    State::Ground
                } else if cancelled(byte) {
                    State::Ground
                } else if bytes.len() >= MAX_BUFFERED_OSC_BYTES {
                    State::DiscardString(DiscardString::with_escape(
                        StringTerminator::StOrBel,
                        byte == 0x1b,
                        if is_hyperlink_osc(&bytes) {
                            DiscardCompletion::CloseHyperlink
                        } else {
                            DiscardCompletion::Drop
                        },
                    ))
                } else {
                    bytes.push(byte);
                    State::Osc {
                        bytes,
                        escaped: byte == 0x1b,
                    }
                }
            }
            State::DiscardString(string) => discard_string(string, byte, output),
            State::Dcs(dcs) => dcs_sequence(dcs, byte),
        };
    }
}

fn forward_ground_utf8(sequence: &PendingUtf8, output: &mut Vec<u8>) {
    let Ok(value) = std::str::from_utf8(sequence.bytes()) else {
        output.extend_from_slice(UTF8_REPLACEMENT);
        return;
    };
    let Some(character) = value.chars().next() else {
        output.extend_from_slice(UTF8_REPLACEMENT);
        return;
    };
    if !matches!(u32::from(character), 0x80..=0x9f) {
        output.extend_from_slice(sequence.bytes());
    }
}

fn ground(byte: u8, output: &mut Vec<u8>) -> State {
    match byte {
        0x1b => State::Escape,
        0x18 | 0x1a => State::Ground,
        _ => {
            output.push(byte);
            State::Ground
        }
    }
}

fn escape_sequence(byte: u8, output: &mut Vec<u8>) -> State {
    if cancelled(byte) {
        return State::Ground;
    }
    match byte {
        b']' => State::Osc {
            bytes: vec![0x1b, b']'],
            escaped: false,
        },
        b'P' => State::Dcs(DcsState::Entry),
        b'X' | b'^' | b'_' | b'k' => State::DiscardString(DiscardString::new(StringTerminator::St)),
        // Executing a C0 control does not leave the terminal's Escape state.
        0x00..=0x17 | 0x19 | 0x1c..=0x1f => {
            output.push(byte);
            State::Escape
        }
        0x1b => State::Escape,
        0x7f..=0xff => State::Escape,
        _ => {
            output.push(0x1b);
            output.push(byte);
            State::Ground
        }
    }
}

fn discard_string(mut string: DiscardString, byte: u8, output: &mut Vec<u8>) -> State {
    if string.escaped {
        return if byte == b'\\' {
            complete_discard(string.completion, output);
            State::Ground
        } else {
            complete_discard(string.completion, output);
            escape_sequence(byte, output)
        };
    }
    if cancelled(byte) {
        return State::Ground;
    }
    if matches!(string.terminator, StringTerminator::StOrBel) && byte == 0x07 {
        complete_discard(string.completion, output);
        return State::Ground;
    }
    string.escaped = byte == 0x1b;
    State::DiscardString(string)
}

fn complete_discard(completion: DiscardCompletion, output: &mut Vec<u8>) {
    if matches!(completion, DiscardCompletion::CloseHyperlink) {
        output.extend_from_slice(HYPERLINK_CLOSE_ST);
    }
}

fn complete_osc(sequence: &[u8], role: WebShareConnectRole, output: &mut Vec<u8>) {
    match osc_disposition(sequence, role) {
        OscDisposition::Forward => output.extend_from_slice(sequence),
        OscDisposition::Drop => {}
        OscDisposition::CloseHyperlink => output.extend_from_slice(HYPERLINK_CLOSE_ST),
    }
}

fn close_rejected_hyperlink(sequence: &[u8], role: WebShareConnectRole, output: &mut Vec<u8>) {
    if matches!(
        osc_disposition(sequence, role),
        OscDisposition::CloseHyperlink
    ) {
        output.extend_from_slice(HYPERLINK_CLOSE_ST);
    }
}

fn dcs_sequence(state: DcsState, byte: u8) -> State {
    match state {
        DcsState::Entry => match byte {
            0x18 | 0x1a => State::Ground,
            0x1b => State::Escape,
            0x20..=0x2f => State::Dcs(DcsState::Intermediate),
            0x30..=0x39 | 0x3b..=0x3f => State::Dcs(DcsState::Parameter),
            0x3a => State::Dcs(DcsState::Ignore),
            0x40..=0x7e => State::Dcs(DcsState::Passthrough),
            _ => State::Dcs(DcsState::Entry),
        },
        DcsState::Parameter => match byte {
            0x18 | 0x1a => State::Ground,
            0x1b => State::Escape,
            0x20..=0x2f => State::Dcs(DcsState::Intermediate),
            0x30..=0x39 | 0x3b => State::Dcs(DcsState::Parameter),
            0x3a | 0x3c..=0x3f => State::Dcs(DcsState::Ignore),
            0x40..=0x7e => State::Dcs(DcsState::Passthrough),
            _ => State::Dcs(DcsState::Parameter),
        },
        DcsState::Intermediate => match byte {
            0x18 | 0x1a => State::Ground,
            0x1b => State::Escape,
            0x20..=0x2f => State::Dcs(DcsState::Intermediate),
            0x30..=0x3f => State::Dcs(DcsState::Ignore),
            0x40..=0x7e => State::Dcs(DcsState::Passthrough),
            _ => State::Dcs(DcsState::Intermediate),
        },
        DcsState::Ignore => match byte {
            0x18 | 0x1a => State::Ground,
            0x1b => State::Escape,
            _ => State::Dcs(DcsState::Ignore),
        },
        DcsState::Passthrough => {
            if byte == 0x1b {
                State::Dcs(DcsState::PassthroughEscape)
            } else {
                State::Dcs(DcsState::Passthrough)
            }
        }
        DcsState::PassthroughEscape => {
            if byte == b'\\' {
                State::Ground
            } else {
                State::Dcs(DcsState::Passthrough)
            }
        }
    }
}

const fn cancelled(byte: u8) -> bool {
    matches!(byte, 0x18 | 0x1a)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OscDisposition {
    Forward,
    Drop,
    CloseHyperlink,
}

fn osc_disposition(sequence: &[u8], role: WebShareConnectRole) -> OscDisposition {
    let Some(payload) = sequence.strip_prefix(b"\x1b]".as_slice()) else {
        return OscDisposition::Drop;
    };
    let encoded_c1 = payload
        .windows(2)
        .any(|pair| pair[0] == 0xc2 && (0x80..=0x9f).contains(&pair[1]));
    let code_end = payload
        .iter()
        .position(|byte| *byte == b';' || *byte == 0x07 || *byte == 0x1b)
        .unwrap_or(payload.len());
    let Ok(code) = std::str::from_utf8(&payload[..code_end]) else {
        return OscDisposition::Drop;
    };
    if code == "8" {
        return if !encoded_c1 && allowed_hyperlink(&payload[code_end..]) {
            OscDisposition::Forward
        } else {
            OscDisposition::CloseHyperlink
        };
    }
    if encoded_c1 {
        return OscDisposition::Drop;
    }
    let visual = matches!(
        code,
        "4" | "10" | "11" | "12" | "104" | "110" | "111" | "112"
    );
    let private_metadata = matches!(code, "0" | "1" | "2" | "7" | "133");
    if visual || (matches!(role, WebShareConnectRole::Operator) && private_metadata) {
        OscDisposition::Forward
    } else {
        OscDisposition::Drop
    }
}

fn is_hyperlink_osc(sequence: &[u8]) -> bool {
    let Some(payload) = sequence.strip_prefix(b"\x1b]".as_slice()) else {
        return false;
    };
    let code_end = payload
        .iter()
        .position(|byte| *byte == b';' || *byte == 0x07 || *byte == 0x1b)
        .unwrap_or(payload.len());
    std::str::from_utf8(&payload[..code_end]) == Ok("8")
}

fn allowed_hyperlink(payload: &[u8]) -> bool {
    let payload = payload.strip_prefix(b";").unwrap_or(payload);
    let payload = strip_osc_terminator(payload);
    let Some(separator) = payload.iter().position(|byte| *byte == b';') else {
        return false;
    };
    let uri = &payload[separator + 1..];
    if uri.is_empty() {
        return true;
    }
    let Ok(uri) = std::str::from_utf8(uri) else {
        return false;
    };
    let Some((scheme, _)) = uri.split_once(':') else {
        return false;
    };
    matches!(
        scheme.to_ascii_lowercase().as_str(),
        "http" | "https" | "mailto"
    )
}

fn strip_osc_terminator(mut payload: &[u8]) -> &[u8] {
    if payload.ends_with(b"\x1b\\") {
        payload = &payload[..payload.len() - 2];
    } else if payload.last() == Some(&0x07) {
        payload = &payload[..payload.len() - 1];
    }
    payload
}

#[cfg(test)]
#[path = "stream_sanitizer/oracle_tests.rs"]
mod oracle_tests;

#[cfg(test)]
#[path = "stream_sanitizer/tests.rs"]
mod tests;