Skip to content

Commit c637b91

Browse files
committed
cp: report symlink copy failures in archive mode
1 parent 2a072db commit c637b91

4 files changed

Lines changed: 120 additions & 78 deletions

File tree

‎src/uu/cp/locales/en-US.ftl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ cp-error-failed-to-clone = failed to clone { $dest } from { $source }: { $error
6262
cp-error-cannot-change-attribute = cannot change attribute { $dest }: Source file is a non regular file
6363
cp-error-cannot-stat = cannot stat { $source }: No such file or directory
6464
cp-error-cannot-stat-context = cannot stat { $source }
65+
cp-error-cannot-create-symbolic-link-file-exists = cannot create symbolic link { $dest }: File exists
6566
cp-error-cannot-create-symlink = cannot create symlink { $dest } to { $source }
6667
cp-error-cannot-create-hard-link = cannot create hard link { $dest } to { $source }
6768
cp-error-omitting-directory = -r not specified; omitting directory { $dir }

‎src/uu/cp/src/copydir.rs‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -313,13 +313,11 @@ fn copy_direntry(
313313
}
314314
return Ok(false);
315315
}
316-
if preserve_hard_links {
317-
if !source_is_symlink {
318-
return Err(err);
319-
}
320-
// silent the error with a symlink
321-
// In case we do --archive, we might copy the symlink
322-
// before the file itself
316+
if source_is_symlink {
317+
crate::show_error_if_needed(&err);
318+
set_exit_code(crate::EXIT_ERR);
319+
} else if preserve_hard_links {
320+
return Err(err);
323321
} else {
324322
// At this point, `path` is just a plain old file.
325323
// Terminate this function immediately if there is any

‎src/uu/cp/src/cp.rs‎

Lines changed: 71 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -2261,7 +2261,8 @@ fn handle_existing_dest(
22612261
dest: &Path,
22622262
options: &Options,
22632263
source_in_command_line: bool,
2264-
copied_files: &HashMap<FileInformation, PathBuf>,
2264+
dest_metadata: &Metadata,
2265+
copied_files: &mut HashMap<FileInformation, PathBuf>,
22652266
) -> CopyResult<()> {
22662267
// Disallow copying a file to itself, unless `--force` and
22672268
// `--backup` are both specified.
@@ -2283,6 +2284,36 @@ fn handle_existing_dest(
22832284
options.overwrite.verify(dest, options.debug)?;
22842285
}
22852286

2287+
// Refuse the conflict before touching the directory or its backup. A
2288+
// skipped update still counts as a destination for hard-link preservation.
2289+
if dest_metadata.is_dir() && !options.dereference(source_in_command_line) && source.is_symlink()
2290+
{
2291+
if options.copy_mode == CopyMode::Update
2292+
&& !should_update(&source.symlink_metadata()?, dest, options)?
2293+
{
2294+
if options.preserve_hard_links() {
2295+
copied_files.insert(
2296+
FileInformation::from_path(source, false)?,
2297+
dest.to_path_buf(),
2298+
);
2299+
}
2300+
return Err(CpError::Skipped(false));
2301+
}
2302+
if options.backup != BackupMode::None {
2303+
if options.copy_mode == CopyMode::Link {
2304+
let context = translate!("cp-error-cannot-create-hard-link",
2305+
"dest" => dest.quote(), "source" => source.quote());
2306+
return Err(translate!("cp-error-file-exists", "path" => context).into());
2307+
}
2308+
return Err(translate!("cp-error-cannot-create-symbolic-link-file-exists", "dest" => dest.quote()).into());
2309+
}
2310+
return Err(
2311+
translate!("cp-error-cannot-overwrite-directory-with-non-directory",
2312+
"dir" => dest.quote(), "source" => source.quote())
2313+
.into(),
2314+
);
2315+
}
2316+
22862317
let mut is_dest_removed = false;
22872318
let backup_path = backup_control::get_backup_path(options.backup, dest, &options.backup_suffix);
22882319
if let Some(backup_path) = backup_path {
@@ -2551,6 +2582,29 @@ fn print_paths(parents: bool, source: &Path, dest: &Path) -> CopyResult<()> {
25512582
Ok(())
25522583
}
25532584

2585+
/// Decide whether an existing destination should be updated.
2586+
fn should_update(source_metadata: &Metadata, dest: &Path, options: &Options) -> CopyResult<bool> {
2587+
match options.update {
2588+
UpdateMode::All => Ok(true),
2589+
UpdateMode::None => {
2590+
if options.debug {
2591+
println!("skipped {}", dest.quote());
2592+
}
2593+
Ok(false)
2594+
}
2595+
UpdateMode::NoneFail => {
2596+
Err(translate!("cp-error-not-replacing", "file" => dest.quote()).into())
2597+
}
2598+
UpdateMode::IfOlder => {
2599+
if source_metadata.modified()? <= dest.symlink_metadata()?.modified()? {
2600+
return Ok(false);
2601+
}
2602+
options.overwrite.verify(dest, options.debug)?;
2603+
Ok(true)
2604+
}
2605+
}
2606+
}
2607+
25542608
/// Handles the copy mode for a file copy operation.
25552609
///
25562610
/// This function determines how to copy a file based on the provided options.
@@ -2603,7 +2657,13 @@ fn handle_copy_mode(
26032657
)
26042658
})?;
26052659
}
2606-
CopyMode::Copy => {
2660+
CopyMode::Copy | CopyMode::Update => {
2661+
if options.copy_mode == CopyMode::Update
2662+
&& dest.exists()
2663+
&& !should_update(source_metadata, dest, options)?
2664+
{
2665+
return Ok(PerformedAction::Skipped);
2666+
}
26072667
copy_helper(
26082668
source,
26092669
dest,
@@ -2624,69 +2684,6 @@ fn handle_copy_mode(
26242684
symlink_file(source, dest, symlinked_files)?;
26252685
}
26262686
}
2627-
CopyMode::Update => {
2628-
if dest.exists() {
2629-
match options.update {
2630-
UpdateMode::All => {
2631-
copy_helper(
2632-
source,
2633-
dest,
2634-
options,
2635-
context,
2636-
source_metadata,
2637-
symlinked_files,
2638-
source_in_command_line,
2639-
created_parent_dirs,
2640-
)?;
2641-
}
2642-
UpdateMode::None => {
2643-
if options.debug {
2644-
println!("skipped {}", dest.quote());
2645-
}
2646-
2647-
return Ok(PerformedAction::Skipped);
2648-
}
2649-
UpdateMode::NoneFail => {
2650-
return Err(CpError::Error(
2651-
translate!("cp-error-not-replacing", "file" => dest.quote()),
2652-
));
2653-
}
2654-
UpdateMode::IfOlder => {
2655-
let dest_metadata = fs::symlink_metadata(dest)?;
2656-
2657-
let src_time = source_metadata.modified()?;
2658-
let dest_time = dest_metadata.modified()?;
2659-
if src_time <= dest_time {
2660-
return Ok(PerformedAction::Skipped);
2661-
}
2662-
2663-
options.overwrite.verify(dest, options.debug)?;
2664-
2665-
copy_helper(
2666-
source,
2667-
dest,
2668-
options,
2669-
context,
2670-
source_metadata,
2671-
symlinked_files,
2672-
source_in_command_line,
2673-
created_parent_dirs,
2674-
)?;
2675-
}
2676-
}
2677-
} else {
2678-
copy_helper(
2679-
source,
2680-
dest,
2681-
options,
2682-
context,
2683-
source_metadata,
2684-
symlinked_files,
2685-
source_in_command_line,
2686-
created_parent_dirs,
2687-
)?;
2688-
}
2689-
}
26902687
CopyMode::AttrOnly => {
26912688
// The destination must have the source's type. Creating a regular
26922689
// file for a FIFO or a device both gets the type wrong and, for a
@@ -2854,7 +2851,7 @@ fn copy_file(
28542851
fs::remove_file(dest)?;
28552852
}
28562853

2857-
if initial_dest_metadata.is_some()
2854+
if let Some(dest_metadata) = &initial_dest_metadata
28582855
&& (!options.attributes_only
28592856
|| matches!(
28602857
options.overwrite,
@@ -2879,7 +2876,14 @@ fn copy_file(
28792876
}
28802877
}
28812878
}
2882-
handle_existing_dest(source, dest, options, source_in_command_line, copied_files)?;
2879+
handle_existing_dest(
2880+
source,
2881+
dest,
2882+
options,
2883+
source_in_command_line,
2884+
dest_metadata,
2885+
copied_files,
2886+
)?;
28832887
if are_hardlinks_to_same_file(source, dest) {
28842888
if options.copy_mode == CopyMode::Copy {
28852889
return Ok(());

‎tests/by-util/test_cp.rs‎

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4547,6 +4547,42 @@ fn test_cp_dir_vs_dangling_symlink(#[case] flags: &str) {
45474547
assert!(!at.dir_exists("nowhere"));
45484548
}
45494549

4550+
#[rstest]
4551+
#[case::archive("-a")]
4552+
#[case::with_backup("-ab")]
4553+
fn test_cp_archive_cannot_overwrite_directory_with_symlink(#[case] flags: &str) {
4554+
let (at, mut ucmd) = at_and_ucmd!();
4555+
at.mkdir_all("src/v2");
4556+
at.write("src/v2/version", "new");
4557+
at.relative_symlink_dir("v2", "src/current");
4558+
at.mkdir_all("backup/src/current");
4559+
at.write("backup/src/current/version", "old");
4560+
at.write("backup/src/current~", "previous backup");
4561+
4562+
let dest = path!("backup", "src", "current");
4563+
ucmd.arg(flags);
4564+
// WASI cannot preserve the mode of the copied version file.
4565+
#[cfg(wasi_runner)]
4566+
ucmd.arg("--no-preserve=mode");
4567+
let expected = if flags == "-a" {
4568+
format!(
4569+
"cannot overwrite directory {} with non-directory {}",
4570+
dest.quote(),
4571+
path!("src", "current").quote()
4572+
)
4573+
} else {
4574+
format!("cannot create symbolic link {}: File exists", dest.quote())
4575+
};
4576+
ucmd.args(&["src", "backup"])
4577+
.fails_with_code(1)
4578+
.stderr_only(format!("cp: {expected}\n"));
4579+
4580+
assert!(!at.is_symlink("backup/src/current"));
4581+
assert_eq!(at.read("backup/src/current/version"), "old");
4582+
assert_eq!(at.read("backup/src/current~"), "previous backup");
4583+
assert_eq!(at.read("backup/src/v2/version"), "new");
4584+
}
4585+
45504586
#[test]
45514587
fn test_cp_recursive_dest_subdir_is_file() {
45524588
// A directory whose destination already exists as a file is reported
@@ -9031,8 +9067,9 @@ fn test_cp_archive_deref_symlinks_inside_dir() {
90319067
let scene = TestScenario::new(util_name!());
90329068
let at = &scene.fixtures;
90339069
at.mkdir("srcdir");
9034-
at.touch("srcdir/real.txt");
9035-
symlink("real.txt", at.plus("srcdir/link.txt")).unwrap();
9070+
// An external target tests dereferencing without requiring hard-link support.
9071+
at.write("real.txt", "contents");
9072+
symlink("../real.txt", at.plus("srcdir/link.txt")).unwrap();
90369073

90379074
// -a (no deref): inner symlinks preserved
90389075
scene.ucmd().args(&["-a", "srcdir", "dest_a"]).succeeds();
@@ -9047,6 +9084,7 @@ fn test_cp_archive_deref_symlinks_inside_dir() {
90479084
!at.is_symlink("dest_aL/link.txt"),
90489085
"-aL: inner symlink should be dereferenced"
90499086
);
9087+
assert_eq!(at.read("dest_aL/link.txt"), "contents");
90509088

90519089
// -La (last is -a, no deref): inner symlinks preserved
90529090
scene.ucmd().args(&["-La", "srcdir", "dest_La"]).succeeds();
@@ -9092,8 +9130,8 @@ fn test_cp_archive_deref_repeated_flag_last_wins() {
90929130
let scene = TestScenario::new(util_name!());
90939131
let at = &scene.fixtures;
90949132
at.mkdir("srcdir");
9095-
at.touch("srcdir/real.txt");
9096-
symlink("real.txt", at.plus("srcdir/link.txt")).unwrap();
9133+
at.write("real.txt", "contents");
9134+
symlink("../real.txt", at.plus("srcdir/link.txt")).unwrap();
90979135

90989136
// -aL -a: -a is last, inner symlinks preserved
90999137
scene
@@ -9114,6 +9152,7 @@ fn test_cp_archive_deref_repeated_flag_last_wins() {
91149152
!at.is_symlink("dest2/link.txt"),
91159153
"-La -L: last -L should dereference inner symlinks"
91169154
);
9155+
assert_eq!(at.read("dest2/link.txt"), "contents");
91179156
}
91189157

91199158
#[test]

0 commit comments

Comments
 (0)