use std::{
io::Write,
path::Path,
time::{SystemTime, UNIX_EPOCH},
};
use base64::{Engine, engine::general_purpose::STANDARD};
use sha2::{Digest, Sha256};
use crate::Error;
pub(crate) fn write_report<W: Write>(
writer: &mut W,
argv: &[String],
cwd: Option<&Path>,
token: &str,
) -> Result<(), Error> {
validate_argv(argv)?;
let cwd = match cwd {
Some(path) => {
if !path.is_absolute() {
return Err(Error::InvalidReport("cwd must be an absolute path"));
}
let cwd = path
.to_str()
.ok_or(Error::InvalidReport("cwd must be valid UTF-8"))?;
validate_text(cwd, "cwd")?;
Some(STANDARD.encode(cwd.as_bytes()))
}
None => None,
};
let encoded_argv = argv
.iter()
.map(|arg| STANDARD.encode(arg.as_bytes()))
.collect::<Vec<_>>()
.join(",");
let now = unix_time()?;
let mut body = format!("pid={}:time={now}:argv={encoded_argv}", std::process::id());
if let Some(cwd) = cwd {
body.push_str(":cwd=");
body.push_str(&cwd);
}
write_sequence(writer, &body, token)
}
pub(crate) fn write_clear<W: Write>(writer: &mut W, token: &str) -> Result<(), Error> {
let body = format!("pid={}:time={}:clear=1", std::process::id(), unix_time()?);
write_sequence(writer, &body, token)
}
pub(crate) fn validate_token(token: &str) -> Result<(), Error> {
if (22..=64).contains(&token.len())
&& token
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
{
Ok(())
} else {
Err(Error::InvalidToken)
}
}
fn write_sequence<W: Write>(writer: &mut W, body: &str, token: &str) -> Result<(), Error> {
let mut hasher = Sha256::new();
hasher.update(body.as_bytes());
hasher.update(b":");
hasher.update(token.as_bytes());
use std::fmt::Write as _;
let digest = hasher.finalize();
let mut mac = String::with_capacity(digest.len() * 2);
for byte in digest {
write!(&mut mac, "{byte:02x}").expect("writing to a String cannot fail");
}
if body.len() + 78 > 2048 {
return Err(Error::InvalidReport(
"report exceeds the 2048-byte portable limit",
));
}
write!(writer, "\x1b]7577;{body}:mac={mac}\x1b\\")?;
writer.flush()?;
Ok(())
}
fn validate_argv(argv: &[String]) -> Result<(), Error> {
if argv.len() > 64 {
return Err(Error::InvalidReport(
"argv must contain at most 64 elements",
));
}
let Some(program) = argv.first() else {
return Err(Error::InvalidReport(
"argv must contain at least one element",
));
};
validate_text(program, "argv[0]")?;
if program.is_empty() {
return Err(Error::InvalidReport("argv[0] must not be empty"));
}
let path = Path::new(program);
let is_bare_name = !program.contains('/') && !program.contains('\\');
if !path.is_absolute() && (!is_bare_name || program.starts_with('-')) {
return Err(Error::InvalidReport(
"argv[0] must be a bare executable name or an absolute path",
));
}
for arg in argv.iter().skip(1) {
validate_text(arg, "argument")?;
}
Ok(())
}
fn validate_text(value: &str, field: &'static str) -> Result<(), Error> {
if value.chars().any(char::is_control) {
return Err(Error::InvalidReport(match field {
"cwd" => "cwd must not contain control characters",
"argv[0]" => "argv[0] must not contain control characters",
_ => "arguments must not contain control characters",
}));
}
Ok(())
}
fn unix_time() -> Result<u64, Error> {
Ok(SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(Error::InvalidClock)?
.as_secs())
}