diff --git a/bench/fs-cp/cp.mjs b/bench/fs-cp/cp.mjs index 4a9f6fd436fc..c04d2fa8d13b 100644 --- a/bench/fs-cp/cp.mjs +++ b/bench/fs-cp/cp.mjs @@ -73,6 +73,35 @@ recursiveCopyBench(`fs.promises.cp recursive (${totalFiles} files, tree contains promises.cp(symlinkSrc, dest, { recursive: true }), ); +// One small file: most of the time is cpSync's checks of the two paths. The +// destination two directories away has two more folders above it to check. +const fileSrc = join(root, "file-src.txt"); +writeFileSync(fileSrc, data); +const nearDest = join(root, "file-dest.txt"); +const farDest = join(root, "far", "away", "file-dest.txt"); +mkdirSync(join(root, "far", "away"), { recursive: true }); + +// Each copy makes a new file: the computed parameter removes the last one +// without counting towards the measured time. +function singleFileBench(label, dest, options) { + bench(label, function* () { + yield { + [0]() { + rmSync(dest, { force: true }); + return dest; + }, + bench(dest) { + return cpSync(fileSrc, dest, options); + }, + }; + }); +} + +singleFileBench("cpSync single file (dest in the same directory)", nearDest); +singleFileBench("cpSync single file (dest two directories away)", farDest); +singleFileBench("cpSync single file (with a filter)", nearDest, { filter: () => true }); +bench("cpSync single file (over an existing file)", () => cpSync(fileSrc, nearDest)); + try { await run(); } finally { diff --git a/src/js/internal/fs/cp-sync.ts b/src/js/internal/fs/cp-sync.ts index 981592c5cc26..53683ff1bec7 100644 --- a/src/js/internal/fs/cp-sync.ts +++ b/src/js/internal/fs/cp-sync.ts @@ -2,7 +2,14 @@ // Also hosts the option validation and SystemError construction shared with // internal/fs/cp (async) and the fs.cpSync/fs.cp/fs.promises.cp dispatchers, // ported from node lib/internal/fs/utils.js and lib/internal/errors.js. -const { validateObject, validateBoolean, validateFunction, validateInteger } = require("internal/validators"); +const { + validateObject, + validateBoolean, + validateFunction, + validateInteger, + validateString, +} = require("internal/validators"); +const binding = require("internal/fs/binding"); const { chmodSync, copyFileSync, @@ -16,7 +23,7 @@ const { unlinkSync, utimesSync, } = require("node:fs"); -const { dirname, isAbsolute, join, parse, resolve, sep } = require("node:path"); +const { dirname, isAbsolute, join, resolve, sep } = require("node:path"); const { EEXIST, EISDIR, EINVAL, ENOTDIR } = $processBindingConstants.os.errno; @@ -178,6 +185,8 @@ function isSrcSubdir(src: string, dest: string) { type Stats = $Node.Stats; type BigIntStats = $Node.BigIntStats; type AnyStats = Stats | BigIntStats; +// The walker only asks whether dest is there, and `cpSyncFn` knows that much of the path it was given. +type DestinationStats = BigIntStats | boolean | null | undefined; interface CpOptions { dereference: boolean; @@ -204,8 +213,6 @@ interface SkippedPaths { skipped: true; } -function checkPathsSync(src: string, dest: string, opts: CpOptions & { filter: undefined }): CheckedPaths; -function checkPathsSync(src: string, dest: string, opts: CpOptions): CheckedPaths | SkippedPaths; function checkPathsSync(src: string, dest: string, opts: CpOptions): CheckedPaths | SkippedPaths { if (opts.filter) { const shouldCopy = opts.filter(src, dest); @@ -273,29 +280,6 @@ function getStatsSync(src: string, dest: string, opts: CpOptions) { return { srcStat, destStat }; } -function checkParentPathsSync(src: string, srcStat: BigIntStats, dest: string) { - const srcParent = resolve(dirname(src)); - const destParent = resolve(dirname(dest)); - if (destParent === srcParent || destParent === parse(destParent).root) return; - let destStat: BigIntStats; - try { - destStat = statSync(destParent, { bigint: true }); - } catch (err: any) { - if (err.code === "ENOENT") return; - throw err; - } - if (areIdentical(srcStat, destStat)) { - throw fsCpEinvalError({ - message: `cannot copy ${src} to a subdirectory of self ${dest}`, - path: dest, - syscall: "cp", - errno: EINVAL, - code: "EINVAL", - }); - } - return checkParentPathsSync(src, srcStat, destParent); -} - // The native recursive copy (a single clonefile() on macOS) copies symlinks // verbatim and clones special files, while node rewrites relative symlink // targets against the source tree and raises ERR_FS_CP_SOCKET / @@ -325,54 +309,63 @@ function treeContainsOnlyFilesAndDirsSync(root: string) { return true; } -// node-correct validation before handing off to the native fast path -// (which performs the copy but does not implement node's cp error codes). -function tryNativeFastPathSync(src: string, dest: string, opts: CpOptions & { filter: undefined }) { - const checked = checkPathsSync(src, dest, opts); - const { srcStat, destStat } = checked; - checkParentPathsSync(src, srcStat, dest); - if (srcStat.isDirectory() && !opts.recursive) { - throw fsEisdirError({ - message: `${src} is a directory (not copied)`, - path: src, - syscall: "cp", - errno: EISDIR, - code: "EISDIR", - }); +// What `binding.cpSyncCheckPaths` answers: `CpSyncPaths::bits` in src/runtime/node/node_fs.rs. +const kSrcIsDirectory = 1 << 0; +const kSrcIsFile = 1 << 1; +const kDestExists = 1 << 2; +const kDestIsFile = 1 << 3; + +// Whether `binding.cpSync` does the copy. It reads none of the options tested here. +function copiesNatively(paths: number, src: string, opts: CpOptions) { + if ( + opts.filter || + opts.dereference || + opts.preserveTimestamps || + opts.verbatimSymlinks || + opts.mode || + opts.errorOnExist || + !opts.force + ) { + return false; } - if (srcStat.isDirectory()) { + if (paths & kSrcIsDirectory) { // On macOS the native path clones the whole tree with a single // clonefile(). Only take it when the result is indistinguishable from // node's walker: dest must not exist (no merge semantics) and the tree // must contain only regular files and directories. - return { - ok: process.platform === "darwin" && !destStat && treeContainsOnlyFilesAndDirsSync(src), - checked, - }; + return process.platform === "darwin" && !(paths & kDestExists) && treeContainsOnlyFilesAndDirsSync(src); } - // The single-file native copy is only node-equivalent for regular-file -> - // regular-file (or missing dest). Symlinks (node resolves relative link - // targets) and special files (node-specific error codes) must go through - // the ported implementation. - return { ok: srcStat.isFile() && (!destStat || destStat.isFile()), checked }; + // A regular file onto a regular file or onto nothing. The native copy writes into a dest that is there, where the walker unlinks it first. + return (paths & kSrcIsFile) !== 0 && (!(paths & kDestExists) || (paths & kDestIsFile) !== 0); } -function cpSyncFn(src: string, dest: string, opts: CpOptions, checked?: CheckedPaths) { - // `checked` carries the stats from a preceding tryNativeFastPathSync so the - // fallback doesn't re-run the same checkPaths/checkParentPaths syscalls. - const { srcStat, destStat, skipped } = checked ?? checkPathsSync(src, dest, opts); - if (skipped) return; - if (checked === undefined) checkParentPathsSync(src, srcStat, dest); - return checkParentDir(destStat, src, dest, opts); +// https://github.com/nodejs/node/blob/v26.12.1/lib/internal/fs/cp/cp-sync.js#L41-L59 +function cpSyncFn(src: string, dest: string, opts: CpOptions) { + if (opts.filter) { + const shouldCopy = opts.filter(src, dest); + if ($isPromise(shouldCopy)) { + throw $ERR_INVALID_RETURN_VALUE("boolean", "filter", shouldCopy); + } + if (!shouldCopy) return; + } + // Throws as node's C++ does, where the walker below throws a SystemError: `NodeFS::cp_sync_check_paths` in src/runtime/node/node_fs.rs. + const paths = binding.cpSyncCheckPaths(src, dest, opts.dereference, opts.recursive); + // The walker joins and resolves its paths with node:path, which takes strings. + validateString(src, "src"); + validateString(dest, "dest"); + if (copiesNatively(paths, src, opts)) { + return binding.cpSync(src, dest, opts.recursive, false, true, 0); + } + return checkParentDir((paths & kDestExists) !== 0, src, dest, opts); } -function checkParentDir(destStat: BigIntStats | null | undefined, src: string, dest: string, opts: CpOptions) { +function checkParentDir(destStat: DestinationStats, src: string, dest: string, opts: CpOptions) { const destParent = dirname(dest); if (!existsSync(destParent)) mkdirSync(destParent, { recursive: true }); return getStats(destStat, src, dest, opts); } -function getStats(destStat: BigIntStats | null | undefined, src: string, dest: string, opts: CpOptions) { +function getStats(destStat: DestinationStats, src: string, dest: string, opts: CpOptions) { const statSyncFn = opts.dereference ? statSync : lstatSync; const srcStat = statSyncFn(src); @@ -416,7 +409,7 @@ function getStats(destStat: BigIntStats | null | undefined, src: string, dest: s }); } -function onFile(srcStat: Stats, destStat: BigIntStats | null | undefined, src: string, dest: string, opts: CpOptions) { +function onFile(srcStat: Stats, destStat: DestinationStats, src: string, dest: string, opts: CpOptions) { if (!destStat) return copyFile(srcStat, src, dest, opts); return mayCopyFile(srcStat, src, dest, opts); } @@ -470,7 +463,7 @@ function setDestTimestamps(src: string, dest: string) { return utimesSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime); } -function onDir(srcStat: Stats, destStat: BigIntStats | null | undefined, src: string, dest: string, opts: CpOptions) { +function onDir(srcStat: Stats, destStat: DestinationStats, src: string, dest: string, opts: CpOptions) { if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts); if (opts.errorOnExist && !opts.force) { throw fsCpEExistError({ @@ -500,7 +493,7 @@ function copyDir(src: string, dest: string, opts: CpOptions) { } } -function onLink(destStat: BigIntStats | null | undefined, src: string, dest: string, opts: CpOptions) { +function onLink(destStat: DestinationStats, src: string, dest: string, opts: CpOptions) { let resolvedSrc = readlinkSync(src); if (!opts.verbatimSymlinks && !isAbsolute(resolvedSrc)) { resolvedSrc = resolve(dirname(src), resolvedSrc); @@ -559,7 +552,6 @@ function copyLink(resolvedSrc: string, dest: string) { export default { cpSyncFn, validateCpOptions, - tryNativeFastPathSync, errno: { EEXIST, EISDIR, EINVAL, ENOTDIR }, fsCpDirToNonDirError, fsCpEExistError, diff --git a/src/js/node/fs.ts b/src/js/node/fs.ts index dae063b87fab..72f1d13a3d22 100644 --- a/src/js/node/fs.ts +++ b/src/js/node/fs.ts @@ -998,19 +998,11 @@ realpathSync.native = fs.realpathNativeSync.bind(fs); // and on MacOS, simple cases of recursive directory trees can be done in a single `clonefile()` // using filter and other options uses a lazily loaded js fallback ported from node.js function cpSync(src, dest, options?) { - const { cpSyncFn, validateCpOptions, tryNativeFastPathSync } = require("internal/fs/cp-sync"); + const { cpSyncFn, validateCpOptions } = require("internal/fs/cp-sync"); const { getValidatedFsPath } = require("internal/validators"); options = validateCpOptions(options); src = getValidatedFsPath(src, "src"); dest = getValidatedFsPath(dest, "dest"); - const { filter, dereference, preserveTimestamps, verbatimSymlinks, mode, errorOnExist, force, recursive } = options; - if (!filter && !dereference && !preserveTimestamps && !verbatimSymlinks && !mode && !errorOnExist && force) { - const { ok, checked } = tryNativeFastPathSync(src, dest, options); - if (ok) { - return fs.cpSync(src, dest, recursive, errorOnExist, force, mode); - } - return cpSyncFn(src, dest, options, checked); - } return cpSyncFn(src, dest, options); } diff --git a/src/js/private.d.ts b/src/js/private.d.ts index 9805a13b7c82..e9c2a6971f71 100644 --- a/src/js/private.d.ts +++ b/src/js/private.d.ts @@ -1974,6 +1974,13 @@ declare namespace $Node { force: boolean, mode: number, ): void; + /** The checks `fs.cpSync` makes of its two paths, which throw. The answer is read by `cpSyncFn` in internal/fs/cp-sync. */ + cpSyncCheckPaths( + source: string | Uint8Array, + destination: string | Uint8Array, + dereference: boolean, + recursive: boolean, + ): number; existsSync(path: PathLike): boolean; fchmodSync(fd: number, mode: number | string): void; fchownSync(fd: number, uid: number, gid: number): void; diff --git a/src/runtime/node/Stat.rs b/src/runtime/node/Stat.rs index 6b8cc3b8b375..ef6c2f595f36 100644 --- a/src/runtime/node/Stat.rs +++ b/src/runtime/node/Stat.rs @@ -207,6 +207,14 @@ impl Stats { } } + /// What the system call read. + pub(crate) fn posix(&self) -> &PosixStat { + match self { + Stats::Big(v) => &v.value, + Stats::Small(v) => &v.value, + } + } + // A `to_js` method is intentionally omitted to force callers toward // `to_js_newly_created` — misuse is a hard "no method named `to_js`" // compile error. diff --git a/src/runtime/node/node_fs.rs b/src/runtime/node/node_fs.rs index c5af7c0cd798..eac4794c2d76 100644 --- a/src/runtime/node/node_fs.rs +++ b/src/runtime/node/node_fs.rs @@ -151,7 +151,7 @@ use super::time_like::TimeLike; use super::types::{ ArgumentsSlice, Dirent, Encoding, FdArgExt as _, FileSystemFlags, FileSystemFlagsKind, NameTooLong, PathLike, PathLikeExt as _, PathOrFdExt as _, StringObjects, StringOrBuffer, - ThreadIsolated, ThreadIsolatedArg, VectorArrayBuffer, + ThreadIsolated, ThreadIsolatedArg, VectorArrayBuffer, path_like_from_working_directory, }; // Re-exported publicly: `crate::node::fs::PathOrFileDescriptor` is the // canonical path used by `cli/build_command.rs` et al., and `node_fs::Flavor` @@ -485,6 +485,160 @@ fn stat_failure(err: sys::Error, path: &[u8], args: &args::Stat) -> Maybe bool { + dest.ino != 0 && dest.dev != 0 && dest.ino == src.ino && dest.dev == src.dev +} + +/// What [`NodeFS::cp_sync_check_paths`] found for two paths that `fs.cpSync` may copy. +#[derive(Clone, Copy)] +pub(crate) struct CpSyncPaths { + src_is_directory: bool, + src_is_file: bool, + dest_exists: bool, + dest_is_file: bool, +} + +impl CpSyncPaths { + // `kSrcIsDirectory`, `kSrcIsFile`, `kDestExists` and `kDestIsFile` of src/js/internal/fs/cp-sync.ts. + const SRC_IS_DIRECTORY: i32 = 1 << 0; + const SRC_IS_FILE: i32 = 1 << 1; + const DEST_EXISTS: i32 = 1 << 2; + const DEST_IS_FILE: i32 = 1 << 3; + + /// What `cpSyncFn` of src/js/internal/fs/cp-sync.ts reads. + pub(crate) fn bits(self) -> i32 { + let bit = |set: bool, bit: i32| if set { bit } else { 0 }; + bit(self.src_is_directory, Self::SRC_IS_DIRECTORY) + | bit(self.src_is_file, Self::SRC_IS_FILE) + | bit(self.dest_exists, Self::DEST_EXISTS) + | bit(self.dest_is_file, Self::DEST_IS_FILE) + } +} + +/// A pair of paths that `fs.cpSync` does not copy, in the order that node's `CpSyncCheckPaths` asks. +#[derive(Clone, Copy)] +enum CpSyncVerdict { + SameFile, + DirectoryOntoNonDirectory, + NonDirectoryOntoDirectory, + DestInsideSrc, + DirectoryWithoutRecursive, + Socket, + Fifo, + UnknownType, +} + +/// Why [`NodeFS::cp_sync_check_paths`] lets nothing be copied. +pub(crate) enum CpSyncRefusal { + /// A `stat` failed. + System(sys::Error), + /// Node throws these from C++: an `Error` whose one own property is `code`. + Verdict { + code: bun_jsc::ErrorCode, + message: Vec, + }, +} + +impl From for CpSyncRefusal { + fn from(err: sys::Error) -> Self { + CpSyncRefusal::System(err) + } +} + +impl CpSyncRefusal { + /// The code and the text of node's `CpSyncCheckPaths` for `verdict`. + fn of(verdict: CpSyncVerdict, src: &[u8], dest: &[u8]) -> Self { + use bun_jsc::ErrorCode as Code; + let (src, dest) = (as_node_shows(src), as_node_shows(dest)); + let (src, dest): (&[u8], &[u8]) = (&src, &dest); + let separator = paths::SEP_STR.as_bytes(); + let after_src: &[u8] = if src.ends_with(separator) { + b"" + } else { + separator + }; + let (code, message): (Code, &[&[u8]]) = match verdict { + CpSyncVerdict::SameFile => ( + Code::ERR_FS_CP_EINVAL, + &[b"src and dest cannot be the same ", dest], + ), + CpSyncVerdict::DirectoryOntoNonDirectory => ( + Code::ERR_FS_CP_DIR_TO_NON_DIR, + &[ + b"Cannot overwrite non-directory ", + dest, + b" with directory ", + src, + ], + ), + CpSyncVerdict::NonDirectoryOntoDirectory => ( + Code::ERR_FS_CP_NON_DIR_TO_DIR, + &[ + b"Cannot overwrite directory ", + dest, + b" with non-directory ", + src, + ], + ), + CpSyncVerdict::DestInsideSrc => ( + Code::ERR_FS_CP_EINVAL, + &[ + b"Cannot copy ", + src, + after_src, + b" to a subdirectory of self ", + dest, + ], + ), + CpSyncVerdict::DirectoryWithoutRecursive => ( + Code::ERR_FS_EISDIR, + &[ + b"Recursive option not enabled, cannot copy a directory: ", + src, + after_src, + ], + ), + CpSyncVerdict::Socket => ( + Code::ERR_FS_CP_SOCKET, + &[b"Cannot copy a socket file: ", dest], + ), + CpSyncVerdict::Fifo => ( + Code::ERR_FS_CP_FIFO_PIPE, + &[b"Cannot copy a FIFO pipe: ", dest], + ), + CpSyncVerdict::UnknownType => ( + Code::ERR_FS_CP_UNKNOWN, + &[b"Cannot copy an unknown file type: ", dest], + ), + }; + CpSyncRefusal::Verdict { + code, + message: message.concat(), + } + } +} + +/// A path after node's `ToNamespacedPath`, which changes it on Windows only: https://github.com/nodejs/node/blob/v26.12.1/src/path.cc#L282-L327 +fn as_node_shows(path: &[u8]) -> std::borrow::Cow<'_, [u8]> { + if cfg!(windows) && !path.is_empty() { + let len = bun_node_path::to_namespaced_path_buf_len(path); + let mut buffers = vec![0u8; len * 2]; + let (buf, scratch) = buffers.split_at_mut(len); + if let Ok(namespaced) = bun_node_path::to_namespaced_path_windows_t(path, buf, scratch) { + return std::borrow::Cow::Owned(namespaced.to_vec()); + } + } + std::borrow::Cow::Borrowed(path) +} + /// `access` of what `graph` holds at `path`; `None` if it holds nothing there. fn access_in_graph( graph: &bun_standalone_graph::Graph, @@ -4874,6 +5028,44 @@ pub(crate) mod args { } } + /// `(src, dest, dereference, recursive)` of [`NodeFS::cp_sync_check_paths`]. + pub(crate) struct CpSyncCheckPaths<'a> { + pub(crate) src: PathLike<'a>, + pub(crate) dest: PathLike<'a>, + pub(crate) dereference: bool, + pub(crate) recursive: bool, + } + impl CpSyncCheckPaths<'static> { + pub(crate) fn from_js( + ctx: &JSGlobalObject, + arguments: &mut ArgumentsSlice, + ) -> JsResult { + // The length of a string is not checked here: as in node, a path that is too long fails the `stat` that it is given to. + let mut path = |name: &str| match arguments.next() { + Some(path) if path.is_string() => { + arguments.eat(); + path_like_from_working_directory(ctx, path.to_bun_string(ctx)?, false) + } + _ => PathLike::from_js(ctx, arguments)?.ok_or_else(|| { + ctx.throw_invalid_arguments(format_args!( + "{name} must be a string or TypedArray" + )) + }), + }; + let src = path("src")?; + let dest = path("dest")?; + // Node's C++ asks `IsTrue()` of both. + let dereference = arguments.next_eat() == Some(JSValue::TRUE); + let recursive = arguments.next_eat() == Some(JSValue::TRUE); + Ok(CpSyncCheckPaths { + src, + dest, + dereference, + recursive, + }) + } + } + pub(crate) type Watch<'a> = super::Watcher::Arguments<'a>; // `StatWatcher::Arguments` owns its `PathLike` (no borrowed slice), so it // has no lifetime parameter — unlike `Watcher::Arguments<'a>` above. @@ -8715,6 +8907,155 @@ impl NodeFS { ) } + /// What `fs.cpSync` asks of its two paths before it writes. The order, the text and the shape of the error are those of node's `CpSyncCheckPaths`: https://github.com/nodejs/node/blob/v26.12.1/src/node_file.cc#L4515-L4652 + pub(crate) fn cp_sync_check_paths( + &mut self, + args: &args::CpSyncCheckPaths, + ) -> Result { + // Each check decides as node's JavaScript `checkPaths` does. Its C++ follows a link at `src` unless `dereference` (nodejs/node#60945) and ends the process for a dangling link at `dest`: https://github.com/nodejs/node/blob/v26.12.1/lib/internal/fs/cp/cp.js#L76-L196 + let of = if args.dereference { + StatOf::LinkTarget + } else { + StatOf::Link + }; + let src = self.cp_sync_stat(&args.src, of)?; + // Node's check goes on without a `dest` that it cannot read, and the stat that follows the check throws. + let (dest, dest_error) = match self.cp_sync_stat(&args.dest, of) { + Ok(dest) => (Some(dest), None), + Err(err) if err.get_errno() == E::ENOENT => (None, None), + Err(err) => (None, Some(err)), + }; + let src_mode = src.mode as Mode; + let src_is_directory = sys::S::ISDIR(src_mode); + let (src_path, dest_path) = (args.src.as_written(), args.dest.as_written()); + let refuse = |verdict| Err(CpSyncRefusal::of(verdict, src_path, dest_path)); + + if let Some(dest) = &dest { + if is_same_file(&src, dest) { + return refuse(CpSyncVerdict::SameFile); + } + let dest_is_directory = sys::S::ISDIR(dest.mode as Mode); + if src_is_directory && !dest_is_directory { + return refuse(CpSyncVerdict::DirectoryOntoNonDirectory); + } + if !src_is_directory && dest_is_directory { + return refuse(CpSyncVerdict::NonDirectoryOntoDirectory); + } + } + // A folder above `dest` that cannot be read is an error, as in node's JavaScript `checkParentPaths`. It waits as the error of `dest` does. + let (dest_is_inside_src, walk_error) = if src_is_directory { + match self.cp_sync_dest_is_inside_src(&src, src_path, dest_path) { + Ok(inside) => (inside, None), + Err(err) => (false, Some(err)), + } + } else { + (false, None) + }; + if dest_is_inside_src { + return refuse(CpSyncVerdict::DestInsideSrc); + } + if src_is_directory && !args.recursive { + return refuse(CpSyncVerdict::DirectoryWithoutRecursive); + } + match src_mode & sys::S::IFMT { + sys::S::IFSOCK => return refuse(CpSyncVerdict::Socket), + sys::S::IFIFO => return refuse(CpSyncVerdict::Fifo), + sys::S::IFDIR | sys::S::IFREG | sys::S::IFLNK | sys::S::IFCHR | sys::S::IFBLK => {} + _ => return refuse(CpSyncVerdict::UnknownType), + } + if let Some(err) = dest_error.or(walk_error) { + return Err(err.into()); + } + + Ok(CpSyncPaths { + src_is_directory, + src_is_file: sys::S::ISREG(src_mode), + dest_exists: dest.is_some(), + dest_is_file: dest.is_some_and(|dest| sys::S::ISREG(dest.mode as Mode)), + }) + } + + /// `lstat` or `stat` of `path`, with the error that `fs.lstatSync` or `fs.statSync` throws for it. + fn cp_sync_stat(&mut self, path: &PathLike<'_>, of: StatOf) -> Maybe { + let syscall = match of { + StatOf::Link => sys::Tag::lstat, + StatOf::LinkTarget => sys::Tag::stat, + }; + let failure = |errno: E| sys::Error::from_code(errno, syscall).with_path(path.as_written()); + // No `PathBuffer` holds a path of this length: this is what the system call answers for it. + if path.slice().len() >= paths::MAX_PATH_BYTES { + return Err(failure(E::ENAMETOOLONG)); + } + // In an executable, `error_for_caller` makes ENOTDIR of a path below an embedded file, so a path that is not there is an error here. + let args = args::Stat { + path: PathLike::borrowed(path.slice()), + big_int: false, + throw_if_no_entry: true, + }; + let found = match of { + StatOf::Link => self.lstat(&args, Flavor::Sync), + StatOf::LinkTarget => self.stat(&args, Flavor::Sync), + }; + match found { + Ok(StatOrNotFound::Stats(stats)) => Ok(*stats.posix()), + Ok(StatOrNotFound::NotFound) => Err(failure(E::ENOENT)), + Err(err) => Err(error_for_caller([Some(path), None], err)), + } + } + + /// Whether `dest` is inside the directory `src`: by the text of the two resolved paths (node's JavaScript `isSrcSubdir`), or a folder above `dest` is `src` by device and inode, which sees through a link (its `checkParentPaths`). + fn cp_sync_dest_is_inside_src( + &mut self, + src: &PosixStat, + src_path: &[u8], + dest_path: &[u8], + ) -> Maybe { + use bun_node_path as node_path; + #[cfg(not(windows))] + use node_path::{ + dirname_posix_t as dirname, parse_posix_t as parse, resolve_posix_t as resolve, + }; + #[cfg(windows)] + use node_path::{ + dirname_windows_t as dirname, parse_windows_t as parse, resolve_windows_t as resolve, + }; + + let len = node_path::resolve_buf_len(cfg!(windows), &[src_path]) + .max(node_path::resolve_buf_len(cfg!(windows), &[dest_path])); + let mut buffers = vec![0u8; len * 3]; + let (of_src, rest) = buffers.split_at_mut(len); + let (of_dest, scratch) = rest.split_at_mut(len); + + { + let src_resolved = resolve(&[src_path], of_src, scratch)?; + let dest_resolved = resolve(&[dest_path], of_dest, scratch)?; + let separator = paths::SEP_STR.as_bytes(); + let mut dest_parts = strings::tokenize(dest_resolved, separator); + if strings::tokenize(src_resolved, separator) + .all(|part| dest_parts.next() == Some(part)) + { + return Ok(true); + } + } + + let src_parent = resolve(&[dirname(src_path)], of_src, scratch)?; + // A resolved path's `dirname` is resolved too, so each folder further up is a prefix of this one. + let mut dest_parent = resolve(&[dirname(dest_path)], of_dest, scratch)?; + while dest_parent != src_parent && dest_parent != parse(dest_parent).root { + let stat = match self.cp_sync_stat(&PathLike::borrowed(dest_parent), StatOf::LinkTarget) + { + Ok(stat) => stat, + Err(err) if err.get_errno() == E::ENOENT => break, + Err(err) => return Err(err), + }; + if is_same_file(src, &stat) { + return Ok(true); + } + dest_parent = dirname(dest_parent); + } + Ok(false) + } + pub(crate) fn os_path_into_sync_error_buf(&mut self, slice: &[OSPathChar]) -> &[u8] { Self::os_path_into_buf(&mut self.sync_error_buf, slice) } diff --git a/src/runtime/node/node_fs_binding.bind.ts b/src/runtime/node/node_fs_binding.bind.ts index 9cc9a959704a..d7e1401373a4 100644 --- a/src/runtime/node/node_fs_binding.bind.ts +++ b/src/runtime/node/node_fs_binding.bind.ts @@ -119,6 +119,7 @@ export const NodeJSFS = b.class({ ]), ["cp", { ...operation(2, "Promise"), uses }] as const, ["cpSync", { ...operation(2, "undefined"), uses }] as const, + ["cpSyncCheckPaths", { ...operation(4, "int32"), uses }] as const, ["watch", operation(3, "FSWatcher", "undefined")] as const, ["watchFile", operation(3, "StatWatcher", "undefined")] as const, ["Dirent", getter] as const, diff --git a/src/runtime/node/node_fs_binding.rs b/src/runtime/node/node_fs_binding.rs index a4328c4f67e2..f740efc7ac77 100644 --- a/src/runtime/node/node_fs_binding.rs +++ b/src/runtime/node/node_fs_binding.rs @@ -2,6 +2,7 @@ use core::ptr::NonNull; use bun_jsc::bindgen::{JsLocal, JsPayload as _, JsScope, JsWrapper}; use bun_jsc::call_frame::ArgumentsSlice; +use bun_jsc::js_global_object::SysErrOptions; use bun_jsc::virtual_machine::VirtualMachine; use bun_jsc::{JSGlobalObject, JSPromise, JSValue, JsCell, JsResult, SysErrorJsc as _}; use bun_sys_jsc::SystemErrorJsc as _; @@ -9,8 +10,8 @@ use bun_sys_jsc::SystemErrorJsc as _; use crate::generated_bindgen::node_fs_binding::RmOptions; use crate::node::ThreadIsolated; use crate::node::fs::{ - self, AsyncCpTask, AsyncReaddirRecursiveTask, Flavor, FsArgument, FsReturn, NodeFS, - NodeFSDispatch, NodeFSFunctionEnum, Op, args, async_, ret, + self, AsyncCpTask, AsyncReaddirRecursiveTask, CpSyncRefusal, Flavor, FsArgument, FsReturn, + NodeFS, NodeFSDispatch, NodeFSFunctionEnum, Op, args, async_, ret, }; // The (`args::*`, `ret::*`, `NodeFS::`, `async_::*`) quadruples are @@ -196,6 +197,34 @@ impl Binding { } } + /// `fs.cpSync`'s checks of its two paths: [`NodeFS::cp_sync_check_paths`]. + pub(crate) fn cp_sync_check_paths( + &self, + cx: &mut JsScope<'_>, + args: &[JsLocal<'_>], + ) -> JsResult { + let global = cx.global(); + let vm: &VirtualMachine = global.bun_vm(); + let mut slice = ArgumentsSlice::init(vm, JsLocal::to_js_slice(args)); + let check_args = args::CpSyncCheckPaths::from_js(global, &mut slice)?; + + match self + .node_fs + .with_mut(|nfs| nfs.cp_sync_check_paths(&check_args)) + { + Ok(paths) => Ok(JSValue::js_number_from_int32(paths.bits())), + Err(CpSyncRefusal::System(ref err)) => Err(global.throw_value(err.to_js(global))), + Err(CpSyncRefusal::Verdict { code, message }) => Err(global.throw_sys_error( + &SysErrOptions { + code, + errno: None, + name: None, + }, + format_args!("{}", bstr::BStr::new(&message)), + )), + } + } + /// `callAsync(.readdir)` — `args.recursive` selects /// `AsyncReaddirRecursiveTask` instead of the generic `AsyncFSTask`. pub(crate) fn readdir(&self, cx: &mut JsScope<'_>, args: &[JsLocal<'_>]) -> JsResult { diff --git a/src/runtime/node/types.rs b/src/runtime/node/types.rs index 5b3930480f63..6c68ecb01112 100644 --- a/src/runtime/node/types.rs +++ b/src/runtime/node/types.rs @@ -1212,7 +1212,7 @@ fn join_onto_working_directory_in_executable(path: &[u8]) -> Option fs.renameSync(asset, asset + "2")); result.chmod = code(() => fs.chmodSync(asset, 0o600)); result.bunWrite = await Bun.write(asset, "x").then(() => "fine", error => error.code); + const refusal = (run: () => unknown) => { try { run(); return "fine"; } catch (error: any) { return error.message.replaceAll(path.basename(asset), "asset.txt"); } }; + result.cpSyncRoot = refusal(() => fs.cpSync(root, before + "/copy")); + result.cpSyncAssetOntoRoot = refusal(() => fs.cpSync(asset, root)); + result.cpSyncBelowAsset = code(() => fs.cpSync(before + "/main.ts", asset + "/below")); + result.cpSyncDirectoryBelowAsset = code(() => fs.cpSync(before, asset + "/below")); + process.chdir(root); + result.cpSyncRelative = refusal(() => fs.cpSync(".", path.basename(asset))); + process.chdir(before); result.stillThere = fs.readFileSync(asset, "utf8"); console.log(JSON.stringify(result)); `, @@ -85,6 +93,11 @@ test.skipIf(isWindows)("the embedded root of an executable can be entered and ca rename: "EROFS", chmod: "EROFS", bunWrite: "EROFS", + cpSyncRoot: "Recursive option not enabled, cannot copy a directory: /$bunfs/root/", + cpSyncAssetOntoRoot: "Cannot overwrite directory /$bunfs/root with non-directory /$bunfs/root/asset.txt", + cpSyncBelowAsset: "ENOTDIR", + cpSyncDirectoryBelowAsset: "ERR_FS_EISDIR", + cpSyncRelative: "Cannot overwrite non-directory asset.txt with directory .", stillThere: "hello asset", }, stderr: "", diff --git a/test/js/node/fs/cp-sync-check-paths.test.ts b/test/js/node/fs/cp-sync-check-paths.test.ts new file mode 100644 index 000000000000..e94623b64aa3 --- /dev/null +++ b/test/js/node/fs/cp-sync-check-paths.test.ts @@ -0,0 +1,774 @@ +/** + * All tests in this file run in both Bun and Node.js: `bun test` runs them + * here, and the last test runs this same file under Node.js. + * + * fs.cpSync checks the two paths it is given in one native function, + * CpSyncCheckPaths, before it writes anything: + * https://github.com/nodejs/node/blob/v26.12.1/src/node_file.cc#L4515-L4652 + * What that function throws is an Error with a `code` and nothing else. The + * errors that cpSync's walker, fs.cp and fs.promises.cp build in JavaScript + * are SystemErrors: errno, syscall, path and info. + */ +import assert from "node:assert"; +import { execFileSync, spawnSync } from "node:child_process"; +import { once } from "node:events"; +import fs from "node:fs"; +import { createServer } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { describe, test } from "node:test"; +import { fileURLToPath } from "node:url"; + +const isWindows = process.platform === "win32"; +const isBun = typeof Bun !== "undefined"; +const isRoot = !isWindows && process.getuid!() === 0; +const { EEXIST, EISDIR } = os.constants.errno; + +async function inTempDir(run: (dir: string) => unknown) { + // A short name: the socket's path has to fit in the 104 bytes that macOS gives a socket address. + const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "cpsync-"))); + try { + await run(dir); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +function thrownBy(fn: () => void): any { + try { + fn(); + } catch (err) { + return err; + } + assert.fail("cpSync did not throw"); +} + +/** A path in a message of CpSyncCheckPaths: after ToNamespacedPath, which changes it on Windows only. */ +const shown = (given: string) => path.toNamespacedPath(given); +/** The same for `src` where the message has one separator after it. */ +const shownWithSeparator = (src: string) => (shown(src).endsWith(path.sep) ? shown(src) : shown(src) + path.sep); + +/** An error of CpSyncCheckPaths: node's C++ makes an Error and gives it one property, `code`. */ +function assertNativeError(err: any, code: string, message: string) { + const enumerable: string[] = []; + for (const key in err) enumerable.push(key); + assert.deepStrictEqual( + { + string: String(err), + prototypeIsErrors: Object.getPrototypeOf(err) === Error.prototype, + code: err.code, + keys: Object.keys(err), + enumerable, + errno: err.errno, + syscall: err.syscall, + path: err.path, + info: err.info, + }, + { + string: `Error: ${message}`, + prototypeIsErrors: true, + code, + keys: ["code"], + enumerable: ["code"], + errno: undefined, + syscall: undefined, + path: undefined, + info: undefined, + }, + ); +} + +/** An error that JavaScript builds: `new ERR_FS_*({ message, path, syscall, errno, code })` in node. */ +function assertSystemError( + err: any, + code: string, + prefix: string, + errno: number, + errnoName: string, + detail: string, + at: string, +) { + assert.deepStrictEqual( + { + name: err.name, + code: err.code, + message: err.message, + errno: err.errno, + syscall: err.syscall, + path: err.path, + info: err.info, + }, + { + name: "SystemError", + code, + message: `${prefix}: cp returned ${errnoName} (${detail}) ${at}`, + errno, + syscall: "cp", + path: at, + info: { message: detail, path: at, syscall: "cp", errno, code: errnoName }, + }, + ); +} + +/** On Linux: a descriptor of this process that stat gives no file type for, such as the event loop's epoll. */ +function fileOfNoKnownType() { + if (process.platform !== "linux") return undefined; + for (const fd of fs.readdirSync("/proc/self/fd")) { + const link = `/proc/self/fd/${fd}`; + try { + if (fs.readlinkSync(link).startsWith("anon_inode:") && (fs.statSync(link).mode & fs.constants.S_IFMT) === 0) { + return link; + } + } catch { + // The descriptor that listed the folder is closed by now. + } + } +} + +const optionSets: [label: string, options: fs.CopySyncOptions | undefined][] = [ + ["no options", undefined], + ["filter", { filter: () => true }], + ["dereference", { dereference: true }], + ["force: false", { force: false }], + ["preserveTimestamps", { preserveTimestamps: true }], +]; + +describe("fs.cpSync checks its two paths in the order of node's CpSyncCheckPaths, with its errors", () => { + for (const [label, options] of optionSets) { + test(`a directory without recursive (${label})`, () => + inTempDir(dir => { + const src = path.join(dir, "src"); + const dest = path.join(dir, "new", "sub", "dest"); + fs.mkdirSync(src); + fs.writeFileSync(path.join(src, "file"), "a"); + + assertNativeError( + thrownBy(() => fs.cpSync(src, dest, options)), + "ERR_FS_EISDIR", + `Recursive option not enabled, cannot copy a directory: ${shownWithSeparator(src)}`, + ); + // Nothing is written before the check: the folders above dest are made by the copy. + assert.deepStrictEqual(fs.readdirSync(dir), ["src"]); + fs.cpSync(src, dest, { ...options, recursive: true }); + assert.strictEqual(fs.readFileSync(path.join(dest, "file"), "utf8"), "a"); + })); + } + + test("a directory without recursive: a relative path, and a path that ends with a separator", () => + inTempDir(dir => { + const src = path.join(dir, "src"); + fs.mkdirSync(src); + fs.mkdirSync(path.join(dir, "dest")); + const relative = path.relative(process.cwd(), src); + for (const given of [src + path.sep, relative]) { + for (const dest of [path.join(dir, "dest"), path.join(dir, "missing")]) { + assertNativeError( + thrownBy(() => fs.cpSync(given, dest)), + "ERR_FS_EISDIR", + `Recursive option not enabled, cannot copy a directory: ${shownWithSeparator(given)}`, + ); + } + } + // A lone surrogate is U+FFFD in the bytes of a path, and the message shows those bytes. + if (!isWindows) { + fs.mkdirSync(path.join(dir, "a\uD800b")); + assertNativeError( + thrownBy(() => fs.cpSync(path.join(dir, "a\uD800b"), path.join(dir, "missing"))), + "ERR_FS_EISDIR", + `Recursive option not enabled, cannot copy a directory: ${path.join(dir, "a\uFFFDb")}${path.sep}`, + ); + } + })); + + test("a directory without recursive: fs.cp and fs.promises.cp throw a SystemError", () => + inTempDir(async dir => { + const src = path.join(dir, "src"); + const dest = path.join(dir, "dest"); + fs.mkdirSync(src); + const { promise, resolve } = Promise.withResolvers(); + fs.cp(src, dest, resolve); + const rejected = fs.promises.cp(src, dest).then( + () => assert.fail("cp did not reject"), + err => err, + ); + for (const err of [await promise, await rejected]) { + assertSystemError( + err, + "ERR_FS_EISDIR", + "Path is a directory", + EISDIR, + "EISDIR", + `${src} is a directory (not copied)`, + src, + ); + } + assertNativeError( + thrownBy(() => fs.cpSync(src, dest)), + "ERR_FS_EISDIR", + `Recursive option not enabled, cannot copy a directory: ${shownWithSeparator(src)}`, + ); + })); + + test("src and dest are the same file", () => + inTempDir(dir => { + const file = path.join(dir, "file"); + const link = path.join(dir, "hard-link"); + fs.writeFileSync(file, "a"); + fs.linkSync(file, link); + for (const dest of [file, link]) { + for (const options of [undefined, { filter: () => true }]) { + assertNativeError( + thrownBy(() => fs.cpSync(file, dest, options)), + "ERR_FS_CP_EINVAL", + `src and dest cannot be the same ${shown(dest)}`, + ); + } + } + // The walker builds this one in JavaScript, in node too. + const other = path.join(dir, "other"); + fs.writeFileSync(other, "b"); + assertSystemError( + thrownBy(() => fs.cpSync(file, other, { force: false, errorOnExist: true })), + "ERR_FS_CP_EEXIST", + "Target already exists", + EEXIST, + "EEXIST", + `${other} already exists`, + other, + ); + })); + + test("src and dest are the same directory, with and without recursive", () => + inTempDir(dir => { + const src = path.join(dir, "src"); + fs.mkdirSync(src); + for (const options of [undefined, { recursive: true }, { recursive: true, filter: () => true }]) { + assertNativeError( + thrownBy(() => fs.cpSync(src, src, options)), + "ERR_FS_CP_EINVAL", + `src and dest cannot be the same ${shown(src)}`, + ); + } + })); + + test("a directory onto a file, with and without recursive", () => + inTempDir(dir => { + const src = path.join(dir, "src"); + const dest = path.join(dir, "dest"); + fs.mkdirSync(src); + fs.writeFileSync(dest, "a"); + for (const options of [undefined, { recursive: true }, { recursive: true, filter: () => true }]) { + assertNativeError( + thrownBy(() => fs.cpSync(src, dest, options)), + "ERR_FS_CP_DIR_TO_NON_DIR", + `Cannot overwrite non-directory ${shown(dest)} with directory ${shown(src)}`, + ); + } + assert.strictEqual(fs.readFileSync(dest, "utf8"), "a"); + })); + + test("a file onto a directory", () => + inTempDir(dir => { + const src = path.join(dir, "src"); + const dest = path.join(dir, "dest"); + fs.writeFileSync(src, "a"); + fs.mkdirSync(dest); + for (const options of [undefined, { recursive: true }, { filter: () => true }]) { + assertNativeError( + thrownBy(() => fs.cpSync(src, dest, options)), + "ERR_FS_CP_NON_DIR_TO_DIR", + `Cannot overwrite directory ${shown(dest)} with non-directory ${shown(src)}`, + ); + } + })); + + test("a file onto a link to a directory, with dereference", () => + inTempDir(dir => { + const src = path.join(dir, "src"); + const dest = path.join(dir, "link"); + fs.writeFileSync(src, "a"); + fs.mkdirSync(path.join(dir, "directory")); + fs.symlinkSync(path.join(dir, "directory"), dest, isWindows ? "junction" : "dir"); + assertNativeError( + thrownBy(() => fs.cpSync(src, dest, { dereference: true })), + "ERR_FS_CP_NON_DIR_TO_DIR", + `Cannot overwrite directory ${shown(dest)} with non-directory ${shown(src)}`, + ); + })); + + test("dest is inside src, with and without recursive", () => + inTempDir(dir => { + const src = path.join(dir, "src"); + const dest = path.join(src, "new", "dest"); + fs.mkdirSync(src); + for (const options of [undefined, { recursive: true }, { recursive: true, filter: () => true }]) { + assertNativeError( + thrownBy(() => fs.cpSync(src, dest, options)), + "ERR_FS_CP_EINVAL", + `Cannot copy ${shownWithSeparator(src)} to a subdirectory of self ${shown(dest)}`, + ); + } + assert.deepStrictEqual(fs.readdirSync(src), []); + // A name that only starts with src's is another directory. + fs.cpSync(src, src + "-copy", { recursive: true }); + assert.deepStrictEqual(fs.readdirSync(dir).sort(), ["src", "src-copy"]); + })); + + test("what dest is comes before whether dest is inside src", () => + inTempDir(dir => { + const src = path.join(dir, "src"); + const inside = path.join(src, "file"); + const link = path.join(dir, "elsewhere", "link"); + fs.mkdirSync(src); + fs.writeFileSync(inside, "a"); + fs.mkdirSync(path.join(dir, "elsewhere")); + fs.symlinkSync(src, link, isWindows ? "junction" : "dir"); + for (const dest of [inside, path.join(link, "file")]) { + for (const options of [undefined, { recursive: true }, { recursive: true, filter: () => true }]) { + assertNativeError( + thrownBy(() => fs.cpSync(src, dest, options)), + "ERR_FS_CP_DIR_TO_NON_DIR", + `Cannot overwrite non-directory ${shown(dest)} with directory ${shown(src)}`, + ); + } + } + assert.strictEqual(fs.readFileSync(inside, "utf8"), "a"); + })); + + test("the folder above dest is a link to src", () => + inTempDir(dir => { + const src = path.join(dir, "src"); + const link = path.join(dir, "elsewhere", "link"); + const dest = path.join(link, "dest"); + fs.mkdirSync(path.join(src, "inside"), { recursive: true }); + fs.mkdirSync(path.join(dir, "elsewhere")); + fs.symlinkSync(src, link, isWindows ? "junction" : "dir"); + for (const options of [{ recursive: true }, undefined]) { + assertNativeError( + thrownBy(() => fs.cpSync(src, dest, options)), + "ERR_FS_CP_EINVAL", + `Cannot copy ${shownWithSeparator(src)} to a subdirectory of self ${shown(dest)}`, + ); + } + assert.deepStrictEqual(fs.readdirSync(src), ["inside"]); + })); + + test("a FIFO", { skip: isWindows }, () => + inTempDir(dir => { + const src = path.join(dir, "fifo"); + const missing = path.join(dir, "new", "sub", "dest"); + const file = path.join(dir, "file"); + const directory = path.join(dir, "directory"); + execFileSync("mkfifo", [src]); + fs.writeFileSync(file, "a"); + fs.mkdirSync(directory); + for (const dest of [missing, file]) { + for (const options of [undefined, { recursive: true }, { filter: () => true }]) { + assertNativeError( + thrownBy(() => fs.cpSync(src, dest, options)), + "ERR_FS_CP_FIFO_PIPE", + `Cannot copy a FIFO pipe: ${dest}`, + ); + } + } + // What dest is comes before what src is. + assertNativeError( + thrownBy(() => fs.cpSync(src, directory)), + "ERR_FS_CP_NON_DIR_TO_DIR", + `Cannot overwrite directory ${directory} with non-directory ${src}`, + ); + assert.deepStrictEqual(fs.readdirSync(dir).sort(), ["directory", "fifo", "file"]); + }), + ); + + test("a socket", { skip: isWindows }, () => + inTempDir(async dir => { + const src = path.join(dir, "s"); + const dest = path.join(dir, "new", "sub", "dest"); + const server = createServer(); + try { + server.listen(src); + await once(server, "listening"); + for (const options of [undefined, { filter: () => true }]) { + assertNativeError( + thrownBy(() => fs.cpSync(src, dest, options)), + "ERR_FS_CP_SOCKET", + `Cannot copy a socket file: ${dest}`, + ); + } + assert.deepStrictEqual(fs.readdirSync(dir), ["s"]); + } finally { + server.close(); + } + }), + ); + + const noKnownType = fileOfNoKnownType(); + test("a file of no known type", { skip: noKnownType ? false : "no such file on this system" }, () => + inTempDir(dir => { + const dest = path.join(dir, "new", "sub", "dest"); + // The file is behind a link. Node's check follows a link at src unless `dereference` is set, and Bun's if it is set. + const follow = isBun ? { dereference: true } : {}; + for (const options of [follow, { ...follow, filter: () => true }]) { + assertNativeError( + thrownBy(() => fs.cpSync(noKnownType!, dest, options)), + "ERR_FS_CP_UNKNOWN", + `Cannot copy an unknown file type: ${dest}`, + ); + } + assert.deepStrictEqual(fs.readdirSync(dir), []); + }), + ); + + test("a dest that cannot be read does not come before what src is", { skip: isWindows }, () => + inTempDir(dir => { + const directory = path.join(dir, "directory"); + const fifo = path.join(dir, "fifo"); + const file = path.join(dir, "file"); + const other = path.join(dir, "other"); + const loop = path.join(dir, "loop"); + const locked = path.join(dir, "locked"); + fs.mkdirSync(directory); + execFileSync("mkfifo", [fifo]); + fs.writeFileSync(file, "a"); + fs.writeFileSync(other, "b"); + fs.symlinkSync(loop, loop); + fs.mkdirSync(locked, { mode: 0 }); + try { + const unreadable: [dest: string, code: string][] = [ + [path.join(other, "dest"), "ENOTDIR"], + [path.join(loop, "dest"), "ELOOP"], + // Longer than PATH_MAX on every system. + [path.join(dir, Buffer.alloc(5000, "a").toString()), "ENAMETOOLONG"], + ]; + // Every folder can be searched by root. + if (!isRoot) unreadable.push([path.join(locked, "dest"), "EACCES"]); + for (const [dest, code] of unreadable) { + for (const options of [undefined, { filter: () => true }]) { + assertNativeError( + thrownBy(() => fs.cpSync(directory, dest, options)), + "ERR_FS_EISDIR", + `Recursive option not enabled, cannot copy a directory: ${directory}${path.sep}`, + ); + assertNativeError( + thrownBy(() => fs.cpSync(fifo, dest, options)), + "ERR_FS_CP_FIFO_PIPE", + `Cannot copy a FIFO pipe: ${dest}`, + ); + // Nothing refuses a file, so the stat of dest is what fails. + const err = thrownBy(() => fs.cpSync(file, dest, options)); + assert.deepStrictEqual( + { code: err.code, syscall: err.syscall, path: err.path }, + { code, syscall: "lstat", path: dest }, + ); + } + } + } finally { + fs.chmodSync(locked, 0o700); + } + assert.deepStrictEqual(fs.readdirSync(dir).sort(), ["directory", "fifo", "file", "locked", "loop", "other"]); + assert.strictEqual(fs.readFileSync(other, "utf8"), "b"); + }), + ); + + test("a path in a Buffer is checked as a string is", () => + inTempDir(dir => { + const src = path.join(dir, "src"); + const file = path.join(dir, "file"); + const bytes = (given: string) => Buffer.from(given) as any; + fs.mkdirSync(src); + fs.writeFileSync(file, "a"); + assertNativeError( + thrownBy(() => fs.cpSync(bytes(src), path.join(dir, "new", "dest"))), + "ERR_FS_EISDIR", + `Recursive option not enabled, cannot copy a directory: ${shownWithSeparator(src)}`, + ); + assertNativeError( + thrownBy(() => fs.cpSync(bytes(file), bytes(file))), + "ERR_FS_CP_EINVAL", + `src and dest cannot be the same ${shown(file)}`, + ); + assertNativeError( + thrownBy(() => fs.cpSync(bytes(src), bytes(file), { recursive: true })), + "ERR_FS_CP_DIR_TO_NON_DIR", + `Cannot overwrite non-directory ${shown(file)} with directory ${shown(src)}`, + ); + assertNativeError( + thrownBy(() => fs.cpSync(file, bytes(src))), + "ERR_FS_CP_NON_DIR_TO_DIR", + `Cannot overwrite directory ${shown(src)} with non-directory ${shown(file)}`, + ); + assert.deepStrictEqual(fs.readdirSync(dir).sort(), ["file", "src"]); + })); + + test("the filter runs first, and the check reads the options after it", () => + inTempDir(dir => { + const src = path.join(dir, "src"); + const dest = path.join(dir, "dest"); + const missing = path.join(dir, "missing"); + fs.mkdirSync(src); + fs.writeFileSync(path.join(src, "file"), "a"); + + assert.strictEqual(fs.cpSync(missing, dest, { filter: () => false }), undefined); + assert.strictEqual(fs.cpSync(Buffer.from(missing) as any, dest, { filter: () => false }), undefined); + assert.strictEqual( + thrownBy(() => fs.cpSync(missing, dest, { filter: (() => Promise.resolve(true)) as any })).code, + "ERR_INVALID_RETURN_VALUE", + ); + // Node's C++ takes `recursive` to be set only if it is `true`. + for (const notTrue of [false, 1]) { + assertNativeError( + thrownBy(() => + fs.cpSync(src, dest, { + recursive: true, + filter(this: any) { + this.recursive = notTrue; + return true; + }, + }), + ), + "ERR_FS_EISDIR", + `Recursive option not enabled, cannot copy a directory: ${shownWithSeparator(src)}`, + ); + } + fs.cpSync(src, dest, { + filter(this: fs.CopySyncOptions) { + this.recursive = true; + return true; + }, + } as fs.CopySyncOptions); + assert.strictEqual(fs.readFileSync(path.join(dest, "file"), "utf8"), "a"); + })); + + test("a src that is not there, or too long a path, fails the stat", { skip: isWindows }, () => + inTempDir(dir => { + const missing = path.join(dir, "missing"); + const dest = path.join(dir, "new", "dest"); + // Longer than PATH_MAX on every system. + const tooLong = path.join(dir, Buffer.alloc(5000, "a").toString()); + for (const [src, options, code, syscall] of [ + [missing, undefined, "ENOENT", "lstat"], + [missing, { dereference: true }, "ENOENT", "stat"], + [Buffer.from(missing), undefined, "ENOENT", "lstat"], + [tooLong, undefined, "ENAMETOOLONG", "lstat"], + [tooLong, { dereference: true, filter: () => true }, "ENAMETOOLONG", "stat"], + ] as const) { + const err = thrownBy(() => fs.cpSync(src as any, dest, options)); + assert.deepStrictEqual( + { code: err.code, syscall: err.syscall, path: err.path, keys: Object.keys(err).sort() }, + { code, syscall, path: String(src), keys: ["code", "errno", "path", "syscall"] }, + ); + } + assert.deepStrictEqual(fs.readdirSync(dir), []); + }), + ); + + test("a check that fails calls no function of the fs module", () => + inTempDir(dir => { + fs.mkdirSync(path.join(dir, "src")); + // In a process of its own: cpSync reads the functions of `fs` when it is first called. + const script = ` + const fs = require("node:fs"); + const calls = []; + for (const name of ["lstatSync", "statSync", "existsSync", "mkdirSync"]) { + const original = fs[name]; + fs[name] = function (...args) { + calls.push(name); + return original.apply(this, args); + }; + } + let code; + try { + fs.cpSync("src", "new/sub/dest", { filter: () => true }); + } catch (err) { + code = err.code; + } + console.log(JSON.stringify({ code, calls })); + `; + const child = spawnSync(process.execPath, ["-e", script], { + cwd: dir, + encoding: "utf8", + env: { ...process.env, BUN_DEBUG_QUIET_LOGS: "1" }, + }); + assert.deepStrictEqual( + { stdout: child.stdout.trim(), status: child.status }, + { stdout: JSON.stringify({ code: "ERR_FS_EISDIR", calls: [] }), status: 0 }, + ); + })); +}); + +// Only in Bun: when Node.js runs this file it must not spawn itself again. +if (isBun) { + const { bunEnv, nodeExeAtLeast } = await import("harness"); + + // Node's C++ reads a link at src the other way round (https://github.com/nodejs/node/pull/60945), and ends the + // process for some pairs. Bun decides these as node's JavaScript does, in cpSync's walker and in fs.cp. + describe("fs.cpSync decides as node's JavaScript checkPaths does", () => { + type Outcome = { code: string; message?: string } | { dest: string }; + const rows: [label: string, src: string, dest: string, options: fs.CopySyncOptions | undefined, Outcome][] = [ + ["a link to a directory onto nothing", "link-to-directory", "new", undefined, { dest: "link to directory" }], + [ + "a link to a directory onto a directory", + "link-to-directory", + "directory2", + { recursive: true }, + { code: "ERR_FS_CP_NON_DIR_TO_DIR", message: "Cannot overwrite directory with non-directory " }, + ], + ["a link to a directory onto a file", "link-to-directory", "file2", undefined, { code: "EEXIST" }], + ["a link to a file onto nothing, with dereference", "link-to-file", "new", { dereference: true }, { dest: "a" }], + ["a link to nothing onto nothing", "link-to-nothing", "new", undefined, { dest: "link to nothing" }], + [ + "a link to nothing onto a directory", + "link-to-nothing", + "directory2", + undefined, + { code: "ERR_FS_CP_NON_DIR_TO_DIR", message: "Cannot overwrite directory with non-directory " }, + ], + ["a file onto a link to it", "file", "link-to-file", undefined, { dest: "a" }], + ["a file onto a link to nothing", "file", "link-to-nothing", undefined, { dest: "a" }], + [ + "a directory onto a link to nothing", + "directory", + "link-to-nothing", + { recursive: true }, + { code: "ERR_FS_CP_DIR_TO_NON_DIR", message: "Cannot overwrite non-directory with directory " }, + ], + [ + "a FIFO onto a FIFO", + "fifo", + "fifo2", + undefined, + { code: "ERR_FS_CP_FIFO_PIPE", message: "Cannot copy a FIFO pipe: " }, + ], + // Only a directory is looked for in the folders above dest. Node also looks for a file, and for a FIFO where + // the C++ library that it was built with compares two of them. + ["a file onto a path below it", "file", "file/below", undefined, { code: "ENOTDIR" }], + [ + "a FIFO onto a path below it", + "fifo", + "fifo/below", + undefined, + { code: "ERR_FS_CP_FIFO_PIPE", message: "Cannot copy a FIFO pipe: " }, + ], + ]; + for (const [label, srcName, destName, options, expected] of rows) { + test(label, { skip: isWindows }, () => + inTempDir(dir => { + const at = (name: string) => path.join(dir, name); + const [src, dest] = [at(srcName), at(destName)]; + fs.mkdirSync(at("directory")); + fs.mkdirSync(at("directory2")); + fs.writeFileSync(at("file"), "a"); + fs.writeFileSync(at("file2"), "b"); + fs.symlinkSync(at("directory"), at("link-to-directory")); + fs.symlinkSync(at("file"), at("link-to-file")); + fs.symlinkSync(at("nothing"), at("link-to-nothing")); + execFileSync("mkfifo", [at("fifo"), at("fifo2")]); + + if ("dest" in expected) { + fs.cpSync(src, dest, options); + const found = fs.lstatSync(dest).isSymbolicLink() + ? `link to ${path.basename(fs.readlinkSync(dest))}` + : fs.readFileSync(dest, "utf8"); + assert.deepStrictEqual( + { dest: found, src: fs.readFileSync(at("file"), "utf8") }, + { ...expected, src: "a" }, + ); + } else if (expected.message) { + const message = expected.message.replace("", src).replace("", dest); + assertNativeError( + thrownBy(() => fs.cpSync(src, dest, options)), + expected.code, + message, + ); + } else { + assert.strictEqual(thrownBy(() => fs.cpSync(src, dest, options)).code, expected.code); + } + }), + ); + } + + // The folders above dest are read by their resolved paths, and one of those can be too long to read where the + // path that was given is short. Nothing then says that the folder is not src, so nothing is copied. + test("a folder above dest that cannot be read stops the copy", { skip: process.platform !== "linux" }, () => + inTempDir(dir => { + const script = ` + const fs = require("node:fs"); + // Go down until the working directory is a few bytes short of PATH_MAX. + const made = []; + const down = name => { + fs.mkdirSync(name); + process.chdir(name); + made.push(name); + }; + while (process.cwd().length + 256 < 4090) down(Buffer.alloc(250, "d").toString()); + down(Buffer.alloc(4090 - process.cwd().length - 1, "e").toString()); + fs.mkdirSync("src"); + fs.symlinkSync("src", "link"); + let code; + try { + fs.cpSync("src", "link/sub/dest", { recursive: true }); + } catch (err) { + code = err.code; + } + const written = fs.readdirSync("src"); + fs.rmSync("src", { recursive: true, force: true }); + fs.unlinkSync("link"); + while (made.length) { + process.chdir(".."); + fs.rmdirSync(made.pop()); + } + console.log(JSON.stringify({ code, written })); + `; + const child = spawnSync(process.execPath, ["-e", script], { + cwd: dir, + encoding: "utf8", + env: { ...process.env, BUN_DEBUG_QUIET_LOGS: "1" }, + }); + assert.deepStrictEqual( + { stdout: child.stdout.trim(), status: child.status }, + { stdout: JSON.stringify({ code: "ENAMETOOLONG", written: [] }), status: 0 }, + ); + }), + ); + + test("a Buffer path that the check lets through is refused before anything is written", () => + inTempDir(dir => { + const src = path.join(dir, "src"); + const dest = path.join(dir, "new", "sub", "dest"); + fs.writeFileSync(src, "a"); + const given: [src: any, dest: any, name: string][] = [ + [Buffer.from(src), dest, "src"], + [src, Buffer.from(dest), "dest"], + ]; + for (const [givenSrc, givenDest, name] of given) { + for (const options of [undefined, { filter: () => true }]) { + const err = thrownBy(() => fs.cpSync(givenSrc, givenDest, options)); + assert.deepStrictEqual( + { code: err.code, message: err.message }, + { + code: "ERR_INVALID_ARG_TYPE", + message: `The "${name}" argument must be of type string. Received an instance of Buffer`, + }, + ); + } + } + assert.deepStrictEqual(fs.readdirSync(dir), ["src"]); + })); + }); + + describe("Node.js compatibility", () => { + // The text of the errors is that of v26.3.0 and later. + const node = nodeExeAtLeast("26.3.0"); + (node ? test : test.skip)("all tests pass in Node.js", async () => { + await using proc = Bun.spawn({ + cmd: [node!, fileURLToPath(import.meta.url)], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + assert.deepStrictEqual({ exitCode, output: exitCode === 0 ? "" : stdout + stderr }, { exitCode: 0, output: "" }); + }); + }); +} diff --git a/test/js/node/fs/cp.test.ts b/test/js/node/fs/cp.test.ts index 036ff3e26658..d494b668f7d7 100644 --- a/test/js/node/fs/cp.test.ts +++ b/test/js/node/fs/cp.test.ts @@ -43,10 +43,15 @@ for (const [name, copy] of impls) { }); const e = await copyShouldThrow(basename + "/from", basename + "/result"); - expect(e.code).toBe("ERR_FS_EISDIR"); - // The path field echoes the caller's string verbatim (node does not - // resolve or normalize it), so expect the same concatenation we passed. - expect(e.path).toBe(basename + "/from"); + // fs.promises.cp builds this error in JavaScript: the path field echoes the + // caller's string verbatim (node does not resolve or normalize it), so + // expect the same concatenation we passed. fs.cpSync throws it from its + // native path check, where node sets `code` and no path + // (cp-sync-check-paths.test.ts). + expect({ code: e.code, path: e.path }).toEqual({ + code: "ERR_FS_EISDIR", + path: name === "cpSync" ? undefined : basename + "/from", + }); }); test("recursive directory structure - no destination", async () => {