diff --git a/mount.go b/mount.go index 23db0a8e..0566c694 100644 --- a/mount.go +++ b/mount.go @@ -133,7 +133,7 @@ func fusermount(binary string, argv []string, additionalEnv []string, wait bool, debugLogger.Println("Creating a socket pair") } // Create a socket pair. - fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM, 0) + fds, err := cloexecSocketpair() if err != nil { return nil, fmt.Errorf("Socketpair: %v", err) } @@ -143,7 +143,6 @@ func fusermount(binary string, argv []string, additionalEnv []string, wait bool, } // Wrap the sockets into os.File objects that we will pass off to fusermount. writeFile := os.NewFile(uintptr(fds[0]), "fusermount-child-writes") - defer writeFile.Close() readFile := os.NewFile(uintptr(fds[1]), "fusermount-parent-reads") defer readFile.Close() @@ -164,9 +163,16 @@ func fusermount(binary string, argv []string, additionalEnv []string, wait bool, } else { err = cmd.Start() } + // Close our copy of the helper's end, so that the read below ends once + // the helper exits, even when it passes no device. + writeFile.Close() if err != nil { return nil, fmt.Errorf("running %v: %v", binary, err) } + if !wait { + // Nothing else waits for the helper. Reap it once it exits. + go cmd.Wait() + } if debugLogger != nil { debugLogger.Println("Wrapping socket pair in a connection") @@ -231,3 +237,18 @@ func fusermount(binary string, argv []string, additionalEnv []string, wait bool, // Turn the FD into an os.File. return os.NewFile(uintptr(gotFds[0]), "/dev/fuse"), nil } + +// cloexecSocketpair returns a connected pair of Unix stream sockets that a +// child process inherits only when it is passed one explicitly. It holds +// syscall.ForkLock so that no fork in between inherits them. +func cloexecSocketpair() ([2]int, error) { + syscall.ForkLock.RLock() + defer syscall.ForkLock.RUnlock() + fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM, 0) + if err != nil { + return fds, err + } + syscall.CloseOnExec(fds[0]) + syscall.CloseOnExec(fds[1]) + return fds, nil +} diff --git a/mount_helper_test.go b/mount_helper_test.go new file mode 100644 index 00000000..7bcd929b --- /dev/null +++ b/mount_helper_test.go @@ -0,0 +1,130 @@ +// Copyright 2026 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package fuse + +import ( + "fmt" + "os" + "slices" + "strconv" + "strings" + "syscall" + "testing" +) + +// These tests run the test binary as the mount helper that fusermount starts. +// None of them mounts. + +// fakeMountHelper makes TestFakeMountHelper act as a mount helper. Its value +// says what the helper does: +// +// - "exit": exit with status 0 without passing a device. +// - "pass:": exit with status 1 when the helper inherited a socket other +// than fd 3, its end of the socket pair, and the comma-separated . +// Otherwise pass /dev/null back as the device and exit with status 0. +const fakeMountHelper = "FUSE_TEST_FAKE_MOUNT_HELPER" + +// runFakeMountHelper runs fusermount with TestFakeMountHelper as the helper. +func runFakeMountHelper(mode string, wait bool) (*os.File, error) { + argv := []string{"-test.run=^TestFakeMountHelper$", "-test.timeout=1m"} + return fusermount(os.Args[0], argv, []string{fakeMountHelper + "=" + mode}, wait, nil) +} + +// openSockets returns the open file descriptors above 3 that are sockets. +func openSockets() ([]string, error) { + entries, err := os.ReadDir("/dev/fd") + if err != nil { + return nil, err + } + var sockets []string + for _, entry := range entries { + fd, err := strconv.Atoi(entry.Name()) + if err != nil || fd <= 3 { + continue + } + var st syscall.Stat_t + if syscall.Fstat(fd, &st) == nil && st.Mode&syscall.S_IFMT == syscall.S_IFSOCK { + sockets = append(sockets, entry.Name()) + } + } + return sockets, nil +} + +func TestFakeMountHelper(t *testing.T) { + mode, ok := os.LookupEnv(fakeMountHelper) + if !ok { + t.Skip("runs only as the mount helper that fusermount starts") + } + if mode == "exit" { + os.Exit(0) + } + held, ok := strings.CutPrefix(mode, "pass:") + if !ok { + os.Exit(2) + } + sockets, err := openSockets() + if err != nil { + os.Exit(2) + } + for _, fd := range sockets { + if !slices.Contains(strings.Split(held, ","), fd) { + fmt.Fprintf(os.Stderr, "the mount helper inherited socket %s\n", fd) + os.Exit(1) + } + } + dev, err := os.Open(os.DevNull) + if err != nil { + os.Exit(2) + } + if err := syscall.Sendmsg(3, []byte{0}, syscall.UnixRights(int(dev.Fd())), nil, 0); err != nil { + os.Exit(2) + } + os.Exit(0) +} + +// A helper that exits without passing a device makes fusermount fail. +func TestFusermountFailsWhenTheHelperPassesNoDevice(t *testing.T) { + for _, wait := range []bool{true, false} { + t.Run(fmt.Sprintf("wait=%v", wait), func(t *testing.T) { + dev, err := runFakeMountHelper("exit", wait) + if err == nil { + dev.Close() + t.Fatal("fusermount succeeded, want an error") + } + // Depending on the Go version, ReadMsgUnix returns io.EOF bare or in + // a *net.OpError. + if got := err.Error(); !strings.HasPrefix(got, "ReadMsgUnix: ") || !strings.HasSuffix(got, ": EOF") { + t.Errorf("fusermount error = %q, want ReadMsgUnix to fail with EOF", got) + } + }) + } +} + +// The helper inherits only fd 3 of the socket pair. A process that holds +// another copy of the helper's end keeps fusermount's read from ending when +// the helper exits without passing a device. +func TestMountHelperInheritsOnlyItsEndOfTheSocket(t *testing.T) { + // The test process can hold sockets it inherited, as on some CI runners. + // The helper inherits those too, so it ignores them. + held, err := openSockets() + if err != nil { + t.Fatalf("listing open sockets: %v", err) + } + dev, err := runFakeMountHelper("pass:"+strings.Join(held, ","), true) + if err != nil { + t.Fatalf("fusermount: %v", err) + } + dev.Close() +}