torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! Safe relative paths under a host-owned download root.

use std::path::{Component, Path, PathBuf};

use crate::error::{Error, Result};

/// Sanitize a torrent-relative path so it cannot escape a host-chosen root.
///
/// Rejects absolute paths, `..`, empty components, and NUL bytes. The host
/// project sets the write roots (`Config.download_dir` for content,
/// `Config.state_dir` for ledger/state); this crate only places torrent
/// files under `{download_dir}/{info_hash}/` using these relative paths.
pub fn sanitize_torrent_relative_path(path: impl AsRef<Path>) -> Result<PathBuf> {
    let path = path.as_ref();
    if path.as_os_str().is_empty() {
        return Err(Error::Torrent("empty torrent path".into()));
    }
    if path.is_absolute() {
        return Err(Error::Torrent(format!(
            "torrent path must be relative (got {})",
            path.display()
        )));
    }

    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            Component::Normal(part) => {
                let text = part.to_str().ok_or_else(|| {
                    Error::Torrent("torrent path component is not utf-8".into())
                })?;
                if text.is_empty() || text.contains('\0') {
                    return Err(Error::Torrent(
                        "torrent path component is empty or contains NUL".into(),
                    ));
                }
                if text == "." || text == ".." {
                    return Err(Error::Torrent(format!(
                        "torrent path component not allowed: {text}"
                    )));
                }
                out.push(text);
            }
            Component::CurDir => {}
            Component::ParentDir
            | Component::RootDir
            | Component::Prefix(_) => {
                return Err(Error::Torrent(format!(
                    "torrent path escapes host download root: {}",
                    path.display()
                )));
            }
        }
    }

    if out.as_os_str().is_empty() {
        return Err(Error::Torrent("torrent path resolved empty".into()));
    }
    Ok(out)
}

/// Join `relative` under `root` and refuse any escape (lexical containment).
pub fn join_under_root(root: &Path, relative: &Path) -> Result<PathBuf> {
    let relative = sanitize_torrent_relative_path(relative)?;
    let joined = root.join(&relative);
    ensure_path_within_root(root, &joined)?;
    Ok(joined)
}

pub(crate) fn ensure_path_within_root(root: &Path, candidate: &Path) -> Result<()> {
    let root_components: Vec<_> = root.components().collect();
    let cand_components: Vec<_> = candidate.components().collect();
    if cand_components.len() < root_components.len() {
        return Err(Error::Store(format!(
            "path {} escapes download root {}",
            candidate.display(),
            root.display()
        )));
    }
    if cand_components[..root_components.len()] != root_components[..] {
        return Err(Error::Store(format!(
            "path {} escapes download root {}",
            candidate.display(),
            root.display()
        )));
    }
    for component in &cand_components[root_components.len()..] {
        match component {
            Component::Normal(_) | Component::CurDir => {}
            _ => {
                return Err(Error::Store(format!(
                    "path {} escapes download root {}",
                    candidate.display(),
                    root.display()
                )));
            }
        }
    }
    Ok(())
}

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

    #[test]
    fn accepts_normal_relative() {
        let p = sanitize_torrent_relative_path("dir/file.bin").expect("ok");
        assert_eq!(p, PathBuf::from("dir/file.bin"));
    }

    #[test]
    fn rejects_parent_and_absolute() {
        assert!(sanitize_torrent_relative_path("../etc/passwd").is_err());
        assert!(sanitize_torrent_relative_path("/etc/passwd").is_err());
        assert!(sanitize_torrent_relative_path("a/../../b").is_err());
    }

    #[test]
    fn join_stays_under_root() {
        let root = PathBuf::from("/tmp/downloads/abc");
        let joined = join_under_root(&root, Path::new("name/file.bin")).expect("join");
        assert_eq!(joined, root.join("name/file.bin"));
        assert!(join_under_root(&root, Path::new("../x")).is_err());
    }
}