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::fs::{self, File, Metadata, OpenOptions, Permissions};
Expand Down Expand Up @@ -1868,6 +1869,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 @@ -5574,6 +5574,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_is("cp: dir/file: can make relative symbolic links only in current directory\n");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fails on Windows, because there it generates the error message with a backslash.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I see! Really appreciate the review. About the broken test in Windows, I think stderr_contains() can be used instead of stderr_is() to address this, I'm going to try it to solve this compatibility issue with Windows, along with the conflicts.


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