From 8caa5dddeebaf7116c9fa12a64cac1aca567df58 Mon Sep 17 00:00:00 2001 From: Jakob Unterwurzacher Date: Wed, 11 Nov 2026 21:05:14 +0100 Subject: fusefrontend: openWriteOnlyFile: reopen the same file, not just the same name openWriteOnlyFile chmods the file via woFd and then reopens it by name. O_NOFOLLOW prevents following symlinks, but cName could still have been replaced by a different regular file in between, and we would return an fd to that file. Add syscallcompat.ReopenFd(): * Linux: open /proc/self/fd/N, which always resolves to the file woFd refers to. * Other platforms: reopen by name and compare dev/ino against woFd, returning EAGAIN on mismatch. Co-Authored-By: Claude Opus 5.5 --- internal/syscallcompat/reopen_other.go | 37 ++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 internal/syscallcompat/reopen_other.go (limited to 'internal/syscallcompat/reopen_other.go') diff --git a/internal/syscallcompat/reopen_other.go b/internal/syscallcompat/reopen_other.go new file mode 100644 index 0000000..15d868d --- /dev/null +++ b/internal/syscallcompat/reopen_other.go @@ -0,0 +1,37 @@ +//go:build !linux + +package syscallcompat + +import ( + "syscall" + + "github.com/rfjakob/gocryptfs/v2/internal/tlog" +) + +// ReopenFd opens the file referenced by "fd" again, with new "flags". +// +// There is no /proc/self/fd outside Linux, so we reopen "name" relative to +// "dirfd" and verify that we got the same file as "fd". If "name" has been +// replaced by a different file in the meantime, EAGAIN is returned. +// Retries on EINTR. +func ReopenFd(fd int, dirfd int, name string, flags int) (int, error) { + var st syscall.Stat_t + if err := syscall.Fstat(fd, &st); err != nil { + return -1, err + } + fd2, err := Openat(dirfd, name, flags, 0) + if err != nil { + return -1, err + } + var st2 syscall.Stat_t + if err := syscall.Fstat(fd2, &st2); err != nil { + syscall.Close(fd2) + return -1, err + } + if st2.Dev != st.Dev || st2.Ino != st.Ino { + tlog.Warn.Printf("ReopenFd: %q was replaced concurrently, returning EAGAIN", name) + syscall.Close(fd2) + return -1, syscall.EAGAIN + } + return fd2, nil +} -- cgit v1.2.3