sail-rs 0.6.3

Official Rust SDK for Sail: create and drive sailboxes (sandboxed cloud VMs) with lifecycle, streaming exec, file transfer, and ingress.
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
//! Byte-level scanning of interactive-shell stdin for the two local inputs
//! the bridge forwards into the guest: bracketed pastes (what a file dragged
//! onto the terminal produces) and the Ctrl+V paste chord. Everything else
//! passes through verbatim. Pure state machine β€” no I/O β€” so the splitting,
//! carry, and classification logic is unit-testable; [`crate::shell`] owns
//! what to do with the events.

use std::path::PathBuf;

pub(crate) const PASTE_START: &[u8] = b"\x1b[200~";
pub(crate) const PASTE_END: &[u8] = b"\x1b[201~";

/// Most bytes buffered for one bracketed paste before giving up on rewriting
/// it. Dragged paths are tiny; anything larger is a genuine text paste that
/// should stream through rather than sit in memory awaiting its end marker.
const PASTE_BUFFER_CAP: usize = 64 * 1024;

/// Longest escape sequence held awaiting more bytes. CSI sequences the scanner
/// cares about are all shorter; anything longer is forwarded as ordinary input.
const MAX_CARRY: usize = 16;

/// One classified span of stdin.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum InputEvent {
    /// Forward verbatim.
    Bytes(Vec<u8>),
    /// A complete bracketed paste, markers stripped. The handler either
    /// rewrites it (a dragged file) or re-wraps and forwards it unchanged.
    Paste(Vec<u8>),
    /// A Ctrl+V chord, carrying its exact wire encoding so an unhandled chord
    /// forwards byte-identically.
    PasteChord(Vec<u8>),
}

enum State {
    Normal,
    /// Buffering a bracketed paste until its end marker (or the cap).
    InPaste(Vec<u8>),
    /// A paste that outgrew the cap: stream bytes through until the end
    /// marker, with no chord or paste detection inside.
    PassthroughPaste,
}

/// Scans raw stdin into [`InputEvent`]s, tolerating escape sequences split
/// across reads: an ambiguous suffix is carried into the next `scan` call, and
/// the driver flushes it after a short idle ([`has_idle_carry`] then
/// [`take_carry`]) so a lone ESC keypress still reaches the guest promptly.
///
/// [`has_idle_carry`]: Self::has_idle_carry
/// [`take_carry`]: Self::take_carry
pub(crate) struct InputScanner {
    state: State,
    carry: Vec<u8>,
}

impl InputScanner {
    pub(crate) fn new() -> InputScanner {
        InputScanner {
            state: State::Normal,
            carry: Vec::new(),
        }
    }

    /// Whether held bytes should flush after a short idle. True only outside
    /// a paste: there a carried prefix may be a real keypress (a lone ESC)
    /// that no further bytes will complete. Inside a paste the carry is a
    /// partial end marker whose remaining bytes are still coming β€” flushing
    /// it early would strip the marker's ESC and leave the paste unable to
    /// terminate.
    pub(crate) fn has_idle_carry(&self) -> bool {
        matches!(self.state, State::Normal) && !self.carry.is_empty()
    }

    /// Give up on the carried prefix and return it for verbatim forwarding.
    /// Only meaningful after [`has_idle_carry`](Self::has_idle_carry).
    pub(crate) fn take_carry(&mut self) -> Vec<u8> {
        std::mem::take(&mut self.carry)
    }

    /// Everything still held, reconstructed verbatim, for the final flush
    /// when stdin closes: an unterminated paste flushes as its original
    /// bytes, start marker included.
    pub(crate) fn flush_all(&mut self) -> Vec<u8> {
        let mut out = Vec::new();
        if let State::InPaste(body) = std::mem::replace(&mut self.state, State::Normal) {
            out.extend_from_slice(PASTE_START);
            out.extend_from_slice(&body);
        }
        out.append(&mut self.carry);
        out
    }

