smb2-cli 0.9.1

Command-line SMB2/3 client: list, stat, move, and delete files on a share without mounting it
//! Parsing of SMB targets like `//host/share/path`.

use anyhow::{bail, Result};

use crate::escape;

/// A location on an SMB server: which host, which share, and which path
/// inside that share.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
    pub host: String,
    pub port: u16,
    pub share: String,
    /// Path inside the share, with `/` separators and no leading slash.
    /// Empty means the share root.
    pub path: String,
    /// Whether the path was written with a trailing separator. `path` itself is
    /// always trimmed, so this is the only record of it, and `put` needs it:
    /// `.../dir/` means "into that directory", the way `cp` reads it.
    pub trailing_slash: bool,
}

impl Target {
    /// Parses `smb://host[:port]/share[/path]`, `//host[:port]/share[/path]`,
    /// or the Windows form `\\host\share\path`.
    ///
    /// In the first two, the share and path are in the text form `ls` prints
    /// (`escape::parse`: `\\` for a backslash, `\u{D800}` for a unit no
    /// string can hold). In the Windows form every backslash is a separator,
    /// so it takes plain names only.
    pub fn parse(input: &str) -> Result<Self> {
        let (rest, escaped) = if let Some(unc) = input.strip_prefix(r"\\") {
            (unc.replace('\\', "/"), false)
        } else {
            let rest = input
                .strip_prefix("smb://")
                .or_else(|| input.strip_prefix("//"))
                .ok_or_else(|| {
                    anyhow::anyhow!("target must look like //host/share/path, got {input:?}")
                })?;
            (rest.to_string(), true)
        };
        let unescape = |text: &str| {
            if escaped {
                escape::parse(text)
            } else {
                Ok(text.to_string())
            }
        };

        let (authority, remainder) = match rest.split_once('/') {
            Some((authority, remainder)) => (authority, remainder),
            None => bail!("target {input:?} names a host but no share"),
        };
        if authority.is_empty() {
            bail!("target {input:?} has an empty host");
        }

        let (host, port) = match authority.rsplit_once(':') {
            Some((host, port)) => (host.to_string(), port.parse().unwrap_or(445)),
            None => (authority.to_string(), 445),
        };

        let (share, path) = match remainder.split_once('/') {
            Some((share, path)) => (share, path),
            None => (remainder, ""),
        };
        if share.is_empty() {
            bail!("target {input:?} has an empty share name");
        }

        Ok(Self {
            host,
            port,
            share: unescape(share)?,
            path: trim_path(&unescape(path)?),
            trailing_slash: !path.is_empty() && path.ends_with('/'),
        })
    }

    /// The `host:port` string the smb2 crate wants.
    pub fn addr(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }

    /// The same location with a different path inside the share.
    pub fn with_path(&self, path: &str) -> Self {
        Self {
            path: trim_path(path),
            trailing_slash: path.ends_with('/'),
            ..self.clone()
        }
    }

    /// Resolves a path that may be absolute (`//host/share/x`) or relative to
    /// this target's path. Used for batch inputs, where repeating the full
    /// target on every line would be noise. A relative path is in the same
    /// text form as a target's (`escape::parse`).
    pub fn resolve(&self, path: &str) -> Result<Self> {
        if path.starts_with("//") || path.starts_with("smb://") || path.starts_with("\\\\") {
            return Target::parse(path);
        }
        let path = escape::parse(path)?;
        let joined = if self.path.is_empty() {
            trim_path(&path)
        } else {
            format!("{}/{}", self.path, trim_path(&path))
        };
        Ok(self.with_path(&joined))
    }

    /// Display form, `//host/share/path`, with the share and path in the text
    /// form [`Target::parse`] reads back.
    pub fn display(&self) -> String {
        let port = if self.port == 445 {
            String::new()
        } else {
            format!(":{}", self.port)
        };
        let share = escape::display(&self.share);
        if self.path.is_empty() {
            format!("//{}{}/{}", self.host, port, share)
        } else {
            let path = escape::display(&self.path);
            format!("//{}{}/{}/{}", self.host, port, share, path)
        }
    }
}

