moshpits 0.19.0

moshpits server (mps) — server daemon for moshpit remote terminal sessions
// Copyright (c) 2025 moshpit developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Scan raw PTY output for OSC 0/1/2 (window/icon title) and OSC 52 (clipboard write)
//! escape sequences, so they can be forwarded to the client's real terminal alongside
//! the normal diff/scrollback pipeline (which otherwise absorbs them as harmless no-ops
//! in the vt100 emulator).
//!
//! [`scan_osc`] is a pure, read-only scan: it never strips or mutates the bytes the
//! caller separately forwards to scrollback / the vt100 emulator / `Bytes`-family
//! frames — the events it returns are an *additional*, parallel notification channel.

use tracing::warn;

/// Maximum number of carry-over bytes retained across [`scan_osc`] calls for an
/// as-yet-unterminated OSC sequence. Bounds memory if a program emits `ESC ]` and
/// never terminates it, and keeps any forwarded sequence comfortably under the
/// encrypted-frame size cap.
const OSC_CARRY_CAP: usize = 8192;

/// A window-title or clipboard-write event detected by [`scan_osc`], carrying the raw
/// escape sequence bytes exactly as captured (including the leading `ESC ]` and the
/// terminator) so the client can write them straight to its real stdout unmodified.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum OscEvent {
    /// Raw OSC 0/1/2 window/icon-title sequence.
    Title(Vec<u8>),
    /// Raw OSC 52 clipboard-write sequence (selector `c`, write direction only).
    Clipboard(Vec<u8>),
}

/// What an OSC sequence's params (`0`, `52;c;...`, etc.) classify as.
enum OscKind {
    Title,
    Clipboard,
}

/// Scan `buf` (one chunk of raw PTY output) for complete OSC 0/1/2 (title) and OSC 52
/// (clipboard write, selector `c` only) escape sequences, reassembling sequences split
/// across PTY `read()` calls using `carry`.
///
/// `carry` holds the tail of an in-progress, not-yet-terminated OSC sequence from the
/// previous call and is updated in place: extended when this call ends mid-sequence,
/// cleared once the sequence completes or overflows [`OSC_CARRY_CAP`] (in which case the
/// partial sequence is dropped and a warning logged).
///
/// OSC 52 read requests (`52;c;?`) and non-`c` selectors (`p`, `s`, `0`-`7`, multi-selector
/// forms) are recognized but intentionally not returned as events — see the module docs
/// and the design notes on why only the clipboard-write direction is forwarded.
pub(crate) fn scan_osc(buf: &[u8], carry: &mut Vec<u8>) -> Vec<OscEvent> {
    let mut events = Vec::new();
    let owned;
    let data: &[u8] = if carry.is_empty() {
        buf
    } else {
        let mut w = std::mem::take(carry);
        w.extend_from_slice(buf);
        owned = w;
        &owned
    };

    let mut i = 0;
    while i < data.len() {
        if data[i] != 0x1b {
            i += 1;
            continue;
        }
        // Found ESC; need one more byte to know if this is an OSC start ("ESC ]").
        if i + 1 >= data.len() {
            carry.extend_from_slice(&data[i..]);
            return events;
        }
        if data[i + 1] != b']' {
            i += 1;
            continue;
        }

        let start = i;
        let mut j = i + 2;
        let mut terminator_len = 0usize;
        while j < data.len() {
            if data[j] == 0x07 {
                terminator_len = 1;
                break;
            }
            if data[j] == 0x1b {
                if j + 1 >= data.len() {
                    // Possible split ST (`ESC \`) — wait for more bytes.
                    break;
                }
                if data[j + 1] == b'\\' {
                    terminator_len = 2;
                    break;
                }
            }
            j += 1;
        }

        if terminator_len == 0 {
            let remaining = &data[start..];
            if remaining.len() > OSC_CARRY_CAP {
                warn!(
                    len = remaining.len(),
                    "unterminated OSC sequence exceeded carry cap; dropping"
                );
            } else {
                carry.extend_from_slice(remaining);
            }
            return events;
        }

        let end = j + terminator_len;
        let params = &data[start + 2..j];
        if let Some(kind) = classify_osc(params) {
            let seq = data[start..end].to_vec();
            events.push(match kind {
                OscKind::Title => OscEvent::Title(seq),
                OscKind::Clipboard => OscEvent::Clipboard(seq),
            });
        }
        i = end;
    }
    events
}

