Skip to content

Commit 54ce907

Browse files
limadog9sylvestre
authored andcommitted
cp: report symlink copy failures in archive mode
1 parent f88b235 commit 54ce907

4 files changed

Lines changed: 176 additions & 7 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: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -313,13 +313,15 @@ fn copy_direntry(
313313
}
314314
return Ok(false);
315315
}
316-
if preserve_hard_links {
316+
if source_is_symlink && !options.dereference {
317+
crate::show_error_if_needed(&err);
318+
set_exit_code(crate::EXIT_ERR);
319+
} else if preserve_hard_links {
320+
// With -aL a symlink entry may be a second name for a file
321+
// already copied. Keep the existing handling for that case.
317322
if !source_is_symlink {
318323
return Err(err);
319324
}
320-
// silent the error with a symlink
321-
// In case we do --archive, we might copy the symlink
322-
// before the file itself
323325
} else {
324326
// At this point, `path` is just a plain old file.
325327
// Terminate this function immediately if there is any

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

Lines changed: 48 additions & 3 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,43 @@ 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+
match (&options.copy_mode, &options.update) {
2292+
(CopyMode::Update, UpdateMode::NoneFail) => {
2293+
return Err(translate!("cp-error-not-replacing", "file" => dest.quote()).into());
2294+
}
2295+
(CopyMode::Update, UpdateMode::IfOlder) => {
2296+
if source.symlink_metadata()?.modified()? <= dest_metadata.modified()? {
2297+
if options.preserve_hard_links() {
2298+
copied_files.insert(
2299+
FileInformation::from_path(source, false)?,
2300+
dest.to_path_buf(),
2301+
);
2302+
}
2303+
return Err(CpError::Skipped(false));
2304+
}
2305+
options.overwrite.verify(dest, options.debug)?;
2306+
}
2307+
_ => {}
2308+
}
2309+
if options.backup != BackupMode::None {
2310+
if options.copy_mode == CopyMode::Link {
2311+
let context = translate!("cp-error-cannot-create-hard-link",
2312+
"dest" => dest.quote(), "source" => source.quote());
2313+
return Err(translate!("cp-error-file-exists", "path" => context).into());
2314+
}
2315+
return Err(translate!("cp-error-cannot-create-symbolic-link-file-exists", "dest" => dest.quote()).into());
2316+
}
2317+
return Err(
2318+
translate!("cp-error-cannot-overwrite-directory-with-non-directory",
2319+
"dir" => dest.quote(), "source" => source.quote())
2320+
.into(),
2321+
);
2322+
}
2323+
22862324
let mut is_dest_removed = false;
22872325
let backup_path = backup_control::get_backup_path(options.backup, dest, &options.backup_suffix);
22882326
if let Some(backup_path) = backup_path {
@@ -2854,7 +2892,7 @@ fn copy_file(
28542892
fs::remove_file(dest)?;
28552893
}
28562894

2857-
if initial_dest_metadata.is_some()
2895+
if let Some(dest_metadata) = &initial_dest_metadata
28582896
&& (!options.attributes_only
28592897
|| matches!(
28602898
options.overwrite,
@@ -2879,7 +2917,14 @@ fn copy_file(
28792917
}
28802918
}
28812919
}
2882-
handle_existing_dest(source, dest, options, source_in_command_line, copied_files)?;
2920+
handle_existing_dest(
2921+
source,
2922+
dest,
2923+
options,
2924+
source_in_command_line,
2925+
dest_metadata,
2926+
copied_files,
2927+
)?;
28832928
if are_hardlinks_to_same_file(source, dest) {
28842929
if options.copy_mode == CopyMode::Copy {
28852930
return Ok(());

‎tests/by-util/test_cp.rs‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4547,6 +4547,127 @@ 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+
4586+
#[rstest]
4587+
#[case::older_symlink(&["-au"], 1, true)]
4588+
#[case::newer_symlink(&["-a", "--update=older"], 3, false)]
4589+
fn test_cp_archive_update_symlink_over_directory(
4590+
#[case] flags: &[&str],
4591+
#[case] link_mtime: i64,
4592+
#[case] skipped: bool,
4593+
) {
4594+
use filetime::FileTime;
4595+
4596+
let (at, mut ucmd) = at_and_ucmd!();
4597+
at.mkdir("src");
4598+
at.mkdir("target");
4599+
at.relative_symlink_dir("../target", "src/current");
4600+
at.mkdir_all("backup/src/current");
4601+
at.write("backup/src/current/version", "old");
4602+
let time = FileTime::from_unix_time(link_mtime, 0);
4603+
filetime::set_symlink_file_times(at.plus("src/current"), time, time).unwrap();
4604+
filetime::set_file_mtime(
4605+
at.plus("backup/src/current"),
4606+
FileTime::from_unix_time(2, 0),
4607+
)
4608+
.unwrap();
4609+
4610+
ucmd.args(flags);
4611+
#[cfg(wasi_runner)]
4612+
ucmd.arg("--no-preserve=mode");
4613+
ucmd.args(&["src", "backup"]);
4614+
if skipped {
4615+
ucmd.succeeds().no_stderr();
4616+
} else {
4617+
ucmd.fails_with_code(1).stderr_only(format!(
4618+
"cp: cannot overwrite directory {} with non-directory {}\n",
4619+
path!("backup", "src", "current").quote(),
4620+
path!("src", "current").quote()
4621+
));
4622+
}
4623+
assert!(!at.is_symlink("backup/src/current"));
4624+
assert_eq!(at.read("backup/src/current/version"), "old");
4625+
}
4626+
4627+
#[test]
4628+
fn test_cp_archive_link_backup_symlink_over_directory() {
4629+
let (at, mut ucmd) = at_and_ucmd!();
4630+
at.mkdir("src");
4631+
at.mkdir("target");
4632+
at.relative_symlink_dir("../target", "src/current");
4633+
at.mkdir_all("backup/src/current");
4634+
at.write("backup/src/current/version", "old");
4635+
at.write("backup/src/current~", "previous backup");
4636+
4637+
ucmd.args(&["-a", "--link", "--backup"]);
4638+
#[cfg(wasi_runner)]
4639+
ucmd.arg("--no-preserve=mode");
4640+
ucmd.args(&["src", "backup"])
4641+
.fails_with_code(1)
4642+
.stderr_only(format!(
4643+
"cp: cannot create hard link {} to {}: File exists\n",
4644+
path!("backup", "src", "current").quote(),
4645+
path!("src", "current").quote()
4646+
));
4647+
assert!(!at.is_symlink("backup/src/current"));
4648+
assert_eq!(at.read("backup/src/current/version"), "old");
4649+
assert_eq!(at.read("backup/src/current~"), "previous backup");
4650+
}
4651+
4652+
#[test]
4653+
fn test_cp_archive_deref_symlink_over_directory() {
4654+
let (at, mut ucmd) = at_and_ucmd!();
4655+
at.mkdir("src");
4656+
at.mkdir("target");
4657+
at.write("target/version", "new");
4658+
at.relative_symlink_dir("../target", "src/current");
4659+
at.mkdir_all("backup/src/current");
4660+
at.touch("backup/src/current/keep");
4661+
4662+
ucmd.arg("-aL");
4663+
#[cfg(wasi_runner)]
4664+
ucmd.arg("--no-preserve=mode");
4665+
ucmd.args(&["src", "backup"]).succeeds().no_stderr();
4666+
assert!(!at.is_symlink("backup/src/current"));
4667+
assert!(at.file_exists("backup/src/current/keep"));
4668+
assert_eq!(at.read("backup/src/current/version"), "new");
4669+
}
4670+
45504671
#[test]
45514672
fn test_cp_recursive_dest_subdir_is_file() {
45524673
// A directory whose destination already exists as a file is reported

0 commit comments

Comments
 (0)