    /// Consume one stdin read and return the events it completes.
    pub(crate) fn scan(&mut self, input: &[u8]) -> Vec<InputEvent> {
        let mut buf = std::mem::take(&mut self.carry);
        buf.extend_from_slice(input);
        let mut events = Vec::new();
        let mut plain = Vec::new(); // pending Bytes run, coalesced
        let mut i = 0;

        let flush_plain = |plain: &mut Vec<u8>, events: &mut Vec<InputEvent>| {
            if !plain.is_empty() {
                events.push(InputEvent::Bytes(std::mem::take(plain)));
            }
        };

        while i < buf.len() {
            match &mut self.state {
                State::Normal => match classify_at(&buf[i..]) {
                    Classified::Plain(n) => {
                        plain.extend_from_slice(&buf[i..i + n]);
                        i += n;
                    }
                    Classified::Chord(n) => {
                        flush_plain(&mut plain, &mut events);
                        events.push(InputEvent::PasteChord(buf[i..i + n].to_vec()));
                        i += n;
                    }
                    Classified::PasteStart => {
                        flush_plain(&mut plain, &mut events);
                        self.state = State::InPaste(Vec::new());
                        i += PASTE_START.len();
                    }
                    Classified::NeedMore => {
                        // An ambiguous suffix: hold it for the next read (or a
                        // take_carry flush), unless it can no longer be one of
                        // the short sequences this scanner recognizes.
                        if buf.len() - i > MAX_CARRY {
                            plain.push(buf[i]);
                            i += 1;
                        } else {
                            self.carry = buf[i..].to_vec();
                            i = buf.len();
                        }
                    }
                },
                State::InPaste(body) => {
                    if let Some(end) = find(&buf[i..], PASTE_END) {
                        body.extend_from_slice(&buf[i..i + end]);
                        let body = std::mem::take(body);
                        events.push(InputEvent::Paste(body));
                        self.state = State::Normal;
                        i += end + PASTE_END.len();
                        continue;
                    }
                    // No end marker yet: buffer everything except a suffix that
                    // might start one, which waits for the next read.
                    let keep = partial_suffix_len(&buf[i..], PASTE_END);
                    body.extend_from_slice(&buf[i..buf.len() - keep]);
                    if keep > 0 {
                        self.carry = buf[buf.len() - keep..].to_vec();
                    }
                    if body.len() > PASTE_BUFFER_CAP {
                        // Too big to rewrite: forward what we swallowed (start
                        // marker included) and stream the rest through.
                        let mut raw = PASTE_START.to_vec();
                        raw.append(body);
                        flush_plain(&mut plain, &mut events);
                        events.push(InputEvent::Bytes(raw));
                        self.state = State::PassthroughPaste;
                    }
                    i = buf.len();
                }
                State::PassthroughPaste => {
                    if let Some(end) = find(&buf[i..], PASTE_END) {
                        let through = i + end + PASTE_END.len();
                        plain.extend_from_slice(&buf[i..through]);
                        self.state = State::Normal;
                        i = through;
                        continue;
                    }
                    let keep = partial_suffix_len(&buf[i..], PASTE_END);
                    plain.extend_from_slice(&buf[i..buf.len() - keep]);
                    if keep > 0 {
                        self.carry = buf[buf.len() - keep..].to_vec();
                    }
                    i = buf.len();
                }
            }
        }
        flush_plain(&mut plain, &mut events);
        events
    }
}

enum Classified {
    /// The next `n` bytes are ordinary input.
    Plain(usize),
    /// The next `n` bytes are a Ctrl+V chord.
    Chord(usize),
    /// A bracketed paste begins here.
    PasteStart,
    /// The buffer ends inside a possible sequence; wait for more bytes.
    NeedMore,
}

/// Classify the input at the head of `buf` (Normal state only).
fn classify_at(buf: &[u8]) -> Classified {
    match buf[0] {
        // Ctrl+V as the raw control byte, the common legacy-keyboard encoding.
        0x16 => Classified::Chord(1),
        0x1b => classify_escape(buf),
        _ => {
            // Everything up to the next byte of interest is one plain run.
            let n = buf
                .iter()
                .position(|&b| b == 0x1b || b == 0x16)
                .unwrap_or(buf.len());
            Classified::Plain(n)
        }
    }
}