/// Classify OSC params (the bytes between `ESC ]` and the terminator) as a title-setting
/// sequence (`0`, `1`, or `2`), a clipboard-write sequence (`52;c;<data>` where `<data>`
/// is not a bare `?` read request), or neither.
fn classify_osc(params: &[u8]) -> Option<OscKind> {
    let mut it = params.splitn(2, |&b| b == b';');
    let cmd = it.next().unwrap_or(b"");
    match cmd {
        b"0" | b"1" | b"2" => Some(OscKind::Title),
        b"52" => {
            let rest = it.next()?;
            let mut rest_it = rest.splitn(2, |&b| b == b';');
            let selector = rest_it.next()?;
            let data = rest_it.next().unwrap_or(b"");
            if selector == b"c" && data != b"?" {
                Some(OscKind::Clipboard)
            } else {
                None
            }
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::{OSC_CARRY_CAP, OscEvent, scan_osc};

    #[test]
    fn title_bel_terminated_single_chunk() {
        let mut carry = Vec::new();
        let events = scan_osc(b"\x1b]0;my title\x07", &mut carry);
        assert_eq!(
            events,
            vec![OscEvent::Title(b"\x1b]0;my title\x07".to_vec())]
        );
        assert_eq!(carry, Vec::<u8>::new());
    }

    #[test]
    fn title_st_terminated_single_chunk() {
        let mut carry = Vec::new();
        let events = scan_osc(b"\x1b]2;my title\x1b\\", &mut carry);
        assert_eq!(
            events,
            vec![OscEvent::Title(b"\x1b]2;my title\x1b\\".to_vec())]
        );
        assert_eq!(carry, Vec::<u8>::new());
    }

    #[test]
    fn icon_name_osc1_is_title() {
        let mut carry = Vec::new();
        let events = scan_osc(b"\x1b]1;icon\x07", &mut carry);
        assert_eq!(events, vec![OscEvent::Title(b"\x1b]1;icon\x07".to_vec())]);
    }

    #[test]
    fn clipboard_write_bel_terminated() {
        let mut carry = Vec::new();
        let events = scan_osc(b"\x1b]52;c;aGVsbG8=\x07", &mut carry);
        assert_eq!(
            events,
            vec![OscEvent::Clipboard(b"\x1b]52;c;aGVsbG8=\x07".to_vec())]
        );
    }

    #[test]
    fn clipboard_write_st_terminated() {
        let mut carry = Vec::new();
        let events = scan_osc(b"\x1b]52;c;aGVsbG8=\x1b\\", &mut carry);
        assert_eq!(
            events,
            vec![OscEvent::Clipboard(b"\x1b]52;c;aGVsbG8=\x1b\\".to_vec())]
        );
    }

    #[test]
    fn clipboard_empty_payload_is_forwarded() {
        // An empty payload is a "clear clipboard" request in some terminals; harmless
        // to pass through raw.
        let mut carry = Vec::new();
        let events = scan_osc(b"\x1b]52;c;\x07", &mut carry);
        assert_eq!(
            events,
            vec![OscEvent::Clipboard(b"\x1b]52;c;\x07".to_vec())]
        );
    }

    #[test]
    fn clipboard_read_request_is_not_forwarded() {
        let mut carry = Vec::new();
        let events = scan_osc(b"\x1b]52;c;?\x07", &mut carry);
        assert_eq!(events, Vec::<OscEvent>::new());
    }

    #[test]
    fn clipboard_non_clipboard_selector_is_not_forwarded() {
        for selector in [&b"p"[..], b"s", b"0"] {
            let mut carry = Vec::new();
            let mut seq = b"\x1b]52;".to_vec();
            seq.extend_from_slice(selector);
            seq.extend_from_slice(b";aGVsbG8=\x07");
            let events = scan_osc(&seq, &mut carry);
            assert!(
                events.is_empty(),
                "selector {selector:?} should not forward"
            );
        }
    }

    #[test]
    fn unrelated_osc_is_ignored() {
        let mut carry = Vec::new();
        let events = scan_osc(b"\x1b]4;1;rgb:ff/00/00\x07", &mut carry);
        assert_eq!(events, Vec::<OscEvent>::new());
    }

    #[test]
    fn split_across_reads_before_terminator() {
        let mut carry = Vec::new();
        let events1 = scan_osc(b"\x1b]52;c;", &mut carry);
        assert_eq!(events1, Vec::<OscEvent>::new());
        assert_eq!(carry, b"\x1b]52;c;");
        let events2 = scan_osc(b"aGVsbG8=\x07", &mut carry);
        assert_eq!(
            events2,
            vec![OscEvent::Clipboard(b"\x1b]52;c;aGVsbG8=\x07".to_vec())]
        );
        assert_eq!(carry, Vec::<u8>::new());
    }

    #[test]
    fn split_exactly_at_bel_terminator_boundary() {
        // Terminator itself split is impossible for BEL (1 byte), but simulate the
        // read boundary landing right before the BEL.
        let mut carry = Vec::new();
        let events1 = scan_osc(b"\x1b]0;title", &mut carry);
        assert_eq!(events1, Vec::<OscEvent>::new());
        let events2 = scan_osc(b"\x07", &mut carry);
        assert_eq!(events2, vec![OscEvent::Title(b"\x1b]0;title\x07".to_vec())]);
    }

    #[test]
    fn split_exactly_at_st_terminator_boundary() {
        // ESC and `\` of the ST terminator arrive in separate reads.
        let mut carry = Vec::new();
        let events1 = scan_osc(b"\x1b]0;title\x1b", &mut carry);
        assert_eq!(events1, Vec::<OscEvent>::new());
        assert_eq!(carry, b"\x1b]0;title\x1b");
        let events2 = scan_osc(b"\\", &mut carry);
        assert_eq!(
            events2,
            vec![OscEvent::Title(b"\x1b]0;title\x1b\\".to_vec())]
        );
    }

    #[test]
    fn split_exactly_after_lone_esc_before_bracket() {
        // The `ESC` and `]` themselves land in separate reads.
        let mut carry = Vec::new();
        let events1 = scan_osc(b"\x1b", &mut carry);
        assert_eq!(events1, Vec::<OscEvent>::new());
        assert_eq!(carry, b"\x1b");
        let events2 = scan_osc(b"]0;title\x07", &mut carry);
        assert_eq!(events2, vec![OscEvent::Title(b"\x1b]0;title\x07".to_vec())]);
    }

    #[test]
    fn carry_cap_exceeded_drops_and_resets() {
        let mut carry = Vec::new();
        let mut huge = b"\x1b]52;c;".to_vec();
        huge.extend(std::iter::repeat_n(b'A', OSC_CARRY_CAP + 100));
        let events = scan_osc(&huge, &mut carry);
        assert_eq!(events, Vec::<OscEvent>::new());
        assert!(
            carry.is_empty(),
            "carry should be reset, not grow unbounded"
        );
    }

    #[test]
    fn multiple_sequences_in_one_chunk() {
        let mut carry = Vec::new();
        let events = scan_osc(b"\x1b]0;first\x07plain text\x1b]52;c;aGk=\x07", &mut carry);
        assert_eq!(
            events,
            vec![
                OscEvent::Title(b"\x1b]0;first\x07".to_vec()),
                OscEvent::Clipboard(b"\x1b]52;c;aGk=\x07".to_vec()),
            ]
        );
    }

    #[test]
    fn ordinary_text_surrounding_split_is_unaffected() {
        let mut carry = Vec::new();
        let events1 = scan_osc(b"hello \x1b]52;c;", &mut carry);
        assert_eq!(events1, Vec::<OscEvent>::new());
        let events2 = scan_osc(b"d29ybGQ=\x07 world", &mut carry);
        assert_eq!(
            events2,
            vec![OscEvent::Clipboard(b"\x1b]52;c;d29ybGQ=\x07".to_vec())]
        );
    }
}