Skip to content

Commit

Permalink
Merge pull request #3018 from Narasimha1997/fix-cp-recursion
Browse files Browse the repository at this point in the history
Fix: Avoid infinite recursion when source and destinations are same while using `cp -R`
  • Loading branch information
sylvestre authored Feb 20, 2022
2 parents 42eba6c + 0379fca commit 7305180
Show file tree
Hide file tree
Showing 2 changed files with 63 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 @@ -969,6 +969,16 @@ fn copy_directory(
return copy_file(root, target, options, symlinked_files);
}

// check if root is a prefix of target
if path_has_prefix(target, root)? {
return Err(format!(
"cannot copy a directory, {}, into itself, {}",
root.quote(),
target.quote()
)
.into());
}

let current_dir =
env::current_dir().unwrap_or_else(|e| crash!(1, "failed to get current directory {}", e));

Expand Down Expand Up @@ -1573,6 +1583,13 @@ pub fn paths_refer_to_same_file(p1: &Path, p2: &Path) -> io::Result<bool> {
Ok(pathbuf1 == pathbuf2)
}

pub fn path_has_prefix(p1: &Path, p2: &Path) -> io::Result<bool> {
let pathbuf1 = canonicalize(p1, MissingHandling::Normal, ResolveMode::Logical)?;
let pathbuf2 = canonicalize(p2, MissingHandling::Normal, ResolveMode::Logical)?;

Ok(pathbuf1.starts_with(pathbuf2))
}

#[test]
fn test_cp_localize_to_target() {
assert!(
Expand Down
46 changes: 46 additions & 0 deletions tests/by-util/test_cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1462,6 +1462,52 @@ fn test_cp_archive_on_nonexistent_file() {
"cp: cannot stat 'nonexistent_file.txt': No such file or directory (os error 2)",
);
}

#[test]
fn test_dir_recursive_copy() {
let scene = TestScenario::new(util_name!());
let at = &scene.fixtures;

at.mkdir("parent1");
at.mkdir("parent2");
at.mkdir("parent1/child");
at.mkdir("parent2/child1");
at.mkdir("parent2/child1/child2");
at.mkdir("parent2/child1/child2/child3");

// case-1: copy parent1 -> parent1: should fail
scene
.ucmd()
.arg("-R")
.arg("parent1")
.arg("parent1")
.fails()
.stderr_contains("cannot copy a directory");
// case-2: copy parent1 -> parent1/child should fail
scene
.ucmd()
.arg("-R")
.arg("parent1")
.arg("parent1/child")
.fails()
.stderr_contains("cannot copy a directory");
// case-3: copy parent1/child -> parent2 should pass
scene
.ucmd()
.arg("-R")
.arg("parent1/child")
.arg("parent2")
.succeeds();
// case-4: copy parent2/child1/ -> parent2/child1/child2/child3
scene
.ucmd()
.arg("-R")
.arg("parent2/child1/")
.arg("parent2/child1/child2/child3")
.fails()
.stderr_contains("cannot copy a directory");
}

#[test]
fn test_cp_dir_vs_file() {
new_ucmd!()
Expand Down

0 comments on commit 7305180

Please sign in to comment.