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

View file

@ -2,6 +2,7 @@
import errno
import os
import re
import sys
import uuid
from os.path import join
@ -26,7 +27,8 @@ def get_errno(func):
def require_symlink(path, expected, label):
# Inspect the backend: rename/link can leave a cached regular pool inode.
# Inspect the backend: through the pool dst can still be the cached
# regular inode of the source until the kernel revalidates it.
if not os.path.islink(path):
return f"{label}: expected backend symlink fallback"
target = os.readlink(path)
@ -35,6 +37,45 @@ def require_symlink(path, expected, label):
return None
def require_rename_relocation(link_path, pool_dst, mount, mode, src_rel, label):
if not os.path.islink(link_path):
return None, f"{label}: expected backend symlink fallback"
target = os.readlink(link_path)
if mode == "rel-symlink":
if os.path.isabs(target):
return None, f"{label}: relative mode returned absolute target {target!r}"
pool_target = os.path.normpath(join(os.path.dirname(pool_dst), target))
else:
pool_target = target
expected_prefix = join(mount, ".mergerfs_rename_exdev") + os.sep
if not pool_target.startswith(expected_prefix):
return None, f"{label}: absolute target {target!r} is outside staging"
mount_prefix = mount.rstrip(os.sep) + os.sep
if not pool_target.startswith(mount_prefix):
return None, f"{label}: target {pool_target!r} escapes the pool"
relocated = os.path.relpath(pool_target, mount)
native = join(".mergerfs_rename_exdev", src_rel)
portable_suffix = join(os.path.dirname(src_rel), ".payload", os.path.basename(src_rel))
portable = re.fullmatch(
re.escape(join(".mergerfs_rename_exdev", ""))
+ r"\.p-[0-9a-f]{16}/" + re.escape(portable_suffix),
relocated,
)
if relocated != native and portable is None:
return None, f"{label}: invalid relocated target {relocated!r}"
expected = (
os.path.relpath(pool_target, os.path.dirname(pool_dst))
if mode == "rel-symlink"
else pool_target
)
if target != expected:
return None, f"{label}: target {target!r} != {expected!r}"
return relocated, None
def require_payload(path, label):
with open(path, "rb") as fp:
if fp.read() != b"src":
@ -123,11 +164,20 @@ def main():
err = get_errno(lambda: os.rename(src, dst))
if err != 0:
return fail(f"rename-exdev={mode}, root={root} returned errno={err}")
staged_rel = join(".mergerfs_rename_exdev", src_rel)
pool_target = join(mount, staged_rel)
expected = os.path.relpath(pool_target, os.path.dirname(dst)) if mode == "rel-symlink" else pool_target
label = f"rename-exdev={mode}, root={root}"
err_msg = require_symlink(join(branches[1], dst_rel), expected, label)
# The kernel still has the source's inode at dst. Using
# it must not fail (it used to return EIO as the inode
# appeared to change type).
try:
os.lstat(dst)
with open(dst, "rb") as fp:
if fp.read() != b"src":
return fail(f"{label}: pool payload mismatch")
except OSError as exc:
return fail(f"{label}: pool access after rename failed, errno={exc.errno}")
staged_rel, err_msg = require_rename_relocation(
join(branches[1], dst_rel), dst, mount, mode, src_rel, label
)
if err_msg:
return fail(err_msg)
if os.path.lexists(join(branches[0], src_rel)):
@ -143,11 +193,10 @@ def main():
finally:
for branch in branches:
cleanup_dir(join(branch, rel_base))
cleanup_dir(join(branch, ".mergerfs_rename_exdev", rel_base))
for src_rel in root_sources:
for path in (join(branch, src_rel), join(branch, ".mergerfs_rename_exdev", src_rel)):
if os.path.lexists(path):
os.unlink(path)
if os.path.lexists(join(branch, src_rel)):
os.unlink(join(branch, src_rel))
cleanup_dir(join(branch, ".mergerfs_rename_exdev"))
except RuntimeError as exc:
if str(exc) in ("mergerfs binary not found", "fusermount3/fusermount not found"):
print(str(exc), end="")

334
tests/TEST_rename_exdev_portable Executable file
View file

