#[must_use]
pub fn printable(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len());
for c in String::from_utf8_lossy(bytes).chars() {
match c {
'\\' => out.push_str("\\\\"),
c if c.is_control() => out.push_str(&format!("\\x{:02x}", c as u32)),
c if is_direction_control(c) => out.push_str(&format!("\\u{{{:04x}}}", c as u32)),
c => out.push(c),
}
}
out
}
pub(crate) fn printable_path(path: &std::path::Path) -> String {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
printable(path.as_os_str().as_bytes())
}
#[cfg(not(unix))]
{
printable(path.as_os_str().to_string_lossy().as_bytes())
}
}
pub fn push_json_string(out: &mut String, s: &str) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c.is_control() || is_direction_control(c) => push_json_escape(out, c),
c => out.push(c),
}
}
out.push('"');
}
#[must_use]
pub fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for &b in bytes {
for shift in [4, 0] {
let nibble = u32::from((b >> shift) & 0xf);
out.push(char::from_digit(nibble, 16).expect("a nibble is a hex digit"));
}
}
out
}
fn push_json_escape(out: &mut String, c: char) {
let point = c as u32;
out.push_str("\\u");
for shift in [12, 8, 4, 0] {
let nibble = (point >> shift) & 0xf;
out.push(char::from_digit(nibble, 16).expect("a nibble is a hex digit"));
}
}
fn is_direction_control(c: char) -> bool {
matches!(
c,
'\u{200e}' | '\u{200f}' | '\u{061c}'
| '\u{202a}'..='\u{202e}'
| '\u{2066}'..='\u{2069}'
)
}
#[cfg(test)]
mod tests {
use super::{hex, printable, push_json_string};
#[test]
fn hex_states_bytes_exactly_and_at_a_fixed_width() {
assert_eq!(hex(b"\x00\x0f\xf0\xff"), "000ff0ff");
assert_eq!(hex(&[]), "");
assert_eq!(hex(&[1u8; 16]).len(), 32);
assert_eq!(hex(b"\xab\xcd"), "abcd");
}
fn json(s: &str) -> String {
let mut out = String::new();
push_json_string(&mut out, s);
out
}
#[test]
fn ordinary_text_passes_through() {
assert_eq!(printable(b"/etc/passwd"), "/etc/passwd");
assert_eq!(printable("naïve".as_bytes()), "naïve");
assert_eq!(printable(b""), "");
}
#[test]
fn everything_a_terminal_acts_on_is_escaped() {
assert_eq!(
printable(b"\x1b[2J\x1b[1;1Hclean\x1b[0m"),
"\\x1b[2J\\x1b[1;1Hclean\\x1b[0m"
);
assert_eq!(printable(b"a\rb\0c\x7fd"), "a\\x0db\\x00c\\x7fd");
assert_eq!(printable("\u{9b}[31m".as_bytes()), "\\x9b[31m");
assert_eq!(printable("gpj.\u{202e}exe".as_bytes()), "gpj.\\u{202e}exe");
}
#[test]
fn every_escape_names_exactly_one_character() {
assert_eq!(printable(b"a\\x1bb"), "a\\\\x1bb");
assert_eq!(printable(b"\\"), "\\\\");
assert_ne!(printable(br"a\x1bb"), printable(b"a\x1bb"));
}
#[test]
fn a_json_string_escapes_what_the_grammar_requires() {
assert_eq!(json("a\"b\\c\nd\te\u{1}f"), r#""a\"b\\c\nd\te\u0001f""#);
}
#[test]
fn a_json_string_escapes_what_a_terminal_acts_on_as_well() {
assert_eq!(
json("a\u{7f}b\u{9b}[31mc\u{9f}"),
r#""a\u007fb\u009b[31mc\u009f""#
);
assert_eq!(json("photo\u{202e}gnp.exe"), r#""photo\u202egnp.exe""#);
assert_eq!(json("a\u{2066}b\u{200f}c"), r#""a\u2066b\u200fc""#);
assert_eq!(json("caf\u{e9}"), "\"caf\u{e9}\"");
}
#[test]
#[cfg(feature = "tar")]
fn every_error_that_names_a_path_renders_it_through_this() {
let hostile = b"/tmp/\x1b[2Jgone\r".to_vec();
let messages = [
crate::archive::ArchiveError::Unrepresentable {
path: hostile.clone(),
}
.to_string(),
crate::archive::ArchiveError::XattrNameUnrepresentable {
path: hostile.clone(),
name: b"user.\x1b[31m".to_vec(),
}
.to_string(),
crate::archive::ArchiveError::Bad {
path: hostile.clone(),
reason: "a reason",
}
.to_string(),
];
for message in messages {
assert!(
!message.chars().any(char::is_control),
"an error message carries a raw control byte: {message:?}"
);
assert!(
message.contains("\\x1b"),
"and still names the path: {message:?}"
);
}
}
#[test]
#[cfg(all(feature = "dir", any(target_os = "linux", target_os = "android")))]
fn a_path_off_the_host_is_escaped_like_one_off_an_image() {
use std::path::PathBuf;
let hostile = PathBuf::from("staging/\u{1b}[2Jgone");
let messages = [
crate::HostError::NotADirectory {
path: hostile.clone(),
}
.to_string(),
crate::HostError::Unsupported {
path: hostile.clone(),
}
.to_string(),
crate::HostError::NotEmpty {
path: hostile.clone(),
}
.to_string(),
crate::HostError::RepeatedDirectory {
path: hostile.clone(),
first: hostile.clone(),
}
.to_string(),
crate::HostError::UnstableXattrs {
path: hostile,
name: Some(b"user.\x1b[31m".to_vec()),
attempts: 4,
}
.to_string(),
];
for message in messages {
assert!(
!message.chars().any(char::is_control),
"an error message carries a raw control byte: {message:?}"
);
assert!(
message.contains("\\x1b"),
"and still names the path: {message:?}"
);
}
}
#[test]
fn invalid_utf8_still_names_the_entry() {
assert_eq!(printable(b"caf\xc3"), "caf\u{fffd}");
assert_eq!(printable(b"\xff\xfe"), "\u{fffd}\u{fffd}");
}
}