fn trim_path(path: &str) -> String {
    path.trim_matches('/').to_string()
}

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

    #[test]
    fn parses_the_double_slash_form() {
        let target = Target::parse("//raspi/PiHDD/xiaomi/788b").unwrap();
        assert_eq!(target.host, "raspi");
        assert_eq!(target.port, 445);
        assert_eq!(target.share, "PiHDD");
        assert_eq!(target.path, "xiaomi/788b");
    }

    #[test]
    fn parses_the_smb_scheme_and_a_port() {
        let target = Target::parse("smb://10.0.0.1:4450/share").unwrap();
        assert_eq!(target.host, "10.0.0.1");
        assert_eq!(target.port, 4450);
        assert_eq!(target.share, "share");
        assert_eq!(target.path, "");
    }

    #[test]
    fn parses_the_windows_form() {
        let target = Target::parse(r"\\host\share\dir\file.txt").unwrap();
        assert_eq!(target.share, "share");
        assert_eq!(target.path, "dir/file.txt");
    }

    #[test]
    fn rejects_a_target_without_a_share() {
        assert!(Target::parse("//host").is_err());
        assert!(Target::parse("relative/path").is_err());
    }

    #[test]
    fn resolves_relative_and_absolute_paths() {
        let base = Target::parse("//host/share/base").unwrap();
        assert_eq!(base.resolve("child").unwrap().path, "base/child");
        assert_eq!(
            base.resolve("//other/share2/x").unwrap().display(),
            "//other/share2/x"
        );
    }

    #[test]
    fn remembers_a_trailing_separator() {
        assert!(Target::parse("//host/share/dir/").unwrap().trailing_slash);
        assert!(Target::parse(r"\\host\share\dir\").unwrap().trailing_slash);
        assert!(!Target::parse("//host/share/dir").unwrap().trailing_slash);
        // The share root is a directory whether or not it's spelled with one.
        assert!(!Target::parse("//host/share").unwrap().trailing_slash);
        assert!(!Target::parse("//host/share/").unwrap().trailing_slash);
    }

    #[test]
    fn round_trips_through_display() {
        for input in [
            "//host/share",
            "//host/share/a/b",
            "//host:4450/share/a",
            r"//host/share/a\u{D800}b",
            r"//host/share/back\\slash",
            r"//host/odd\u{DC00}share/x",
        ] {
            let target = Target::parse(input).unwrap();
            assert_eq!(target.display(), input);
        }
    }

    #[test]
    fn reads_the_escapes_in_a_share_and_a_path() {
        let lone = smb2::name::from_utf16(&[0x61, 0xD800, 0x62]);
        let target = Target::parse(r"//host/share/dir/a\u{D800}b").unwrap();
        assert_eq!(target.path, format!("dir/{lone}"));
        let target = Target::parse(r"smb://host/share/back\\slash").unwrap();
        assert_eq!(target.path, r"back\slash");
        let target = Target::parse(r"//host/odd\u{D800}/x").unwrap();
        assert_eq!(
            target.share,
            smb2::name::from_utf16(&[0x6F, 0x64, 0x64, 0xD800])
        );
    }

    #[test]
    fn refuses_a_backslash_that_isnt_an_escape_in_the_slash_forms() {
        assert!(Target::parse(r"//host/share/dir\file").is_err());
    }

    #[test]
    fn resolves_an_escaped_relative_path() {
        let base = Target::parse("//host/share/base").unwrap();
        let lone = smb2::name::from_utf16(&[0xDC00]);
        assert_eq!(
            base.resolve(r"\u{DC00}").unwrap().path,
            format!("base/{lone}")
        );
        assert!(base.resolve(r"dir\file").is_err());
    }
}