/// Classify a buffer starting with ESC: a paste marker, a Ctrl+V chord in the
/// kitty (`CSI 118;5 u`) or modifyOtherKeys (`CSI 27;5;118 ~`) encodings, some
/// other complete CSI sequence (plain), or too short to tell.
fn classify_escape(buf: &[u8]) -> Classified {
    if buf.len() < 2 {
        return Classified::NeedMore;
    }
    if buf[1] != b'[' {
        // Not a CSI sequence; forward the ESC and let the next byte rescan.
        return Classified::Plain(1);
    }
    // CSI: parameter bytes (0x30-0x3F), then intermediates (0x20-0x2F), then a
    // final byte (0x40-0x7E).
    let mut i = 2;
    while i < buf.len() && (0x30..=0x3f).contains(&buf[i]) {
        i += 1;
    }
    while i < buf.len() && (0x20..=0x2f).contains(&buf[i]) {
        i += 1;
    }
    let Some(&fin) = buf.get(i) else {
        return Classified::NeedMore;
    };
    if !(0x40..=0x7e).contains(&fin) {
        // Malformed CSI; treat the ESC as plain input.
        return Classified::Plain(1);
    }
    let params = &buf[2..i];
    let len = i + 1;
    if fin == b'~' && params == b"200" {
        return Classified::PasteStart;
    }
    if is_ctrl_v_csi(params, fin) {
        return Classified::Chord(len);
    }
    Classified::Plain(len)
}

/// Whether a CSI `params` + final byte encodes a Ctrl+V press. Kitty keyboard
/// protocol: `118;5u` β€” codepoint 118 ('v'), modifier 5 (Ctrl), optionally a
/// `:1` (press) or `:2` (repeat) event subparameter; `:3` is a release and
/// must pass through untouched. xterm modifyOtherKeys: `27;5;118~`.
fn is_ctrl_v_csi(params: &[u8], fin: u8) -> bool {
    match fin {
        b'u' => matches!(params, b"118;5" | b"118;5:1" | b"118;5:2"),
        b'~' => params == b"27;5;118",
        _ => false,
    }
}

pub(crate) fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

/// Length of the longest strict suffix of `buf` that is a prefix of `pattern`,
/// i.e. bytes that might complete into `pattern` on the next read.
pub(crate) fn partial_suffix_len(buf: &[u8], pattern: &[u8]) -> usize {
    let max = pattern.len().min(buf.len() + 1) - 1;
    for take in (1..=max).rev() {
        if buf[buf.len() - take..] == pattern[..take] {
            return take;
        }
    }
    0
}

/// If a bracketed paste is a drag-and-drop of local files, return their paths.
///
/// A dragged file arrives as its shell-escaped absolute path, and terminals
/// add a trailing space (several files come space-separated, still with the
/// trailing space; some terminals use file:// URLs instead). The paste
/// qualifies only when it carries one of those drag signals β€” the trailing
/// space, or the URL form on every token β€” and every token is an existing
/// local regular file. Paths pasted as ordinary text carry neither:
/// a line copied from terminal output ends with a newline, not a space, and
/// acting on it would silently upload local files (a private key, say) whose
/// paths the user only meant to mention. Everything that does not qualify
/// returns None and forwards unchanged.
pub(crate) fn dropped_local_files(paste: &[u8]) -> Option<Vec<PathBuf>> {
    let text = std::str::from_utf8(paste).ok()?;
    let tokens = shell_words::split(text.trim()).ok()?;
    if tokens.is_empty() {
        return None;
    }
    let dragged = text.ends_with(' ') || tokens.iter().all(|token| token.starts_with("file://"));
    if !dragged {
        return None;
    }
    let mut paths = Vec::with_capacity(tokens.len());
    for token in tokens {
        let path = if token.starts_with("file://") {
            url::Url::parse(&token).ok()?.to_file_path().ok()?
        } else {
            PathBuf::from(token)
        };
        if !path.is_absolute() {
            return None;
        }
        if !std::fs::metadata(&path).is_ok_and(|meta| meta.is_file()) {
            return None;
        }
        paths.push(path);
    }
    Some(paths)
}

