From 60652b35347959c5a18ea5ea6d9a95e1a7430724 Mon Sep 17 00:00:00 2001 From: Jake Wallin Date: Mon, 30 Nov 2026 03:55:10 +0000 Subject: [PATCH] cp: report symlink copy failures in archive mode --- src/uu/cp/locales/en-US.ftl | 1 + src/uu/cp/src/copydir.rs | 10 +-- src/uu/cp/src/cp.rs | 51 +++++++++++++++- tests/by-util/test_cp.rs | 119 ++++++++++++++++++++++++++++++++++++ 4 files changed, 174 insertions(+), 7 deletions(-) diff --git a/src/uu/cp/locales/en-US.ftl b/src/uu/cp/locales/en-US.ftl index 58d2ab99c09..93495d00897 100644 --- a/src/uu/cp/locales/en-US.ftl +++ b/src/uu/cp/locales/en-US.ftl @@ -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 } diff --git a/src/uu/cp/src/copydir.rs b/src/uu/cp/src/copydir.rs index b474c7f43c6..efe48ce3386 100644 --- a/src/uu/cp/src/copydir.rs +++ b/src/uu/cp/src/copydir.rs @@ -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 diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index 1196b83b4df..b9e0905c627 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -2261,7 +2261,8 @@ fn handle_existing_dest( dest: &Path, options: &Options, source_in_command_line: bool, - copied_files: &HashMap, + dest_metadata: &Metadata, + copied_files: &mut HashMap, ) -> CopyResult<()> { // Disallow copying a file to itself, unless `--force` and // `--backup` are both specified. @@ -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 { + 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 { @@ -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, @@ -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(()); diff --git a/tests/by-util/test_cp.rs b/tests/by-util/test_cp.rs index 06a9178ccf2..9f3d05f9de4 100644 --- a/tests/by-util/test_cp.rs +++ b/tests/by-util/test_cp.rs @@ -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")] +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