fix: make the rename-exdev fallback safe and transactional

rename-exdev (opt-in; the default is passthrough) moves a source it
cannot rename across branches into a staging tree and publishes a
symlink at the destination. This reworks that fallback so a rename
either completes or leaves both names as they were.

- Staging opens every component relative to a pinned parent with
  O_NOFOLLOW, requires a daemon-owned staging root, and refuses when
  the tree can't be trusted.
- Staged names are taken without replacement and must be free on
  every configured branch, not only those holding the source, so a
  later lookup cannot reach another rename's payload. Over-long names
  are shortened. Fallback renames are serialized.
- Destinations: a compatible existing destination is replaced, kept
  under a temporary name until every branch is published, and
  restored if a later branch fails. A destination on a read-only
  branch, or a no-create one where the link can't be created, is
  refused before anything moves. Temporary and restore names never
  replace an entry, and a restore that fails is reported.
- An ordinary rename (rename-exdev=passthrough) also refuses with
  EXDEV when the destination exists on a read-only branch that does
  not hold the source: that copy could neither be replaced nor
  removed and would shadow the renamed file there. It is never
  scheduled for removal either.
- The replacement symlink is prepared in a daemon-private directory,
  its UID and GID are verified through a pinned descriptor, and it is
  published without replacement, before any source moves. A sticky,
  world-writable destination directory under Linux protected symlinks
  is refused. Each prepared link is tracked by identity for cleanup.
- Symlink sources are recreated with their original text, owner and
  times instead of staged, since staging changes where a relative
  target resolves. Sources of different types on different branches
  are refused. A hidden source that cannot be removed fails the rename.
- libfuse re-parents the kernel's node onto the staged inode, using a
  name allocated before publication, so open handles and cached
  dentries keep working and nothing can fail after the rename commits.
- Without renameat2 (FreeBSD 14.4 and 15.0, or seccomp), regular
  files and directories use a portable layout: a fresh daemon-owned
  wrapper, access gates that mirror the source's parents with the
  source's GID and its read and execute bits only, and the payload
  directory inside the last gate. Foreign-owned parents, unsettable
  group ownership and non-trivial ACLs are refused before the source
  moves. A namespace the source never entered is removed. A portable
  directory that can't be restored stays staged with its path logged,
  and an existing directory destination is refused before a portable
  source moves: keeping it aside would need the no-replace rename the
  portable layout lacks.
- Document the fallback, its refusals and FreeBSD limits.
- TEST_rename_exdev_publication, TEST_rename_exdev_portable and
  tests.cpp cover publication rollback, shadows, collisions,
  ownership, sticky directories, mixed source types, a refused portable
  directory destination and the portable layout through a mounted
  pool. TEST_rename_exdev_publication keeps its fixture if its tmpfs
  can't be detached.

Performance: an ordinary rename only adds an lstat per read-only
branch, and only when one is configured. The fallback adds about two
lstats per branch plus the staging work, and fallback renames run one
at a time.
This commit is contained in:
Antonio SJ Musumeci 2026-11-25 13:45:42 -05:00
parent 036246140b
commit c9854f236f
16 changed files with 3962 additions and 202 deletions

94
src/fs_renameat.hpp Normal file
View file

