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 src/uu/cp/locales/en-US.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ cp-error-failed-to-clone = failed to clone { $dest } from { $source }: { $error
cp-error-cannot-change-attribute = cannot change attribute { $dest }: Source file is a non regular file
cp-error-cannot-stat = cannot stat { $source }: No such file or directory
cp-error-cannot-stat-context = cannot stat { $source }
cp-error-cannot-create-symbolic-link-file-exists = cannot create symbolic link { $dest }: File exists
cp-error-cannot-create-symlink = cannot create symlink { $dest } to { $source }
cp-error-cannot-create-hard-link = cannot create hard link { $dest } to { $source }
cp-error-omitting-directory = -r not specified; omitting directory { $dir }
Expand Down
10 changes: 6 additions & 4 deletions src/uu/cp/src/copydir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,13 +313,15 @@ fn copy_direntry(
}
return Ok(false);
}
if preserve_hard_links {
if source_is_symlink && !options.dereference {
crate::show_error_if_needed(&err);
set_exit_code(crate::EXIT_ERR);
} else if preserve_hard_links {
// With -aL a symlink entry may be a second name for a file
// already copied. Keep the existing handling for that case.
if !source_is_symlink {
return Err(err);
}
// silent the error with a symlink
// In case we do --archive, we might copy the symlink
// before the file itself
} else {
// At this point, `path` is just a plain old file.
// Terminate this function immediately if there is any
Expand Down
51 changes: 48 additions & 3 deletions src/uu/cp/src/cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2261,7 +2261,8 @@ fn handle_existing_dest(
dest: &Path,
options: &Options,
source_in_command_line: bool,
copied_files: &HashMap<FileInformation, PathBuf>,
dest_metadata: &Metadata,
copied_files: &mut HashMap<FileInformation, PathBuf>,
) -> CopyResult<()> {
// Disallow copying a file to itself, unless `--force` and
// `--backup` are both specified.
Expand All @@ -2283,6 +2284,43 @@ fn handle_existing_dest(
options.overwrite.verify(dest, options.debug)?;
}

// Refuse the conflict before touching the directory or its backup. A
// skipped update still counts as a destination for hard-link preservation.
if dest_metadata.is_dir() && !options.dereference(source_in_command_line) && source.is_symlink()
{
match (&options.copy_mode, &options.update) {
(CopyMode::Update, UpdateMode::NoneFail) => {
return Err(translate!("cp-error-not-replacing", "file" => dest.quote()).into());
}
(CopyMode::Update, UpdateMode::IfOlder) => {
if source.symlink_metadata()?.modified()? <= dest_metadata.modified()? {
if options.preserve_hard_links() {
copied_files.insert(
FileInformation::from_path(source, false)?,
dest.to_path_buf(),
);
}
return Err(CpError::Skipped(false));
}
options.overwrite.verify(dest, options.debug)?;
}
_ => {}
}
if options.backup != BackupMode::None {
if options.copy_mode == CopyMode::Link {

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.

same for the --link --backup path, please add a test

let context = translate!("cp-error-cannot-create-hard-link",
"dest" => dest.quote(), "source" => source.quote());
return Err(translate!("cp-error-file-exists", "path" => context).into());
}
return Err(translate!("cp-error-cannot-create-symbolic-link-file-exists", "dest" => dest.quote()).into());
}
return Err(
translate!("cp-error-cannot-overwrite-directory-with-non-directory",
"dir" => dest.quote(), "source" => source.quote())
.into(),
);
}

let mut is_dest_removed = false;
let backup_path = backup_control::get_backup_path(options.backup, dest, &options.backup_suffix);
if let Some(backup_path) = backup_path {
Expand Down Expand Up @@ -2854,7 +2892,7 @@ fn copy_file(
fs::remove_file(dest)?;
}

if initial_dest_metadata.is_some()
if let Some(dest_metadata) = &initial_dest_metadata
&& (!options.attributes_only
|| matches!(
options.overwrite,
Expand All @@ -2879,7 +2917,14 @@ fn copy_file(
}
}
}
handle_existing_dest(source, dest, options, source_in_command_line, copied_files)?;
handle_existing_dest(
source,
dest,
options,
source_in_command_line,
dest_metadata,
copied_files,
)?;
if are_hardlinks_to_same_file(source, dest) {
if options.copy_mode == CopyMode::Copy {
return Ok(());
Expand Down
119 changes: 119 additions & 0 deletions tests/by-util/test_cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4547,6 +4547,125 @@ fn test_cp_dir_vs_dangling_symlink(#[case] flags: &str) {
assert!(!at.dir_exists("nowhere"));
}

#[rstest]
#[case::archive("-a")]
#[case::with_backup("-ab")]

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.

please add a case with -L too, to make sure the deref path still succeeds

fn test_cp_archive_cannot_overwrite_directory_with_symlink(#[case] flags: &str) {
let (at, mut ucmd) = at_and_ucmd!();
at.mkdir_all("src/v2");
at.write("src/v2/version", "new");
at.relative_symlink_dir("v2", "src/current");
at.mkdir_all("backup/src/current");
at.write("backup/src/current/version", "old");
at.write("backup/src/current~", "previous backup");

let dest = path!("backup", "src", "current");
ucmd.arg(flags);
// WASI cannot preserve the mode of the copied version file.
#[cfg(wasi_runner)]
ucmd.arg("--no-preserve=mode");
let expected = if flags == "-a" {
format!(
"cannot overwrite directory {} with non-directory {}",
dest.quote(),
path!("src", "current").quote()
)
} else {
format!("cannot create symbolic link {}: File exists", dest.quote())
};
ucmd.args(&["src", "backup"])
.fails_with_code(1)
.stderr_only(format!("cp: {expected}\n"));

assert!(!at.is_symlink("backup/src/current"));
assert_eq!(at.read("backup/src/current/version"), "old");
assert_eq!(at.read("backup/src/current~"), "previous backup");
assert_eq!(at.read("backup/src/v2/version"), "new");
}

#[rstest]
#[case::older_symlink(&["-au"], 1, true)]
#[case::newer_symlink(&["-a", "--update=older"], 3, false)]
fn test_cp_archive_update_symlink_over_directory(
#[case] flags: &[&str],
#[case] link_mtime: i64,
#[case] skipped: bool,
) {
use filetime::FileTime;

let (at, mut ucmd) = at_and_ucmd!();
at.mkdir("src");
at.mkdir("target");
at.relative_symlink_dir("../target", "src/current");
at.mkdir_all("backup/src/current");
at.write("backup/src/current/version", "old");
let time = FileTime::from_unix_time(link_mtime, 0);
filetime::set_symlink_file_times(at.plus("src/current"), time, time).unwrap();
filetime::set_file_mtime(
at.plus("backup/src/current"),
FileTime::from_unix_time(2, 0),
)
.unwrap();

ucmd.args(flags);
#[cfg(wasi_runner)]
ucmd.arg("--no-preserve=mode");
ucmd.args(&["src", "backup"]);
if skipped {
ucmd.succeeds().no_stderr();
} else {
ucmd.fails_with_code(1).stderr_only(format!(
"cp: cannot overwrite directory {} with non-directory {}\n",
path!("backup", "src", "current").quote(),
path!("src", "current").quote()
));
}
assert!(!at.is_symlink("backup/src/current"));
assert_eq!(at.read("backup/src/current/version"), "old");
}

#[test]
fn test_cp_archive_link_backup_symlink_over_directory() {
let (at, mut ucmd) = at_and_ucmd!();
at.mkdir("src");
at.mkdir("target");
at.relative_symlink_dir("../target", "src/current");
at.mkdir_all("backup/src/current");
at.write("backup/src/current/version", "old");
at.write("backup/src/current~", "previous backup");

ucmd.args(&["-a", "--link", "--backup"]);
#[cfg(wasi_runner)]
ucmd.arg("--no-preserve=mode");
ucmd.args(&["src", "backup"])
.fails_with_code(1)
.stderr_only(format!(
"cp: cannot create hard link {} to {}: File exists\n",
path!("backup", "src", "current").quote(),
path!("src", "current").quote()
));
assert!(!at.is_symlink("backup/src/current"));
assert_eq!(at.read("backup/src/current/version"), "old");
assert_eq!(at.read("backup/src/current~"), "previous backup");
}

#[uutests::wasi_ignore(SymlinkHardlinkCaps)]
#[test]
fn test_cp_archive_deref_symlink_over_directory() {
let (at, mut ucmd) = at_and_ucmd!();
at.mkdir("src");
at.mkdir("target");
at.write("target/version", "new");
at.relative_symlink_dir("../target", "src/current");
at.mkdir_all("backup/src/current");
at.touch("backup/src/current/keep");

ucmd.args(&["-aL", "src", "backup"]).succeeds().no_stderr();
assert!(!at.is_symlink("backup/src/current"));
assert!(at.file_exists("backup/src/current/keep"));
assert_eq!(at.read("backup/src/current/version"), "new");
}

#[test]
fn test_cp_recursive_dest_subdir_is_file() {
// A directory whose destination already exists as a file is reported
Expand Down
Loading