1use 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
24pub const TOKEN_ENV: &str = "OSC7577_TOKEN";
30
31pub const MAX_SEQUENCE_LEN: usize = 2048;
34
35pub const MAX_ARGV: usize = 64;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct ProgramResume<'a> {
44 pub argv: &'a [&'a str],
50 pub cwd: Option<&'a str>,
53}
54
55impl<'a> ProgramResume<'a> {
56 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 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 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
127fn 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
148pub 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
199pub 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 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}