Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cp: Fix broken symlinks to parent-dir #6464

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
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::ffi::OsString;
Expand Down Expand Up @@ -1979,6 +1980,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 @@ -5745,6 +5745,34 @@ fn test_preserve_attrs_overriding_2() {
}
}

#[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_contains("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"));
}

/// Test the behavior of preserving permissions when copying through a symlink
#[test]
#[cfg(unix)]
Expand Down
Loading