/// A guest-side file name for an uploaded drop: the local basename reduced to
/// safe characters, so the injected path never needs quoting in a composer.
pub(crate) fn sanitize_drop_name(path: &std::path::Path) -> String {
    let name: String = path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_default()
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
                c
            } else {
                '-'
            }
        })
        .take(128)
        .collect();
    if name.trim_matches(|c| c == '.' || c == '-').is_empty() {
        "file".to_string()
    } else {
        name
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn scan_all(scanner: &mut InputScanner, chunks: &[&[u8]]) -> Vec<InputEvent> {
        let mut events = Vec::new();
        for chunk in chunks {
            events.extend(scanner.scan(chunk));
        }
        events
    }

    #[test]
    fn plain_bytes_pass_through() {
        let mut s = InputScanner::new();
        assert_eq!(s.scan(b"hello"), vec![InputEvent::Bytes(b"hello".to_vec())]);
        assert!(!s.has_idle_carry());
    }

    #[test]
    fn ctrl_v_chord_in_every_encoding() {
        let chords: [&[u8]; 5] = [
            b"\x16",
            b"\x1b[118;5u",
            b"\x1b[118;5:1u",
            b"\x1b[118;5:2u",
            b"\x1b[27;5;118~",
        ];
        for chord in chords {
            let mut s = InputScanner::new();
            assert_eq!(
                s.scan(chord),
                vec![InputEvent::PasteChord(chord.to_vec())],
                "chord {chord:?}"
            );
        }
    }

    #[test]
    fn ctrl_v_release_passes_through() {
        let mut s = InputScanner::new();
        assert_eq!(
            s.scan(b"\x1b[118;5:3u"),
            vec![InputEvent::Bytes(b"\x1b[118;5:3u".to_vec())]
        );
    }

    #[test]
    fn paste_collected_across_split_reads() {
        let mut s = InputScanner::new();
        let events = scan_all(&mut s, &[b"ab\x1b[20", b"0~/tmp/x ", b"\x1b[2", b"01~cd"]);
        assert_eq!(
            events,
            vec![
                InputEvent::Bytes(b"ab".to_vec()),
                InputEvent::Paste(b"/tmp/x ".to_vec()),
                InputEvent::Bytes(b"cd".to_vec()),
            ]
        );
    }

    #[test]
    fn chord_split_across_reads() {
        let mut s = InputScanner::new();
        let events = scan_all(&mut s, &[b"\x1b", b"[118;5u"]);
        assert_eq!(
            events,
            vec![InputEvent::PasteChord(b"\x1b[118;5u".to_vec())]
        );
    }

    #[test]
    fn lone_escape_is_carried_then_flushed() {
        let mut s = InputScanner::new();
        assert_eq!(s.scan(b"\x1b"), vec![]);
        assert!(s.has_idle_carry());
        assert_eq!(s.take_carry(), b"\x1b".to_vec());
    }

    #[test]
    fn partial_end_marker_is_held_through_idle_not_flushed() {
        // A paste that stalls mid-end-marker (a slow or throttled terminal)
        // must not have its held ESC flushed by the idle path: that would
        // strip the marker and leave the paste unable to terminate.
        let mut s = InputScanner::new();
        assert_eq!(s.scan(b"\x1b[200~body\x1b"), vec![]);
        assert!(!s.has_idle_carry());
        assert_eq!(s.scan(b"[201~"), vec![InputEvent::Paste(b"body".to_vec())]);
    }

    #[test]
    fn eof_flushes_an_unterminated_paste_verbatim() {
        let mut s = InputScanner::new();
        assert_eq!(s.scan(b"\x1b[200~body\x1b"), vec![]);
        assert_eq!(s.flush_all(), b"\x1b[200~body\x1b".to_vec());
        assert!(!s.has_idle_carry());
    }

    #[test]
    fn arrow_key_passes_through_unbroken() {
        let mut s = InputScanner::new();
        assert_eq!(
            s.scan(b"\x1b[A"),
            vec![InputEvent::Bytes(b"\x1b[A".to_vec())]
        );
    }

    #[test]
    fn chord_inside_paste_is_literal() {
        let mut s = InputScanner::new();
        let events = s.scan(b"\x1b[200~a\x16b\x1b[201~");
        assert_eq!(events, vec![InputEvent::Paste(b"a\x16b".to_vec())]);
    }

    #[test]
    fn oversized_paste_streams_through() {
        let mut s = InputScanner::new();
        let big = vec![b'x'; PASTE_BUFFER_CAP + 10];
        let mut first = PASTE_START.to_vec();
        first.extend_from_slice(&big);
        let mut events = s.scan(&first);
        events.extend(s.scan(b"tail\x1b[201~after"));
        // Every byte comes back verbatim, in order, as Bytes events.
        let forwarded: Vec<u8> = events
            .iter()
            .flat_map(|e| match e {
                InputEvent::Bytes(b) => b.clone(),
                _ => panic!("unexpected event {e:?}"),
            })
            .collect();
        let mut expected = first.clone();
        expected.extend_from_slice(b"tail\x1b[201~after");
        assert_eq!(forwarded, expected);
    }

    #[test]
    fn dropped_paths_parse_escaped_and_quoted_forms() {
        let dir = tempfile::tempdir().unwrap();
        let spaced = dir.path().join("my file.png");
        std::fs::write(&spaced, b"x").unwrap();
        let plain = dir.path().join("b.txt");
        std::fs::write(&plain, b"y").unwrap();

        let escaped = format!(
            "{}/my\\ file.png '{}' ",
            dir.path().display(),
            plain.display()
        );
        let paths = dropped_local_files(escaped.as_bytes()).unwrap();
        assert_eq!(paths, vec![spaced.clone(), plain.clone()]);

        let uri = format!("file://{}/my%20file.png", dir.path().display());
        assert_eq!(dropped_local_files(uri.as_bytes()).unwrap(), vec![spaced]);
    }

    #[test]
    fn non_paths_and_directories_do_not_qualify() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(dropped_local_files(b"hello world"), None);
        assert_eq!(dropped_local_files(b""), None);
        // A bare single path with no trailing space is pasted text, not a
        // drag: acting on it would upload a file the user only mentioned.
        let secret = dir.path().join("id_ed25519");
        std::fs::write(&secret, b"key").unwrap();
        assert_eq!(
            dropped_local_files(secret.to_string_lossy().as_bytes()),
            None
        );
        // A newline-terminated path is a copied line of terminal output, not
        // a drag: only the trailing space terminals append to drops counts.
        let copied_line = format!("{}\n", secret.display());
        assert_eq!(dropped_local_files(copied_line.as_bytes()), None);
        // The same path with a drag's trailing space qualifies.
        let dragged = format!("{} ", secret.display());
        assert_eq!(
            dropped_local_files(dragged.as_bytes()).unwrap(),
            vec![secret.clone()]
        );
        // Several existing paths pasted as text (no trailing space) are still
        // text: real multi-file drags carry the trailing space too.
        let second = dir.path().join("also-real");
        std::fs::write(&second, b"x").unwrap();
        let two_no_space = format!("{} {}", secret.display(), second.display());
        assert_eq!(dropped_local_files(two_no_space.as_bytes()), None);
        // A URL form only counts as the drag signal when every token has it;
        // a bare path smuggled after a file:// token stays text.
        let mixed = format!("file://{} {}", second.display(), secret.display());
        assert_eq!(dropped_local_files(mixed.as_bytes()), None);
        // A directory is not a file drop.
        assert_eq!(
            dropped_local_files(dir.path().to_string_lossy().as_bytes()),
            None
        );
        // One real file plus one bogus token disqualifies the whole paste.
        let real = dir.path().join("a");
        std::fs::write(&real, b"x").unwrap();
        let mixed = format!("{} /definitely/not/here", real.display());
        assert_eq!(dropped_local_files(mixed.as_bytes()), None);
    }

    #[test]
    fn sanitize_drop_name_reduces_to_safe_chars() {
        assert_eq!(
            sanitize_drop_name(std::path::Path::new("/a/Screen Shot (1).png")),
            "Screen-Shot--1-.png"
        );
        assert_eq!(
            sanitize_drop_name(std::path::Path::new("/a/ΓΌ~!.png")),
            "---.png"
        );
        assert_eq!(sanitize_drop_name(std::path::Path::new("/")), "file");
    }
}