Skip to content

Commit

Permalink
cp: Fix broken symlinks to parent-dir
Browse files Browse the repository at this point in the history
According to the GNU cp official documentation[1], a symlink is only
created if all source paths are absolute, unless the destination files
are in the current directory.

This fix solves this GNU cp incompatibility by:
- Adding verifications when handling symlinks, to ensure that a symlink
  with relative path are only created if the destination is within the
  current directory.
- Adding unit tests to cover this modifications, and ensure the behavior
  is correctly align with GNU documentation.

[1]:
https://www.gnu.org/software/coreutils/manual/html_node/cp-invocation.html#index-_002ds-16
  • Loading branch information
luigieli committed Jun 13, 2024
1 parent d03c488 commit 61f114c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/uu/cp/src/cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use quick_error::quick_error;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::env;
#[cfg(not(windows))]
use std::ffi::CString;
use std::fs::{self, File, Metadata, OpenOptions, Permissions};
Expand Down Expand Up @@ -1864,6 +1865,22 @@ fn handle_copy_mode(
if dest.exists() && options.overwrite == OverwriteMode::Clobber(ClobberMode::Force) {
fs::remove_file(dest)?;
}
if source.is_relative() {
let current_dir = env::current_dir()?;
let abs_dest =
canonicalize(dest, MissingHandling::Missing, ResolveMode::Physical).unwrap();
if let Some(parent) = abs_dest.parent() {
if parent != current_dir {
{
return Err(format!(
"{}: can make relative symbolic links only in current directory",
dest.maybe_quote()
)
.into());
}
}
}
}
symlink_file(source, dest, symlinked_files)?;
}
CopyMode::Update => {
Expand Down
28 changes: 28 additions & 0 deletions tests/by-util/test_cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5573,3 +5573,31 @@ fn test_preserve_attrs_overriding_2() {
assert_ne!(dest_file1_metadata.ino(), dest_file2_metadata.ino());
}
}

#[test]
fn test_symlink_to_subdir() {
let (at, mut ucmd) = at_and_ucmd!();

at.touch("file");
at.mkdir("dir");

ucmd.args(&["--symbolic", "file", "dir"])
.fails()
.no_stdout()
.stderr_is("cp: dir/file: can make relative symbolic links only in current directory\n");

assert!(at.dir_exists("dir"));
assert!(!at.file_exists("dir/file"));
}

#[test]
fn test_symlink_from_subdir() {
let (at, mut ucmd) = at_and_ucmd!();

at.mkdir("dir");
at.touch("dir/file");

ucmd.args(&["--symbolic", "dir/file", "."]).succeeds();

assert!(at.symlink_exists("file"));
}

0 comments on commit 61f114c

Please sign in to comment.