Skip to main content

uncurses/ansi/
program_resume.rs

1//! Program resume reports through OSC 7577.
2//!
3//! A report tells the terminal which command brings the program back after
4//! the terminal restarts. The terminal decides whether to store the record
5//! and whether to run it. A clear report removes the record.
6//!
7//! Writers use `ESC ] 7577 ; pairs ESC \`. Each `argv` element and the `cwd`
8//! are standard base64 of UTF-8. The final `mac` key is the SHA-256 hash of
9//! the body before `:mac=`, one `:`, and the token from [`TOKEN_ENV`]. The
10//! token never appears in the output.
11//!
12//! Support is present when [`TOKEN_ENV`] is set. The protocol has no query.
13//!
14//! See the [protocol specification](https://www.superlogical.com/rex/docs/build/program-resume).
15
16use std::fmt::Write as _;
17use std::io::{self, Write};
18use std::path::{Component, Path};
19
20use base64::Engine as _;
21use base64::engine::general_purpose::STANDARD;
22use sha2::{Digest, Sha256};
23
24/// Environment variable that holds the terminal's OSC 7577 token.
25///
26/// A program that reports should remove it from the environment of the
27/// programs it starts, for example with
28/// [`Command::env_remove`](std::process::Command::env_remove).
29pub const TOKEN_ENV: &str = "OSC7577_TOKEN";
30
31/// Largest complete sequence, in bytes, that every supporting terminal
32/// accepts.
33pub const MAX_SEQUENCE_LEN: usize = 2048;
34
35/// Largest number of `argv` elements that every supporting terminal accepts.
36pub const MAX_ARGV: usize = 64;
37
38/// A resume command, with borrowed text.
39///
40/// The writer validates the command before any output. Callers supply plain
41/// UTF-8, not base64.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct ProgramResume<'a> {
44    /// The command and its arguments. The first element is a bare command
45    /// name that does not start with `-`, or an absolute path for the host
46    /// platform. The terminal
47    /// looks up a bare name on `PATH` when it resumes the program. Later
48    /// elements can be empty. No element can contain a control character.
49    pub argv: &'a [&'a str],
50    /// Optional working directory for the resumed command, as an absolute
51    /// path for the host platform.
52    pub cwd: Option<&'a str>,
53}
54
55impl<'a> ProgramResume<'a> {
56    /// Create a report for `argv` with no working directory.
57    pub const fn new(argv: &'a [&'a str]) -> Self {
58        Self { argv, cwd: None }
59    }
60}
61
62fn invalid(message: &str) -> io::Error {
63    io::Error::new(io::ErrorKind::InvalidInput, message.to_string())
64}
65
66fn validate_auth(pid: u32, time: u64, token: &str) -> io::Result<()> {
67    if !(22..=64).contains(&token.len())
68        || !token
69            .bytes()
70            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
71    {
72        return Err(invalid(
73            "program resume token must be 22-64 characters from [A-Za-z0-9_-]",
74        ));
75    }
76    if pid == 0 || time == 0 {
77        return Err(invalid("program resume pid and time must be nonzero"));
78    }
79    Ok(())
80}
81
82fn validate_report(report: &ProgramResume<'_>) -> io::Result<()> {
83    let Some(program) = report.argv.first() else {
84        return Err(invalid("program resume argv is empty"));
85    };
86    if report.argv.len() > MAX_ARGV {
87        return Err(invalid("program resume argv exceeds 64 elements"));
88    }
89    // Base64 never shrinks its input, so text longer than the whole sequence
90    // limit cannot fit. Reject it before scanning, encoding, and hashing.
91    let raw_len = report
92        .argv
93        .iter()
94        .chain(report.cwd.as_ref())
95        .map(|s| s.len());
96    if raw_len.fold(0usize, usize::saturating_add) > MAX_SEQUENCE_LEN {
97        return Err(invalid("program resume sequence exceeds 2048 bytes"));
98    }
99    // A bare name is one normal component, so `.`, `..`, and Windows
100    // drive-relative names such as `C:app` count as relative paths.
101    let mut parts = Path::new(program).components();
102    let bare = !program.contains(std::path::is_separator)
103        && !program.starts_with('-')
104        && matches!(
105            (parts.next(), parts.next()),
106            (Some(Component::Normal(_)), None)
107        );
108    if program.is_empty() || !(bare || Path::new(program).is_absolute()) {
109        return Err(invalid(
110            "program resume argv[0] must be an absolute path or a bare command name",
111        ));
112    }
113    if report
114        .argv
115        .iter()
116        .chain(report.cwd.as_ref())
117        .any(|s| s.chars().any(char::is_control))
118    {
119        return Err(invalid("program resume text contains a control character"));
120    }
121    if report.cwd.is_some_and(|cwd| !Path::new(cwd).is_absolute()) {
122        return Err(invalid("program resume cwd must be an absolute path"));
123    }
124    Ok(())
125}
126
127/// Append `:mac=<hex>` for `body` and frame the sequence.
128fn finish(body: String, token: &str) -> io::Result<String> {
129    let digest = Sha256::new()
130        .chain_update(body.as_bytes())
131        .chain_update(b":")
132        .chain_update(token.as_bytes())
133        .finalize();
134    let mut sequence = String::with_capacity(body.len() + 82);
135    sequence.push_str("\x1b]7577;");
136    sequence.push_str(&body);
137    sequence.push_str(":mac=");
138    for byte in digest {
139        write!(sequence, "{byte:02x}").unwrap();
140    }
141    sequence.push_str("\x1b\\");
142    if sequence.len() > MAX_SEQUENCE_LEN {
143        return Err(invalid("program resume sequence exceeds 2048 bytes"));
144    }
145    Ok(sequence)
146}
147
148/// Write one program resume report without flushing.
149///
150/// `pid` is the process that `report` brings back. It is usually
151/// [`std::process::id`], but a wrapper can report for the process it
152/// starts. `time` is the current time in seconds since the Unix epoch.
153/// Terminals ignore a report whose time is far from their clock, so build
154/// each report when it is sent. `token` is the value of [`TOKEN_ENV`].
155///
156/// All inputs are validated before any bytes are written. An invalid token,
157/// a zero `pid` or `time`, an invalid command or directory, or a sequence
158/// beyond [`MAX_SEQUENCE_LEN`] bytes or [`MAX_ARGV`] elements returns
159/// [`io::ErrorKind::InvalidInput`]. When the command changes to one that
160/// this function rejects, send [`write_program_resume_clear`] so that the
161/// terminal does not resume the earlier command.
162///
163/// ```
164/// use uncurses::ansi::program_resume::{ProgramResume, write_program_resume};
165///
166/// let report = ProgramResume::new(&["resume-wrap", "ssh", "devbox"]);
167/// let mut bytes = Vec::new();
168/// write_program_resume(&mut bytes, &report, 90412, 1795543200, "dummy-token-replace-me")
169///     .unwrap();
170/// assert_eq!(
171///     bytes,
172///     b"\x1b]7577;pid=90412:time=1795543200:argv=cmVzdW1lLXdyYXA=,c3No,ZGV2Ym94\
173///       :mac=e76149d0ba54a83570ffab0583867dacdfa23928ba9d18604f0badea88b62b65\x1b\\",
174/// );
175/// ```
176pub fn write_program_resume<W: Write>(
177    w: &mut W,
178    report: &ProgramResume<'_>,
179    pid: u32,
180    time: u64,
181    token: &str,
182) -> io::Result<()> {
183    validate_auth(pid, time, token)?;
184    validate_report(report)?;
185    let mut body = format!("pid={pid}:time={time}:argv=");
186    for (i, arg) in report.argv.iter().enumerate() {
187        if i > 0 {
188            body.push(',');
189        }
190        STANDARD.encode_string(arg, &mut body);
191    }
192    if let Some(cwd) = report.cwd {
193        body.push_str(":cwd=");
194        STANDARD.encode_string(cwd, &mut body);
195    }
196    w.write_all(finish(body, token)?.as_bytes())
197}
198
199/// Write one clear report for `pid` without flushing.
200///
201/// The terminal removes the record for `pid`. Send it when the user ends the
202/// program, not when the program exits because the terminal closed.
203/// `pid`, `time`, and `token` follow the rules of [`write_program_resume`].
204pub fn write_program_resume_clear<W: Write>(
205    w: &mut W,
206    pid: u32,
207    time: u64,
208    token: &str,
209) -> io::Result<()> {
210    validate_auth(pid, time, token)?;
211    w.write_all(finish(format!("pid={pid}:time={time}:clear=1"), token)?.as_bytes())
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    const TOKEN: &str = "dummy-token-replace-me";
219    const PID: u32 = 74877;
220    const TIME: u64 = 1795543200;
221
222    fn report(report: &ProgramResume<'_>, pid: u32) -> io::Result<Vec<u8>> {
223        let mut bytes = Vec::new();
224        write_program_resume(&mut bytes, report, pid, TIME, TOKEN).map(|()| bytes)
225    }
226
227    #[test]
228    fn program_resume_matches_specification_examples() {
229        let nvim = [
230            "nvim",
231            "-S",
232            "/home/user/.local/state/nvim/sessions/8f2c1d.vim",
233        ];
234        assert_eq!(
235            report(&ProgramResume::new(&nvim), PID).unwrap(),
236            b"\x1b]7577;pid=74877:time=1795543200:argv=bnZpbQ==,LVM=,\
237              L2hvbWUvdXNlci8ubG9jYWwvc3RhdGUvbnZpbS9zZXNzaW9ucy84ZjJjMWQudmlt\
238              :mac=9dbb99bfb856749a87563839d7ce9062818d78cf25909db93f309e0cd3b1909b\x1b\\"
239        );
240        assert_eq!(
241            report(
242                &ProgramResume::new(&["resume-wrap", "ssh", "devbox"]),
243                90412
244            )
245            .unwrap(),
246            b"\x1b]7577;pid=90412:time=1795543200:argv=cmVzdW1lLXdyYXA=,c3No,ZGV2Ym94\
247              :mac=e76149d0ba54a83570ffab0583867dacdfa23928ba9d18604f0badea88b62b65\x1b\\"
248        );
249
250        #[cfg(unix)]
251        {
252            let mut lazygit = ProgramResume::new(&["lazygit"]);
253            lazygit.cwd = Some("/home/user/src/project");
254            assert_eq!(
255                report(&lazygit, PID).unwrap(),
256                b"\x1b]7577;pid=74877:time=1795543200:argv=bGF6eWdpdA==\
257                  :cwd=L2hvbWUvdXNlci9zcmMvcHJvamVjdA==\
258                  :mac=35cb909805c380336efd3689a125acc774a9dec8422a1d21492ebec06ca758e1\x1b\\"
259            );
260        }
261
262        let mut clear = Vec::new();
263        write_program_resume_clear(&mut clear, PID, TIME, TOKEN).unwrap();
264        assert_eq!(
265            clear,
266            b"\x1b]7577;pid=74877:time=1795543200:clear=1\
267              :mac=c30603369f98fef581a4098be889175b0c74f0641e49f8b25f4326cb38f97c93\x1b\\"
268        );
269    }
270
271    #[test]
272    fn program_resume_accepts_empty_later_arguments() {
273        let bytes = report(&ProgramResume::new(&["app", ""]), PID).unwrap();
274        let text = String::from_utf8(bytes).unwrap();
275        assert!(text.contains(":argv=YXBw,:mac="), "{text:?}");
276    }
277
278    #[cfg(windows)]
279    #[test]
280    fn program_resume_accepts_windows_absolute_paths() {
281        let mut resume = ProgramResume::new(&[r"C:\Program Files\App\app.exe"]);
282        resume.cwd = Some(r"C:\work");
283        assert!(report(&resume, PID).is_ok());
284        resume.cwd = Some(r"\work");
285        assert!(report(&resume, PID).is_err());
286        assert!(report(&ProgramResume::new(&["C:app.exe"]), PID).is_err());
287    }
288
289    #[test]
290    fn invalid_program_resume_writes_nothing() {
291        let long = "x".repeat(MAX_SEQUENCE_LEN);
292        let many = ["a"; MAX_ARGV + 1];
293        for (argv, cwd) in [
294            (&[][..], None),
295            (&[""][..], None),
296            (&["./run.sh"][..], None),
297            (&["."][..], None),
298            (&[".."][..], None),
299            (&["bin/app"][..], None),
300            (&["-x"][..], None),
301            (&["app", "a\nb"][..], None),
302            (&["app", "\u{85}"][..], None),
303            (&["app"][..], Some("relative")),
304            (&["app"][..], Some("/tmp/\x1b")),
305            (&["app", long.as_str()][..], None),
306            (&many[..], None),
307        ] {
308            let resume = ProgramResume { argv, cwd };
309            let mut bytes = Vec::new();
310            let err = write_program_resume(&mut bytes, &resume, PID, TIME, TOKEN).unwrap_err();
311            assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{argv:?} {cwd:?}");
312            assert!(bytes.is_empty(), "{argv:?} {cwd:?}");
313        }
314
315        let ok = ProgramResume::new(&["app"]);
316        for (pid, time, token) in [
317            (0, TIME, TOKEN),
318            (PID, 0, TOKEN),
319            (PID, TIME, "short"),
320            (PID, TIME, "dummy:token:replace:me"),
321            (PID, TIME, &"t".repeat(65)),
322        ] {
323            let mut bytes = Vec::new();
324            let err = write_program_resume(&mut bytes, &ok, pid, time, token).unwrap_err();
325            assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
326            let err = write_program_resume_clear(&mut bytes, pid, time, token).unwrap_err();
327            assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
328            assert!(bytes.is_empty());
329        }
330    }
331
332    #[test]
333    fn program_resume_sequence_limit_counts_framing() {
334        // The framing, keys, mac, and `app,` use 114 bytes with this pid and
335        // time. 1449 bytes encode to 1932, so one more base64 group exceeds
336        // the limit.
337        let fits = "a".repeat(1449);
338        let fits_bytes = report(&ProgramResume::new(&["app", &fits]), PID).unwrap();
339        assert!(fits_bytes.len() <= MAX_SEQUENCE_LEN);
340        let over = "a".repeat(fits.len() + 3);
341        assert!(fits_bytes.len() + 4 > MAX_SEQUENCE_LEN);
342        assert!(report(&ProgramResume::new(&["app", &over]), PID).is_err());
343        assert!(report(&ProgramResume::new(&["a"; MAX_ARGV]), PID).is_ok());
344    }
345}