Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 76 additions & 37 deletions src/runtime/node/node_fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4343,6 +4343,12 @@ pub mod args {
pub(crate) recursive: bool,
pub(crate) error_on_exist: bool,
pub(crate) force: bool,
/// A symlink source is followed and the file it points at is copied,
/// the way `cp` without `-R` treats its operands. Off, a symlink is
/// recreated (`fs.cp` handles `dereference` itself and never sets
/// this). Only consulted by `copy_single_file_sync`; directories are
/// still classified without following links.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) dereference: bool,
}

pub struct Cp {
Expand Down Expand Up @@ -4389,6 +4395,7 @@ pub mod args {
recursive,
error_on_exist,
force,
dereference: false,
},
})
}
Expand Down Expand Up @@ -8539,7 +8546,42 @@ impl NodeFS {
Syscall::symlink(ZStr::from_buf(&resolved_buf[..], resolved_len), dest)
}

/// This is `copyFile`, but it copies symlinks as-is
/// The stat `copy_single_file_sync` classifies its source by. Callers pass
/// the `lstat` they already took as `reuse_stat`; when dereferencing, a
/// symlink is stat'd again so the copy is described by its target.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[cfg(not(windows))]
fn cp_source_stat(
src: &ZStr,
reuse_stat: Option<&sys::Stat>,
dereference: bool,
) -> Maybe<sys::Stat> {
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)
}
}

/// Opens the file a dereferenced source resolves to. The kind is checked
/// from the stat first: `open(2)` on a FIFO blocks until a writer shows up.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]
fn cp_open_dereferenced_source(src: &ZStr, reuse_stat: Option<&sys::Stat>) -> Maybe<FD> {
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.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn copy_single_file_sync(
&mut self,
src: &OSPathSliceZ,
Expand All @@ -8550,8 +8592,6 @@ impl NodeFS {
#[cfg(not(windows))] reuse_stat: Option<&sys::Stat>,
args: &args::Cp,
) -> Maybe<ret::CopyFile> {
let _ = args; // only the Windows branch consults `args` (shouldIgnoreEbusy)

// TODO: do we need to fchown?
#[cfg(target_os = "macos")]
{
Expand All @@ -8564,16 +8604,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) {
Expand Down Expand Up @@ -8657,9 +8688,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;
}
Expand Down Expand Up @@ -8688,21 +8720,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::<ret::CopyFile>::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.
Comment thread
robobun marked this conversation as resolved.
Resolved
return self.cp_symlink(src, dest);
}
return Err(err);
}
return Err(err);
}
};
let _close_src = scopeguard::guard(src_fd, |fd| fd.close());
Expand Down Expand Up @@ -8856,7 +8891,6 @@ impl NodeFS {

#[cfg(target_os = "freebsd")]
{
let _ = reuse_stat;
if mode.is_force_clone() {
return Err(sys::Error {
errno: SystemErrno::EOPNOTSUPP as _,
Expand All @@ -8865,16 +8899,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.
Comment thread
robobun marked this conversation as resolved.
Resolved
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());
Expand Down Expand Up @@ -9025,7 +9063,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(),
Expand Down Expand Up @@ -9133,7 +9172,7 @@ impl NodeFS {
windows
)))]
{
let _ = (src, dest, mode, reuse_stat);
let _ = (src, dest, mode, reuse_stat, args);
Maybe::<ret::CopyFile>::todo()
}
}
Expand Down
56 changes: 54 additions & 2 deletions src/runtime/shell/builtin/cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,7 @@
.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<bool> {
#[cfg(windows)]
{
Expand All @@ -581,6 +582,22 @@
}
}

/// Is `tgt` the file `src_stat` describes? `follow` says whether a symlink
/// at `tgt` is looked through, and must match how `src_stat` was taken.
/// An inode number of 0 means the filesystem reports no identity.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn is_same_file(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)
};
tgt_stat.is_ok_and(|tgt_stat| {
src_stat.st_ino != 0
&& src_stat.st_ino == tgt_stat.st_ino

Check warning on line 596 in src/runtime/shell/builtin/cp.rs

View check run for this annotation

Claude / Claude Code Review

is_same_file with -R misses a symlink destination that points at the source

Under `-R`, `is_same_file` compares `lstat(src)` against `lstat(tgt)`, but the destination is opened without `O_NOFOLLOW`, so `cp -R f l` where `l -> f` isn't caught (the symlink's own inode ≠ the file's) and proceeds — coreutils refuses it as "same file". Not a regression (the guard is new and behaviour matches pre-PR, and the description scopes destination-symlink classification out), but since the PR does add `-R` same-file tests it's worth noting: for the identity check to match cp(1) here,
Comment thread
robobun marked this conversation as resolved.
Resolved
&& src_stat.st_dev == tgt_stat.st_dev
})
}

/// Resolves src/tgt to absolute paths, classifies them per the three
/// POSIX `cp` synopses
/// (<https://man7.org/linux/man-pages/man1/cp.1p.html>), then hands off to
Expand Down Expand Up @@ -616,10 +633,20 @@
// 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.
Comment thread
robobun marked this conversation as resolved.
Resolved
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 {
Expand Down Expand Up @@ -651,6 +678,8 @@
};

let mut _copying_many = false;
// Set when the copy lands at `tgt/<basename of src>`, 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 {
Expand All @@ -663,6 +692,7 @@
buf3.as_mut_slice(),
&[tgt.as_bytes(), basename],
);
dest_basename = Some(basename);
} else if self.operands == 2 {
// source_dir -> new_target_dir.
} else {
Expand Down Expand Up @@ -694,9 +724,30 @@
buf3.as_mut_slice(),
&[tgt.as_bytes(), basename],
);
dest_basename = Some(basename);
_copying_many = true;
}

// Copying a file onto itself (through a link, a hard link or a path
// going through a directory symlink, which the path comparison above
// misses) is refused, as cp(1) does. Reading and writing one file would
// otherwise go ahead, and the macOS copy unlinks the destination first.
Comment thread
robobun marked this conversation as resolved.
Resolved
if !src_is_dir && Self::is_same_file(&src_stat, tgt, follow_src) {
let shown_tgt = match dest_basename {
Some(basename) => bun_paths::join_sep_maybe_z::<false>(&[&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());

Expand All @@ -713,6 +764,7 @@
recursive: self.opts.recursive,
force: true,
error_on_exist: false,
dereference: follow_src,
},
};

Expand Down
Loading