smb2-cli 0.9.0

Command-line SMB2/3 client: list, stat, move, and delete files on a share without mounting it
//! The text form of a remote name: what `ls` prints and what an argument
//! takes, for names no terminal can show as they are.
//!
//! An NTFS name can hold an unpaired UTF-16 surrogate, which the library
//! carries inside a `String` as a NUL plus a plane-16 code point
//! (`smb2::name::from_utf16`). Printed raw, that's an invisible NUL, and no
//! argument can hold a NUL at all. So the CLI spells it the way Rust does:
//!
//! - an unpaired surrogate (and a NUL) prints as `\u{D800}`, its unit in hex
//! - a real backslash prints as `\\`, so the two can never be confused
//! - everything else prints as itself
//!
//! [`parse`] reads that form back, so a name pasted from `ls` names the same
//! file. It also takes `\u{...}` for any other character, which is one more
//! way to spell it. A backslash followed by anything else is refused rather
//! than guessed at.

use std::borrow::Cow;
use std::ffi::OsString;

use anyhow::{bail, Result};

/// The text form of a remote name or path.
pub fn display(name: &str) -> Cow<'_, str> {
    if !name.contains(['\\', '\0']) {
        return Cow::Borrowed(name);
    }
    let mut out = String::with_capacity(name.len() + 8);
    for decoded in char::decode_utf16(smb2::name::to_utf16(name)) {
        match decoded {
            Ok('\\') => out.push_str(r"\\"),
            Ok('\0') => out.push_str(r"\u{0}"),
            Ok(c) => out.push(c),
            Err(lone) => out.push_str(&format!(r"\u{{{:X}}}", lone.unpaired_surrogate())),
        }
    }
    Cow::Owned(out)
}

/// The remote name or path an argument spells, undoing [`display`].
pub fn parse(text: &str) -> Result<String> {
    if !text.contains('\\') {
        return Ok(text.to_string());
    }
    let mut units: Vec<u16> = Vec::with_capacity(text.len());
    let mut chars = text.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            let mut buf = [0u16; 2];
            units.extend_from_slice(c.encode_utf16(&mut buf));
            continue;
        }
        match chars.next() {
            Some('\\') => units.push(u16::from(b'\\')),
            Some('u') => {
                let rest = chars.as_str();
                let Some(hex) = rest
                    .strip_prefix('{')
                    .and_then(|after| after.split_once('}'))
                    .map(|(hex, _)| hex)
                    .filter(|hex| {
                        (1..=6).contains(&hex.len()) && hex.chars().all(|c| c.is_ascii_hexdigit())
                    })
                else {
                    bail!(r"{text:?}: write a character as \u{{HEX}}, like \u{{D800}}");
                };
                let value = u32::from_str_radix(hex, 16).expect("checked: one to six hex digits");
                if let Ok(unit) = u16::try_from(value) {
                    units.push(unit);
                } else if let Some(c) = char::from_u32(value) {
                    let mut buf = [0u16; 2];
                    units.extend_from_slice(c.encode_utf16(&mut buf));
                } else {
                    bail!(r"{text:?}: \u{{{hex}}} is past the last Unicode character");
                }
                // `{`, the digits, and `}`.
                chars = rest[hex.len() + 2..].chars();
            }
            _ => bail!(
                r"{text:?}: a backslash starts \\ (a backslash) or \u{{HEX}} (a character); write a backslash in a name as \\"
            ),
        }
    }
    Ok(smb2::name::from_utf16(&units))
}

/// The local file name `get` writes a remote file under.
///
/// A name with an unpaired surrogate can't be a file name here as it is
/// (Unix refuses the NUL in its escape), so on Unix it gets the same text form
/// `ls` shows, which reads back to the same remote name. Windows file names
/// are UTF-16 too, so there it keeps its exact units. Every other name is
/// written as itself.
pub fn local_file_name(name: &str) -> OsString {
    if !smb2::name::has_unpaired_surrogate(name) {
        return OsString::from(name);
    }
    #[cfg(windows)]
    {
        use std::os::windows::ffi::OsStringExt;
        OsString::from_wide(&smb2::name::to_utf16(name))
    }
    #[cfg(not(windows))]
    {
        OsString::from(display(name).into_owned())
    }
}

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

    /// A name holding an unpaired high surrogate, the way a listing returns it.
    fn lone_high() -> String {
        smb2::name::from_utf16(&[0x61, 0xD800, 0x62])
    }

    #[test]
    fn plain_names_are_untouched_both_ways() {
        for name in ["plain.txt", "a b/c.d", "émoji 😀", "dir/sub"] {
            assert!(matches!(display(name), Cow::Borrowed(_)));
            assert_eq!(parse(name).unwrap(), name);
        }
    }

    #[test]
    fn an_unpaired_surrogate_prints_as_its_unit() {
        assert_eq!(display(&lone_high()), r"a\u{D800}b");
        let low = smb2::name::from_utf16(&[0xDFFF]);
        assert_eq!(display(&low), r"\u{DFFF}");
    }

    #[test]
    fn a_backslash_prints_doubled() {
        assert_eq!(display(r"a\b"), r"a\\b");
        assert_eq!(display(r"\u{D800}"), r"\\u{D800}");
    }

    #[test]
    fn every_printed_name_parses_back_to_itself() {
        let names = [
            lone_high(),
            r"a\b".to_string(),
            r"\u{D800}".to_string(),
            r"a\\".to_string(),
            format!(r"x\{}y", lone_high()),
            smb2::name::from_utf16(&[0xDC00, 0xD800]),
            // A real NUL before a real U+10E800, which only a misbehaving
            // server sends: the library escapes it so it can't read as a unit.
            smb2::name::from_utf16(&[0x0000, 0xDBFA, 0xDC00]),
            "dir/sub/file".to_string(),
        ];
        for name in names {
            let text = display(&name);
            assert!(!text.contains('\0'), "{text:?} has a NUL in it");
            assert_eq!(parse(&text).unwrap(), name, "via {text:?}");
        }
    }

    #[test]
    fn a_pasted_escape_names_the_listed_file() {
        assert_eq!(
            parse(r"dir/a\u{D800}b").unwrap(),
            format!("dir/{}", lone_high())
        );
        assert_eq!(parse(r"a\u{d800}b").unwrap(), lone_high());
    }

    #[test]
    fn an_escaped_pair_or_character_is_that_character() {
        assert_eq!(parse(r"\u{D83D}\u{DE00}").unwrap(), "😀");
        assert_eq!(parse(r"\u{1F600}").unwrap(), "😀");
        assert_eq!(parse(r"\u{41}").unwrap(), "A");
    }

    #[test]
    fn a_stray_or_malformed_backslash_is_refused() {
        for text in [
            r"a\b",
            r"trailing\",
            r"\u",
            r"\u{}",
            r"\u{D800",
            r"\u{XYZ}",
            r"\u{1234567}",
            r"\u{110000}",
        ] {
            assert!(parse(text).is_err(), "{text:?} parsed");
        }
    }

    #[test]
    fn a_local_name_is_the_name_unless_it_cant_be() {
        assert_eq!(local_file_name("plain.txt"), OsString::from("plain.txt"));
        // A backslash is a legal Unix file name character, so it stays.
        #[cfg(not(windows))]
        assert_eq!(local_file_name(r"a\b"), OsString::from(r"a\b"));
        #[cfg(not(windows))]
        assert_eq!(local_file_name(&lone_high()), OsString::from(r"a\u{D800}b"));
    }
}