diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index f8ce6f241..938ecfe03 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -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)); @@ -1570,6 +1580,13 @@ pub fn paths_refer_to_same_file(p1: &Path, p2: &Path) -> io::Result { Ok(pathbuf1 == pathbuf2) } +pub fn path_has_prefix(p1: &Path, p2: &Path) -> io::Result { + 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!( diff --git a/tests/by-util/test_cp.rs b/tests/by-util/test_cp.rs index 92637dfbe..0a4dfd16d 100644 --- a/tests/by-util/test_cp.rs +++ b/tests/by-util/test_cp.rs @@ -1444,3 +1444,48 @@ 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"); +}