Skip to main content

normalize_entry_path

Function normalize_entry_path 

Source
pub fn normalize_entry_path<P: AsRef<Path>>(path: P) -> PathBuf
Expand description

Rewrites a path into a name that is safe to store in an archive.

An entry name that starts at the filesystem root, or that climbs out of the archive with .., is a path-traversal hazard for whoever extracts it later. The tar backend refuses such names outright, while zip, 7z, cab and cpio used to write them verbatim (issue #90). Normalizing here keeps every backend consistent and every archive totebag produces safe to extract.

The rules follow tar(1), which reports “Removing leading `../’ from member names” for the same inputs:

  • the root and any drive prefix are dropped, so /etc/hosts becomes etc/hosts;
  • . components are dropped, so ./src/main.rs becomes src/main.rs;
  • .. cancels the preceding component when there is one, so a/../b becomes b;
  • a leading .. that cannot cancel anything is dropped, so ../foo/bar becomes foo/bar.

This is a purely lexical transformation: the filesystem is never consulted, so symbolic links are left for the caller to deal with.

use std::path::{Path, PathBuf};
use totebag::normalize_entry_path;

assert_eq!(normalize_entry_path(Path::new("../foo/bar")), PathBuf::from("foo/bar"));
assert_eq!(normalize_entry_path(Path::new("./src/main.rs")), PathBuf::from("src/main.rs"));
assert_eq!(normalize_entry_path(Path::new("a/../b")), PathBuf::from("b"));