mirror of
https://github.com/trapexit/mergerfs.git
synced 2026-12-02 21:00:13 -05:00
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:
parent
036246140b
commit
c9854f236f
16 changed files with 3962 additions and 202 deletions
|
|
@ -13,16 +13,32 @@ the newpath. The target value is determined by the value of
|
|||
mount point.
|
||||
* Defaults to `passthrough`.
|
||||
|
||||
Replacement symlinks retain the source inode's UID and GID, read without
|
||||
following a source symlink. Relative and pool targets use the first
|
||||
`getattr`-policy source branch; absolute branch targets use the source
|
||||
selected by the `open` policy. Creation uses daemon credentials, then
|
||||
sets the source ownership, rather than using the link request's UID/GID,
|
||||
which may be invalid when `allow-idmap` is enabled. A newly created
|
||||
replacement is removed if its ownership cannot be set.
|
||||
Replacement symlinks retain the source inode's UID and GID where
|
||||
supported, read without following a source symlink. Relative and pool
|
||||
targets use the first `getattr`-policy source branch; absolute branch
|
||||
targets use the source selected by the `open` policy. The replacement
|
||||
is prepared before publication in the daemon-private
|
||||
`.mergerfs_symlink_exdev` directory at the branch root. An inherited
|
||||
setgid bit is cleared on the pinned staging directory before creation so
|
||||
source credentials produce the source UID and GID. Any remaining
|
||||
ownership fixup is made through a pinned file descriptor. Linux
|
||||
publishes with a no-replace rename or a hard link from the private
|
||||
staging directory; neither replaces an existing link destination.
|
||||
|
||||
Source branch selection and path construction retain the same branch
|
||||
snapshot, even when the branch list is updated at runtime.
|
||||
FreeBSD corrects the pinned symlink's ownership and publishes it with
|
||||
a hard link from the private staging directory.
|
||||
If the source ownership cannot be represented or the verified symlink
|
||||
cannot be published, the fallback fails rather than publishing a link
|
||||
with the daemon's UID or a setgid parent's GID. The link request's
|
||||
UID/GID is never used: it may be invalid when `allow-idmap` is enabled.
|
||||
|
||||
In a sticky, world-writable directory (such as a shared `/tmp`-like
|
||||
directory) a symlink can only be followed by its owner unless the
|
||||
directory's owner also owns it (Linux's `fs.protected_symlinks`, on by
|
||||
default). A replacement symlink owned by the source's owner there would
|
||||
be unusable by everyone else, root included, so in that case mergerfs
|
||||
does not use the fallback and returns `EXDEV`, as if it were set to
|
||||
`passthrough`.
|
||||
|
||||
**NOTE:** It is possible that some applications check the file they
|
||||
link. In those cases, it is possible it will error or complain.
|
||||
|
|
|
|||
|
|
@ -2,10 +2,71 @@
|
|||
|
||||
If using path preservation and a `rename` fails with `EXDEV`:
|
||||
|
||||
1. Move file from `/mnt/hdd/disk0/a/b/c` to
|
||||
`/mnt/hdd/disk0/.mergerfs_rename_exdev/a/b/c`.
|
||||
1. Move the source into `.mergerfs_rename_exdev` at the root of its
|
||||
branch. The original `a/b/c` layout is used when atomic no-replace
|
||||
rename is available. Otherwise a fresh portable namespace is used.
|
||||
The replacement symlink names the file
|
||||
`.mergerfs_rename_exdev/<random>/a/b/.payload/c`, where `a/b` are
|
||||
real directories mirroring the source's parent directories and the
|
||||
final `.payload` is a real directory containing the moved file; a
|
||||
root source stages at
|
||||
`.mergerfs_rename_exdev/<random>/.payload/c`.
|
||||
2. symlink the rename's `newpath` to the moved file.
|
||||
|
||||
As with `rename(2)` an existing `newpath` is replaced: the symlink is
|
||||
created under a temporary name next to `newpath` and renamed over it,
|
||||
and copies of `newpath` on other branches are removed. A file can't
|
||||
replace a directory (`EISDIR`), a directory can't replace a
|
||||
non-directory (`ENOTDIR`) and a directory can only replace an empty
|
||||
directory (`ENOTEMPTY`). Those cases are detected before the source is
|
||||
moved. Before anything is moved, mergerfs also scans every configured
|
||||
branch once and pins which of them hold the destination, together with
|
||||
each copy's identity. A destination on a branch configured read-only
|
||||
cannot be removed, and on a branch configured no-create the
|
||||
replacement link cannot be created, so in both cases the old entry
|
||||
would shadow the published link there and the fallback refuses, as it
|
||||
does when two configured branches are the same underlying directory. Publication then touches a
|
||||
destination copy only on a branch of that scan and only while the copy
|
||||
still matches its pinned identity: a copy on a branch which will not
|
||||
publish the link, one which appeared after the scan, and one which
|
||||
cannot be verified all refuse the rename instead of being moved or
|
||||
deleted. A destination the scan found absent is never replaced either:
|
||||
if something is there by the time the link is published, the rename is
|
||||
refused instead of clobbering it. When publishing on several branches,
|
||||
mergerfs keeps each replaced destination under a temporary name until
|
||||
the last publication. If publication fails, it attempts to restore the
|
||||
destinations and source without overwriting any name created in the
|
||||
meantime. A portable directory cannot be restored atomically and stays
|
||||
at the recovery path reported in the log. A destination copy that
|
||||
disappeared before publication is not recreated.
|
||||
|
||||
An ordinary rename, with `rename-exdev=passthrough`, refuses the same
|
||||
way when the destination exists on a branch configured read-only which
|
||||
does not hold the source, and a destination copy left on one is not
|
||||
scheduled for removal either. Branches which may be modified, including
|
||||
no-create ones, keep their usual behavior of removing destination copies
|
||||
left on them.
|
||||
|
||||
A symlink being renamed is not moved into the staging directory, as
|
||||
that would break a relative target (including those of replacement
|
||||
symlinks made by `rel-symlink`). Since `rename(2)` does not change a
|
||||
symlink's content, the symlink is recreated at `newpath` with the same
|
||||
target, owner and timestamps and the original is removed. Recreation
|
||||
collapses every branch's copy of the symlink into the one target of
|
||||
the first source, so a symlink which exists on more than one branch is
|
||||
refused before anything is moved; single-source renames keep working.
|
||||
Sources of differing types across the selected branches are refused
|
||||
the same way before anything is moved, whether the first source is the
|
||||
symlink or a regular file or directory behind it: the staged copies
|
||||
all sit at the one path the replacement link points at, and a symlink
|
||||
among them, staged one directory deeper, would resolve its relative
|
||||
target from inside the staging directory and dangle.
|
||||
Every source link is moved aside before the new one is published, so a
|
||||
source which can't be moved aside fails the rename and nothing
|
||||
changes. If a moved source cannot then be unlinked, the rename fails
|
||||
and that source remains under its temporary name beside the original
|
||||
parent.
|
||||
|
||||
The `target` value is determined by the value of `rename-exdev`.
|
||||
|
||||
* `rename-exdev=passthrough`: Return `EXDEV` as normal.
|
||||
|
|
@ -18,14 +79,126 @@ The staging directory is created on demand, including for files at the
|
|||
pool root. Relative targets are calculated within the pool's relative
|
||||
path namespace.
|
||||
|
||||
`.mergerfs_rename_exdev` itself must be a real directory owned by the
|
||||
mergerfs process and is kept writable only by it (group and other
|
||||
write permission is removed from directories made by older releases).
|
||||
Components are opened without following symlinks. Existing targets in
|
||||
the original `a/b/c` layout remain usable.
|
||||
|
||||
With the original layout, a staged file is never replaced. The staged
|
||||
path is verified absent from every configured branch, including
|
||||
read-only and no-create ones, before it is used: a missing name is
|
||||
free, a name which is there is a collision and another suffixed name
|
||||
is tried, and any other inspection error cannot be verified and fails
|
||||
the rename rather than being mistaken for either. Fallback
|
||||
transactions are serialized against each other so two of them cannot
|
||||
take the same name, and a retry shortens the leaf as needed to fit the
|
||||
staging directory's `NAME_MAX`; when even the shortest suffixed form
|
||||
of the source's leaf cannot fit, the retry uses a bounded opaque
|
||||
random leaf instead of failing. Staging and rollback use atomic
|
||||
no-replace renames.
|
||||
|
||||
Without atomic no-replace rename, mergerfs creates a fresh `.p-`
|
||||
prefixed random directory under the secured staging root. The source's
|
||||
pool parent directories are reproduced inside it as access gates,
|
||||
owned by the mergerfs process, with the source's GID and only the
|
||||
source's read and execute permission bits: every write bit and the
|
||||
setid and sticky bits are cleared, applied once after all gates exist
|
||||
and before the source moves. An ancestor owned by another user cannot
|
||||
be represented that way and the fallback refuses before the source
|
||||
moves. The backing branch root is deliberately not copied: reaching
|
||||
the staging tree already means traversing the branch root itself, so
|
||||
its permissions apply to the staged payload exactly as they do to the
|
||||
source's original path, whatever the pool presents at its own root.
|
||||
UID, GID and mode are verified exactly before publication. A mergerfs
|
||||
process which cannot give a gate the source's GID (for example an
|
||||
unprivileged one, not a member of that group) refuses rather than leave
|
||||
the group bits applying to a different group. The native layout above
|
||||
copies parent metadata on a best-effort basis, as `clonepath` does, so
|
||||
the two layouts can differ in this case. Portable staging refuses an
|
||||
existing directory destination with `EXDEV`, before moving the source:
|
||||
directories cannot be hard-linked aside for rollback. Native staging
|
||||
can replace an empty directory when no-replace rename is supported.
|
||||
Portable staging supports mode-representable access only: Linux
|
||||
sources with POSIX access or default ACL xattrs are refused, and
|
||||
FreeBSD accepts only native trivial ACLs (including UFS's empty
|
||||
default ACL representation). Nontrivial or unverifiable ACLs fail
|
||||
before the source moves rather than broadening access. These gates
|
||||
prevent the additional pathname components from bypassing restrictive
|
||||
source parents.
|
||||
|
||||
The real `.payload` directory is the last component of the route,
|
||||
created inside the final gate (directly in the wrapper for a root
|
||||
source) while the whole namespace is still private. There is no
|
||||
intermediate link and no path to the payload which does not pass
|
||||
through every gate. Gates belong to the mergerfs process and are not
|
||||
writable by anyone, so no gate owner exists who could rename the
|
||||
payload out of its mirror or replace anything inside a gate. A source
|
||||
component named `.payload` is an ordinary mirrored directory like any
|
||||
other; only the final `.payload` is created by mergerfs. The wrapper
|
||||
and `.payload` are owned by the daemon, created exclusively 0700 and
|
||||
verified as real directories through pinned descriptors. They become 0555
|
||||
only after the move and access-gate setup completes; they are never
|
||||
publicly writable. The source is staged under its original leaf name
|
||||
in `.payload`. The extra components can make an otherwise
|
||||
maximum-length source path too long to relocate.
|
||||
|
||||
Before any move, mergerfs prepares the actual temporary replacement
|
||||
symlink, including its required ownership. Common creation and
|
||||
permission failures therefore happen before the source is moved. A
|
||||
portable namespace the source never entered is removed again. Native
|
||||
rollback uses atomic no-replace rename. A portable non-directory
|
||||
is rolled back by atomically hard-linking it at the old source name and
|
||||
then unlinking the staged link, so a recreated source is never
|
||||
replaced. No equivalent portable atomic operation exists for a
|
||||
directory. If later publication or rollback fails, a portable
|
||||
directory is left intact in its staged namespace and mergerfs logs its
|
||||
recovery path rather than risking the source. Empty staging directories
|
||||
may remain after a completed rollback.
|
||||
|
||||
**FreeBSD 14.4 and 15.0:** These releases' headers do not provide
|
||||
`SYS_renameat2`, so regular-file and directory staging uses the portable
|
||||
layout. Both files and directories can be staged, subject to the
|
||||
directory-destination and rollback limits above. Ordinary renames and
|
||||
the fallback for a source symlink do not use this layout. Because every
|
||||
mirrored ancestor must be owned by the mergerfs process, the portable
|
||||
layout refuses ordinary user-owned trees unless mergerfs runs as that
|
||||
owner. On Linux the standalone portable fixture makes `renameat2`
|
||||
return `ENOSYS` with a process-local seccomp filter and verifies the
|
||||
portable layout. A host without filter support skips the forced
|
||||
portable fixture explicitly.
|
||||
|
||||
Replacement symlinks retain the UID and GID of the first source inode
|
||||
selected by the rename action policy, read before moving the source and
|
||||
without following source symlinks. Creation uses daemon credentials,
|
||||
then sets the source ownership; it does not use the rename request's
|
||||
UID/GID, which may be invalid when `allow-idmap` is enabled. A newly
|
||||
created replacement is removed if its ownership cannot be set. If
|
||||
replacement creation fails, mergerfs attempts to restore the original
|
||||
source paths.
|
||||
selected by the rename action policy where supported, read before moving
|
||||
the source and without following source symlinks. The replacement is
|
||||
prepared in the daemon-private `.mergerfs_symlink_exdev` directory at
|
||||
the branch root. An inherited
|
||||
setgid bit is cleared on the pinned staging directory before creation so
|
||||
source credentials produce the source UID and GID. Any remaining
|
||||
ownership fixup is made through a pinned file descriptor. Linux
|
||||
publishes the temporary link exclusively, using a no-replace rename or
|
||||
a hard link from the private staging directory.
|
||||
|
||||
FreeBSD corrects the pinned symlink's ownership and publishes it with
|
||||
a hard link from the private staging directory.
|
||||
If source ownership cannot be represented or the verified replacement
|
||||
cannot be published, the fallback fails rather than publishing a link
|
||||
with different ownership. The request's UID/GID is never used: it may
|
||||
be invalid with `allow-idmap`. If replacement creation fails, mergerfs
|
||||
attempts to restore the original source paths.
|
||||
|
||||
In a sticky, world-writable directory (such as a shared `/tmp`-like
|
||||
directory) a symlink can only be followed by its owner unless the
|
||||
directory's owner also owns it (Linux's `fs.protected_symlinks`, on by
|
||||
default). A replacement symlink owned by the source's owner there would
|
||||
be unusable by everyone else, root included, so in that case mergerfs
|
||||
does not use the fallback and returns `EXDEV`, as if it were set to
|
||||
`passthrough`. This is checked before the source is moved.
|
||||
|
||||
Until the kernel's cached entry for `newpath` expires (see
|
||||
`cache.entry`) `newpath` keeps referring to the moved file itself, as
|
||||
after a normal rename, and open handles keep working. After that,
|
||||
`newpath` is seen as the symlink.
|
||||
|
||||
**NOTE:** It is possible that some applications check the file they
|
||||
rename. In those cases it is possible it will error or complain.
|
||||
|
|
|
|||
|
|
@ -47,6 +47,13 @@ below.
|
|||
The removals are subject to normal entitlement checks. If the unlink
|
||||
fails it will fail silently.
|
||||
|
||||
A target on a branch configured read-only (`RO`) which holds no
|
||||
source file can be neither replaced nor removed, and would keep
|
||||
shadowing the renamed file there. The rename returns EXDEV before
|
||||
anything is changed, and such a target is never scheduled for
|
||||
removal. Branches which may be modified, including no-create (`NC`)
|
||||
ones, keep the removal behavior described above.
|
||||
|
||||
The above behavior will help minimize the likelihood of EXDEV being
|
||||
returned but it will still be possible.
|
||||
|
||||
|
|
|
|||
|
|
@ -261,11 +261,21 @@ As of v2.42.0 mergerfs now runs as root more generally. Either
|
|||
changing credentials when creating files (Linux) or chown'ing them
|
||||
after creation (FreeBSD).
|
||||
|
||||
The optional EXDEV link and rename fallbacks create replacement
|
||||
symlinks under daemon credentials and then preserve the source inode's
|
||||
UID and GID. They do not use the link or rename request's UID/GID:
|
||||
these may be invalid with `allow-idmap`. Ordinary symlink creation
|
||||
continues to use the creation request's credentials.
|
||||
The optional EXDEV link and rename fallbacks preserve the source inode's
|
||||
UID and GID by preparing the replacement in the daemon-private
|
||||
`.mergerfs_symlink_exdev` staging directory at the branch root.
|
||||
Inherited setgid mode is cleared on the pinned staging directory before
|
||||
source-credential creation. Any remaining correction uses the pinned
|
||||
replacement descriptor. Linux publishes with a no-replace rename or a
|
||||
hard link from the private staging directory. FreeBSD uses descriptor-
|
||||
based ownership correction and a hard link. No ownership correction
|
||||
is made through a public pathname.
|
||||
|
||||
If the source IDs cannot be represented, or the verified replacement
|
||||
cannot be published, mergerfs fails the fallback instead of creating a
|
||||
link with different ownership. It never uses the link or rename request's
|
||||
UID/GID, which may be invalid with `allow-idmap`. Ordinary symlink
|
||||
creation continues to use the creation request's credentials.
|
||||
|
||||
As a result of this change it is now necessary for the FUSE
|
||||
`default_permissions` feature be used for proper entitlements
|
||||
|
|
|
|||
94
src/fs_renameat.hpp
Normal file
94
src/fs_renameat.hpp
Normal 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
|
||||
}
|
||||
}
|
||||
2090
src/fuse_rename.cpp
2090
src/fuse_rename.cpp
File diff suppressed because it is too large
Load diff
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
30
src/rename_exdev_staging.hpp
Normal file
30
src/rename_exdev_staging.hpp
Normal 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";
|
||||
}
|
||||
|
|
@ -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
334
tests/TEST_rename_exdev_portable
Executable 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())
|
||||
305
tests/TEST_rename_exdev_publication
Executable file
305
tests/TEST_rename_exdev_publication
Executable 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())
|
||||
361
tests/tests.cpp
361
tests/tests.cpp
|
|
@ -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},
|
||||
|
|
|
|||
|
|
@ -89,9 +89,17 @@ struct fuse_operations
|
|||
const char *,
|
||||
struct stat *,
|
||||
fuse_timeouts_t *);
|
||||
/*
|
||||
If the filesystem could not move the source to newpath and instead
|
||||
moved it elsewhere and put a different object at newpath (as
|
||||
mergerfs' rename-exdev fallback does) it should set *relocated to a
|
||||
malloc()ed copy of the source's new path, relative to the mount
|
||||
root and without a leading '/'. It is freed by the caller.
|
||||
*/
|
||||
int (*rename)(const fuse_req_ctx_t *,
|
||||
const char *,
|
||||
const char *);
|
||||
const char *oldpath,
|
||||
const char *newpath,
|
||||
char **relocated);
|
||||
int (*link)(const fuse_req_ctx_t *,
|
||||
const char *,
|
||||
const char *,
|
||||
|
|
|
|||
|
|
@ -406,13 +406,12 @@ remerge_name()
|
|||
}
|
||||
}
|
||||
|
||||
// Detach from the name bucket without changing the use count. The caller
|
||||
// either transfers the node to a new bucket or drops the old reference.
|
||||
static
|
||||
void
|
||||
unhash_name(node_t *node)
|
||||
unlink_name(node_t *node)
|
||||
{
|
||||
if(not (node && node->name && node->parent))
|
||||
return;
|
||||
|
||||
size_t hash = name_hash(node->parent->nodeid,node->name);
|
||||
node_t **nodep = &f.name_table.array[hash];
|
||||
|
||||
|
|
@ -423,14 +422,6 @@ unhash_name(node_t *node)
|
|||
|
||||
*nodep = node->name_next;
|
||||
node->name_next = NULL;
|
||||
unref_node(node->parent);
|
||||
free(node->name);
|
||||
node->name = NULL;
|
||||
node->parent = NULL;
|
||||
f.name_table.use--;
|
||||
|
||||
if(f.name_table.use < f.name_table.size / 4)
|
||||
remerge_name();
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -438,6 +429,34 @@ unhash_name(node_t *node)
|
|||
node->nodeid);
|
||||
}
|
||||
|
||||
static
|
||||
void
|
||||
relink_name(node_t *node)
|
||||
{
|
||||
size_t hash = name_hash(node->parent->nodeid,node->name);
|
||||
|
||||
node->name_next = f.name_table.array[hash];
|
||||
f.name_table.array[hash] = node;
|
||||
}
|
||||
|
||||
static
|
||||
void
|
||||
unhash_name(node_t *node)
|
||||
{
|
||||
if(not (node && node->name && node->parent))
|
||||
return;
|
||||
|
||||
unlink_name(node);
|
||||
unref_node(node->parent);
|
||||
free(node->name);
|
||||
node->name = NULL;
|
||||
node->parent = NULL;
|
||||
f.name_table.use--;
|
||||
|
||||
if(f.name_table.use < f.name_table.size / 4)
|
||||
remerge_name();
|
||||
}
|
||||
|
||||
static
|
||||
void
|
||||
rehash_name()
|
||||
|
|
@ -1264,6 +1283,50 @@ rename_node(uint64_t olddir,
|
|||
return err;
|
||||
}
|
||||
|
||||
/*
|
||||
The filesystem replaced newname with a different object (a symlink)
|
||||
and moved the source to `relpath_` instead. The kernel has already
|
||||
moved the source's dentry, and with it this node, to newname and
|
||||
keeps using it until it revalidates the dentry. Requests for the node
|
||||
must reach the source, not the object now at newname: if they did,
|
||||
the kernel would see the inode change type and fail the request with
|
||||
EIO, and would mark the inode bad, breaking any handle still open on
|
||||
it. So re-parent the node to `relpath_` under the root. Kernel lookups
|
||||
never contain '/', so that name can't collide with a real entry. Any
|
||||
node at newname is dropped so the next lookup there creates a new
|
||||
one for the new object.
|
||||
*/
|
||||
static
|
||||
void
|
||||
relocate_node(uint64_t olddir,
|
||||
const char *oldname,
|
||||
uint64_t newdir,
|
||||
const char *newname,
|
||||
char *relpath_)
|
||||
{
|
||||
mutex_lockguard(f.lock);
|
||||
node_t *node = lookup_node(olddir,oldname);
|
||||
node_t *newnode = lookup_node(newdir,newname);
|
||||
if((newnode != NULL) && (newnode != node))
|
||||
unlink_node(newnode);
|
||||
if(node == NULL)
|
||||
{
|
||||
free(relpath_);
|
||||
return;
|
||||
}
|
||||
|
||||
// Publication has committed. Adopt the name reserved by the callback:
|
||||
// no strdup, table growth, or other fallible insertion remains here.
|
||||
node_t *root = get_node(FUSE_ROOT_ID);
|
||||
root->refctr++;
|
||||
unlink_name(node);
|
||||
unref_node(node->parent);
|
||||
free(node->name);
|
||||
node->name = relpath_;
|
||||
node->parent = root;
|
||||
relink_name(node);
|
||||
}
|
||||
|
||||
static
|
||||
void
|
||||
set_stat(uint64_t nodeid,
|
||||
|
|
@ -2049,11 +2112,20 @@ fuse_lib_rename(fuse_req_t *req_,
|
|||
|
||||
if(!err)
|
||||
{
|
||||
char *relocated = NULL;
|
||||
|
||||
err = f.ops.rename(&req_->ctx,
|
||||
&oldpath[1],
|
||||
&newpath[1]);
|
||||
if(!err)
|
||||
err = rename_node(hdr_->nodeid,oldname,arg->newdir,newname);
|
||||
&newpath[1],
|
||||
&relocated);
|
||||
if(!err && (relocated != NULL))
|
||||
relocate_node(hdr_->nodeid,oldname,arg->newdir,newname,relocated);
|
||||
else
|
||||
{
|
||||
free(relocated);
|
||||
if(!err)
|
||||
err = rename_node(hdr_->nodeid,oldname,arg->newdir,newname);
|
||||
}
|
||||
|
||||
free_path2(hdr_->nodeid,arg->newdir,wnode1,wnode2,oldpath,newpath);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue