From 11e759101d5c770a964a8ad0147aa73a7238647f Mon Sep 17 00:00:00 2001 From: Antonio SJ Musumeci Date: Wed, 25 Nov 2026 12:59:47 -0500 Subject: [PATCH] fix: make the preload helper correct on FreeBSD and safe on reopen - The helper called Linux fgetxattr on FreeBSD. Read mergerfs.fullpath there through extattr_get_fd in EXTATTR_NAMESPACE_USER; Linux keeps user.mergerfs.fullpath. - FreeBSD mode_t is promoted when passed through an ellipsis, so reading it back as mode_t was undefined. Read the promoted type. - O_TMPFILE includes O_DIRECTORY on Linux, so a plain directory open consumed a mode argument that wasn't passed. Require O_CREAT or the whole nonzero O_TMPFILE mask. - The backing path is returned without a terminating NUL. Reject empty or oversized values and terminate it before reopening; keep the already-open descriptor when no usable path is available. - The reopen of the backing file repeated O_TRUNC, and creat() ran creat() again. The open through mergerfs had already truncated that file, so the second truncation could only destroy data another process wrote in between. Drop O_TRUNC from the reopen and reopen creat()ed files O_WRONLY. - fopen and fopen64 reopened the branch path with the caller's mode, so w truncated a second time and a could recreate a name removed in between. Redirect only modes starting with r, including r+, as given, and keep the original stream otherwise; tooling.md says so. TEST_preload_fopen_modes checks the bytes and that a missing branch name is not created. - fs_fstatat.hpp used AT_SYMLINK_NOFOLLOW without including fcntl.h, which failed against FreeBSD headers. --- mkdocs/docs/tooling.md | 6 ++ src/fs_fstatat.hpp | 1 + tests/TEST_preload_fopen_modes | 103 +++++++++++++++++++ tools/preload.c | 175 ++++++++++++++++----------------- 4 files changed, 195 insertions(+), 90 deletions(-) create mode 100755 tests/TEST_preload_fopen_modes diff --git a/mkdocs/docs/tooling.md b/mkdocs/docs/tooling.md index 0f5d0e93..91dfeb97 100644 --- a/mkdocs/docs/tooling.md +++ b/mkdocs/docs/tooling.md @@ -97,6 +97,12 @@ this also means certain mergerfs features that work by interrupting the read/write workflow, such as [moveonenospc](config/moveonenospc.md), will no longer work. +`fopen` and `fopen64` redirect modes beginning with `r`, including +`r+`, without rewriting the mode. They keep the original stream for +`w`, `a`, or any mode containing `x`: opening the branch path a second +time could truncate a file twice or recreate a name that no longer +exists. Writes on a retained stream still go through mergerfs. + Also, understand that this will only work on dynamically linked software (that is dynamically linked with the same general libc version as the software being used with it.) Anything statically compiled will diff --git a/src/fs_fstatat.hpp b/src/fs_fstatat.hpp index dfd7de2d..edc0d3a3 100644 --- a/src/fs_fstatat.hpp +++ b/src/fs_fstatat.hpp @@ -21,6 +21,7 @@ #include "fs_path.hpp" #include "to_neg_errno.hpp" +#include #include diff --git a/tests/TEST_preload_fopen_modes b/tests/TEST_preload_fopen_modes new file mode 100755 index 00000000..d6003925 --- /dev/null +++ b/tests/TEST_preload_fopen_modes @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Check both stream interposers on ordinary files without requiring FUSE.""" + +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + + +# The executable exports the virtual fullpath lookup. Only the fopen under +# test sees the alternate path; verification is done by the Python parent. +DRIVER = r''' +#define _GNU_SOURCE +#include + +#include +#include +#include + +static const char *g_BACKING; + +ssize_t +fgetxattr(int fd_, const char *name_, void *out_, size_t size_) +{ + (void)fd_; + if((g_BACKING == NULL) || (strcmp(name_,"user.mergerfs.fullpath") != 0)) + { + errno = ENODATA; + return -1; + } + + size_t len = strlen(g_BACKING); + if(size_ < len) + { + errno = ERANGE; + return -1; + } + + memcpy(out_,g_BACKING,len); + return (ssize_t)len; +} + + +int +main(int argc_, char **argv_) +{ + FILE *stream; + + if(argc_ != 4) + return 1; + g_BACKING = argv_[3]; + stream = (strcmp(argv_[1],"fopen") == 0) ? fopen("view",argv_[2]) : fopen64("view",argv_[2]); + g_BACKING = NULL; + if(stream == NULL) + return 1; + if(fputc('X',stream) == EOF) + return 1; + return (fclose(stream) != 0); +} +''' + + +def main(): + cc = shutil.which("cc") + if not sys.platform.startswith("linux") or not cc: + print("requires Linux and a C compiler") + return 77 + root = Path(__file__).resolve().parents[1] + with tempfile.TemporaryDirectory(prefix="mergerfs-fopen-") as tmp: + work = Path(tmp) + so = work / "preload.so" + src = work / "driver.c" + src.write_text(DRIVER, encoding="ascii") + subprocess.run([cc, "-shared", "-fPIC", "-O2", root / "tools/preload.c", + "-o", so, "-ldl"], check=True) + exe = work / "driver" + subprocess.run([cc, "-O2", "-rdynamic", src, "-o", exe], check=True) + view, backing = work / "view", work / "backing" + for spelling in ("fopen", "fopen64"): + # r+ is the positive interposition control. The others must not + # touch the second pathname, even if it is absent or exclusive. + for mode, seed, original, want_view, want_backing in ( + ("r+", b"abc", b"def", b"abc", b"Xef"), + ("w", b"abc", b"def", b"X", b"def"), + ("a+", b"abc", None, b"abcX", None), + ("wx", None, b"def", b"X", b"def")): + for path, data in ((view, seed), (backing, original)): + if data is not None: + path.write_bytes(data) + elif path.exists(): + path.unlink() + subprocess.run([exe, spelling, mode, backing], cwd=work, check=True, + env={**os.environ, "LD_PRELOAD": str(so)}) + if (view.read_bytes() != want_view or + (backing.read_bytes() if backing.exists() else None) != want_backing): + sys.exit(f"{spelling}({mode}): incorrect view or backing file after write") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/preload.c b/tools/preload.c index 800b673b..bcb94d0e 100644 --- a/tools/preload.c +++ b/tools/preload.c @@ -40,6 +40,16 @@ #endif #include +// Unary + applies the same integer promotion as a variadic argument. +typedef __typeof__(+(mode_t)0) OpenModeArg; + +static +int +_open_needs_mode(const int flags_) +{ + return ((flags_ & O_CREAT) || (O_TMPFILE && ((flags_ & O_TMPFILE) == O_TMPFILE))); +} + typedef char IOCTL_BUF[4096]; #define IOCTL_APP_TYPE 0xDF #define IOCTL_FILE_INFO _IOWR(IOCTL_APP_TYPE,0,IOCTL_BUF) @@ -77,33 +87,22 @@ get_underlying_filepath(int fd_, char *filepath_, size_t filepath_size_) { - int rv; + ssize_t rv; +#ifdef __FreeBSD__ + rv = extattr_get_fd(fd_,EXTATTR_NAMESPACE_USER,"mergerfs.fullpath",filepath_,filepath_size_); +#else rv = fgetxattr(fd_,"user.mergerfs.fullpath",filepath_,filepath_size_); - if(rv == -1) +#endif + if((rv <= 0) || ((size_t)rv >= filepath_size_)) return -1; + // The virtual xattr contains pathname bytes, not a trailing NUL. + filepath_[rv] = '\0'; + return rv; } -static -void -strip_exec(const char *orig_mode_, - char *new_mode_) -{ - size_t i; - size_t j; - - for(i = j = 0; orig_mode_[i]; i++) - { - if(orig_mode_[i] == 'x') - continue; - new_mode_[j++] = orig_mode_[i]; - } - - new_mode_[j] = '\0'; -} - #ifndef _FILE_OFFSET_BITS int open(const char *pathname_, @@ -118,11 +117,11 @@ open(const char *pathname_, LOAD_FUNC(open); mode = 0; - if(flags_ & (O_CREAT|O_TMPFILE)) + if(_open_needs_mode(flags_)) { va_list args; va_start(args,flags_); - mode = va_arg(args,mode_t); + mode = va_arg(args,OpenModeArg); va_end(args); } @@ -143,7 +142,8 @@ open(const char *pathname_, if(rv == -1) return fd; - flags_ &= ~(O_EXCL|O_CREAT); + // Truncation already happened on the mergerfs open; do not repeat it. + flags_ &= ~(O_EXCL|O_CREAT|O_TRUNC); rv = _libc_open(real_pathname,flags_,mode); if(rv == -1) return fd; @@ -167,11 +167,11 @@ open64(const char *pathname_, LOAD_FUNC(open64); mode = 0; - if(flags_ & (O_CREAT|O_TMPFILE)) + if(_open_needs_mode(flags_)) { va_list args; va_start(args,flags_); - mode = va_arg(args,mode_t); + mode = va_arg(args,OpenModeArg); va_end(args); } @@ -192,7 +192,8 @@ open64(const char *pathname_, if(rv == -1) return fd; - flags_ &= ~(O_EXCL|O_CREAT); + // Truncation already happened on the mergerfs open; do not repeat it. + flags_ &= ~(O_EXCL|O_CREAT|O_TRUNC); rv = _libc_open64(real_pathname,flags_,mode); if(rv == -1) return fd; @@ -217,11 +218,11 @@ openat(int dirfd_, LOAD_FUNC(openat); mode = 0; - if(flags_ & (O_CREAT|O_TMPFILE)) + if(_open_needs_mode(flags_)) { va_list args; va_start(args,flags_); - mode = va_arg(args,mode_t); + mode = va_arg(args,OpenModeArg); va_end(args); } @@ -242,7 +243,8 @@ openat(int dirfd_, if(rv == -1) return fd; - flags_ &= ~(O_EXCL|O_CREAT); + // Truncation already happened on the mergerfs open; do not repeat it. + flags_ &= ~(O_EXCL|O_CREAT|O_TRUNC); rv = _libc_openat(dirfd_,real_pathname,flags_,mode); if(rv == -1) return fd; @@ -267,11 +269,11 @@ openat64(int dirfd_, LOAD_FUNC(openat64); mode = 0; - if(flags_ & (O_CREAT|O_TMPFILE)) + if(_open_needs_mode(flags_)) { va_list args; va_start(args,flags_); - mode = va_arg(args,mode_t); + mode = va_arg(args,OpenModeArg); va_end(args); } @@ -292,7 +294,8 @@ openat64(int dirfd_, if(rv == -1) return fd; - flags_ &= ~(O_EXCL|O_CREAT); + // Truncation already happened on the mergerfs open; do not repeat it. + flags_ &= ~(O_EXCL|O_CREAT|O_TRUNC); rv = _libc_openat64(dirfd_,real_pathname,flags_,mode); if(rv == -1) return fd; @@ -302,16 +305,54 @@ openat64(int dirfd_, return rv; } +// Replaying a creating or truncating mode could recreate a vanished +// name or truncate an existing file twice. Only redirect read modes. +static +FILE* +_fopen_try_backing_stream(FILE *f_, + const char *mode_, + fopen_func_t fopen_func_) +{ + int fd; + int rv; + FILE *f2; + char real_pathname[PATH_MAX]; + struct stat st; + + if((mode_[0] != 'r') || (strchr(mode_,'x') != NULL)) + return f_; + + fd = fileno(f_); + if(fd == -1) + return f_; + + rv = fstat(fd,&st); + if(rv == -1) + return f_; + + if((st.st_mode & S_IFMT) != S_IFREG) + return f_; + + rv = get_underlying_filepath(fd,real_pathname,sizeof(real_pathname)); + if(rv == -1) + return f_; + + f2 = fopen_func_(real_pathname,mode_); + if(f2 == NULL) + return f_; + + fclose(f_); + + return f2; +} + + #ifndef _FILE_OFFSET_BITS FILE* fopen(const char *pathname_, const char *mode_) { - int fd; - int rv; FILE *f; - FILE *f2; - struct stat st; LOAD_FUNC(fopen); @@ -319,30 +360,7 @@ fopen(const char *pathname_, if(f == NULL) return NULL; - fd = fileno(f); - if(fd == -1) - return f; - - rv = fstat(fd,&st); - if(rv == -1) - return f; - if((st.st_mode & S_IFMT) != S_IFREG) - return f; - - char real_pathname[PATH_MAX]; - rv = get_underlying_filepath(fd,real_pathname,sizeof(real_pathname)); - if(rv == -1) - return f; - - char new_mode[64]; - strip_exec(mode_,new_mode); - f2 = _libc_fopen(real_pathname,new_mode); - if(f2 == NULL) - return f; - - fclose(f); - - return f2; + return _fopen_try_backing_stream(f,mode_,_libc_fopen); } #endif @@ -350,11 +368,7 @@ FILE* fopen64(const char *pathname_, const char *mode_) { - int fd; - int rv; FILE *f; - FILE *f2; - struct stat st; LOAD_FUNC(fopen64); @@ -362,30 +376,7 @@ fopen64(const char *pathname_, if(f == NULL) return NULL; - fd = fileno(f); - if(fd == -1) - return f; - - rv = fstat(fd,&st); - if(rv == -1) - return f; - if((st.st_mode & S_IFMT) != S_IFREG) - return f; - - char real_pathname[PATH_MAX]; - rv = get_underlying_filepath(fd,real_pathname,sizeof(real_pathname)); - if(rv == -1) - return f; - - char new_mode[64]; - strip_exec(mode_,new_mode); - f2 = _libc_fopen64(real_pathname,new_mode); - if(f2 == NULL) - return f; - - fclose(f); - - return f2; + return _fopen_try_backing_stream(f,mode_,_libc_fopen64); } #ifndef _FILE_OFFSET_BITS @@ -397,6 +388,7 @@ creat(const char *pathname_, int rv; LOAD_FUNC(creat); + LOAD_FUNC(open); fd = _libc_creat(pathname_,mode_); if(fd == -1) @@ -407,7 +399,8 @@ creat(const char *pathname_, if(rv == -1) return fd; - rv = _libc_creat(real_pathname,mode_); + // The mergerfs creat already created and truncated the backing file. + rv = _libc_open(real_pathname,O_WRONLY); if(rv == -1) return fd; @@ -425,6 +418,7 @@ creat64(const char *pathname_, int rv; LOAD_FUNC(creat64); + LOAD_FUNC(open64); fd = _libc_creat64(pathname_,mode_); if(fd == -1) @@ -435,7 +429,8 @@ creat64(const char *pathname_, if(rv == -1) return fd; - rv = _libc_creat64(real_pathname,mode_); + // The mergerfs creat already created and truncated the backing file. + rv = _libc_open64(real_pathname,O_WRONLY); if(rv == -1) return fd;