diff --git a/src/runtime/node/node_fs.rs b/src/runtime/node/node_fs.rs index f0941840d3d2..dd1e0f565601 100644 --- a/src/runtime/node/node_fs.rs +++ b/src/runtime/node/node_fs.rs @@ -4343,6 +4343,10 @@ pub mod args { pub(crate) recursive: bool, pub(crate) error_on_exist: bool, pub(crate) force: bool, + /// Copy the file a symlink source points at instead of recreating the + /// link (`cp` without `-R`). Read by `copy_single_file_sync` only; + /// `fs.cp` never sets it. + pub(crate) dereference: bool, } pub struct Cp { @@ -4389,6 +4393,7 @@ pub mod args { recursive, error_on_exist, force, + dereference: false, }, }) } @@ -8539,7 +8544,40 @@ impl NodeFS { Syscall::symlink(ZStr::from_buf(&resolved_buf[..], resolved_len), dest) } - /// This is `copyFile`, but it copies symlinks as-is + /// `reuse_stat` is the caller's `lstat`, so when dereferencing a symlink + /// is stat'd again to describe its target. + #[cfg(not(windows))] + fn cp_source_stat( + src: &ZStr, + reuse_stat: Option<&sys::Stat>, + dereference: bool, + ) -> Maybe { + if let Some(stat_) = reuse_stat { + if !dereference || !sys::S::ISLNK(stat_.st_mode as Mode) { + return Ok(*stat_); + } + } + if dereference { + Syscall::stat(src) + } else { + Syscall::lstat(src) + } + } + + /// The kind is checked before the open: `open(2)` on a FIFO blocks. + #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] + fn cp_open_dereferenced_source(src: &ZStr, reuse_stat: Option<&sys::Stat>) -> Maybe { + let stat_ = Self::cp_source_stat(src, reuse_stat, true)?; + if !sys::S::ISREG(stat_.st_mode as Mode) { + return Err( + sys::Error::from_code(E::ENOTSUP, sys::Tag::copyfile).with_path(src.as_bytes()) + ); + } + Syscall::open(src, sys::O::RDONLY, 0o644) + } + + /// This is `copyFile`, but it copies symlinks as-is unless + /// `args.flags.dereference` is set. pub(crate) fn copy_single_file_sync( &mut self, src: &OSPathSliceZ, @@ -8550,8 +8588,6 @@ impl NodeFS { #[cfg(not(windows))] reuse_stat: Option<&sys::Stat>, args: &args::Cp, ) -> Maybe { - let _ = args; // only the Windows branch consults `args` (shouldIgnoreEbusy) - // TODO: do we need to fchown? #[cfg(target_os = "macos")] { @@ -8564,16 +8600,7 @@ impl NodeFS { ) .unwrap_or(Ok(())); } - let stat_ = match reuse_stat { - Some(s) => *s, - None => match Syscall::lstat(src) { - Ok(result) => result, - Err(err) => { - self.sync_error_buf[..src.len()].copy_from_slice(src.as_bytes()); - return Err(err.with_path(&self.sync_error_buf[..src.len()])); - } - }, - }; + let stat_ = Self::cp_source_stat(src, reuse_stat, args.flags.dereference)?; if !sys::S::ISREG(stat_.st_mode as u32) { if sys::S::ISLNK(stat_.st_mode as u32) { @@ -8657,9 +8684,10 @@ impl NodeFS { // we fallback to copyfile() when the file is > 128 KB and clonefile fails // clonefile() isn't supported on all devices // nor is it supported across devices - let mut mode_: u32 = bun_sys::c::COPYFILE_ACL - | bun_sys::c::COPYFILE_DATA - | bun_sys::c::COPYFILE_NOFOLLOW_SRC; + let mut mode_: u32 = bun_sys::c::COPYFILE_ACL | bun_sys::c::COPYFILE_DATA; + if !args.flags.dereference { + mode_ |= bun_sys::c::COPYFILE_NOFOLLOW_SRC; + } if mode.shouldnt_overwrite() { mode_ |= bun_sys::c::COPYFILE_EXCL; } @@ -8688,21 +8716,24 @@ impl NodeFS { #[cfg(any(target_os = "linux", target_os = "android"))] { - let _ = reuse_stat; // https://manpages.debian.org/testing/manpages-dev/ioctl_ficlone.2.en.html if mode.is_force_clone() { return Maybe::::todo(); } - let src_fd = match Syscall::open(src, sys::O::RDONLY | sys::O::NOFOLLOW, 0o644) { - Ok(result) => result, - Err(err) => { - if err.get_errno() == E::ELOOP { - // ELOOP is returned when you open a symlink with NOFOLLOW. - // as in, it does not actually let you open it. - return self.cp_symlink(src, dest); + let src_fd = if args.flags.dereference { + Self::cp_open_dereferenced_source(src, reuse_stat)? + } else { + match Syscall::open(src, sys::O::RDONLY | sys::O::NOFOLLOW, 0o644) { + Ok(result) => result, + Err(err) => { + if err.get_errno() == E::ELOOP { + // ELOOP is returned when you open a symlink with NOFOLLOW. + // as in, it does not actually let you open it. + return self.cp_symlink(src, dest); + } + return Err(err); } - return Err(err); } }; let _close_src = scopeguard::guard(src_fd, |fd| fd.close()); @@ -8856,7 +8887,6 @@ impl NodeFS { #[cfg(target_os = "freebsd")] { - let _ = reuse_stat; if mode.is_force_clone() { return Err(sys::Error { errno: SystemErrno::EOPNOTSUPP as _, @@ -8865,16 +8895,20 @@ impl NodeFS { }); } - let src_fd = match Syscall::open(src, sys::O::RDONLY | sys::O::NOFOLLOW, 0o644) { - Ok(result) => result, - Err(err) => { - // O_NOFOLLOW on a symlink → recreate the link. FreeBSD's - // open(2) returns EMLINK for this case, though POSIX - // specifies ELOOP; accept either. - if matches!(err.get_errno(), E::EMLINK | E::ELOOP) { - return self.cp_symlink(src, dest); + let src_fd = if args.flags.dereference { + Self::cp_open_dereferenced_source(src, reuse_stat)? + } else { + match Syscall::open(src, sys::O::RDONLY | sys::O::NOFOLLOW, 0o644) { + Ok(result) => result, + Err(err) => { + // O_NOFOLLOW on a symlink → recreate the link. FreeBSD's + // open(2) returns EMLINK for this case, though POSIX + // specifies ELOOP; accept either. + if matches!(err.get_errno(), E::EMLINK | E::ELOOP) { + return self.cp_symlink(src, dest); + } + return Err(err); } - return Err(err); } }; let _close_src = scopeguard::guard(src_fd, |fd| fd.close()); @@ -9025,7 +9059,8 @@ impl NodeFS { a } }; - if stat_ & sys::c::FILE_ATTRIBUTE_REPARSE_POINT == 0 { + // `CopyFileW` itself copies the file a symlink source points at. + if stat_ & sys::c::FILE_ATTRIBUTE_REPARSE_POINT == 0 || args.flags.dereference { if unsafe { sys::c::CopyFileW( src.as_ptr(), @@ -9133,7 +9168,7 @@ impl NodeFS { windows )))] { - let _ = (src, dest, mode, reuse_stat); + let _ = (src, dest, mode, reuse_stat, args); Maybe::::todo() } } diff --git a/src/runtime/shell/builtin/cp.rs b/src/runtime/shell/builtin/cp.rs index bb84b01e0054..0c9cdef79972 100644 --- a/src/runtime/shell/builtin/cp.rs +++ b/src/runtime/shell/builtin/cp.rs @@ -563,6 +563,7 @@ impl ShellCpTask { .is_some_and(|&c| resolve_path::Platform::AUTO.is_separator(c)) } + /// Classifies the target operand without following a symlink. fn is_dir(path: &bun_core::ZStr) -> bun_sys::Maybe { #[cfg(windows)] { @@ -581,6 +582,46 @@ impl ShellCpTask { } } + /// An inode number of 0 means the filesystem reports no identity. + fn is_same_inode(a: &bun_sys::Stat, b: &bun_sys::Stat) -> bool { + a.st_ino != 0 && a.st_ino == b.st_ino && a.st_dev == b.st_dev + } + + /// Would the copy read and write one file? `follow` must match how + /// `src_stat` was taken. + fn is_same_file( + src: &bun_core::ZStr, + src_stat: &bun_sys::Stat, + tgt: &bun_core::ZStr, + follow: bool, + ) -> bool { + let tgt_stat = if follow { + bun_sys::stat(tgt) + } else { + bun_sys::lstat(tgt) + }; + let Ok(tgt_stat) = tgt_stat else { + return false; + }; + if Self::is_same_inode(src_stat, &tgt_stat) { + return true; + } + if follow { + return false; + } + // -R copies a link as a link, so one link may be copied over another + // link to the same file. A link on one side only is copied onto, or + // recreated over, the file it points at. + match ( + bun_sys::S::ISLNK(src_stat.st_mode as _), + bun_sys::S::ISLNK(tgt_stat.st_mode as _), + ) { + (true, false) => bun_sys::stat(src).is_ok_and(|s| Self::is_same_inode(&s, &tgt_stat)), + (false, true) => bun_sys::stat(tgt).is_ok_and(|t| Self::is_same_inode(src_stat, &t)), + _ => false, + } + } + /// Resolves src/tgt to absolute paths, classifies them per the three /// POSIX `cp` synopses /// (), then hands off to @@ -616,10 +657,20 @@ impl ShellCpTask { // folder -> folder // We need to check dest to see what it is; if it doesn't exist we // need to create it. - let src_is_dir = match Self::is_dir(src) { - Ok(x) => x, + + // cp(1) copies the file a symlink operand points at; only `-R` copies + // the link itself. + let follow_src = !self.opts.recursive; + let src_stat = if follow_src { + bun_sys::stat(src) + } else { + bun_sys::lstat(src) + }; + let src_stat = match src_stat { + Ok(st) => st, Err(e) => return Some(ShellErr::new_sys(&e)), }; + let src_is_dir = bun_sys::S::ISDIR(src_stat.st_mode as _); // Any source directory without -R is an error. if src_is_dir && !self.opts.recursive { @@ -651,6 +702,8 @@ impl ShellCpTask { }; let mut _copying_many = false; + // Set when the copy lands at `tgt/`, for error messages. + let mut dest_basename: Option<&[u8]> = None; // The following logic is based on the POSIX spec. if !src_is_dir && !tgt_is_dir && self.operands == 2 { @@ -663,6 +716,7 @@ impl ShellCpTask { buf3.as_mut_slice(), &[tgt.as_bytes(), basename], ); + dest_basename = Some(basename); } else if self.operands == 2 { // source_dir -> new_target_dir. } else { @@ -694,9 +748,29 @@ impl ShellCpTask { buf3.as_mut_slice(), &[tgt.as_bytes(), basename], ); + dest_basename = Some(basename); _copying_many = true; } + // A link, hard link or directory symlink can name `src` again; copying + // a file onto itself is refused like cp(1) does (on macOS the copy + // would unlink it first). + if !src_is_dir && Self::is_same_file(src, &src_stat, tgt, follow_src) { + let shown_tgt = match dest_basename { + Some(basename) => bun_paths::join_sep_maybe_z::(&[&self.tgt, basename]), + None => self.tgt.as_slice().into(), + }; + return Some(ShellErr::Custom( + format!( + "{} and {} are identical (not copied)", + bstr::BStr::new(&self.src), + bstr::BStr::new(&shown_tgt) + ) + .into_bytes() + .into_boxed_slice(), + )); + } + self.src_absolute = Some(src.as_bytes().to_vec()); self.tgt_absolute = Some(tgt.as_bytes().to_vec()); @@ -713,6 +787,7 @@ impl ShellCpTask { recursive: self.opts.recursive, force: true, error_on_exist: false, + dereference: follow_src, }, }; diff --git a/test/js/bun/shell/commands/cp.test.ts b/test/js/bun/shell/commands/cp.test.ts index 80a28d2c7e2c..8a40890f5aab 100644 --- a/test/js/bun/shell/commands/cp.test.ts +++ b/test/js/bun/shell/commands/cp.test.ts @@ -1,7 +1,10 @@ import { $ } from "bun"; import { shellInternals } from "bun:internal-for-testing"; -import { describe, expect } from "bun:test"; -import { tempDirWithFiles } from "harness"; +import { describe, expect, test } from "bun:test"; +import { bunEnv, DirectoryTree, isMacOS, isWindows, tempDir, tempDirWithFiles } from "harness"; +import { mkfifo } from "mkfifo"; +import { linkSync, lstatSync, readFileSync, readlinkSync, statSync, symlinkSync } from "node:fs"; +import { join } from "node:path"; import { bunExe, createTestBuilder } from "../test_builder"; import { sortedShellOutput } from "../util"; const { builtinDisabled } = shellInternals; @@ -173,6 +176,257 @@ describe.if(!builtinDisabled("cp"))("bunshell cp", async () => { }); }); +// The builtin is the default only on Windows; on POSIX it is switched on by an +// env var that is read once per process, so every cp below runs in a child bun. +describe.concurrent("bunshell cp operands that are links", () => { + const builtinEnv = { ...bunEnv, BUN_ENABLE_EXPERIMENTAL_SHELL_BUILTINS: "1" }; + + // Runs argv[2] through the shell inside `work/` and prints what cp returned. + const runCpScript = /* ts */ ` + import { $ } from "bun"; + import { join } from "node:path"; + const result = await $\`\${{ raw: process.argv[2] }}\`.cwd(join(import.meta.dir, "work")).nothrow().quiet(); + console.log(JSON.stringify({ exitCode: result.exitCode, stderr: result.stderr.toString() })); + `; + + /** + * A temp dir holding the runner script and `work/`, which contains + * `inner/target`, an empty `dest/`, the link `rel -> inner/target` and + * whatever `extra` adds. Returns the temp dir; `work()` locates paths in it. + */ + function setup(name: string, extra: DirectoryTree = {}) { + const dir = tempDir(`shell-cp-links-${name}`, { + "run-cp.ts": runCpScript, + "work": { "inner/target": "target\n", "dest": {}, ...extra }, + }); + symlinkSync(join("inner", "target"), work(dir, "rel")); + return dir; + } + + function work(dir: string, ...inside: string[]): string { + return join(String(dir), "work", ...inside); + } + + async function cp(dir: string, command: string): Promise<{ exitCode: number; stderr: string }> { + await using proc = Bun.spawn({ + cmd: [bunExe(), "run-cp.ts", command], + cwd: String(dir), + env: builtinEnv, + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(exitCode).toBe(0); + return JSON.parse(stdout); + } + + const copied = { exitCode: 0, stderr: "" }; + + function identical(src: string, tgt: string) { + return { exitCode: 1, stderr: `cp: ${src} and ${tgt} are identical (not copied)\n` }; + } + + /** What `work/` is now: a regular file's contents, a symlink's target, or `missing`. */ + function entry(dir: string, name: string): string { + const path = work(dir, name); + const stat = lstatSync(path, { throwIfNoEntry: false }); + if (stat === undefined) return "missing"; + if (stat.isSymbolicLink()) return `symlink -> ${readlinkSync(path)}`; + return `file: ${readFileSync(path, "utf8")}`; + } + + // Past 128 KiB the macOS copy switches from read/write to clonefile(), and + // unlinks an existing destination first. + const big = Buffer.alloc(300 * 1024, "big file\n").toString(); + + // cp(1) copies the file a symlink operand points at; only `cp -R` copies the + // link itself. + describe("a symlink source is followed unless -R is given", () => { + test("cp link file copies the file the link points at", async () => { + using dir = setup("file"); + expect(await cp(dir, "cp rel out")).toEqual(copied); + expect(entry(dir, "out")).toBe("file: target\n"); + }); + + test("cp link... dir copies the files the links point at", async () => { + using dir = setup("into-dir", { "outside.txt": "outside\n", "elsewhere": {} }); + symlinkSync(join("..", "outside.txt"), work(dir, "elsewhere", "up")); + expect(await cp(dir, "cp rel elsewhere/up dest")).toEqual(copied); + expect([entry(dir, "dest/rel"), entry(dir, "dest/up")]).toEqual(["file: target\n", "file: outside\n"]); + }); + + test("a link to a large file is copied as a file", async () => { + using dir = setup("big", { big }); + symlinkSync("big", work(dir, "biglink")); + expect(await cp(dir, "cp biglink out")).toEqual(copied); + expect(lstatSync(work(dir, "out")).isSymbolicLink()).toBe(false); + expect(readFileSync(work(dir, "out"), "utf8")).toBe(big); + }); + + // The temp dir is on the data volume and /usr/share on the sealed system + // volume, so clonefile() fails with EXDEV and the copy takes the copyfile() + // fallback, the one large-file path the other tests do not reach. + test.skipIf(!isMacOS)("a link to a large file on another volume is copied as a file", async () => { + const systemFile = "/usr/share/dict/words"; + expect(statSync(systemFile).size).toBeGreaterThan(128 * 1024); + using dir = setup("other-volume"); + symlinkSync(systemFile, work(dir, "syslink")); + expect(await cp(dir, "cp syslink out")).toEqual(copied); + expect(lstatSync(work(dir, "out")).isSymbolicLink()).toBe(false); + expect(readFileSync(work(dir, "out")).equals(readFileSync(systemFile))).toBe(true); + }); + + test("a dangling link is an error", async () => { + using dir = setup("dangling"); + symlinkSync("missing", work(dir, "dangling")); + expect(await cp(dir, "cp dangling out")).toEqual({ + exitCode: 1, + stderr: `cp: No such file or directory: ${work(dir, "dangling")}\n`, + }); + expect(entry(dir, "out")).toBe("missing"); + }); + + test("a link to a directory is an error without -R", async () => { + using dir = setup("dirlink"); + symlinkSync("inner", work(dir, "dirlink"), "dir"); + expect(await cp(dir, "cp dirlink out")).toEqual({ + exitCode: 1, + stderr: "cp: dirlink is a directory (not copied)\n", + }); + expect(entry(dir, "out")).toBe("missing"); + }); + + // Following the link must not mean reading the FIFO: open(2) on a FIFO with + // no writer blocks forever. + test.skipIf(isWindows)("a link to a FIFO is refused", async () => { + using dir = setup("fifo"); + mkfifo(work(dir, "fifo")); + symlinkSync("fifo", work(dir, "fifolink")); + expect(await cp(dir, "cp fifolink out")).toEqual({ + exitCode: 1, + stderr: `cp: Operation not supported: ${work(dir, "fifolink")}\n`, + }); + expect(entry(dir, "out")).toBe("missing"); + }); + + test("cp -R copies the links themselves", async () => { + using dir = setup("recursive"); + symlinkSync("inner", work(dir, "dirlink"), "dir"); + expect(await cp(dir, "cp -R rel dirlink dest")).toEqual(copied); + expect(entry(dir, "dest/rel")).toStartWith("symlink -> "); + expect(entry(dir, "dest/dirlink")).toStartWith("symlink -> "); + }); + }); + + // The source and the destination are compared by inode, so every way of + // naming the same file twice is refused, not only spelling the path twice. + describe("copying a file onto itself is refused", () => { + test("a link and the file it points at", async () => { + using dir = setup("link-and-target"); + expect(await cp(dir, "cp rel inner/target")).toEqual(identical("rel", "inner/target")); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); + + test("a link and the large file it points at", async () => { + using dir = setup("link-and-big-target", { big }); + symlinkSync("big", work(dir, "biglink")); + expect(await cp(dir, "cp biglink big")).toEqual(identical("biglink", "big")); + expect(readFileSync(work(dir, "big"), "utf8")).toBe(big); + }); + + test("a file and a link pointing at it", async () => { + using dir = setup("target-and-link"); + expect(await cp(dir, "cp inner/target rel")).toEqual(identical("inner/target", "rel")); + expect(entry(dir, "rel")).toBe(`symlink -> ${join("inner", "target")}`); + }); + + test("two links to one file", async () => { + using dir = setup("two-links"); + symlinkSync(join("inner", "target"), work(dir, "rel2")); + expect(await cp(dir, "cp rel rel2")).toEqual(identical("rel", "rel2")); + expect(entry(dir, "rel2")).toBe(`symlink -> ${join("inner", "target")}`); + }); + + test("a file and a hard link to it", async () => { + using dir = setup("hard-link"); + linkSync(work(dir, "inner", "target"), work(dir, "hard")); + expect(await cp(dir, "cp inner/target hard")).toEqual(identical("inner/target", "hard")); + expect(entry(dir, "hard")).toBe("file: target\n"); + }); + + test("a file and the directory it is in", async () => { + using dir = setup("own-directory"); + expect(await cp(dir, "cp inner/target inner")).toEqual(identical("inner/target", p("inner/target"))); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); + + test("a link and the same-named file it points at in the destination directory", async () => { + using dir = setup("link-into-target-dir", { "elsewhere": {} }); + symlinkSync(join("..", "inner", "target"), work(dir, "elsewhere", "target")); + expect(await cp(dir, "cp elsewhere/target inner")).toEqual(identical("elsewhere/target", p("inner/target"))); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); + + test("the other operands are still copied", async () => { + using dir = setup("one-of-many", { "outside.txt": "outside\n" }); + linkSync(work(dir, "inner", "target"), work(dir, "dest", "rel")); + expect(await cp(dir, "cp rel outside.txt dest")).toEqual(identical("rel", p("dest/rel"))); + expect([entry(dir, "dest/rel"), entry(dir, "dest/outside.txt")]).toEqual(["file: target\n", "file: outside\n"]); + }); + + test("with -R, a file and a hard link to it", async () => { + using dir = setup("recursive-hard-link"); + linkSync(work(dir, "inner", "target"), work(dir, "hard")); + expect(await cp(dir, "cp -R inner/target hard")).toEqual(identical("inner/target", "hard")); + expect(entry(dir, "hard")).toBe("file: target\n"); + }); + + test("with -R, a file and itself inside the destination directory", async () => { + using dir = setup("recursive-into-dir"); + linkSync(work(dir, "inner", "target"), work(dir, "dest", "target")); + expect(await cp(dir, "cp -R inner/target dest")).toEqual(identical("inner/target", p("dest/target"))); + expect(entry(dir, "dest/target")).toBe("file: target\n"); + }); + + test("with -R, a large file and itself reached through a directory link", async () => { + using dir = setup("recursive-through-dirlink", { "d/big": big }); + symlinkSync("d", work(dir, "dlink"), "dir"); + expect(await cp(dir, "cp -R d/big dlink/big")).toEqual(identical("d/big", "dlink/big")); + expect(readFileSync(work(dir, "d", "big"), "utf8")).toBe(big); + }); + + test("with -R, a link and itself inside the destination directory", async () => { + using dir = setup("recursive-link"); + expect(await cp(dir, "cp -R rel .")).toEqual(identical("rel", p("./rel"))); + expect(entry(dir, "rel")).toBe(`symlink -> ${join("inner", "target")}`); + }); + + // Under -R the file is written through a link at the destination, and a + // link source would be recreated over the very file it points at. + test("with -R, a file and a link pointing at it", async () => { + using dir = setup("recursive-target-and-link"); + expect(await cp(dir, "cp -R inner/target rel")).toEqual(identical("inner/target", "rel")); + expect(entry(dir, "rel")).toBe(`symlink -> ${join("inner", "target")}`); + }); + + test("with -R, a link and the file it points at", async () => { + using dir = setup("recursive-link-and-target"); + expect(await cp(dir, "cp -R rel inner/target")).toEqual(identical("rel", "inner/target")); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); + + // Two links to one file are not the same file under -R: the link itself is + // what gets copied, as cp(1) also allows. + test("with -R, two links to one file are copied", async () => { + using dir = setup("recursive-two-links"); + symlinkSync(join("inner", "target"), work(dir, "rel2")); + expect(await cp(dir, "cp -R rel rel2")).toEqual(copied); + expect(entry(dir, "rel2")).toStartWith("symlink -> "); + expect(entry(dir, "inner/target")).toBe("file: target\n"); + }); + }); +}); + function expectSortedOutput(expected: string) { return (stdout: string, tempdir: string) => expect(sortedShellOutput(stdout).join("\n")).toEqual(