diff --git a/mkdocs/docs/config/link-exdev.md b/mkdocs/docs/config/link-exdev.md index 1eca5141..fa351997 100644 --- a/mkdocs/docs/config/link-exdev.md +++ b/mkdocs/docs/config/link-exdev.md @@ -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. diff --git a/mkdocs/docs/config/rename-exdev.md b/mkdocs/docs/config/rename-exdev.md index 62f7e3fc..af420cd8 100644 --- a/mkdocs/docs/config/rename-exdev.md +++ b/mkdocs/docs/config/rename-exdev.md @@ -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//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//.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. diff --git a/mkdocs/docs/config/rename_and_link.md b/mkdocs/docs/config/rename_and_link.md index 1da66e2c..afe70a6d 100644 --- a/mkdocs/docs/config/rename_and_link.md +++ b/mkdocs/docs/config/rename_and_link.md @@ -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. diff --git a/mkdocs/docs/faq/technical_behavior_and_limitations.md b/mkdocs/docs/faq/technical_behavior_and_limitations.md index 26177ec0..2b7b1bff 100644 --- a/mkdocs/docs/faq/technical_behavior_and_limitations.md +++ b/mkdocs/docs/faq/technical_behavior_and_limitations.md @@ -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 diff --git a/src/fs_renameat.hpp b/src/fs_renameat.hpp new file mode 100644 index 00000000..7c4592b7 --- /dev/null +++ b/src/fs_renameat.hpp @@ -0,0 +1,94 @@ +/* + ISC License + + Copyright (c) 2026, Antonio SJ Musumeci + + 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 + +#include +#include +#include +#include +#include + +#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 + } +} diff --git a/src/fuse_rename.cpp b/src/fuse_rename.cpp index fd2cd7fc..3a13dd9d 100644 --- a/src/fuse_rename.cpp +++ b/src/fuse_rename.cpp @@ -21,22 +21,58 @@ #include "config.hpp" #include "error.hpp" #include "errno.hpp" +#include "fs_attr.hpp" #include "fs_clonepath.hpp" +#include "fs_close.hpp" +#include "fs_fchmod.hpp" +#include "fs_fchown.hpp" +#include "fs_fstat.hpp" +#include "fs_fstatat.hpp" +#include "fs_futimens.hpp" +#include "fs_is_same_file.hpp" #include "fs_link.hpp" #include "fs_lstat.hpp" -#include "fs_mkdir_as.hpp" +#include "fs_mkdirat.hpp" +#include "fs_open.hpp" +#include "fs_openat.hpp" +#include "fs_lutimens.hpp" #include "fs_path.hpp" +#include "fs_readlink.hpp" #include "fs_remove.hpp" #include "fs_rename.hpp" +#include "fs_renameat.hpp" #include "fs_symlink.hpp" #include "fs_unlink.hpp" +#include "fs_xattr.hpp" #include "fuse_symlink.hpp" +#include "rnd.hpp" +#include "syslog.hpp" + +#include "rename_exdev_staging.hpp" + +#include "scope_guard/scope_guard.hpp" #include #include +#include #include +#include #include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +# include +#elif defined(__FreeBSD__) +# include +#endif + static bool @@ -68,6 +104,40 @@ _remove(const StrVec &toremove_) fs::remove(path); } +// A destination copy on a branch configured read-only can neither be +// replaced nor removed by the rename: it would outlive it and keep +// shadowing the new name there, which rename(2) could not have done. +// Refuse the rename before anything moves; the EXDEV fallback refuses +// for the same reason. Branches which may be modified, including +// no-create ones, keep their usual cleanup behavior. +static +int +_rename_check_unselected_ro_destination(const Branches::Ptr &branches_, + const std::vector &oldbranches_, + const fs::path &newfusepath_) +{ + int rv; + struct stat st; + + for(const auto &branch : *branches_) + { + if(::_contains(oldbranches_,branch.path)) + continue; + if(!branch.ro()) + continue; + + rv = fs::lstat(branch.path / newfusepath_,&st); + if(rv == -ENOENT) + continue; + if(rv < 0) + return rv; + + return -EXDEV; + } + + return 0; +} + static int _rename_create_path(const Policy::Search &searchPolicy_, @@ -96,13 +166,22 @@ _rename_create_path(const Policy::Search &searchPolicy_, if(newbranches.empty()) return -ENOENT; + rv = ::_rename_check_unselected_ro_destination(branches_,oldbranches,newfusepath_); + if(rv < 0) + return rv; + for(auto &branch : *branches_) { newfullpath = branch.path / newfusepath_; if(!::_contains(oldbranches,branch.path)) { - toremove.push_back(newfullpath); + // The preflight refuses when a destination exists on an + // unselected read-only branch, so scheduling one for removal + // here could only ever hit a copy which appeared after that + // check. Such a copy is not scheduled for mutation. + if(!branch.ro()) + toremove.push_back(newfullpath); continue; } @@ -147,6 +226,10 @@ _rename_preserve_path(const Policy::Action &actionPolicy_, if(rv < 0) return rv; + rv = ::_rename_check_unselected_ro_destination(branches_,oldbranches,newfusepath_); + if(rv < 0) + return rv; + success = false; for(auto &branch : *branches_) { @@ -154,7 +237,12 @@ _rename_preserve_path(const Policy::Action &actionPolicy_, if(!::_contains(oldbranches,branch.path)) { - toremove.push_back(newfullpath); + // The preflight refuses when a destination exists on an + // unselected read-only branch, so scheduling one for removal + // here could only ever hit a copy which appeared after that + // check. Such a copy is not scheduled for mutation. + if(!branch.ro()) + toremove.push_back(newfullpath); continue; } @@ -179,143 +267,1912 @@ _rename_preserve_path(const Policy::Action &actionPolicy_, return 0; } -static -void -_rename_exdev_rename_back(const std::vector &branches_, - const fs::path &oldfusepath_) +// The EXDEV fallback moves the source into a staging tree at the root +// of each branch and then points a symlink at it. The daemon does that +// work as root while the staging tree is reachable through the pool, +// so anything already in it may have been planted by a pool user. To +// avoid following planted symlinks out of the branch every component +// is opened relative to its already verified parent with O_NOFOLLOW +// and the final move is done with renameat() on those fds. Nothing in +// the staging tree is resolved by path. The staging directory name is +// the shared rename_exdev::STAGING_DIR constant. + +static constexpr int STAGING_DIR_FLAGS = (O_RDONLY|O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC); + +namespace { - fs::path oldpath; - fs::path newpath; - - for(auto &branch : branches_) + class FD + { + public: + FD() = default; + explicit FD(const int fd_) : _fd(fd_) {} + FD(const FD&) = delete; + FD& operator=(const FD&) = delete; + FD(FD &&o_) noexcept : _fd(o_.release()) {} + FD& operator=(FD &&o_) noexcept { - oldpath = branch->path; - oldpath /= ".mergerfs_rename_exdev"; - oldpath /= oldfusepath_; - - newpath = branch->path; - newpath /= oldfusepath_; - - fs::rename(oldpath,newpath); + if(this != &o_) + reset(o_.release()); + return *this; } + ~FD() { reset(); } + + public: + int get() const { return _fd; } + int release() { int fd = _fd; _fd = -1; return fd; } + void reset(const int fd_ = -1) + { + if(_fd >= 0) + fs::close(_fd); + _fd = fd_; + } + + private: + int _fd = -1; + }; + + struct Staged + { + FD srcdir; + FD dstdir; + bool portable = false; + bool directory = false; + bool moved = false; + std::string name; + fs::path branch; + fs::path relocated; + }; + + struct AccessGate + { + FD srcdir; + FD dir; + struct stat source; + std::string name; + }; +} + +// The staging root must be a real directory owned by the daemon and +// not writable by anyone else. Older releases created it 01777 so +// group/other write is removed from an existing one. +static +int +_open_staging_root(const int branchfd_) +{ + int rv; + struct stat st; + + rv = fs::mkdirat(branchfd_,rename_exdev::STAGING_DIR,0755); + if((rv < 0) && (rv != -EEXIST)) + return rv; + + FD fd(fs::openat(branchfd_,rename_exdev::STAGING_DIR,STAGING_DIR_FLAGS)); + if(fd.get() < 0) + return fd.release(); + + rv = fs::fstat(fd.get(),&st); + if(rv < 0) + return rv; + if(st.st_uid != ::geteuid()) + return -EPERM; + + if(st.st_mode & (S_IWGRP|S_IWOTH)) + { + rv = fs::fchmod(fd.get(),(st.st_mode & 07777 & ~(S_IWGRP|S_IWOTH))); + if(rv < 0) + return rv; + } + + return fd.release(); +} + +// Open the source directory `name_` under `srcfd_` and the directory +// mirroring it under `dstfd_`, creating the latter with the source's +// metadata if needed. An existing staging directory must be owned by +// the owner of the source directory it mirrors (as a clone would be) +// and is not allowed to grant permissions the source does not. +static +int +_open_staging_dir(const int srcfd_, + const int dstfd_, + const std::string &name_, + FD &srcout_, + FD &dstout_) +{ + int rv; + struct stat srcst; + struct stat dstst; + + FD srcfd(fs::openat(srcfd_,name_,STAGING_DIR_FLAGS)); + if(srcfd.get() < 0) + return srcfd.release(); + + rv = fs::fstat(srcfd.get(),&srcst); + if(rv < 0) + return rv; + + rv = fs::mkdirat(dstfd_,name_,(srcst.st_mode & 07777)); + if((rv < 0) && (rv != -EEXIST)) + return rv; + const bool created = (rv == 0); + + FD dstfd(fs::openat(dstfd_,name_,STAGING_DIR_FLAGS)); + if(dstfd.get() < 0) + return dstfd.release(); + + if(created) + { + // Metadata is best effort, as with fs::clonepath(). + fs::attr::copy(srcfd.get(),dstfd.get(),FS_ATTR_CLEAR_IMMUTABLE); + fs::xattr::copy(srcfd.get(),dstfd.get()); + fs::fchown_check_on_error(dstfd.get(),srcst); + fs::fchmod_check_on_error(dstfd.get(),srcst); + fs::futimens(dstfd.get(),srcst); + } + else + { + rv = fs::fstat(dstfd.get(),&dstst); + if(rv < 0) + return rv; + if(dstst.st_uid != srcst.st_uid) + return -EPERM; + + const mode_t extra = (dstst.st_mode & ~srcst.st_mode & 07777); + if(extra) + { + rv = fs::fchmod(dstfd.get(),(dstst.st_mode & 07777 & ~extra)); + if(rv < 0) + return rv; + } + } + + srcout_ = std::move(srcfd); + dstout_ = std::move(dstfd); + + return 0; +} + +#if defined(__linux__) +static +bool +_acl_blob_absent(const int rv_) +{ + return ((rv_ == -ENODATA) || (rv_ == -EOPNOTSUPP) || (rv_ == -ENOTSUP)); } static int -_rename_exdev_rename_target(const Policy::Action &actionPolicy_, - const Branches::Ptr ibranches_, - const fs::path &oldfusepath_, - std::vector &obranches_, - struct stat &source_) +_require_acl_absent(const int fd_, + const char *name_) { - int rv; - fs::path clonesrc; - fs::path clonedst; + const ssize_t rv = ::fgetxattr(fd_,name_,NULL,0); + if(rv >= 0) + return -EOPNOTSUPP; + return (::_acl_blob_absent(-errno) ? 0 : -errno); +} - rv = actionPolicy_(ibranches_,oldfusepath_,obranches_); +static +int +_clear_acl_blob(const int fd_, + const char *name_) +{ + const int rv = ::to_neg_errno(::fremovexattr(fd_,name_)); + return (::_acl_blob_absent(rv) ? 0 : rv); +} + +static +int +_prepare_fresh_acl(const int fd_) +{ + int rv = ::_clear_acl_blob(fd_,"system.posix_acl_access"); if(rv < 0) return rv; - if(obranches_.empty()) - return -ENOENT; + return ::_clear_acl_blob(fd_,"system.posix_acl_default"); +} - rv = fs::lstat(obranches_[0]->path / oldfusepath_,&source_); - if(rv < 0) - return rv; - - for(auto &branch : obranches_) +static +int +_verify_mode_only_acl(const int srcfd_, + const int dstfd_) +{ + for(const char *name : {"system.posix_acl_access","system.posix_acl_default"}) { - clonesrc = branch->path; - clonedst = branch->path; - clonedst /= ".mergerfs_rename_exdev"; - - rv = fs::mkdir_as({0,0},clonedst,01777); - if((rv < 0) && (rv != -EEXIST)) - goto error; - - rv = fs::clonepath(clonesrc,clonedst,oldfusepath_.parent_path()); - + int rv = ::_require_acl_absent(srcfd_,name); if(rv < 0) - goto error; - - clonesrc /= oldfusepath_; - clonedst /= oldfusepath_; - - rv = fs::rename(clonesrc,clonedst); + return rv; + rv = ::_require_acl_absent(dstfd_,name); if(rv < 0) - goto error; + return rv; + } + return 0; +} +#elif defined(__FreeBSD__) +struct FreeBSDACLTypes +{ + bool nfs4 = false; + bool posix1e = false; +}; + +static +int +_freebsd_acl_types(const int fd_, + FreeBSDACLTypes &types_) +{ + errno = 0; + const long nfs4 = ::fpathconf(fd_,_PC_ACL_NFS4); + if(nfs4 < 0) + return (errno ? -errno : -EOPNOTSUPP); + types_.nfs4 = (nfs4 == 1); + if(types_.nfs4) + return 0; + + errno = 0; + const long posix1e = ::fpathconf(fd_,_PC_ACL_EXTENDED); + if(posix1e < 0) + return (errno ? -errno : -EOPNOTSUPP); + types_.posix1e = (posix1e == 1); + + return 0; +} + +static +int +_freebsd_require_trivial_acl(const int fd_, + const acl_type_t type_) +{ + acl_t acl = ::acl_get_fd_np(fd_,type_); + if(acl == NULL) + return ((errno == ENOENT) ? 0 : -errno); + + // UFS represents an absent default ACL as a successful zero-entry + // ACL. It is absent for access purposes, not a nontrivial ACL. + acl_entry_t entry; + const int has_entry = ::acl_get_entry(acl,ACL_FIRST_ENTRY,&entry); + if(has_entry <= 0) + { + const int entry_errno = errno; + ::acl_free(acl); + return ((has_entry == 0) ? 0 : -entry_errno); + } + + int trivial = 0; + const int rv = ::acl_is_trivial_np(acl,&trivial); + const int saved_errno = errno; + ::acl_free(acl); + if(rv < 0) + return -saved_errno; + + // No ACL copier is needed: native mode-only ACLs are already exactly + // represented by st_mode. This also leaves ordinary trivial ZFS ACLs + // alone instead of trying the unsupported NFSv4 delete operation. + return (trivial ? 0 : -EOPNOTSUPP); +} + +static +int +_prepare_fresh_acl(const int fd_) +{ + FreeBSDACLTypes types; + int rv = ::_freebsd_acl_types(fd_,types); + if(rv < 0) + return rv; + + if(types.nfs4) + return ::_freebsd_require_trivial_acl(fd_,ACL_TYPE_NFS4); + if(types.posix1e) + { + rv = ::_freebsd_require_trivial_acl(fd_,ACL_TYPE_ACCESS); + if(rv < 0) + return rv; + return ::_freebsd_require_trivial_acl(fd_,ACL_TYPE_DEFAULT); } return 0; +} - error: - ::_rename_exdev_rename_back(obranches_,oldfusepath_); +static +int +_verify_mode_only_acl(const int srcfd_, + const int dstfd_) +{ + FreeBSDACLTypes srctypes; + FreeBSDACLTypes dsttypes; + int rv = ::_freebsd_acl_types(srcfd_,srctypes); + if(rv < 0) + return rv; + rv = ::_freebsd_acl_types(dstfd_,dsttypes); + if(rv < 0) + return rv; + if((srctypes.nfs4 != dsttypes.nfs4) || + (srctypes.posix1e != dsttypes.posix1e)) + return -EOPNOTSUPP; + + if(srctypes.nfs4) + { + rv = ::_freebsd_require_trivial_acl(srcfd_,ACL_TYPE_NFS4); + if(rv < 0) + return rv; + return ::_freebsd_require_trivial_acl(dstfd_,ACL_TYPE_NFS4); + } + if(srctypes.posix1e) + { + for(const acl_type_t type : {ACL_TYPE_ACCESS,ACL_TYPE_DEFAULT}) + { + rv = ::_freebsd_require_trivial_acl(srcfd_,type); + if(rv < 0) + return rv; + rv = ::_freebsd_require_trivial_acl(dstfd_,type); + if(rv < 0) + return rv; + } + } + + return 0; +} +#else +static +int +_prepare_fresh_acl(const int) +{ + return -EOPNOTSUPP; +} + +static +int +_verify_mode_only_acl(const int,const int) +{ + return -EOPNOTSUPP; +} +#endif + +// Create a new directory which only the daemon can enter. The caller +// opens it to 0555 only after the source has been moved and all access +// gates have been populated. A plain renameat() into this empty, +// private directory cannot replace an entry planted by a pool user. +static +int +_open_fresh_staging_dir(const int parentfd_, + const std::string &name_, + FD &out_) +{ + int rv = fs::mkdirat(parentfd_,name_,0700); + if(rv < 0) + return rv; + + // Only the daemon can modify `parentfd_`, so the name still denotes + // the directory just created if it turns out to be unusable. + bool usable = false; + DEFER { if(!usable) ::unlinkat(parentfd_,name_.c_str(),AT_REMOVEDIR); }; + + FD dir(fs::openat(parentfd_,name_,STAGING_DIR_FLAGS)); + if(dir.get() < 0) + return dir.release(); + + struct stat st; + rv = fs::fstat(dir.get(),&st); + if(rv < 0) + return rv; + if(!S_ISDIR(st.st_mode) || + (st.st_uid != ::geteuid()) || + (st.st_mode & (S_IWGRP|S_IWOTH))) + return -EPERM; + + // mkdirat() succeeded exclusively, and the directory is not publicly + // traversable. Remove inherited ACL state where possible; otherwise + // require the inherited ACL to be trivial before using this gate. + rv = ::_prepare_fresh_acl(dir.get()); + if(rv < 0) + return rv; + + usable = true; + out_ = std::move(dir); + return 0; +} + +// Access gates are initially private like the rest of the namespace. +// Their metadata is applied after the complete hierarchy is created +// but before the payload moves. The pinned source and payload fds make +// the later rename independent of the gates' final permissions. +static +int +_prepare_access_gate(const int srcfd_, + const int dstfd_, + const std::string &name_, + std::vector &gates_) +{ + int rv; + struct stat srcst; + + rv = fs::fstat(srcfd_,&srcst); + if(rv < 0) + return rv; + if(!S_ISDIR(srcst.st_mode)) + return -ENOTDIR; + + // A gate must be owned by the daemon: a gate owned by anyone else + // could chmod its own mirror back open and rename the payload out + // of it. Sources with foreign-owned ancestors are refused before + // anything moves. + if(srcst.st_uid != ::geteuid()) + return -EPERM; + + FD srcdir(fs::openat(srcfd_,".",STAGING_DIR_FLAGS)); + if(srcdir.get() < 0) + return srcdir.release(); + FD dst; + rv = ::_open_fresh_staging_dir(dstfd_,name_,dst); + if(rv < 0) + return rv; + + fs::attr::copy(srcfd_,dst.get(),FS_ATTR_CLEAR_IMMUTABLE); + + AccessGate gate; + gate.srcdir = std::move(srcdir); + gate.dir = std::move(dst); + gate.source = srcst; + gate.name = name_; + gates_.emplace_back(std::move(gate)); + + return 0; +} + +static +int +_finalize_access_gates(std::vector &gates_) +{ + for(auto &gate : gates_) + { + int rv = fs::fchown_check_on_error(gate.dir.get(),gate.source); + if(rv < 0) + return rv; + + // Gates are applied once, after all of them exist but before the + // payload moves: they mirror the source's read and execute bits + // and clear every write, setid and sticky bit. There is no + // intermediate window in which a gate is writable by a non-daemon + // user, and no gate owner exists who could change it back. + const mode_t want = gate.source.st_mode & 0555; + rv = fs::fchmod(gate.dir.get(),want); + if(rv < 0) + return rv; + fs::futimens(gate.dir.get(),gate.source); + + rv = ::_verify_mode_only_acl(gate.srcdir.get(),gate.dir.get()); + if(rv < 0) + return rv; + + struct stat st; + rv = fs::fstat(gate.dir.get(),&st); + if(rv < 0) + return rv; + if((st.st_uid != ::geteuid()) || + (st.st_gid != gate.source.st_gid) || + ((st.st_mode & 07777) != want)) + return -EPERM; + } + + return 0; +} + +// Move `branch_/oldfusepath_` to +// `branch_/.mergerfs_rename_exdev//stagedname_` +// without replacing anything already staged there. +static +int +_rename_exdev_stage(const Branch *branch_, + const fs::path &oldfusepath_, + const std::string &stagedname_, + Staged &staged_) +{ + int rv; + FD srcfd; + FD dstfd; + const std::string name = oldfusepath_.filename().string(); + + srcfd.reset(fs::open(branch_->path.string(),(O_RDONLY|O_DIRECTORY|O_CLOEXEC))); + if(srcfd.get() < 0) + return srcfd.release(); + + dstfd.reset(::_open_staging_root(srcfd.get())); + if(dstfd.get() < 0) + return dstfd.release(); + + for(const auto &component : oldfusepath_.parent_path()) + { + FD nextsrc; + FD nextdst; + + rv = ::_open_staging_dir(srcfd.get(), + dstfd.get(), + component.string(), + nextsrc, + nextdst); + if(rv < 0) + return rv; + + srcfd = std::move(nextsrc); + dstfd = std::move(nextdst); + } + + rv = fs::renameat_noreplace(srcfd.get(),name,dstfd.get(),stagedname_); + if(rv < 0) + return rv; + + staged_.srcdir = std::move(srcfd); + staged_.dstdir = std::move(dstfd); + staged_.moved = true; + staged_.name = stagedname_; + staged_.branch = branch_->path; + staged_.relocated = oldfusepath_.parent_path() / stagedname_; + + return 0; +} + +// Remove a portable namespace the source never entered. This request +// created every directory in it and the wrapper keeps them private +// until publication, so removal by name relative to the pinned parents +// can't affect anything else. A failed finalization may have applied +// the source's mode to a gate, so each parent is made writable first. +static +void +_remove_unused_portable_namespace(const int stagingrootfd_, + const std::string &wrappername_, + const FD &wrapper_, + const std::vector &gates_, + const FD &payload_) +{ + if(wrapper_.get() < 0) + return; + + // The real payload directory sits inside the last gate, or directly + // in the wrapper for a root source. + if(payload_.get() >= 0) + { + const int parentfd = (gates_.empty() ? + wrapper_.get() : + gates_.back().dir.get()); + fs::fchmod(parentfd,0700); + ::unlinkat(parentfd,".payload",AT_REMOVEDIR); + } + + for(size_t i = gates_.size(); i-- > 0;) + { + const int parentfd = ((i == 0) ? + wrapper_.get() : + gates_[i - 1].dir.get()); + fs::fchmod(parentfd,0700); + ::unlinkat(parentfd,gates_[i].name.c_str(),AT_REMOVEDIR); + } + + ::unlinkat(stagingrootfd_,wrappername_.c_str(),AT_REMOVEDIR); +} + +// Without renameat2, move the payload into a fresh private namespace: +// +// .mergerfs_rename_exdev///.payload/ +// +// The access gates mirror the old source parents so a pool user meets +// the same directory permissions on the way to the payload. The real +// `.payload` directory is the last component of that route, created +// inside the final gate while the whole namespace is still private +// (directly in the wrapper for a root source). There is no +// intermediate link and no path to the payload which does not pass +// through every gate. Gates are owned by the daemon, so no gate owner +// exists which could rename the payload out of its mirror; their mode +// mirrors the source's read and execute bits with every write, setid +// and sticky bit cleared, applied once before the move. Ancestors +// owned by anyone else cannot be represented this way and are refused +// 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. The wrapper and +// `.payload` are created exclusively 0700 and verified as real +// directories through pinned descriptors, and become 0555 only after +// the move; neither is ever publicly writable. +static +int +_rename_exdev_stage_portable(const Branch *branch_, + const fs::path &oldfusepath_, + const std::string &wrappername_, + Staged &staged_, + fs::path &stagedpath_) +{ + int rv; + const std::string name = oldfusepath_.filename().string(); + + FD srcfd(fs::open(branch_->path.string(),(O_RDONLY|O_DIRECTORY|O_CLOEXEC))); + if(srcfd.get() < 0) + return srcfd.release(); + + FD stagingroot(::_open_staging_root(srcfd.get())); + if(stagingroot.get() < 0) + return stagingroot.release(); + + FD wrapper; + FD payload; + std::vector gates; + bool moved = false; + // Repeated setup failures must not accumulate namespaces. + DEFER + { + if(!moved) + ::_remove_unused_portable_namespace(stagingroot.get(), + wrappername_, + wrapper, + gates, + payload); + }; + + rv = ::_open_fresh_staging_dir(stagingroot.get(),wrappername_,wrapper); + if(rv < 0) + return rv; + + int parentfd = wrapper.get(); + for(const auto &component : oldfusepath_.parent_path()) + { + FD nextsrc(fs::openat(srcfd.get(), + component.string(), + STAGING_DIR_FLAGS)); + if(nextsrc.get() < 0) + return nextsrc.release(); + + rv = ::_prepare_access_gate(nextsrc.get(), + parentfd, + component.string(), + gates); + if(rv < 0) + return rv; + parentfd = gates.back().dir.get(); + srcfd = std::move(nextsrc); + } + + // The real payload directory is created inside the final gate, or + // directly in the wrapper for a root source, while that parent is + // still private and writable by the daemon. It is the only `.payload` + // created by mergerfs: a source component named `.payload` is an + // ordinary mirrored directory like any other. + rv = ::_open_fresh_staging_dir(parentfd,".payload",payload); + if(rv < 0) + return rv; + + // Reject missing ownership, mode, or nontrivial ACLs while the source + // is still at its original path. Only descriptor and final mode + // failures after this point require the conservative rollback below. + rv = ::_finalize_access_gates(gates); + if(rv < 0) + return rv; + + rv = fs::renameat(srcfd.get(),name,payload.get(),name); + if(rv < 0) + return rv; + moved = true; + + staged_.portable = true; + staged_.moved = true; + staged_.name = name; + staged_.branch = branch_->path; + staged_.srcdir = std::move(srcfd); + staged_.dstdir = std::move(payload); + staged_.relocated = fs::path(wrappername_) / + oldfusepath_.parent_path() / ".payload" / name; + + struct stat st; + rv = fs::fstatat_nofollow(staged_.dstdir.get(),name.c_str(),&st); + if(rv < 0) + return rv; + staged_.directory = S_ISDIR(st.st_mode); + + // The payload directory becomes traversable but is never writable. + rv = fs::fchmod(staged_.dstdir.get(),0555); + if(rv < 0) + return rv; + + struct stat payloadst; + rv = fs::fstat(staged_.dstdir.get(),&payloadst); + if(rv < 0) + return rv; + if(payloadst.st_mode & (S_IWUSR|S_IWGRP|S_IWOTH)) + return -EPERM; + + // The name the replacement symlink publishes must reach this same + // `.payload` directory through the gate chain (or the wrapper, for a + // root source). + rv = fs::fstatat_nofollow(parentfd,".payload",&st); + if(rv < 0) + return rv; + if(!fs::same_inode(st,payloadst)) + return -EPERM; + + struct stat wrapperst; + rv = fs::fstat(wrapper.get(),&wrapperst); + if(rv < 0) + return rv; + if(wrapperst.st_mode & (S_IWGRP|S_IWOTH)) + return -EPERM; + + // Verify the wrapper is still the directory this request created, + // then publish the namespace. Until this succeeds no pool user can + // traverse into its access gates or the payload. + rv = fs::fstatat_nofollow(stagingroot.get(),wrappername_.c_str(),&st); + if(rv < 0) + return rv; + if(!fs::same_inode(st,wrapperst)) + return -EPERM; + + rv = fs::fchmod(wrapper.get(),0555); + if(rv < 0) + return rv; + + stagedpath_ = staged_.relocated; + return 0; +} + +// Undo only moves which actually happened. Native staging has an atomic +// no-replace rollback. Portable regular files can be restored with an +// atomic hard-link publication followed by removal of the staged link. +// Portable directories have no portable no-replace publication +// operation. Leave them staged and report their recovery path rather +// than ever replacing a source recreated by another request. +static +bool +_rename_exdev_unstage(std::vector &staged_, + const fs::path &oldfusepath_) +{ + bool restored = true; + const std::string sourcename = oldfusepath_.filename().string(); + + for(auto &staged : staged_) + { + if(!staged.moved) + continue; + + int rv; + if(!staged.portable) + { + rv = fs::renameat_noreplace(staged.dstdir.get(),staged.name, + staged.srcdir.get(),sourcename); + } + else if(staged.directory) + { + rv = -EOPNOTSUPP; + } + else + { + rv = ::to_neg_errno(::linkat(staged.dstdir.get(),staged.name.c_str(), + staged.srcdir.get(),sourcename.c_str(),0)); + // Only after the old name is restored, reopen write permission + // on our pinned, daemon-owned directory to remove the spare link. + if(rv == 0) + rv = fs::fchmod(staged.dstdir.get(),0700); + if(rv == 0) + rv = ::to_neg_errno(::unlinkat(staged.dstdir.get(), + staged.name.c_str(),0)); + } + + if(rv < 0) + { + restored = false; + SysLog::error("rename-exdev rollback failed (errno={}); staged data remains at {}", + -rv, + (staged.branch / rename_exdev::STAGING_DIR / staged.relocated).string()); + } + } + + staged_.clear(); + return restored; +} + +// A random leaf short enough to fit `name_max_`. Used when even the +// shortest suffixed form of the source's name cannot fit: the staged +// name is internal and opaque, so it only has to be unique within the +// staging directory, which a truncated random value provides. The +// smallest name limit POSIX requires is 14 characters, and this fits +// wherever the staging root itself is representable. +static +std::string +_rename_exdev_opaque_leaf_name(const size_t name_max_) +{ + char name[32]; + const int len = snprintf(name,sizeof(name),"%016llx", + (unsigned long long)RND::rand64()); + + if(len <= 0) + return std::string(); + + return std::string(name,std::min((size_t)len,name_max_)); +} + +// The staged name is the source's leaf name, plus a random suffix from +// the second attempt on. The suffixed name must fit the staging +// directory of every branch it is created on, so it is shortened as +// needed; the shortened leaf is opaque and only has to be unique here. +static +std::string +_rename_exdev_staged_name(const fs::path &oldfusepath_, + const int attempt_, + const size_t name_max_) +{ + char suffix[32]; + std::string name = oldfusepath_.filename().string(); + + if(attempt_ == 0) + return name; + + snprintf(suffix,sizeof(suffix),".%016llx", + (unsigned long long)RND::rand64()); + + const size_t suffixlen = strlen(suffix); + if(name.size() + suffixlen > name_max_) + { + // The suffix is 17 characters and the smallest NAME_MAX POSIX + // requires is 14, so some filesystems leave no room for the + // source's name once it is appended. Such a rename still uses a + // bounded opaque random leaf instead of failing outright. + if(name_max_ <= suffixlen) + return ::_rename_exdev_opaque_leaf_name(name_max_); + name.resize(name_max_ - suffixlen); + } + + return name + suffix; +} + +static +std::string +_rename_exdev_wrapper_name() +{ + char name[32]; + snprintf(name,sizeof(name),".p-%016llx", + (unsigned long long)RND::rand64()); + return name; +} + +// The staged leaf is created on every source branch, so the retry +// suffix is fitted to the smallest NAME_MAX among them. Filesystems +// which do not report a limit use NAME_MAX. +static +size_t +_rename_exdev_min_name_max(const std::vector &obranches_) +{ + size_t name_max = NAME_MAX; + + for(const auto &branch : obranches_) + { + const long max = ::pathconf(branch->path.c_str(),_PC_NAME_MAX); + if(max > 0) + name_max = std::min(name_max,(size_t)max); + } + + return name_max; +} + +// The staged path must be absent from every configured branch: the +// published symlink resolves through the pool, so a name occupied on +// any branch, including read-only and no-create ones, could be followed +// instead of the staged copy. A missing name is free. A name which is +// there is a collision, and another name is tried. Any other error +// cannot be verified and fails the rename rather than being mistaken +// for either. +static +int +_rename_exdev_staged_target_absent(const Branches::Ptr &branches_, + const fs::path &stagedpath_) +{ + int rv; + struct stat st; + + for(const auto &branch : *branches_) + { + rv = fs::lstat(branch.path / rename_exdev::STAGING_DIR / stagedpath_,&st); + if(rv == -ENOENT) + continue; + if(rv < 0) + return rv; + return -EEXIST; + } + + return 0; +} + +// A destination copy pinned by the preflight scan: the branch it sits +// on and the identity it had there. Publication may replace an object +// only while it still matches this identity; anything else at the name +// appeared after the scan and is not ours to replace. +struct DestinationMember +{ + fs::path branch; + dev_t dev; + ino_t ino; + bool directory; +}; + +static +const DestinationMember * +_rename_exdev_find_member(const std::vector &members_, + const fs::path &branch_) +{ + for(const auto &member : members_) + { + if(member.branch == branch_) + return &member; + } + + return NULL; +} + +// Every pinned destination copy must sit on a branch where the +// replacement link was created: a copy on any other branch would +// shadow the published name there and could only be removed behind +// the back of a rename(2). Refused before anything is moved, because +// a portable directory cannot always be unstaged once it has been. +static +int +_rename_exdev_check_prepared_covers_members(const std::vector &members_, + const std::vector &prepared_) +{ + for(const auto &member : members_) + { + bool covered = false; + + for(const auto &record : prepared_) + { + if(record.branch == member.branch) + { + covered = true; + break; + } + } + + if(!covered) + return -EXDEV; + } + + return 0; +} + +// Stage the source on every branch in `obranches_`. Every branch gets +// the same relative path so a single symlink can point to it. Prefer +// the original layout when atomic no-replace rename is available. If it +// is not, all branches instead use the same fresh portable namespace. +// Each candidate path is first verified absent from every configured +// branch; a taken name, including one left by an earlier transaction +// on a branch nothing is staged into, is retried under a fresh name +// while an unverifiable one fails the rename. Before each attempt +// `prepare_` creates the real temporary replacement symlink for that +// path, so ownership, permission and usability failures happen before +// anything is moved, and the prepared links are checked against the +// pinned destinations before the first source move: a portable +// directory cannot always be unstaged once it has been. +template +static +int +_rename_exdev_rename_target(const Branches::Ptr &branches_, + const std::vector &obranches_, + const fs::path &oldfusepath_, + const std::vector &members_, + std::vector &prepared_, + std::vector &staged_, + fs::path &stagedpath_, + PrepareSymlink prepare_) +{ + int rv = 0; + const size_t name_max = ::_rename_exdev_min_name_max(obranches_); + + for(int attempt = 0; attempt < 8; attempt++) + { + const std::string stagedname = + ::_rename_exdev_staged_name(oldfusepath_,attempt,name_max); + if(stagedname.empty()) + return -EXDEV; + + const fs::path stagedpath = oldfusepath_.parent_path() / stagedname; + + rv = ::_rename_exdev_staged_target_absent(branches_,stagedpath); + if(rv < 0) + { + if((rv == -EEXIST) || (rv == -ENAMETOOLONG)) + continue; + return rv; + } + + rv = prepare_(stagedpath); + if(rv < 0) + return rv; + + rv = ::_rename_exdev_check_prepared_covers_members(members_,prepared_); + if(rv < 0) + return rv; + + for(auto &branch : obranches_) + { + Staged staged; + rv = ::_rename_exdev_stage(branch,oldfusepath_,stagedname,staged); + if(staged.moved) + staged_.emplace_back(std::move(staged)); + if(rv < 0) + break; + } + + if(rv >= 0) + { + stagedpath_ = stagedpath; + return 0; + } + + const int stage_rv = rv; + if(!::_rename_exdev_unstage(staged_,oldfusepath_)) + return -EXDEV; + if((stage_rv != -EEXIST) && (stage_rv != -EOPNOTSUPP)) + return -EXDEV; + if(stage_rv == -EOPNOTSUPP) + break; + } + + if(rv != -EOPNOTSUPP) + return -EXDEV; + + // Keeping a directory destination for rollback needs no-replace + // rename. Refuse before staging a directory we cannot put back. + for(const auto &member : members_) + { + if(member.directory) + return -EXDEV; + } + + for(int attempt = 0; attempt < 8; attempt++) + { + const std::string wrappername = ::_rename_exdev_wrapper_name(); + fs::path candidate = fs::path(wrappername) / + oldfusepath_.parent_path() / ".payload" / + oldfusepath_.filename(); + + rv = ::_rename_exdev_staged_target_absent(branches_,candidate); + if(rv < 0) + { + if(rv == -EEXIST) + continue; + return rv; + } + + // In particular, create the real temporary symlink and confirm + // it covers every pinned destination before moving a directory. + // Portable directory rollback cannot safely replace a + // concurrently recreated source, so common creation, ownership + // and permission failures must happen before the first move. + rv = prepare_(candidate); + if(rv < 0) + return rv; + + rv = ::_rename_exdev_check_prepared_covers_members(members_,prepared_); + if(rv < 0) + return rv; + + for(auto &branch : obranches_) + { + Staged staged; + fs::path branchpath; + rv = ::_rename_exdev_stage_portable(branch, + oldfusepath_, + wrappername, + staged, + branchpath); + if(rv >= 0) + candidate = branchpath; + if(staged.moved) + staged_.emplace_back(std::move(staged)); + if(rv < 0) + break; + } + + if(rv >= 0) + { + stagedpath_ = candidate; + return 0; + } + + const int stage_rv = rv; + if(!::_rename_exdev_unstage(staged_,oldfusepath_)) + return -EXDEV; + if(stage_rv != -EEXIST) + return -EXDEV; + } return -EXDEV; } +// Returns 0 when the directory is empty, 1 when it is not, and a +// negative errno when it could not be opened or read. A readdir error +// is told apart from the end of the directory by errno, which readdir +// leaves unchanged there. static int -_rename_exdev_rel_symlink(const Policy::Action &actionPolicy_, - const Branches::Ptr branches_, - const fs::path &oldfusepath_, - const fs::path &newfusepath_) +_dir_is_empty(const fs::path &path_) { int rv; - struct stat source; - fs::path target; - fs::path linkpath; - std::vector branches; + DIR *dir; + struct dirent *d; - rv = ::_rename_exdev_rename_target(actionPolicy_, - branches_, - oldfusepath_, - branches, - source); - if(rv < 0) - return rv; + dir = ::opendir(path_.c_str()); + if(dir == NULL) + return -errno; - linkpath = newfusepath_; - target = ".mergerfs_rename_exdev"; - target /= oldfusepath_; - target = target.lexically_relative(linkpath.parent_path()); + rv = 0; + for(;;) + { + errno = 0; + d = ::readdir(dir); + if(d == NULL) + { + if(errno != 0) + rv = -errno; + break; + } + if((strcmp(d->d_name,".") == 0) || (strcmp(d->d_name,"..") == 0)) + continue; + rv = 1; + break; + } - rv = FUSE::symlink_owned({source.st_uid,source.st_gid},target.c_str(),linkpath); - if(rv < 0) - ::_rename_exdev_rename_back(branches,oldfusepath_); + ::closedir(dir); return rv; } +// The sources the action policy selected must be the same kind of +// object on every branch: publication points one replacement symlink +// at the copy staged from the first source, and a later source of a +// different type would be staged beside it, where a symlink's relative +// target would resolve from inside the staging directory and dangle. +// Refused before anything moves, like a symlink which exists on more +// than one branch. A branch whose copy vanished since selection holds +// no source to compare and is left for staging to refuse. static int -_rename_exdev_abs_symlink(const Policy::Action &actionPolicy_, - const Branches::Ptr branches_, - const fs::path &mount_, - const fs::path &oldfusepath_, - const fs::path &newfusepath_) +_rename_exdev_check_source_types(const std::vector &obranches_, + const fs::path &oldfusepath_, + const struct stat &source_) +{ + int rv; + struct stat st; + + for(size_t i = 1; i < obranches_.size(); i++) + { + rv = fs::lstat(obranches_[i]->path / oldfusepath_,&st); + if(rv == -ENOENT) + continue; + if(rv < 0) + return rv; + if((st.st_mode & S_IFMT) != (source_.st_mode & S_IFMT)) + return -EXDEV; + } + + return 0; +} + +// rename(2) replaces an existing destination. Scan every configured +// branch once, before anything is moved, and pin which of them hold a +// destination, rejecting the cases where rename(2) would fail rather +// than discovering them after the source has been staged. A +// destination on a configured read-only branch cannot be removed, and +// on a configured no-create branch the replacement link cannot be +// created, so in both cases the old entry would shadow the published +// link there and the fallback refuses. So do aliases: two configured +// branches with the same underlying root would be published to twice +// and the second would fail. A destination on any other branch is +// pinned; publication refuses those it does not itself replace. +static +int +_rename_exdev_scan_destination(const Branches::Ptr &branches_, + const fs::path &newfusepath_, + const struct stat &source_, + std::vector &members_) +{ + int rv; + struct stat st; + std::vector rootdevs; + std::vector rootinos; + + for(const auto &branch : *branches_) + { + // An unstattable root (missing mountpoint, unmounted branch) + // cannot hold the destination either; the loop below treats it + // as absent, as the pre-scan code did. + rv = fs::lstat(branch.path,&st); + if(rv < 0) + continue; + for(size_t i = 0; i < rootdevs.size(); i++) + { + if((rootdevs[i] == st.st_dev) && (rootinos[i] == st.st_ino)) + return -EXDEV; + } + rootdevs.push_back(st.st_dev); + rootinos.push_back(st.st_ino); + } + + for(const auto &branch : *branches_) + { + rv = fs::lstat(branch.path / newfusepath_,&st); + if(rv == -ENOENT) + continue; + if(rv < 0) + return rv; + + if(branch.ro_or_nc()) + return -EXDEV; + if(S_ISDIR(st.st_mode) && !S_ISDIR(source_.st_mode)) + return -EISDIR; + if(!S_ISDIR(st.st_mode) && S_ISDIR(source_.st_mode)) + return -ENOTDIR; + if(S_ISDIR(st.st_mode)) + { + rv = ::_dir_is_empty(branch.path / newfusepath_); + if(rv < 0) + return rv; + if(rv != 0) + return -ENOTEMPTY; + } + + DestinationMember member; + member.branch = branch.path; + member.dev = st.st_dev; + member.ino = st.st_ino; + member.directory = S_ISDIR(st.st_mode); + members_.emplace_back(member); + } + + return 0; +} + +static +fs::path +_rename_exdev_temp_path(const fs::path &dir_) +{ + char name[64]; + snprintf(name,sizeof(name),"%s_%016llx", + rename_exdev::STAGING_DIR.c_str(), + (unsigned long long)RND::rand64()); + + return dir_ / name; +} + +// Create the replacement symlink for `newfusepath_` under a temporary +// name next to it, on whichever branches the strict preparation API +// creates it, recording each creation together with the identity the +// fresh link had when it was made. The temporary name is taken, never +// replaced: a collision, or a preparation which failed partway, is +// undone through the records - only where the link is still the object +// this request created - and retried under a fresh name. +static +int +_rename_exdev_prepare_symlink(const Branches::Ptr &branches_, + const ugid_t owner_, + const fs::path &target_, + const fs::path &newfusepath_, + fs::path &tmpfusepath_, + std::vector &prepared_) +{ + int rv; + + for(int attempt = 0; attempt < 8; attempt++) + { + tmpfusepath_ = ::_rename_exdev_temp_path(newfusepath_.parent_path()); + + rv = FUSE::symlink_prepare(branches_,owner_,target_.c_str(),tmpfusepath_,prepared_); + if(rv >= 0) + return 0; + + // The attempt may have created the link on some branches before + // failing, and the name may simply have been taken. Either way + // those links are undone before the next attempt, which uses a + // fresh name. + FUSE::symlink_unprepare(prepared_); + if(rv != -EEXIST) + break; + } + + tmpfusepath_.clear(); + return rv; +} + +namespace +{ + // A destination replaced by publication. What was there is kept at + // `backup` until every branch has been published. The published + // link's identity (`dev`/`ino`) is the recorded one, so rollback + // removes it only while the name still refers to that object. + struct Replaced + { + fs::path newpath; + fs::path backup; + dev_t dev = 0; + ino_t ino = 0; + bool directory = false; + bool aside = false; + }; +} + +// Keep the object at `r_.newpath` under a temporary name. A hard link +// leaves a non-directory in place so its replacement stays atomic. A +// directory, or a file which can't be linked, is moved aside. An empty +// directory must still be empty, as rename(2) would require. Temporary +// names are taken with no-replace operations and a fresh name on +// collision, so a temporary name never overwrites an unrelated entry. +// On failure the backup names what is left; the caller undoes it. +static +int +_rename_exdev_keep_destination(Replaced &r_) +{ + int rv = -EXDEV; + + for(int attempt = 0; attempt < 8; attempt++) + { + r_.backup = ::_rename_exdev_temp_path(r_.newpath.parent_path()); + + if(!r_.directory) + { + rv = ::to_neg_errno(::linkat(AT_FDCWD,r_.newpath.c_str(), + AT_FDCWD,r_.backup.c_str(),0)); + if(rv == 0) + return 0; + if(rv == -EEXIST) + continue; + } + + rv = fs::renameat_noreplace(AT_FDCWD,r_.newpath.string(), + AT_FDCWD,r_.backup.string()); + if(rv == 0) + { + r_.aside = true; + // Only a directory must still be empty; a file moved aside + // after a failed link is fine whatever opendir would say. + if(!r_.directory) + return 0; + rv = ::_dir_is_empty(r_.backup); + if(rv < 0) + return rv; + return ((rv != 0) ? -ENOTEMPTY : 0); + } + if(rv != -EEXIST) + break; + } + + r_.backup.clear(); + return rv; +} + +// Undo a keep whose publication did not happen: the object is either +// back at its original name already, in which case only the spare hard +// link is removed, or still at the temporary name, in which case it is +// put back. Restores never replace a name created in the meantime; a +// name which can't be restored is logged and its data remains at the +// temporary name. +static +void +_rename_exdev_unkeep(Replaced &r_) +{ + int rv; + + if(r_.backup.empty()) + return; + + if(r_.aside) + { + rv = fs::renameat_noreplace(AT_FDCWD,r_.backup.string(), + AT_FDCWD,r_.newpath.string()); + if(rv < 0) + SysLog::error("rename-exdev rollback failed (errno={}); previous {} remains at {}", + -rv, + r_.newpath.string(), + r_.backup.string()); + } + else + { + rv = fs::unlink(r_.backup); + if(rv < 0) + SysLog::warning("rename-exdev: could not remove temporary link {} (errno={})", + r_.backup.string(), + -rv); + } + + r_.backup.clear(); +} + +// Undo publication on the branches already replaced: put back what was +// at each destination, or remove the new symlink if nothing was. The +// name is unlinked only while it still refers to the link this request +// published; anything else there appeared afterwards and is not ours +// to remove. The restore itself never replaces a name created in the +// meantime. +static +void +_rename_exdev_unpublish(const std::vector &replaced_) +{ + for(auto r = replaced_.rbegin(); r != replaced_.rend(); ++r) + { + int rv; + + rv = fs::is_same_file(r->newpath,r->dev,r->ino); + if(rv == 0) + { + SysLog::warning("rename-exdev: {} was replaced during rollback; leaving it alone", + r->newpath.string()); + if(!r->backup.empty()) + SysLog::error("rename-exdev rollback failed; previous {} remains at {}", + r->newpath.string(), + r->backup.string()); + continue; + } + if(rv == 1) + { + rv = fs::unlink(r->newpath); + if((rv < 0) && (rv != -ENOENT)) + { + SysLog::error("rename-exdev rollback failed (errno={}); could not remove {}", + -rv, + r->newpath.string()); + if(!r->backup.empty()) + SysLog::error("rename-exdev rollback failed; previous {} remains at {}", + r->newpath.string(), + r->backup.string()); + continue; + } + } + else if(rv != -ENOENT) + { + SysLog::error("rename-exdev rollback failed (errno={}); could not inspect {}", + -rv, + r->newpath.string()); + continue; + } + + if(r->backup.empty()) + continue; + + rv = fs::renameat_noreplace(AT_FDCWD,r->backup.string(), + AT_FDCWD,r->newpath.string()); + if(rv == -EOPNOTSUPP) + { + rv = ::to_neg_errno(::linkat(AT_FDCWD,r->backup.c_str(), + AT_FDCWD,r->newpath.c_str(),0)); + if(rv == 0) + rv = fs::unlink(r->backup); + } + if(rv < 0) + SysLog::error("rename-exdev rollback failed (errno={}); previous {} remains at {}", + -rv, + r->newpath.string(), + r->backup.string()); + } +} + +// Rename the prepared symlink over `newfusepath_` on every branch +// where it was created, as rename(2) would, using only the recorded +// creations: which branches hold the link is never rediscovered by +// rescanning the temporary name. Each prepared link is verified to +// still be the object this request created immediately before it is +// renamed. Destination copies are only touched on branches of the +// pinned preflight scan and only while they still match their pinned +// identity: a copy which appeared after the scan, and one which cannot +// be verified, refuse the rename instead of being moved or deleted. A +// destination the scan found absent is never replaced either: if +// something is there now, the rename is refused. If any branch fails, +// the destinations already replaced are restored so the caller can +// move the source back without leaving links to it. +static +int +_rename_exdev_publish_prepared_symlink(const std::vector &prepared_, + const fs::path &newfusepath_, + const struct stat *times_, + const std::vector &members_) +{ + int rv; + struct stat st; + std::vector replaced; + Replaced r; + + if(prepared_.empty()) + return -ENOENT; + + for(size_t i = 0; i < prepared_.size(); i++) + { + const FUSE::PreparedSymlink &record = prepared_[i]; + const fs::path newpath = record.branch / newfusepath_; + bool dest_exists; + + r = Replaced(); + r.newpath = newpath; + r.dev = record.dev; + r.ino = record.ino; + + // The link must still be the object this request created. + rv = fs::is_same_file(record.path,record.dev,record.ino); + if(rv < 0) + break; + if(rv == 0) + { + rv = -EXDEV; + break; + } + + // The times are promised to survive the rename; failing to set + // them fails the rename. Destinations already replaced by + // earlier records are put back by the failure path below. + if(times_ != NULL) + { + rv = fs::lutimens(record.path.string(),*times_); + if(rv < 0) + break; + } + + rv = fs::lstat(newpath,&st); + if((rv < 0) && (rv != -ENOENT)) + break; + dest_exists = (rv == 0); + + if(dest_exists) + { + const DestinationMember *member = ::_rename_exdev_find_member(members_,record.branch); + + if((member == NULL) || + (member->dev != st.st_dev) || + (member->ino != st.st_ino)) + { + rv = -EXDEV; + break; + } + + r.directory = member->directory; + // A directory can't be renamed over. If the last + // non-directory's rename fails nothing has changed, so it + // needs no backup copy either. + if(r.directory || ((i + 1) < prepared_.size())) + { + rv = ::_rename_exdev_keep_destination(r); + if(rv < 0) + break; + } + } + + // An unpinned destination would have been replaced by a plain + // rename; refusing it is conservative because it appeared after + // the scan and was never verified. + if(dest_exists) + rv = fs::rename(record.path,newpath); + else + rv = fs::renameat_noreplace(AT_FDCWD,record.path.string(), + AT_FDCWD,newpath.string()); + if(rv == -EOPNOTSUPP) + { + // Without renameat2 the name is taken with a hard link, + // which links the symlink itself and cannot replace an + // existing destination, and the temporary name is then + // removed. The inode is unchanged, so the recorded identity + // still describes the published link. + rv = ::to_neg_errno(::linkat(AT_FDCWD,record.path.c_str(), + AT_FDCWD,newpath.c_str(),0)); + if(rv == 0) + { + rv = fs::unlink(record.path); + if(rv < 0) + { + fs::unlink(newpath); + SysLog::error("rename-exdev: could not remove temporary link {} (errno={})", + record.path.string(), + -rv); + } + } + } + if(rv < 0) + break; + + replaced.emplace_back(std::move(r)); + } + + // Every failure after the first record was published must restore + // the destinations already replaced; otherwise their originals + // would be stranded at their backup names with nothing logging it. + if(rv < 0) + { + ::_rename_exdev_unkeep(r); + ::_rename_exdev_unpublish(replaced); + return rv; + } + + // The rename has succeeded everywhere. The kept copies of the + // replaced destinations are now removed, as rename(2) would have. A + // failure leaves the data at the temporary name and is only + // reported. + for(const auto &r : replaced) + { + if(r.backup.empty()) + continue; + rv = fs::remove(r.backup); + if(rv < 0) + SysLog::warning("rename-exdev: could not remove replaced destination {} (errno={})", + r.backup.string(), + -rv); + } + + return 0; +} + +// Put source links that were moved aside back under their original +// names. A source recreated in the meantime is never replaced. +static +void +_rename_exdev_restore_sources(const std::vector> &aside_) +{ + for(const auto &[src,hidden] : aside_) + { + int rv = fs::renameat_noreplace(AT_FDCWD,hidden.string(), + AT_FDCWD,src.string()); + if(rv == -EOPNOTSUPP) + { + rv = ::to_neg_errno(::linkat(AT_FDCWD,hidden.c_str(), + AT_FDCWD,src.c_str(),0)); + if(rv == 0) + rv = fs::unlink(hidden); + } + if(rv < 0) + SysLog::error("rename-exdev rollback failed (errno={}); source symlink remains at {}", + -rv, + hidden.string()); + } +} + +// A symlink being renamed is not staged: moving it one directory deeper +// would break a relative target, including those of the replacement +// symlinks made by rel-symlink. rename(2) leaves a symlink's content +// alone, so recreate it at newpath with the same content, owner and +// times and remove the source. Recreation collapses every branch's +// copy of the symlink into the one target read from the first source, +// so a symlink which exists on more than one branch is refused before +// anything is moved: mirrors whose targets differ would silently lose +// their contents. Single-source renames keep working. +static +int +_rename_exdev_move_symlink(const Branches::Ptr &branches_, + const std::vector &obranches_, + const struct stat &source_, + const fs::path &oldfusepath_, + const fs::path &newfusepath_, + const std::vector &destmembers_) +{ + int rv; + std::string target; + fs::path tmpfusepath; + std::vector prepared; + std::vector> aside; + + if(obranches_.size() > 1) + return -EXDEV; + + target.resize(PATH_MAX); + rv = fs::readlink((obranches_[0]->path / oldfusepath_).string(), + target.data(), + target.size()); + if(rv < 0) + return rv; + if((size_t)rv >= target.size()) + return -ENAMETOOLONG; + target.resize(rv); + + rv = ::_rename_exdev_prepare_symlink(branches_, + {source_.st_uid,source_.st_gid}, + target, + newfusepath_, + tmpfusepath, + prepared); + if(rv < 0) + return rv; + + // A pinned destination on a branch which will not publish the link + // would shadow it there. Refused before any source link moves aside, + // which is the first thing this path changes. + rv = ::_rename_exdev_check_prepared_covers_members(destmembers_,prepared); + if(rv < 0) + { + FUSE::symlink_unprepare(prepared); + return rv; + } + + // Move every source aside before publishing. A source which can't be + // removed then fails the rename while nothing else has changed. Each + // aside is taken under a fresh no-replace name, so a collision with + // an unrelated entry takes another name instead of overwriting it. + // Without renameat2 the name is taken with a hard link, which links + // the symlink itself, and the original name is then removed; a + // failure there removes the link and leaves the source alone. + for(auto &branch : obranches_) + { + const fs::path src = branch->path / oldfusepath_; + fs::path hidden; + + rv = -EEXIST; + for(int attempt = 0; attempt < 8; attempt++) + { + hidden = ::_rename_exdev_temp_path(src.parent_path()); + rv = fs::renameat_noreplace(AT_FDCWD,src.string(), + AT_FDCWD,hidden.string()); + if(rv == -EOPNOTSUPP) + { + rv = ::to_neg_errno(::linkat(AT_FDCWD,src.c_str(), + AT_FDCWD,hidden.c_str(),0)); + if(rv == -EEXIST) + continue; + if(rv < 0) + break; + rv = fs::unlink(src); + if(rv < 0) + { + fs::unlink(hidden); + break; + } + break; + } + if(rv != -EEXIST) + break; + } + if(rv < 0) + break; + aside.emplace_back(src,hidden); + } + + if(rv >= 0) + rv = ::_rename_exdev_publish_prepared_symlink(prepared, + newfusepath_, + &source_, + destmembers_); + if(rv < 0) + { + FUSE::symlink_unprepare(prepared); + ::_rename_exdev_restore_sources(aside); + return rv; + } + + // The published replacement stays: it is the renamed object. A + // source link that is still linked under its hidden name means the + // rename did not remove the original, so the call fails. Returning 0 + // here left both names in place. + int error = 0; + for(const auto &[src,hidden] : aside) + { + rv = fs::unlink(hidden); + if(rv < 0) + { + SysLog::error("rename-exdev: could not remove moved source {} (errno={})", + hidden.string(), + -rv); + if(error == 0) + error = rv; + } + } + + return error; +} + +// Fallback transactions verify a staged target against every +// configured branch and then publish against the same set. Two of them +// running at once could interleave those steps, so they are +// serialized. Renames with the feature disabled never enter the +// fallback and are not affected. +static std::mutex _rename_exdev_fallback_mutex; + +static +int +_rename_exdev_symlink(const RenameEXDEV::ENUM mode_, + const Policy::Action &actionPolicy_, + const Branches::Ptr branches_, + const fs::path &mount_, + const fs::path &oldfusepath_, + const fs::path &newfusepath_, + fs::path &relocated_, + char **relocated_out_) { int rv; struct stat source; fs::path target; - fs::path linkpath; - std::vector branches; + fs::path stagedpath; + std::vector prepared; + std::vector staged; + std::vector obranches; + std::vector destmembers; + const std::lock_guard guard(_rename_exdev_fallback_mutex); - rv = ::_rename_exdev_rename_target(actionPolicy_, - branches_, - oldfusepath_, - branches, - source); + rv = actionPolicy_(branches_,oldfusepath_,obranches); + if(rv < 0) + return rv; + if(obranches.empty()) + return -ENOENT; + + rv = fs::lstat(obranches[0]->path / oldfusepath_,&source); if(rv < 0) return rv; - linkpath = newfusepath_; - target = mount_; - target /= ".mergerfs_rename_exdev"; - target /= oldfusepath_; - - rv = FUSE::symlink_owned({source.st_uid,source.st_gid},target.c_str(),linkpath); + rv = ::_rename_exdev_scan_destination(branches_,newfusepath_,source,destmembers); if(rv < 0) - ::_rename_exdev_rename_back(branches,oldfusepath_); + return rv; + + rv = ::_rename_exdev_check_source_types(obranches,oldfusepath_,source); + if(rv < 0) + return rv; + + if(S_ISLNK(source.st_mode)) + return ::_rename_exdev_move_symlink(branches_, + obranches, + source, + oldfusepath_, + newfusepath_, + destmembers); + + auto prepare = [&](const fs::path &candidate_) + { + fs::path tmpfusepath; + + // A retry stages under a different name, so the links of the + // previous attempt, still pointing at it, go first. + FUSE::symlink_unprepare(prepared); + + fs::path candidate = fs::path(rename_exdev::STAGING_DIR) / candidate_; + if(mode_ == RenameEXDEV::ENUM::ABS_SYMLINK) + target = mount_ / candidate; + else + target = candidate.lexically_relative(newfusepath_.parent_path()); + + return ::_rename_exdev_prepare_symlink(branches_, + {source.st_uid,source.st_gid}, + target, + newfusepath_, + tmpfusepath, + prepared); + }; + + rv = ::_rename_exdev_rename_target(branches_, + obranches, + oldfusepath_, + destmembers, + prepared, + staged, + stagedpath, + prepare); + if(rv < 0) + { + FUSE::symlink_unprepare(prepared); + return rv; + } + + relocated_ = fs::path(rename_exdev::STAGING_DIR) / stagedpath; + // libfuse has to re-parent the kernel node onto the staged path. Do + // that allocation before publishing, while unstage can still put the + // source back. A failure after publication cannot be undone from + // here: the node update has not run, and a second stage would nest. + if(relocated_out_ != NULL) + { + *relocated_out_ = ::strdup(relocated_.c_str()); + if(*relocated_out_ == NULL) + { + FUSE::symlink_unprepare(prepared); + relocated_.clear(); + ::_rename_exdev_unstage(staged,oldfusepath_); + return -ENOMEM; + } + } + + rv = ::_rename_exdev_publish_prepared_symlink(prepared, + newfusepath_, + NULL, + destmembers); + + if(rv < 0) + { + if((relocated_out_ != NULL) && (*relocated_out_ != NULL)) + { + ::free(*relocated_out_); + *relocated_out_ = NULL; + } + FUSE::symlink_unprepare(prepared); + relocated_.clear(); + ::_rename_exdev_unstage(staged,oldfusepath_); + } return rv; } @@ -323,23 +2180,26 @@ _rename_exdev_abs_symlink(const Policy::Action &actionPolicy_, static int _rename_exdev(const fs::path &oldfusepath_, - const fs::path &newfusepath_) + const fs::path &newfusepath_, + fs::path &relocated_, + char **relocated_out_) { - switch(cfg.rename_exdev) + const RenameEXDEV::ENUM mode = cfg.rename_exdev; + + switch(mode) { case RenameEXDEV::ENUM::PASSTHROUGH: return -EXDEV; case RenameEXDEV::ENUM::REL_SYMLINK: - return ::_rename_exdev_rel_symlink(cfg.func.rename.policy, - cfg.branches, - oldfusepath_, - newfusepath_); case RenameEXDEV::ENUM::ABS_SYMLINK: - return ::_rename_exdev_abs_symlink(cfg.func.rename.policy, - cfg.branches, - cfg.mountpoint, - oldfusepath_, - newfusepath_); + return ::_rename_exdev_symlink(mode, + cfg.func.rename.policy, + cfg.branches, + cfg.mountpoint, + oldfusepath_, + newfusepath_, + relocated_, + relocated_out_); } return -EXDEV; @@ -364,17 +2224,23 @@ _rename(const fs::path &oldpath_, } int -FUSE::rename(const fuse_req_ctx_t *ctx_, - const char *oldfusepath_, - const char *newfusepath_) +FUSE::rename(const fuse_req_ctx_t *ctx_, + const char *oldfusepath_, + const char *newfusepath_, + char **relocated_) { int rv; + fs::path relocated; const fs::path oldfusepath{oldfusepath_}; const fs::path newfusepath{newfusepath_}; rv = ::_rename(oldfusepath,newfusepath); - if(rv == -EXDEV) - return ::_rename_exdev(oldfusepath,newfusepath); + if(rv != -EXDEV) + return rv; - return rv; + // A staged file or directory has its relocation path allocated + // before publication, so a failed allocation can still unstage. + // A symlink source is recreated at newpath and leaves the out + // pointer NULL, and libfuse renames that node normally. + return ::_rename_exdev(oldfusepath,newfusepath,relocated,relocated_); } diff --git a/src/fuse_rename.hpp b/src/fuse_rename.hpp index 72fe90df..8086aec7 100644 --- a/src/fuse_rename.hpp +++ b/src/fuse_rename.hpp @@ -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); } diff --git a/src/fuse_symlink.cpp b/src/fuse_symlink.cpp index ba1d59fa..28393f27 100644 --- a/src/fuse_symlink.cpp +++ b/src/fuse_symlink.cpp @@ -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 +#include +#include +#include #include #include +#include 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 &prepared_) +{ + int rv; + fs::path newdirpath; + std::vector newbranches; + std::vector 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(&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 &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 &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 diff --git a/src/fuse_symlink.hpp b/src/fuse_symlink.hpp index 6e0d2742..cc1aa219 100644 --- a/src/fuse_symlink.hpp +++ b/src/fuse_symlink.hpp @@ -18,17 +18,32 @@ #pragma once +#include "branches.hpp" #include "fuse.h" #include "fs_path.hpp" #include "ugid.hpp" #include +#include #include 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 &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 &prepared); } diff --git a/src/rename_exdev_staging.hpp b/src/rename_exdev_staging.hpp new file mode 100644 index 00000000..98a256ff --- /dev/null +++ b/src/rename_exdev_staging.hpp @@ -0,0 +1,30 @@ +/* + ISC License + + Copyright (c) 2026, Antonio SJ Musumeci + + 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 + +// 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"; +} diff --git a/tests/TEST_cfg_link_rename_exdev b/tests/TEST_cfg_link_rename_exdev index 5447bf64..11a41e51 100755 --- a/tests/TEST_cfg_link_rename_exdev +++ b/tests/TEST_cfg_link_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="") diff --git a/tests/TEST_rename_exdev_portable b/tests/TEST_rename_exdev_portable new file mode 100755 index 00000000..32755454 --- /dev/null +++ b/tests/TEST_rename_exdev_portable @@ -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()) diff --git a/tests/TEST_rename_exdev_publication b/tests/TEST_rename_exdev_publication new file mode 100755 index 00000000..9a656dc4 --- /dev/null +++ b/tests/TEST_rename_exdev_publication @@ -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()) diff --git a/tests/tests.cpp b/tests/tests.cpp index 96166d31..ea922dac 100644 --- a/tests/tests.cpp +++ b/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}, diff --git a/vendored/libfuse/include/fuse.h b/vendored/libfuse/include/fuse.h index 6c6cf83a..0a68aebc 100644 --- a/vendored/libfuse/include/fuse.h +++ b/vendored/libfuse/include/fuse.h @@ -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 *, diff --git a/vendored/libfuse/lib/fuse.cpp b/vendored/libfuse/lib/fuse.cpp index ce55a6e6..8872c166 100644 --- a/vendored/libfuse/lib/fuse.cpp +++ b/vendored/libfuse/lib/fuse.cpp @@ -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); }