use std::fs;
use std::path::{Component, Path, PathBuf};
use crate::error::{Error, Result};
pub(crate) fn file_mode(meta: &fs::Metadata) -> u32 {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
meta.permissions().mode() & 0o7777
}
#[cfg(not(unix))]
{
if meta.permissions().readonly() { 0o444 } else { 0o644 }
}
}
pub(crate) fn tar_directory(root: &Path, exclude: &[String]) -> Result<Vec<u8>> {
let patterns = exclude
.iter()
.map(|p| glob::Pattern::new(p).map_err(|e| Error::invalid(format!("exclude pattern {p:?}: {e}"))))
.collect::<Result<Vec<_>>>()?;
let gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::new(6));
let mut archive = tar::Builder::new(gz);
archive.follow_symlinks(false);
add_children(&mut archive, root, Path::new(""), &patterns)?;
let gz = archive.into_inner().map_err(|e| Error::io("archiving", e))?;
gz.finish().map_err(|e| Error::io("archiving", e))
}
fn add_children<W: std::io::Write>(
archive: &mut tar::Builder<W>,
dir: &Path,
prefix: &Path,
exclude: &[glob::Pattern],
) -> Result<()> {
let read = |e| Error::io(format!("reading {}", dir.display()), e);
let mut entries = fs::read_dir(dir)
.map_err(read)?
.collect::<std::io::Result<Vec<_>>>()
.map_err(read)?;
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let file_name = entry.file_name();
let name = file_name.to_string_lossy();
if exclude.iter().any(|p| p.matches(&name)) {
continue;
}
let path = entry.path();
let archived = prefix.join(&file_name);
let failed = |e| Error::io(format!("archiving {}", path.display()), e);
let meta = fs::symlink_metadata(&path).map_err(failed)?;
let mut header = tar::Header::new_gnu();
header.set_metadata_in_mode(&meta, tar::HeaderMode::Complete);
header.set_uid(0);
header.set_gid(0);
header.set_username("").map_err(failed)?;
header.set_groupname("").map_err(failed)?;
if meta.is_dir() {
header.set_size(0);
archive
.append_data(&mut header, &archived, std::io::empty())
.map_err(failed)?;
add_children(archive, &path, &archived, exclude)?;
} else if meta.file_type().is_symlink() {
let target = fs::read_link(&path).map_err(failed)?;
header.set_size(0);
archive.append_link(&mut header, &archived, &target).map_err(failed)?;
} else if meta.is_file() {
let file = fs::File::open(&path).map_err(failed)?;
archive.append_data(&mut header, &archived, file).map_err(failed)?;
}
}
Ok(())
}
pub(crate) fn untar(data: &[u8], root: &Path) -> Result<()> {
let bad = |what: String| Error::invalid(format!("download: refusing {what}"));
let io = |e| Error::io(format!("extracting into {}", root.display()), e);
fs::create_dir_all(root).map_err(io)?;
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(data));
archive.set_preserve_permissions(false);
archive.set_unpack_xattrs(false);
archive.set_overwrite(true);
for entry in archive.entries().map_err(io)? {
let mut entry = entry.map_err(io)?;
let path = entry.path().map_err(io)?.into_owned();
let Some(relative) = inside(Path::new(""), &path) else {
return Err(bad(format!("{} outside the destination", path.display())));
};
match entry.header().entry_type() {
tar::EntryType::Regular | tar::EntryType::Directory | tar::EntryType::Continuous => {}
tar::EntryType::Symlink | tar::EntryType::Link => {
let target = entry
.link_name()
.map_err(io)?
.ok_or_else(|| bad("a link without a target".into()))?;
let base = if entry.header().entry_type() == tar::EntryType::Symlink {
relative.parent().unwrap_or(Path::new("")).to_path_buf()
} else {
PathBuf::new()
};
if inside(&base, &target).is_none() {
return Err(bad(format!(
"link {} to {} outside the destination",
path.display(),
target.display()
)));
}
}
other => return Err(bad(format!("{} of type {other:?}", path.display()))),
}
if !entry.unpack_in(root).map_err(io)? {
return Err(bad(format!("{} outside the destination", path.display())));
}
}
Ok(())
}
fn inside(base: &Path, path: &Path) -> Option<PathBuf> {
let mut out = base.to_path_buf();
for component in path.components() {
match component {
Component::Normal(part) => out.push(part),
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
return None;
}
}
Component::RootDir | Component::Prefix(_) => return None,
}
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("exedev-test-{name}-{}", crate::wire::random_hex(4)));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn round_trip() {
let src = temp("src");
fs::create_dir_all(src.join("a/.git")).unwrap();
fs::write(src.join("a/f.txt"), "hello").unwrap();
fs::write(src.join("a/.git/x"), "no").unwrap();
fs::write(src.join("skip.log"), "no").unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink("a/f.txt", src.join("link")).unwrap();
let data = tar_directory(&src, &[".git".into(), "*.log".into()]).unwrap();
let dst = temp("dst");
untar(&data, &dst).unwrap();
assert_eq!(fs::read_to_string(dst.join("a/f.txt")).unwrap(), "hello");
assert!(!dst.join("a/.git").exists());
assert!(!dst.join("skip.log").exists());
#[cfg(unix)]
assert_eq!(fs::read_to_string(dst.join("link")).unwrap(), "hello");
fs::remove_dir_all(src).unwrap();
fs::remove_dir_all(dst).unwrap();
}
fn archive(build: impl FnOnce(&mut tar::Builder<flate2::write::GzEncoder<Vec<u8>>>)) -> Vec<u8> {
let mut b = tar::Builder::new(flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()));
build(&mut b);
b.into_inner().unwrap().finish().unwrap()
}
#[test]
fn refuses_escapes() {
let link = archive(|b| {
let mut h = tar::Header::new_gnu();
h.set_entry_type(tar::EntryType::Symlink);
h.set_size(0);
b.append_link(&mut h, "evil", "../../etc").unwrap();
});
let dst = temp("esc");
assert!(untar(&link, &dst).is_err());
let absolute = archive(|b| {
let mut h = tar::Header::new_gnu();
h.set_entry_type(tar::EntryType::Symlink);
h.set_size(0);
b.append_link(&mut h, "evil", "/etc/passwd").unwrap();
});
assert!(untar(&absolute, &dst).is_err());
let fifo = archive(|b| {
let mut h = tar::Header::new_gnu();
h.set_entry_type(tar::EntryType::Fifo);
h.set_size(0);
b.append_data(&mut h, "pipe", std::io::empty()).unwrap();
});
assert!(untar(&fifo, &dst).is_err());
assert!(inside(Path::new(""), Path::new("../x")).is_none());
assert_eq!(inside(Path::new("a"), Path::new("../b")), Some(PathBuf::from("b")));
fs::remove_dir_all(dst).unwrap();
}
}