@ -0,0 +1,94 @@
/*
ISC License
Copyright (c) 2026, Antonio SJ Musumeci <trapexit@spawn.link>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include "to_neg_errno.hpp"
#include <string>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifndef RENAME_NOREPLACE
#define RENAME_NOREPLACE (1 << 0)
#endif
namespace fs
{
static
inline
int
renameat(const int olddirfd_,
const char *oldpath_,
const int newdirfd_,
const char *newpath_)
{
int rv;
rv = ::renameat(olddirfd_,oldpath_,newdirfd_,newpath_);
return ::to_neg_errno(rv);
}
static
inline
int
renameat(const int olddirfd_,
const std::string &oldpath_,
const int newdirfd_,
const std::string &newpath_)
{
return fs::renameat(olddirfd_,
oldpath_.c_str(),
newdirfd_,
newpath_.c_str());
}
// Fail with EEXIST rather than replace an existing `newpath_`. A
// check followed by plain renameat() would still replace a file
// created between those operations, so unsupported filesystems and
// kernels must reject the operation instead of risking data loss.
static
inline
int
renameat_noreplace(const int olddirfd_,
const std::string &oldpath_,
const int newdirfd_,
const std::string &newpath_)
{
#if defined SYS_renameat2
const int rv = ::syscall(SYS_renameat2,
olddirfd_,
oldpath_.c_str(),
newdirfd_,
newpath_.c_str(),
RENAME_NOREPLACE);
const int err = ::to_neg_errno(rv);
if((err == -EINVAL) || (err == -ENOSYS))
return -EOPNOTSUPP;
return err;
#else
return -EOPNOTSUPP;
#endif
}
}

File diff suppressed because it is too large Load diff

View file

@ -26,5 +26,6 @@ namespace FUSE
int
rename(const fuse_req_ctx_t *ctx,
const char *from,
const char *to);
const char *to,
char **relocated = nullptr);
}

View file

@ -18,24 +18,41 @@
#include "fuse_symlink.hpp"
#include "branches.hpp"
#include "config.hpp"
#include "errno.hpp"
#include "error.hpp"
#include "fs_clonepath.hpp"
#include "fs_lchown.hpp"
#include "fs_close.hpp"
#include "fs_fstat.hpp"
#include "fs_is_rofs.hpp"
#include "fs_is_same_file.hpp"
#include "fs_lstat.hpp"
#include "fs_mkdirat.hpp"
#include "fs_open.hpp"
#include "fs_openat.hpp"
#include "fs_path.hpp"
#include "fs_inode.hpp"
#include "fs_renameat.hpp"
#include "fs_symlink.hpp"
#include "fs_symlink_as.hpp"
#include "fs_unlink.hpp"
#include "fuse_getattr.hpp"
#include "rnd.hpp"
#include "syslog.hpp"
#include "to_neg_errno.hpp"
#include "ugid.hpp"
#include "fuse.h"
#include "scope_guard/scope_guard.hpp"
#include <algorithm>
#include <fcntl.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <vector>
enum class SymlinkMode
{
@ -44,6 +61,253 @@ enum class SymlinkMode
};
#if defined(__linux__) || \
(defined(__FreeBSD__) && defined(AT_EMPTY_PATH) && defined(O_PATH))
static constexpr char SYMLINK_EXDEV_DIR[] = ".mergerfs_symlink_exdev";
// This single hidden root is private to the daemon. Opening it by
// descriptor and rejecting group/other access prevents another user
// from replacing a staged name while it is being fixed up or published.
static
int
_symlink_open_staging_root(const fs::path &branch_)
{
int rv;
struct stat st;
const int dirflags = (O_RDONLY|O_DIRECTORY|O_CLOEXEC);
const int branchfd = fs::open(branch_.c_str(),dirflags);
if(branchfd < 0)
return branchfd;
DEFER { fs::close(branchfd); };
rv = fs::mkdirat(branchfd,SYMLINK_EXDEV_DIR,0700);
if((rv < 0) && (rv != -EEXIST))
return rv;
const int stagefd = fs::openat(branchfd,
SYMLINK_EXDEV_DIR,
dirflags|O_NOFOLLOW);
if(stagefd < 0)
return stagefd;
rv = fs::fstat(stagefd,&st);
if(rv < 0)
{
fs::close(stagefd);
return rv;
}
if(!S_ISDIR(st.st_mode) ||
(st.st_uid != ::geteuid()) ||
(st.st_mode & 077))
{
fs::close(stagefd);
return -EPERM;
}
// Clear an inherited setgid bit on our pinned directory so creation
// with source credentials yields the source UID and GID without
// depending on CAP_CHOWN. Publication preserves those IDs.
if(st.st_mode & S_ISGID)
{
rv = ::to_neg_errno(::fchmod(stagefd,
st.st_mode & 07777 & ~S_ISGID));
if(rv < 0)
{
fs::close(stagefd);
return rv;
}
}
return stagefd;
}
// Create the symlink through the private staging directory and publish
// it at `linkpath_`. When the creation is finally verified the
// identity of the new link is taken from the pinned descriptor
// (`dev_`/`ino_`), before the staged link is released to its public
// name; the caller must not rediscover it by querying the public path.
static
int
_symlink_staged(const ugid_t ugid_,
const char *target_,
const fs::path &branch_,
const fs::path &linkpath_,
dev_t *dev_,
ino_t *ino_)
{
int rv;
struct stat st;
std::string stagedname;
const int dirflags = (O_RDONLY|O_DIRECTORY|O_CLOEXEC);
const int parentfd = fs::open(linkpath_.parent_path().c_str(),dirflags);
if(parentfd < 0)
return parentfd;
DEFER { fs::close(parentfd); };
const int stagefd = ::_symlink_open_staging_root(branch_);
if(stagefd < 0)
return -EXDEV;
DEFER { fs::close(stagefd); };
rv = -EEXIST;
for(int attempt = 0; attempt < 16; ++attempt)
{
stagedname = std::to_string(RND::rand64());
#if defined __linux__
{
const ugid::SetGuard _(ugid_);
rv = ::to_neg_errno(::symlinkat(target_,
stagefd,
stagedname.c_str()));
}
if((rv == -EACCES) || (rv == -EPERM))
rv = ::to_neg_errno(::symlinkat(target_,
stagefd,
stagedname.c_str()));
#else
rv = ::to_neg_errno(::symlinkat(target_,
stagefd,
stagedname.c_str()));
#endif
if(rv != -EEXIST)
break;
}
if(rv < 0)
return rv;
// Only clean up a name in the pinned private staging directory. Never
// unlink the public destination on an ownership or publication error.
bool staged = true;
DEFER { if(staged) ::unlinkat(stagefd,stagedname.c_str(),0); };
const int pin = fs::openat(stagefd,
stagedname,
O_PATH|O_NOFOLLOW|O_CLOEXEC);
if(pin < 0)
return pin;
DEFER { fs::close(pin); };
rv = fs::fstat(pin,&st);
if(rv < 0)
return rv;
if(!S_ISLNK(st.st_mode))
return -EPERM;
if((st.st_uid != ugid_.uid) || (st.st_gid != ugid_.gid))
{
if(::fchownat(pin,"",ugid_.uid,ugid_.gid,AT_EMPTY_PATH) < 0)
return -EXDEV;
rv = fs::fstat(pin,&st);
if(rv < 0)
return rv;
if((st.st_uid != ugid_.uid) || (st.st_gid != ugid_.gid))
return -EXDEV;
}
// The staged link's identity is final now: publication either moves
// this inode or links it, never replaces it.
if(dev_ != NULL)
*dev_ = st.st_dev;
if(ino_ != NULL)
*ino_ = st.st_ino;
const std::string filename = linkpath_.filename().string();
#if defined __linux__
rv = fs::renameat_noreplace(stagefd,stagedname,parentfd,filename);
if(rv == 0)
{
staged = false;
return 0;
}
if(rv != -EOPNOTSUPP)
return rv;
#endif
// The staged name cannot be replaced by another user. linkat with
// flags=0 links the symlink inode and cannot overwrite the destination.
return ::to_neg_errno(::linkat(stagefd,stagedname.c_str(),parentfd,filename.c_str(),0));
}
#endif
static
int
_symlink_preserve_owner(const ugid_t ugid_,
const char *target_,
const fs::path &branch_,
const fs::path &linkpath_,
dev_t *dev_,
ino_t *ino_)
{
#if defined(__linux__) || \
(defined(__FreeBSD__) && defined(AT_EMPTY_PATH) && defined(O_PATH))
return ::_symlink_staged(ugid_,target_,branch_,linkpath_,dev_,ino_);
#else
(void)dev_;
(void)ino_;
return -EXDEV;
#endif
}
static
bool
_protected_symlinks()
{
int fd;
char c = '1';
fd = ::open("/proc/sys/fs/protected_symlinks",O_RDONLY|O_CLOEXEC);
if(fd < 0)
return true;
if(::read(fd,&c,1) != 1)
c = '1';
::close(fd);
return (c != '0');
}
// With fs.protected_symlinks (on by default) a symlink in a sticky,
// world-writable directory can only be followed by its owner, root
// included, unless the directory's owner also owns it. A replacement
// symlink owned by the source's owner there would be unusable by
// everyone else, so refuse to create one. The EXDEV fallbacks then
// return EXDEV, as when they are disabled (`mv` copies instead).
static
int
_symlink_check_followable(const fs::path &dirpath_,
const fs::path &clonedirpath_,
const ugid_t ugid_)
{
#if defined __linux__
int rv;
struct stat st;
rv = fs::lstat(dirpath_,&st);
if(rv == -ENOENT)
rv = fs::lstat(clonedirpath_,&st);
if(rv < 0)
return 0;
if((st.st_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH))
return 0;
if(st.st_uid == ugid_.uid)
return 0;
if(!::_protected_symlinks())
return 0;
return -EXDEV;
#else
(void)dirpath_;
(void)clonedirpath_;
(void)ugid_;
return 0;
#endif
}
// `dev_`/`ino_` are only set by the PRESERVE_OWNER mode, where the
// new link is created through a pinned descriptor; the aggregate
// paths pass NULL and never report an identity.
static
int
_symlink_loop_core(const ugid_t ugid_,
@ -51,7 +315,9 @@ _symlink_loop_core(const ugid_t ugid_,
const fs::path &newbranch_,
const char *target_,
const fs::path &linkpath_,
struct stat *st_)
struct stat *st_,
dev_t *dev_,
ino_t *ino_)
{
int rv;
fs::path fullnewpath;
@ -59,23 +325,7 @@ _symlink_loop_core(const ugid_t ugid_,
fullnewpath = newbranch_ / linkpath_;
if(mode_ == SymlinkMode::PRESERVE_OWNER)
{
struct stat owner{};
owner.st_uid = ugid_.uid;
owner.st_gid = ugid_.gid;
rv = fs::symlink(target_,fullnewpath.native());
if(rv < 0)
return rv;
rv = fs::lchown_check_on_error(fullnewpath.native(),owner);
if(rv < 0)
{
fs::unlink(fullnewpath.native());
return rv;
}
}
rv = ::_symlink_preserve_owner(ugid_,target_,newbranch_,fullnewpath,dev_,ino_);
else
rv = fs::symlink_as(ugid_,target_,fullnewpath);
@ -100,7 +350,9 @@ _symlink_loop(const ugid_t ugid_,
const char *target_,
const fs::path &linkpath_,
const fs::path &newdirpath_,
struct stat *st_)
struct stat *st_,
dev_t *dev_,
ino_t *ino_)
{
int rv;
Err err;
@ -118,7 +370,9 @@ _symlink_loop(const ugid_t ugid_,
newbranch->path,
target_,
linkpath_,
st_);
st_,
dev_,
ino_);
}
return err;
@ -154,6 +408,22 @@ _symlink(const ugid_t ugid_,
if(newbranches.empty())
return -ENOENT;
// Check every destination before cloning or creating anything. A
// missing destination inherits the source directory's owner and mode.
if(mode_ == SymlinkMode::PRESERVE_OWNER)
{
const fs::path clonedirpath = existingbranches[0]->path / newdirpath;
for(auto &newbranch : newbranches)
{
rv = ::_symlink_check_followable(newbranch->path / newdirpath,
clonedirpath,
ugid_);
if(rv < 0)
return rv;
}
}
return ::_symlink_loop(ugid_,
mode_,
existingbranches[0]->path,
@ -161,7 +431,172 @@ _symlink(const ugid_t ugid_,
target_,
linkpath_,
newdirpath,
st_);
st_,
NULL,
NULL);
}
// The rename fallback's strict preparation: like `_symlink` with
// PRESERVE_OWNER, but bound to the caller's branch set and with the
// opposite failure contract. Every selected branch must end up with
// the link; the first branch which fails ends the loop and the caller
// learns of it together with the links which were already created.
// `prepared_` is expected to be empty.
static
int
_symlink_prepare(const Branches::Ptr &branches_,
const ugid_t owner_,
const char *target_,
const fs::path &linkpath_,
std::vector<FUSE::PreparedSymlink> &prepared_)
{
int rv;
fs::path newdirpath;
std::vector<Branch*> newbranches;
std::vector<Branch*> existingbranches;
newdirpath = linkpath_.parent_path();
rv = cfg.func.getattr.policy(branches_,newdirpath,existingbranches);
if(rv < 0)
return rv;
if(existingbranches.empty())
return -ENOENT;
rv = cfg.func.symlink.policy(branches_,newdirpath,newbranches);
if(rv < 0)
return rv;
if(newbranches.empty())
return -ENOENT;
// Check every destination before cloning or creating anything. A
// missing destination inherits the source directory's owner and mode.
{
const fs::path clonedirpath = existingbranches[0]->path / newdirpath;
for(auto &newbranch : newbranches)
{
rv = ::_symlink_check_followable(newbranch->path / newdirpath,
clonedirpath,
owner_);
if(rv < 0)
return rv;
}
}
for(auto &newbranch : newbranches)
{
dev_t dev;
ino_t ino;
const fs::path fullnewpath = newbranch->path / linkpath_;
rv = fs::clonepath(existingbranches[0]->path,
newbranch->path,
newdirpath);
if(rv < 0)
return rv;
rv = ::_symlink_staged(owner_,target_,newbranch->path,fullnewpath,&dev,&ino);
if(rv < 0)
return rv;
FUSE::PreparedSymlink record;
record.branch = newbranch->path;
record.path = fullnewpath;
record.dev = dev;
record.ino = ino;
prepared_.emplace_back(std::move(record));
}
return 0;
}
// A copy of the caller's branch set with every branch on a read-only
// filesystem marked, so the create policy skips them on the retry
// after EROFS. The caller's snapshot is never modified, and the copy
// shares the branch paths of the request the caller is serving.
static
Branches::Ptr
_branches_mark_ro_filesystems(const Branches::Ptr &branches_)
{
Branches::Ptr copy;
copy = std::make_shared<Branches::Impl>(&cfg.branches.minfreespace);
*copy = *branches_;
for(auto &branch : *copy)
{
if((branch.mode != Branch::Mode::RW) ||
!fs::is_rofs_but_not_mounted_ro(branch.path))
continue;
branch.mode = Branch::Mode::RO;
}
return copy;
}
int
FUSE::symlink_prepare(const Branches::Ptr &branches_,
const ugid_t owner_,
const char *target_,
const fs::path &linkpath_,
std::vector<PreparedSymlink> &prepared_)
{
int rv;
prepared_.clear();
rv = ::_symlink_prepare(branches_,owner_,target_,linkpath_,prepared_);
if(rv != -EROFS)
return rv;
// The links of the failed attempt must not outlive it, and the same
// name cannot be reused for the retry.
symlink_unprepare(prepared_);
// As with the ordinary symlink call, filesystems which turned
// read-only are recorded globally. The retry still uses the
// request's branch set: a local copy with those branches marked,
// never a fresh snapshot of the current configuration.
cfg.branches.find_and_set_mode_ro();
return ::_symlink_prepare(::_branches_mark_ro_filesystems(branches_),
owner_,target_,linkpath_,prepared_);
}
void
FUSE::symlink_unprepare(std::vector<PreparedSymlink> &prepared_)
{
for(const auto &record : prepared_)
{
int rv;
rv = fs::is_same_file(record.path,record.dev,record.ino);
if(rv == -ENOENT)
continue;
if(rv < 0)
{
SysLog::warning("rename-exdev: could not inspect prepared link {} (errno={})",
record.path.string(),
-rv);
continue;
}
if(rv == 0)
{
SysLog::warning("rename-exdev: {} no longer refers to the prepared link; leaving it alone",
record.path.string());
continue;
}
rv = fs::unlink(record.path);
if(rv < 0)
SysLog::error("rename-exdev: could not remove prepared link {} (errno={})",
record.path.string(),
-rv);
}
prepared_.clear();
}
static

View file

@ -18,17 +18,32 @@
#pragma once
#include "branches.hpp"
#include "fuse.h"
#include "fs_path.hpp"
#include "ugid.hpp"
#include <string>
#include <vector>
#include <sys/stat.h>
namespace FUSE
{
// A replacement symlink which was actually created on one branch of
// the caller's branch set. The identity is read from the freshly
// created link through its pinned descriptor before it is published,
// so a later match against it proves an object is the link this
// request created; it is never taken from a later lookup.
struct PreparedSymlink
{
fs::path branch;
fs::path path;
dev_t dev;
ino_t ino;
};
int
symlink(const fuse_req_ctx_t *ctx,
const char *target,
@ -42,4 +57,24 @@ namespace FUSE
const fs::path &linkpath,
struct stat *st = NULL,
fuse_timeouts_t *timeouts = NULL);
// Create the link `linkpath_` (pool relative) on every branch the
// symlink create policy selects within `branches_`, owned by
// `owner_`, using exactly the caller's branch set. All-or-fail: on
// success `prepared_` records every creation, on failure it records
// only the branches where creation succeeded so the caller can undo
// them with symlink_unprepare(). `prepared_` is cleared first; its
// records are only ever successful creations.
int
symlink_prepare(const Branches::Ptr &branches,
const ugid_t owner,
const char *target,
const fs::path &linkpath,
std::vector<PreparedSymlink> &prepared);
// Remove prepared links this request created. A name which no longer
// refers to the recorded identity is not ours and is left in place.
// On return `prepared` is empty.
void
symlink_unprepare(std::vector<PreparedSymlink> &prepared);
}

View file

@ -0,0 +1,30 @@
/*
ISC License
Copyright (c) 2026, Antonio SJ Musumeci <trapexit@spawn.link>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <string>
// Branch-relative directory where the rename-exdev fallback stages an
// inode it cannot rename into place, and under which the published
// replacement symlinks resolve. Every fusepath beneath this component
// denotes a staged entry rather than an ordinary file.
namespace rename_exdev
{
static const std::string STAGING_DIR = ".mergerfs_rename_exdev";
}