Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ chrono = { version = "0.4.37", default-features = false, features = [
] }
clap = { version = "4.4", features = ["wrap_help", "cargo"] }
ctor = "1.0.0"
filetime = "0.2"
flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs"] }
phf = "0.14.0"
phf_codegen = "0.14.0"
Expand Down
1 change: 1 addition & 0 deletions src/uu/tar/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ categories = ["command-line-utilities"]
[dependencies]
chrono = { workspace = true }
clap = { workspace = true }
filetime = { workspace = true }
flate2 = { workspace = true }
regex = { workspace = true }
tar = { workspace = true }
Expand Down
4 changes: 4 additions & 0 deletions src/uu/tar/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ pub enum TarError {
#[error("tar: Refusing to write archive contents to terminal (missing -f option?)")]
RefuseWriteArchiveToTerminal,

/// The modification time of an extracted directory could not be set
#[error("tar: {path}: Cannot utime: {source}")]
CannotUtime { path: PathBuf, source: io::Error },

/// A member name with a `..` component, which is not extracted
#[error("tar: {path}: Member name contains '..'")]
MemberNameContainsDotDot { path: PathBuf },
Expand Down
31 changes: 30 additions & 1 deletion src/uu/tar/src/operations/extract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use crate::compression::open_archive_reader;
use crate::errors::{finish_after_previous_errors, report_recoverable, TarError};
use crate::CompressionMode;
use filetime::FileTime;
use std::collections::HashSet;
use std::io::Read;
use std::io::{self, BufWriter, Write};
Expand Down Expand Up @@ -80,7 +81,19 @@ pub fn extract_archive(
// Children before parents, so a read-only parent is restored last
directories.sort_by(|a, b| b.0.cmp(&a.0));
for (path, mut entry) in directories {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a bit too clever, if !refused then if let Some(mtime) would read better, no?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, it is now if !refused then if let Some(mtime).

refused_member |= unpack_entry(&mut entry, path, &mut out)?;
let mtime = entry.header().mtime().ok();
let refused = unpack_entry(&mut entry, path.clone(), &mut out)?;
refused_member |= refused;
// The archive's mtime, as GNU tar restores it (tar-rs only does it for files)
if !refused {
if let Some(mtime) = mtime {
if let Err(e) = set_directory_mtime(&path, mtime) {
out.flush().map_err(TarError::Io)?;
report_recoverable(&TarError::CannotUtime { path, source: e })?;
refused_member = true;
}
}
}
}

out.flush().map_err(TarError::Io)?;
Expand Down Expand Up @@ -130,6 +143,22 @@ fn unpack_entry<R: Read>(
Ok(!unpacked)
}

/// Sets the mtime of the directory `unpack_in` extracted for the member `path`.
fn set_directory_mtime(path: &Path, mtime: u64) -> io::Result<()> {
// `unpack_in` drops the root, `.` and prefix components of member names
let dst: PathBuf = path
.components()
.filter(|c| matches!(c, Component::Normal(_)))
.collect();
let dst = if dst.as_os_str().is_empty() {
PathBuf::from(".")
} else {
dst
};
// Negative times come back from tar-rs as large u64 values; cast like it does
filetime::set_file_mtime(&dst, FileTime::from_unix_time(mtime as i64, 0))
}

#[cfg(test)]
#[path = "extract_tests.rs"]
mod tests;
38 changes: 38 additions & 0 deletions tests/by-util/test_tar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,44 @@ fn test_extract_nested_read_only_directories() {
assert_eq!(child & 0o777, 0o555);
}

#[test]
fn test_extract_keeps_directory_mtime() {
let (at, mut ucmd) = at_and_ucmd!();
at.mkdir("out");

let mut tar_bytes = Vec::new();
{
let mut builder = TarRsBuilder::new(&mut tar_bytes);
let mut header = TarRsHeader::new_gnu();
header.set_entry_type(tar_rs_crate::EntryType::Directory);
header.set_mode(0o755);
header.set_mtime(1_000_000_000);
header.set_size(0);
builder
.append_data(&mut header, "dir/", std::io::empty())
.unwrap();
let mut header = TarRsHeader::new_gnu();
header.set_mode(0o644);
header.set_mtime(1_000_000_000);
header.set_size(1);
builder
.append_data(&mut header, "dir/f", Cursor::new("x"))
.unwrap();
builder.finish().unwrap();
}
at.write_bytes("dir.tar", &tar_bytes);

ucmd.args(&["-xf", "../dir.tar"])
.current_dir(at.plus("out"))
.succeeds();

let mtime = at.metadata("out/dir").modified().unwrap();
assert_eq!(
mtime,
std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000_000)
);
}

#[test]
fn test_extract_nonexistent_archive() {
new_ucmd!()
Expand Down
Loading