@ -0,0 +1,334 @@
#!/usr/bin/env python3
import ctypes
import errno
import os
import re
import shutil
import subprocess
import sys
import uuid
from os.path import join
import posix_parity
from posix_parity import fail
from posix_parity import mergerfs_get_option
from posix_parity import mergerfs_set_option
from posix_parity import touch
SKIP = 77
class CheckError(Exception):
pass
class SkipTest(Exception):
pass
def require(condition, message):
if not condition:
raise CheckError(message)
def get_errno(func):
try:
func()
return 0
except OSError as exc:
return exc.errno
def portable_relocation(link_path, pool_dst, mount, mode, src_rel):
require(os.path.islink(link_path), f"missing backend symlink: {link_path}")
target = os.readlink(link_path)
if mode == "rel-symlink":
require(not os.path.isabs(target), f"relative mode returned {target!r}")
pool_target = os.path.normpath(join(os.path.dirname(pool_dst), target))
else:
pool_target = target
mount_prefix = mount.rstrip(os.sep) + os.sep
require(pool_target.startswith(mount_prefix), f"target escaped pool: {pool_target!r}")
relocated = os.path.relpath(pool_target, mount)
suffix = join(os.path.dirname(src_rel), ".payload", os.path.basename(src_rel))
match = re.fullmatch(
re.escape(join(".mergerfs_rename_exdev", ""))
+ r"(\.p-[0-9a-f]{16})/" + re.escape(suffix),
relocated,
)
require(match is not None, f"not a portable relocation: {relocated!r}")
expected = (
os.path.relpath(pool_target, os.path.dirname(pool_dst))
if mode == "rel-symlink"
else pool_target
)
require(target == expected, f"target {target!r} != {expected!r}")
return relocated, match.group(1)
def mode_bits(st):
return st.st_mode & 0o7777
def disable_renameat2():
# This test process and the daemon it launches inherit the restriction.
# Unlike a tracer, this does not prevent LeakSanitizer checking daemon exit.
try:
lib = ctypes.CDLL("libseccomp.so.2")
except OSError as exc:
raise SkipTest("libseccomp is needed for the forced portable case") from exc
ptr, uint, sint = ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int
lib.seccomp_init.argtypes = [uint]
lib.seccomp_init.restype = ptr
lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p]
lib.seccomp_rule_add.argtypes = [ptr, uint, sint, ctypes.c_uint]
lib.seccomp_load.argtypes = [ptr]
lib.seccomp_release.argtypes = [ptr]
lib.seccomp_release.restype = None
number = lib.seccomp_syscall_resolve_name(b"renameat2")
if number < 0:
raise SkipTest("libseccomp does not recognize renameat2 on this architecture")
allow = 0x7fff0000 # SCMP_ACT_ALLOW
deny = 0x00050000 | errno.ENOSYS # SCMP_ACT_ERRNO(ENOSYS)
ctx = lib.seccomp_init(allow)
if not ctx:
raise CheckError("could not allocate syscall filter")
try:
require(lib.seccomp_rule_add(ctx, deny, number, 0) == 0, "cannot restrict renameat2")
rc = lib.seccomp_load(ctx)
if rc in (-errno.EPERM, -errno.EACCES, -errno.EOPNOTSUPP):
raise SkipTest("kernel does not allow the test's syscall filter")
require(rc == 0, f"seccomp_load returned {rc}")
finally:
lib.seccomp_release(ctx)
def run_case(mount, branches, mode, directory, sequence):
rel_base = f".mergerfs_portable_test_{os.getpid()}_{uuid.uuid4().hex}"
name = f"case_{sequence}"
# A user component named .payload must not collide with an internal link.
parent = join(rel_base, ".payload")
src_rel = join(parent, name + ".src") if directory else f"{rel_base}_{name}.src"
dst_rel = join(rel_base, "dst", "nested", name)
src = join(mount, src_rel)
dst = join(mount, dst_rel)
os.makedirs(join(branches[0], os.path.dirname(src_rel)), exist_ok=True)
os.makedirs(join(branches[1], os.path.dirname(dst_rel)), exist_ok=True)
if directory:
os.chmod(join(branches[0], parent), 0o700)
source_parent_stat = os.stat(join(branches[0], parent))
os.mkdir(join(branches[0], src_rel), 0o751)
touch(join(branches[0], src_rel, "child"), b"src")
else:
source_parent_stat = None
touch(join(branches[0], src_rel), b"src")
source_stat = os.lstat(join(branches[0], src_rel))
legacy = join(branches[0], ".mergerfs_rename_exdev", src_rel)
os.makedirs(os.path.dirname(legacy), exist_ok=True)
touch(legacy, b"legacy-must-survive")
mergerfs_set_option(mount, "rename-exdev", mode)
err = get_errno(lambda: os.rename(src, dst))
require(err == 0, f"{mode}, directory={directory}: rename errno={err}")
relocated, wrapper = portable_relocation(
join(branches[1], dst_rel), dst, mount, mode, src_rel
)
staged = join(branches[0], relocated)
require(not os.path.lexists(join(branches[0], src_rel)), "source remains after rename")
require(os.stat(staged).st_ino == source_stat.st_ino, "source inode changed")
with open(join(staged, "child") if directory else staged, "rb") as fp:
require(fp.read() == b"src", "staged payload mismatch")
with open(join(dst, "child") if directory else dst, "rb") as fp:
require(fp.read() == b"src", "pool payload mismatch")
with open(legacy, "rb") as fp:
require(fp.read() == b"legacy-must-survive", "legacy entry was overwritten")
wrapper_path = join(branches[0], ".mergerfs_rename_exdev", wrapper)
wrapper_stat = os.stat(wrapper_path)
require(wrapper_stat.st_uid == os.geteuid(), "wrapper is not daemon owned")
require(mode_bits(wrapper_stat) == 0o555, "wrapper is publicly writable or restrictive")
parent_rel = os.path.dirname(src_rel)
gate_path = join(wrapper_path, parent_rel)
# The payload must be below the mirrored parents, not available by
# a shorter route which omits their search permissions.
payload_dir = join(gate_path, ".payload")
payload_stat = os.lstat(payload_dir)
require(payload_stat.st_uid == os.geteuid(), "payload parent is not daemon owned")
require(mode_bits(payload_stat) == 0o555, "payload parent is not 0555")
require(os.path.isdir(payload_dir) and not os.path.islink(payload_dir),
"payload directory is not physically below its gates")
if source_parent_stat is not None:
require(not os.path.lexists(join(wrapper_path, ".payload")),
"payload is reachable without traversing the source's parents")
gate_stat = os.lstat(gate_path)
require(gate_stat.st_uid == source_parent_stat.st_uid, "gate UID mismatch")
require(gate_stat.st_gid == source_parent_stat.st_gid, "gate GID mismatch")
# The daemon keeps the ancestor's read/search permissions, not write access.
expect = mode_bits(source_parent_stat) & 0o555
require(mode_bits(gate_stat) == expect, "gate mode mismatch")
def rejected_setup_leaves_nothing(mount, branches):
# A rejected request must not leave a portable namespace behind. A
# nontrivial ACL on the source parent is refused before the move.
if shutil.which("setfacl") is None:
return
rel_base = f".mergerfs_portable_acl_{os.getpid()}_{uuid.uuid4().hex}"
src_rel = join(rel_base, "acl", "source")
dst_rel = join(rel_base, "dst", "source")
touch(join(branches[0], src_rel), b"acl")
os.makedirs(join(branches[1], os.path.dirname(dst_rel)), exist_ok=True)
acl = subprocess.run(["setfacl", "-m", f"u:{os.geteuid()}:rwx",
join(branches[0], os.path.dirname(src_rel))],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if acl.returncode:
return
def portable_namespaces():
staging = join(branches[0], ".mergerfs_rename_exdev")
if not os.path.isdir(staging):
return set()
return {name for name in os.listdir(staging) if name.startswith(".p-")}
before = portable_namespaces()
mergerfs_set_option(mount, "rename-exdev", "rel-symlink")
for _ in range(3):
err = get_errno(lambda: os.rename(join(mount, src_rel), join(mount, dst_rel)))
require(err == errno.EXDEV, f"ACL rejection returned errno={err}")
after = portable_namespaces()
require(after == before, f"rejected renames left {sorted(after - before)}")
with open(join(branches[0], src_rel), "rb") as fp:
require(fp.read() == b"acl", "rejected rename changed the source")
def foreign_parent_is_refused(mount, branches):
srcdir = join(branches[0], "foreign-parent")
src = join(srcdir, "source")
out = join(branches[1], "foreign-out")
touch(src, b"unchanged")
os.mkdir(out)
try:
os.chown(srcdir, 1 if os.geteuid() != 1 else 2, -1)
except OSError as exc:
if exc.errno not in (errno.EPERM, errno.EINVAL, errno.EACCES):
raise
print("SKIP foreign parent: needs a second mapped UID")
return
mergerfs_set_option(mount, "rename-exdev", "rel-symlink")
staging = join(branches[0], ".mergerfs_rename_exdev")
before = {name for name in os.listdir(staging) if name.startswith(".p-")}
err = get_errno(lambda: os.rename(join(mount, "foreign-parent", "source"),
join(mount, "foreign-out", "dest")))
require(err == errno.EXDEV, f"foreign-parent rename returned {err}, expected EXDEV")
with open(src, "rb") as fp:
require(fp.read() == b"unchanged", "refused rename changed the source")
require(not os.listdir(out), "refused rename published a destination")
after = {name for name in os.listdir(staging) if name.startswith(".p-")}
require(after == before, "refused rename left a portable namespace")
def portable_directory_destination_refused(mount, branches):
# An existing directory destination cannot be kept without atomic
# no-replace rename, and a moved portable directory cannot be
# unstaged. The fallback must refuse such a rename before the
# source moves, leaving source and destination exactly as they
# were, with no portable namespace and no replacement link behind.
rel_base = f".mergerfs_portable_refuse_{os.getpid()}_{uuid.uuid4().hex}"
src_rel = join(rel_base, "srcdir")
dst_rel = join(rel_base, "dst", "nested", "dstdir")
src = join(branches[0], src_rel)
dst = join(branches[1], dst_rel)
os.makedirs(join(branches[0], rel_base))
os.makedirs(join(branches[1], os.path.dirname(dst_rel)))
os.mkdir(src, 0o750)
touch(join(src, "child"), b"src")
os.mkdir(dst)
def residue():
paths = set()
for branch in branches:
for directory, prefix in ((".mergerfs_rename_exdev", ".p-"),
(os.path.dirname(dst_rel), ".mergerfs_rename_exdev_")):
path = join(branch, directory)
if os.path.isdir(path):
paths.update(join(path, n) for n in os.listdir(path) if n.startswith(prefix))
return paths
src_stat, dst_stat = os.lstat(src), os.lstat(dst)
before = residue()
for mode in ("rel-symlink", "abs-symlink"):
mergerfs_set_option(mount, "rename-exdev", mode)
err = get_errno(lambda: os.rename(join(mount, src_rel),
join(mount, dst_rel)))
require(os.path.isdir(src), f"{mode}: source directory missing after refusal (errno={err})")
require(os.path.samestat(src_stat, os.lstat(src)), f"{mode}: source directory changed")
require(os.path.samestat(dst_stat, os.lstat(dst)), f"{mode}: destination directory changed")
with open(join(mount, src_rel, "child"), "rb") as fp:
require(fp.read() == b"src", f"{mode}: source child bytes changed")
require(not os.listdir(dst), f"{mode}: destination is no longer empty")
require(residue() == before, f"{mode}: refusal left staging or replacement names")
require(err == errno.EXDEV, f"{mode}: expected EXDEV, got errno={err}")
def isolated():
options = "defaults,use_ino,category.create=mfs,minfreespace=0"
try:
if sys.platform.startswith("linux"):
disable_renameat2()
with posix_parity.mergerfs_mount(options=options) as (mount, branches):
original_create = mergerfs_get_option(mount, "category.create")
original_rename = mergerfs_get_option(mount, "rename-exdev")
try:
mergerfs_set_option(mount, "category.create", "epmfs")
sequence = 0
for directory in (False, True):
for mode in ("rel-symlink", "abs-symlink"):
run_case(mount, branches, mode, directory, sequence)
sequence += 1
rejected_setup_leaves_nothing(mount, branches)
foreign_parent_is_refused(mount, branches)
portable_directory_destination_refused(mount, branches)
finally:
mergerfs_set_option(mount, "category.create", original_create)
mergerfs_set_option(mount, "rename-exdev", original_rename)
return 0
except SkipTest as exc:
print(str(exc), end="")
return SKIP
except RuntimeError as exc:
if str(exc) in ("mergerfs binary not found", "fusermount3/fusermount not found"):
print(str(exc), end="")
return SKIP
return fail(f"portable EXDEV test failed: {exc}")
except (CheckError, OSError) as exc:
return fail(f"portable EXDEV test failed: {exc}")
def main():
if not sys.platform.startswith("linux"):
return isolated()
if len(sys.argv) == 2 and sys.argv[1] == "--isolated":
return isolated()
# The seccomp filter sets no_new_privs, which a setuid fusermount
# can't run under. Mount directly as root of a private namespace.
if shutil.which("unshare") is None:
print("unshare unavailable", end="")
return SKIP
namespace = ["unshare", "-Urm"]
probe = subprocess.run(namespace + ["true"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if probe.returncode:
print("private user/mount namespaces unavailable", end="")
return SKIP
return subprocess.run(namespace + [sys.executable, os.path.realpath(__file__),
"--isolated"]).returncode
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -0,0 +1,305 @@
#!/usr/bin/env python3
# rename-exdev publication and rollback: a failed publication on a
# later branch must restore the destinations already replaced, and a
# source symlink which can't be removed must fail the rename.
import errno
import os
import shutil
import subprocess
import sys
import tempfile
from os.path import join
from posix_parity import fail
from posix_parity import find_fusermount
from posix_parity import find_mergerfs
from posix_parity import is_mount_point
from posix_parity import mergerfs_get_option
from posix_parity import mergerfs_set_option
from posix_parity import mount_mergerfs
from posix_parity import touch
from posix_parity import unmount_mergerfs
SKIP = 77
OPTIONS = ("minfreespace=0,category.create=epmfs,func.symlink=epall,"
"rename-exdev=rel-symlink,cache.entry=0,cache.attr=0,"
"cache.negative_entry=0")
class Skip(Exception):
pass
def read(path):
with open(path, "rb") as fp:
return fp.read()
def rename_errno(src, dst):
try:
os.rename(src, dst)
return 0
except OSError as exc:
return exc.errno
def bind(source, target, readonly=False):
rv = subprocess.run(["mount", "--bind", source, target],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if rv.returncode:
raise Skip("bind mount unavailable: " + rv.stderr.decode(errors="replace"))
if readonly:
rv = subprocess.run(["mount", "-o", "remount,bind,ro", target],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if rv.returncode:
raise Skip("read-only bind mount unavailable: " +
rv.stderr.decode(errors="replace"))
def unbind(target):
subprocess.run(["umount", "--lazy", target], check=False,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def check_regular(path, data, label):
if os.path.islink(path) or not os.path.isfile(path):
return f"{label}: {path} is not a regular file"
if read(path) != data:
return f"{label}: {path} has {read(path)!r}, expected {data!r}"
return None
def check_only(directory, names, label):
entries = sorted(os.listdir(directory))
if entries != sorted(names):
return f"{label}: {directory} has {entries}, expected {sorted(names)}"
return None
def published(branches, pool):
# Control: publication on both destination branches succeeds and
# leaves no temporary names behind.
touch(join(branches[0], "pub", "source"), b"SOURCE")
for i in (1, 2):
touch(join(branches[i], "pubout", "dest"), f"OLD-B{i}".encode())
err = rename_errno(join(pool, "pub", "source"), join(pool, "pubout", "dest"))
if err:
return f"control rename failed: {errno.errorcode.get(err, err)}"
for i in (1, 2):
dest = join(branches[i], "pubout", "dest")
if not os.path.islink(dest):
return f"control: b{i} destination is not the replacement symlink"
msg = check_only(join(branches[i], "pubout"), ["dest"], "control")
if msg:
return msg
# The payload is staged on b0 only. Resolve the link there rather than
# through the pool so the kernel's cached source node doesn't matter.
link = join(branches[1], "pubout", "dest")
payload = os.path.normpath(join(branches[0], "pubout", os.readlink(link)))
if read(payload) != b"SOURCE":
return "control: destination does not reach the payload"
return None
def partial_publication(branches, pool):
touch(join(branches[0], "work", "source"), b"SOURCE")
for i in (1, 2):
touch(join(branches[i], "out", "dest"), f"OLD-B{i}".encode())
# Renaming over a mount point fails with EBUSY, so publication on the
# second branch fails after the first one was replaced.
busy = join(branches[2], "out", "dest")
bind(busy, busy)
try:
err = rename_errno(join(pool, "work", "source"), join(pool, "out", "dest"))
finally:
unbind(busy)
if err != errno.EBUSY:
return f"partial publication returned {errno.errorcode.get(err, err)}, expected EBUSY"
for msg in (check_regular(join(branches[0], "work", "source"), b"SOURCE", "source"),
check_regular(join(branches[1], "out", "dest"), b"OLD-B1", "b1 destination"),
check_regular(join(branches[2], "out", "dest"), b"OLD-B2", "b2 destination"),
check_only(join(branches[1], "out"), ["dest"], "b1"),
check_only(join(branches[2], "out"), ["dest"], "b2")):
if msg:
return msg
return None
def unremovable_symlink_source(branches, pool):
src = join(branches[0], "lnk", "link")
os.makedirs(os.path.dirname(src))
os.symlink("../relative/target", src)
os.makedirs(join(branches[1], "out2"))
srcdir = os.path.dirname(src)
bind(srcdir, srcdir, readonly=True)
try:
err = rename_errno(join(pool, "lnk", "link"), join(pool, "out2", "link"))
finally:
unbind(srcdir)
if err == 0:
return "symlink source rename succeeded although the source can't be removed"
if not os.path.islink(src) or os.readlink(src) != "../relative/target":
return "symlink source changed after a failed rename"
return check_only(join(branches[1], "out2"), [], "symlink destination")
def mixed_source_types(branches, pool):
# epall sees two different objects at one name. Recreating the first
# link is not permission to discard the second branch's regular file.
src = join("mixed", "source")
dst = join("mixed-out", "dest")
os.mkdir(join(branches[0], "mixed"))
os.symlink("link-text", join(branches[0], src))
touch(join(branches[1], src), b"independent bytes")
os.mkdir(join(branches[2], "mixed-out"))
if not rename_errno(join(pool, src), join(pool, dst)):
return "rename of mixed source types succeeded"
if os.readlink(join(pool, src)) != "link-text" or os.path.lexists(join(pool, dst)):
return "refused rename changed the visible names"
msg = check_regular(join(branches[1], src), b"independent bytes", "hidden source")
if msg:
return msg
# The same refusal when the first branch holds the regular file and
# a later one the symlink: staging would move the link one directory
# deeper, where its relative target dangles.
src = join("mixed2", "source")
dst = join("mixed2-out", "dest")
os.mkdir(join(branches[0], "mixed2"))
touch(join(branches[0], src), b"file bytes")
os.mkdir(join(branches[1], "mixed2"))
os.symlink("link-text", join(branches[1], src))
os.mkdir(join(branches[2], "mixed2-out"))
err = rename_errno(join(pool, src), join(pool, dst))
if err != errno.EXDEV:
return (f"file-first rename of mixed source types returned "
f"{errno.errorcode.get(err, err)}, expected EXDEV")
if read(join(pool, src)) != b"file bytes":
return "file-first refusal changed the visible source"
if os.readlink(join(branches[1], src)) != "link-text":
return "file-first refusal changed the hidden symlink"
if os.path.lexists(join(pool, dst)):
return "file-first refusal published a destination"
return None
def cross_branch_staging_collision(branches, pool):
# Recreate the same maximum-length source on a *different* branch.
# The destinations must resolve independently via the pool, not just
# to two intact backing inodes that happen to have the same union name.
src = join("versions", "x" * os.pathconf(branches[0], "PC_NAME_MAX"))
os.mkdir(join(branches[2], "versions-out"))
targets = []
for branch, name, data in zip(branches, ("first", "second"), (b"one", b"two")):
touch(join(branch, src), data)
dst = join("versions-out", name)
os.rename(join(pool, src), join(pool, dst))
target = os.readlink(join(branches[2], dst))
targets.append(os.path.normpath(join(pool, "versions-out", target)))
if targets[0] == targets[1]:
return "both published links use the same staged pool path"
if [read(target) for target in targets] != [b"one", b"two"]:
return "published targets resolve to the wrong generation through the pool"
if [read(join(pool, "versions-out", name)) for name in ("first", "second")] != [b"one", b"two"]:
return "pool destinations no longer read their respective contents"
return None
def destination_shadows(branches, pool):
original = mergerfs_get_option(pool, "branches")
try:
# A logical RO branch on writable media and a truly unremovable
# file on an NC branch both take precedence over the new link.
for case, mode, native in (("fallback-ro", "RO", False),
("ordinary-ro", "RO", True),
("busy-shadow", "NC", False)):
src = join(case + "-in", "src")
dst = join(case + "-out", "dst")
shadow = join(branches[0], dst)
touch(shadow, b"old")
touch(join(branches[1], src), b"new")
os.mkdir(join(branches[1 if native else 2], case + "-out"))
mergerfs_set_option(pool, "branches", ":".join([branches[0] + "=" + mode, *branches[1:]]))
if mode == "NC":
bind(shadow, shadow)
try:
err = rename_errno(join(pool, src), join(pool, dst))
finally:
if mode == "NC":
unbind(shadow)
if err == 0:
return f"{case}: rename acknowledged a shadowed destination"
if read(join(pool, src)) != b"new" or read(join(pool, dst)) != b"old":
return f"{case}: source or destination changed after refusal"
if any(os.path.lexists(join(branch, dst)) for branch in branches[1:]):
return f"{case}: unexpected published destination after refusal"
finally:
mergerfs_set_option(pool, "branches", original)
return None
def isolated():
root = tempfile.mkdtemp(prefix="mergerfs-exdev-publication-")
# A private tmpfs gives every run the same renameat2 and bind support.
rv = subprocess.run(["mount", "-t", "tmpfs", "tmpfs", root],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if rv.returncode:
shutil.rmtree(root, ignore_errors=True)
print("private tmpfs unavailable", end="")
return SKIP
branches = [join(root, f"b{i}") for i in range(3)]
pool = join(root, "pool")
for path in branches + [pool]:
os.mkdir(path)
try:
mount_mergerfs(branches, pool, OPTIONS)
try:
for case in (published, partial_publication, unremovable_symlink_source,
mixed_source_types, cross_branch_staging_collision, destination_shadows):
msg = case(branches, pool)
if msg:
return fail(f"{case.__name__}: {msg}")
finally:
unmount_mergerfs(pool)
return 0
except Skip as exc:
print(str(exc), end="")
return SKIP
finally:
unbind(root)
if is_mount_point(root):
raise OSError(f"could not detach tmpfs; preserved fixture at {root}")
shutil.rmtree(root)
def main():
if len(sys.argv) == 2 and sys.argv[1] == "--isolated":
return isolated()
if find_mergerfs() is None or find_fusermount() is None:
print("mergerfs or fusermount unavailable", end="")
return SKIP
if any(shutil.which(tool) is None for tool in ("unshare", "mount", "umount")):
print("unshare/mount/umount unavailable", end="")
return SKIP
# Bind mounts provide the failures; keep them in a private namespace.
namespace = ["unshare", "-Urm"]
probe = subprocess.run(namespace + ["true"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if probe.returncode:
print("private user/mount namespaces unavailable", end="")
return SKIP
return subprocess.run(namespace + [sys.executable, os.path.realpath(__file__),
"--isolated"]).returncode
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -3309,31 +3309,30 @@ test_rename_exdev_case(const char *mode_,
output << "existing destination";
}
const int rv = FUSE::rename(&ctx,fixture.source.c_str(),fixture.destination.c_str());
TEST_CHECK(rv == (occupied_ ? -EEXIST : 0));
if(occupied_)
{
check_exdev_payload(fixture.first / fixture.source);
check_exdev_payload(fixture.second / fixture.destination,"existing destination");
check_exdev_absent(fixture.first / fixture.staged());
struct stat restored = {};
TEST_CHECK(::lstat((fixture.first / fixture.source).c_str(),&restored) == 0);
TEST_CHECK(restored.st_ino == source_st.st_ino);
return;
}
if(rv != 0)
// Like rename(2) an existing destination is replaced.
char *relocated = NULL;
const int rv = FUSE::rename(&ctx,fixture.source.c_str(),fixture.destination.c_str(),
&relocated);
TEST_CHECK(rv == 0);
// libfuse needs to know where the source went (see relocate_node()).
TEST_CHECK(relocated != NULL);
const fs::path staged(relocated ? relocated : "");
::free(relocated);
if((rv != 0) || staged.empty())
return;
TEST_CHECK(staged.is_relative());
TEST_CHECK(*staged.begin() == ".mergerfs_rename_exdev");
check_exdev_absent(fixture.first / fixture.source);
check_exdev_absent(fixture.first / fixture.destination);
check_exdev_payload(fixture.first / fixture.staged());
check_exdev_payload(fixture.first / staged);
struct stat staged_st = {};
TEST_CHECK(::lstat((fixture.first / fixture.staged()).c_str(),&staged_st) == 0);
TEST_CHECK(::lstat((fixture.first / staged).c_str(),&staged_st) == 0);
TEST_CHECK(staged_st.st_ino == source_st.st_ino);
TEST_CHECK(staged_st.st_uid == source_st.st_uid);
TEST_CHECK(staged_st.st_gid == source_st.st_gid);
const fs::path expected = (std::string(mode_) == "rel-symlink") ?
fixture.staged().lexically_relative(fixture.destination.parent_path()) :
cfg.mountpoint / fixture.staged();
staged.lexically_relative(fixture.destination.parent_path()) :
cfg.mountpoint / staged;
check_exdev_symlink(fixture.second / fixture.destination,expected,source_st);
}
@ -3429,15 +3428,191 @@ test_fuse_link_exdev_invalid_context()
test_link_exdev_case(mode,fields);
}
static
void
test_rename_exdev_incompatible_destination(const char *mode_,
const bool nonempty_)
{
ExdevFixture fixture;
if(!fixture.ready)
return;
TEST_CASE(mode_);
cfg.rename_exdev.from_string(mode_);
const auto ctx = exdev_context(0);
const auto dst = fixture.second / fixture.destination;
TEST_CHECK(::mkdir(dst.c_str(),0755) == 0);
if(nonempty_)
{
std::ofstream output(dst / "child");
output << "child";
}
// A file can't replace a directory. The fallback must say so before
// touching the source.
const int rv = FUSE::rename(&ctx,fixture.source.c_str(),fixture.destination.c_str());
TEST_CHECK(rv == -EISDIR);
check_exdev_payload(fixture.first / fixture.source);
check_exdev_absent(fixture.first / ".mergerfs_rename_exdev");
struct stat st = {};
TEST_CHECK(::lstat(dst.c_str(),&st) == 0);
TEST_CHECK(S_ISDIR(st.st_mode));
}
static
void
test_rename_exdev_dir_over_nonempty_dir(const char *mode_)
{
ExdevFixture fixture;
if(!fixture.ready)
return;
TEST_CASE(mode_);
cfg.rename_exdev.from_string(mode_);
const auto ctx = exdev_context(0);
const fs::path srcdir = fixture.source.parent_path();
const fs::path dstdir = fixture.destination.parent_path() / "dir";
TEST_CHECK(::mkdir((fixture.second / dstdir).c_str(),0755) == 0);
{
std::ofstream output(fixture.second / dstdir / "child");
output << "child";
}
const int rv = FUSE::rename(&ctx,srcdir.c_str(),dstdir.c_str());
TEST_CHECK(rv == -ENOTEMPTY);
check_exdev_payload(fixture.first / fixture.source);
check_exdev_payload(fixture.second / dstdir / "child","child");
check_exdev_absent(fixture.first / ".mergerfs_rename_exdev");
}
void
test_fuse_exdev_existing_destination()
{
for(const auto mode : {"rel-symlink","abs-symlink"})
test_rename_exdev_case(mode,false,3,true);
{
test_rename_exdev_case(mode,false,3,true);
test_rename_exdev_incompatible_destination(mode,false);
test_rename_exdev_incompatible_destination(mode,true);
test_rename_exdev_dir_over_nonempty_dir(mode);
}
for(const auto mode : {"rel-symlink","abs-base-symlink","abs-pool-symlink"})
test_link_exdev_case(mode,3,true);
}
static
fs::path
exdev_link_branch_target(const ExdevFixture &fixture_,
const fs::path &link_)
{
std::error_code ec;
const auto target = std::filesystem::read_symlink(fixture_.second / link_,ec);
TEST_CHECK(!ec);
if(target.is_absolute())
return fixture_.first / target.lexically_relative(cfg.mountpoint);
return fixture_.first / (link_.parent_path() / target).lexically_normal();
}
void
test_fuse_rename_exdev_staging_collision()
{
// A second EXDEV rename of the same source path must not replace the
// file staged by the first one.
for(const auto mode : {"rel-symlink","abs-symlink"})
{
ExdevFixture fixture;
if(!fixture.ready)
return;
TEST_CASE(mode);
cfg.rename_exdev.from_string(mode);
const auto ctx = exdev_context(0);
const fs::path second_destination = "destination/nested/second";
TEST_CHECK(FUSE::rename(&ctx,fixture.source.c_str(),fixture.destination.c_str()) == 0);
{
std::ofstream output(fixture.first / fixture.source);
output << "second payload";
}
TEST_CHECK(FUSE::rename(&ctx,fixture.source.c_str(),second_destination.c_str()) == 0);
const auto first_staged = exdev_link_branch_target(fixture,fixture.destination);
const auto second_staged = exdev_link_branch_target(fixture,second_destination);
TEST_CHECK(first_staged != second_staged);
check_exdev_payload(first_staged);
check_exdev_payload(second_staged,"second payload");
check_exdev_absent(fixture.first / fixture.source);
}
}
void
test_fuse_rename_exdev_symlink_source()
{
// Renaming a symlink keeps its content. Staging it one directory
// deeper would break a relative target, so it is recreated instead.
for(const auto mode : {"rel-symlink","abs-symlink"})
{
ExdevFixture fixture;
if(!fixture.ready)
return;
TEST_CASE(mode);
cfg.rename_exdev.from_string(mode);
const auto ctx = exdev_context(0);
const auto src = fixture.first / fixture.source;
TEST_CHECK(::unlink(src.c_str()) == 0);
TEST_CHECK(::symlink("../relative/target",src.c_str()) == 0);
struct stat source_st = {};
TEST_CHECK(::lstat(src.c_str(),&source_st) == 0);
char *relocated = NULL;
const int rv = FUSE::rename(&ctx,fixture.source.c_str(),fixture.destination.c_str(),
&relocated);
TEST_CHECK(rv == 0);
// The symlink was recreated at newpath, so the node moves normally.
TEST_CHECK(relocated == NULL);
::free(relocated);
check_exdev_absent(src);
check_exdev_absent(fixture.first / ".mergerfs_rename_exdev");
check_exdev_symlink(fixture.second / fixture.destination,
"../relative/target",
source_st);
struct stat st = {};
TEST_CHECK(::lstat((fixture.second / fixture.destination).c_str(),&st) == 0);
TEST_CHECK(st.st_mtim.tv_sec == source_st.st_mtim.tv_sec);
TEST_CHECK(st.st_mtim.tv_nsec == source_st.st_mtim.tv_nsec);
}
}
void
test_fuse_rename_exdev_symlink_source_unremovable()
{
// A source symlink whose name can't be removed must fail the rename
// rather than leave both the old and the new name in place.
if(::geteuid() == 0)
return; // Directory permissions don't restrict root.
for(const auto mode : {"rel-symlink","abs-symlink"})
{
ExdevFixture fixture;
if(!fixture.ready)
return;
TEST_CASE(mode);
cfg.rename_exdev.from_string(mode);
const auto ctx = exdev_context(0);
const auto src = fixture.first / fixture.source;
const auto srcdir = src.parent_path();
const auto dstdir = fixture.second / fixture.destination.parent_path();
TEST_CHECK(::unlink(src.c_str()) == 0);
TEST_CHECK(::symlink("../relative/target",src.c_str()) == 0);
TEST_CHECK(::chmod(srcdir.c_str(),0555) == 0);
DEFER { ::chmod(srcdir.c_str(),0755); };
const int rv = FUSE::rename(&ctx,fixture.source.c_str(),fixture.destination.c_str());
TEST_CHECK(rv == -EACCES);
TEST_MSG("rv=%d",rv);
std::error_code ec;
TEST_CHECK(std::filesystem::read_symlink(src,ec) == "../relative/target");
TEST_CHECK(!ec);
TEST_CHECK(std::filesystem::is_empty(dstdir,ec));
TEST_CHECK(!ec);
}
}
static
bool
exdev_distinct_ownership_available()
@ -3498,6 +3673,150 @@ test_fuse_exdev_source_ownership()
test_link_exdev_case(mode,fields,false,true);
}
void
test_fuse_exdev_unavailable_owner_staging()
{
ExdevFixture fixture;
if(!fixture.ready)
return;
cfg.link_exdev.from_string("rel-symlink");
const auto ctx = exdev_context(0);
const auto blocked = fixture.second / ".mergerfs_symlink_exdev";
std::ofstream(blocked) << "occupied";
struct stat st = {};
fuse_timeouts_t timeouts = {};
TEST_CHECK(FUSE::link(&ctx,fixture.source.c_str(),fixture.destination.c_str(),
&st,&timeouts) == -EXDEV);
check_exdev_absent(fixture.second / fixture.destination);
check_exdev_payload(blocked,"occupied");
check_exdev_payload(fixture.first / fixture.source);
}
void
test_fuse_exdev_sticky_destination()
{
// A replacement symlink owned by the source owner in a sticky,
// world-writable directory owned by someone else could not be
// followed by anyone else (fs.protected_symlinks), so the fallbacks
// must not make one.
if(!exdev_distinct_ownership_available())
return;
{
std::ifstream sysctl("/proc/sys/fs/protected_symlinks");
char c = '1';
if(sysctl.is_open() && sysctl.get(c) && (c == '0'))
return;
}
for(const auto mode : {"rel-symlink","abs-symlink"})
{
ExdevFixture fixture;
if(!fixture.ready)
return;
TEST_CASE(mode);
cfg.rename_exdev.from_string(mode);
const auto ctx = exdev_context(0);
const auto parent = fixture.second / fixture.destination.parent_path();
TEST_CHECK(::chown((fixture.first / fixture.source).c_str(),12345,23456) == 0);
TEST_CHECK(::chown(parent.c_str(),0,0) == 0);
TEST_CHECK(::chmod(parent.c_str(),01777) == 0);
TEST_CHECK(FUSE::rename(&ctx,fixture.source.c_str(),fixture.destination.c_str()) == -EXDEV);
check_exdev_payload(fixture.first / fixture.source);
// Refused before the source branch is touched at all.
check_exdev_absent(fixture.first / ".mergerfs_rename_exdev");
check_exdev_absent(fixture.second / fixture.destination);
}
for(const auto mode : {"rel-symlink","abs-base-symlink","abs-pool-symlink"})
{
ExdevFixture fixture;
if(!fixture.ready)
return;
TEST_CASE(mode);
cfg.link_exdev.from_string(mode);
const auto ctx = exdev_context(0);
const auto parent = fixture.second / fixture.destination.parent_path();
TEST_CHECK(::chown((fixture.first / fixture.source).c_str(),12345,23456) == 0);
TEST_CHECK(::chown(parent.c_str(),0,0) == 0);
TEST_CHECK(::chmod(parent.c_str(),01777) == 0);
struct stat output_st = {};
fuse_timeouts_t timeouts = {};
TEST_CHECK(FUSE::link(&ctx,fixture.source.c_str(),fixture.destination.c_str(),
&output_st,&timeouts) == -EXDEV);
check_exdev_absent(fixture.second / fixture.destination);
}
}
void
test_fuse_exdev_sticky_destination_all_targets()
{
// The source lives on a third branch so its missing destination parent
// still forces EXDEV. The first two branches both have destination
// parents: a sticky one followed by a viable one. Preflight must refuse
// the whole operation rather than publish on the later branch.
if(!exdev_distinct_ownership_available())
return;
{
std::ifstream sysctl("/proc/sys/fs/protected_symlinks");
char c = '1';
if(sysctl.is_open() && sysctl.get(c) && (c == '0'))
return;
}
ExdevFixture fixture;
if(!fixture.ready)
return;
const fs::path third = fixture.root / "third";
std::error_code ec;
std::filesystem::create_directories(third / fixture.source.parent_path(),ec);
if(!TEST_CHECK(!ec))
return;
std::filesystem::create_directories(fixture.first / fixture.destination.parent_path(),ec);
if(!TEST_CHECK(!ec))
return;
TEST_CHECK(::rename((fixture.first / fixture.source).c_str(),
(third / fixture.source).c_str()) == 0);
TEST_CHECK(::chown((third / fixture.source).c_str(),12345,23456) == 0);
TEST_CHECK(cfg.branches.from_string(fixture.first.string() + ":" +
fixture.second.string() + ":" +
third.string()) == 0);
cfg.func.symlink.from_string("epall");
const auto sticky = fixture.first / fixture.destination.parent_path();
const auto viable = fixture.second / fixture.destination.parent_path();
TEST_CHECK(::chown(sticky.c_str(),0,0) == 0);
TEST_CHECK(::chmod(sticky.c_str(),01777) == 0);
const auto ctx = exdev_context(0);
cfg.rename_exdev.from_string("rel-symlink");
int rv = FUSE::rename(&ctx,fixture.source.c_str(),fixture.destination.c_str());
TEST_CHECK(rv == -EXDEV);
if(rv != -EXDEV)
return;
check_exdev_payload(third / fixture.source);
check_exdev_absent(third / ".mergerfs_rename_exdev");
check_exdev_absent(fixture.first / fixture.destination);
check_exdev_absent(fixture.second / fixture.destination);
TEST_CHECK(std::filesystem::is_empty(sticky,ec));
TEST_CHECK(!ec);
TEST_CHECK(std::filesystem::is_empty(viable,ec));
TEST_CHECK(!ec);
cfg.link_exdev.from_string("rel-symlink");
struct stat output_st = {};
fuse_timeouts_t timeouts = {};
rv = FUSE::link(&ctx,fixture.source.c_str(),fixture.destination.c_str(),
&output_st,&timeouts);
TEST_CHECK(rv == -EXDEV);
if(rv != -EXDEV)
return;
check_exdev_absent(fixture.first / fixture.destination);
check_exdev_absent(fixture.second / fixture.destination);
TEST_CHECK(std::filesystem::is_empty(sticky,ec));
TEST_CHECK(!ec);
TEST_CHECK(std::filesystem::is_empty(viable,ec));
TEST_CHECK(!ec);
}
void
test_fuse_symlink_request_ownership()
{
@ -4703,7 +5022,13 @@ TEST_LIST =
{"fuse_link_exdev_variants",test_fuse_link_exdev_variants},
{"fuse_link_exdev_invalid_context",test_fuse_link_exdev_invalid_context},
{"fuse_exdev_existing_destination",test_fuse_exdev_existing_destination},
{"fuse_rename_exdev_staging_collision",test_fuse_rename_exdev_staging_collision},
{"fuse_rename_exdev_symlink_source",test_fuse_rename_exdev_symlink_source},
{"fuse_rename_exdev_symlink_source_unremovable",test_fuse_rename_exdev_symlink_source_unremovable},
{"fuse_exdev_source_ownership",test_fuse_exdev_source_ownership},
{"fuse_exdev_unavailable_owner_staging",test_fuse_exdev_unavailable_owner_staging},
{"fuse_exdev_sticky_destination",test_fuse_exdev_sticky_destination},
{"fuse_exdev_sticky_destination_all_targets",test_fuse_exdev_sticky_destination_all_targets},
{"fuse_symlink_request_ownership",test_fuse_symlink_request_ownership},
{"fs_copyfile_basic",test_fs_copyfile_basic},
{"fs_copyfile_source_changes_cleanup_tmpfiles",test_fs_copyfile_source_changes_cleanup_tmpfiles},