diff --git a/mountinfo/go.mod b/mountinfo/go.mod index 029f7374..4f0ba582 100644 --- a/mountinfo/go.mod +++ b/mountinfo/go.mod @@ -1,5 +1,7 @@ module github.com/moby/sys/mountinfo -go 1.18 +go 1.26.0 require golang.org/x/sys v0.1.0 + +replace golang.org/x/sys => ../../../golang/x/sys diff --git a/mountinfo/go.sum b/mountinfo/go.sum index b69ea857..e69de29b 100644 --- a/mountinfo/go.sum +++ b/mountinfo/go.sum @@ -1,2 +0,0 @@ -golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U= -golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/mountinfo/mounted_unix.go b/mountinfo/mounted_unix.go index c2b266ed..47873b69 100644 --- a/mountinfo/mounted_unix.go +++ b/mountinfo/mounted_unix.go @@ -3,6 +3,7 @@ package mountinfo import ( + "fmt" "os" "path/filepath" @@ -50,3 +51,46 @@ func mountedByMountinfo(path string) (bool, error) { return len(entries) > 0, nil } + +// mountOfByParentsSlow is like mountOfByParents, but does not require path +// to be normalized. +func mountOfByParentsSlow(path string) (*Info, error) { + path, err := normalizePath(path) + if err != nil { + return nil, err + } + return mountOfByParents(path) +} + +// mountOfByParents finds the mount which path belongs to, by looking for the +// longest mount point which is a parent of path. The path must be normalized. +func mountOfByParents(path string) (*Info, error) { + mounts, err := GetMounts(ParentsFilter(path)) + if err != nil { + return nil, err + } + var res *Info + for _, m := range mounts { + // Several mounts can be stacked on the same mount point, and the + // last one is the topmost one (well, unless MOVE_MOUNT_BENEATH was + // used, which can only be figured out by statx + mount ID). + if res == nil || len(m.Mountpoint) >= len(res.Mountpoint) { + res = m + } + } + if res == nil { + // Should not happen, as / is always mounted. + return nil, fmt.Errorf("no mount found for %q", path) + } + return res, nil +} + +// submountsByPrefixSlow returns all mounts on path or under it, +// using PrefixFilter. The path does not have to be normalized. +func submountsByPrefixSlow(path string) ([]*Info, error) { + path, err := normalizePath(path) + if err != nil { + return nil, err + } + return GetMounts(PrefixFilter(path)) +} diff --git a/mountinfo/mountinfo.go b/mountinfo/mountinfo.go index 574aeb87..978681e6 100644 --- a/mountinfo/mountinfo.go +++ b/mountinfo/mountinfo.go @@ -2,6 +2,8 @@ package mountinfo import ( "os" + "strconv" + "strings" ) // GetMounts retrieves a list of mounts for the current running process, @@ -24,8 +26,43 @@ func Mounted(path string) (bool, error) { return mounted(path) } +// MountOf returns information about the mount which path belongs to (i.e. +// the mount containing the file or directory the path refers to, after +// resolving all symlinks). If several mounts are stacked on the same mount +// point, the topmost (i.e. visible) one is returned. +// +// This is a more efficient and correct alternative to calling GetMounts with +// ParentsFilter and choosing an entry with the longest mount point. On Linux +// 6.13+, it uses statx(2) and statmount(2) and avoids reading mountinfo. +// +// If a non-existent path is specified, an appropriate error is returned, +// which can be checked using errors.Is(err, fs.ErrNotExist). +// +// This function is not implemented on Windows. +func MountOf(path string) (*Info, error) { + return mountOf(path) +} + +// Submounts returns information about all mounts on path (including those +// stacked on the same mount point) and under it, after resolving all symlinks +// in path. The mounts are returned in the same order as GetMounts does. +// +// This is equivalent to GetMounts(PrefixFilter(path)), except path does not +// have to be normalized. On Linux 6.13+, if path is a mount point, it uses +// statx(2), listmount(2) and statmount(2) and avoids reading mountinfo, +// which is much faster when there are many mounts in the system. +// +// If a non-existent path is specified, an appropriate error is returned, +// which can be checked using errors.Is(err, fs.ErrNotExist). +// +// This function is not implemented on Windows. +func Submounts(path string) ([]*Info, error) { + return submounts(path) +} + // Info reveals information about a particular mounted filesystem. This -// struct is populated from the content in the /proc//mountinfo file. +// struct is populated from the content in the /proc//mountinfo file, +// or using statmount(2). type Info struct { // ID is a unique identifier of the mount (may be reused after umount). ID int @@ -64,4 +101,76 @@ type Info struct { // VFSOptions is a comma-separated list of superblock options. VFSOptions string + + // UniqueID is a unique identifier of the mount (never reused), as + // returned by statmount(2) and statx(2) with STATX_MNT_ID_UNIQUE + // (Linux 6.8+). Note that it differs from ID. + // + // It is 0 when not available (e.g. when Info is parsed from mountinfo). + UniqueID uint64 + + // ParentUniqueID is a unique identifier of the parent mount (or of + // self for the root of this mount namespace's mount tree). + // + // It is 0 when not available (e.g. when Info is parsed from mountinfo). + ParentUniqueID uint64 +} + +// optionalField returns the value of a tag from the Optional field +// (e.g. "1" for tag "shared" if Optional is "shared:1 master:2"), +// and whether the tag is present. +func (i *Info) optionalField(tag string) (string, bool) { + for f := range strings.FieldsSeq(i.Optional) { + name, val, _ := strings.Cut(f, ":") + if name == tag { + return val, true + } + } + return "", false +} + +// optionalID is like optionalField, but parses the value as an integer ID. +func (i *Info) optionalID(tag string) (int, bool) { + val, ok := i.optionalField(tag) + if !ok { + return 0, false + } + id, err := strconv.Atoi(val) + if err != nil { + return 0, false + } + return id, true +} + +// PeerGroup returns the ID of the peer group, and true, if the mount is +// shared (i.e. its Optional field contains "shared:ID"). Otherwise, it +// returns 0 and false. +// +// For more information on mount propagation, see mount_namespaces(7). +func (i *Info) PeerGroup() (int, bool) { + return i.optionalID("shared") +} + +// Master returns the ID of the peer group from which the mount receives +// propagation events, and true, if the mount is a slave (i.e. its Optional +// field contains "master:ID"). Otherwise, it returns 0 and false. +// +// Note that a mount can be both a slave and shared, in which case both +// PeerGroup and Master return true. +func (i *Info) Master() (int, bool) { + return i.optionalID("master") +} + +// PropagateFrom returns the ID of the closest dominant peer group under the +// process's root directory, and true, if it differs from the one returned +// by Master (i.e. its Optional field contains "propagate_from:ID"). +// Otherwise, it returns 0 and false. +func (i *Info) PropagateFrom() (int, bool) { + return i.optionalID("propagate_from") +} + +// Unbindable reports whether the mount is unbindable. +func (i *Info) Unbindable() bool { + _, ok := i.optionalField("unbindable") + return ok } diff --git a/mountinfo/mountinfo_bsd.go b/mountinfo/mountinfo_bsd.go index d92ef22a..63a6863f 100644 --- a/mountinfo/mountinfo_bsd.go +++ b/mountinfo/mountinfo_bsd.go @@ -53,3 +53,11 @@ func mounted(path string) (bool, error) { // Fallback to parsing mountinfo return mountedByMountinfo(path) } + +func mountOf(path string) (*Info, error) { + return mountOfByParentsSlow(path) +} + +func submounts(path string) ([]*Info, error) { + return submountsByPrefixSlow(path) +} diff --git a/mountinfo/mountinfo_optional_test.go b/mountinfo/mountinfo_optional_test.go new file mode 100644 index 00000000..42b7821e --- /dev/null +++ b/mountinfo/mountinfo_optional_test.go @@ -0,0 +1,47 @@ +package mountinfo + +import "testing" + +func TestInfoOptional(t *testing.T) { + type idOK struct { + id int + ok bool + } + for _, tc := range []struct { + optional string + peerGroup idOK + master idOK + propagateFrom idOK + unbindable bool + }{ + {optional: ""}, + {optional: "shared:1", peerGroup: idOK{1, true}}, + // Make sure "shared:12" is not treated as "shared:1". + {optional: "shared:12", peerGroup: idOK{12, true}}, + {optional: "master:3", master: idOK{3, true}}, + {optional: "master:3 propagate_from:5", master: idOK{3, true}, propagateFrom: idOK{5, true}}, + {optional: "shared:2 master:3", peerGroup: idOK{2, true}, master: idOK{3, true}}, + {optional: "unbindable", unbindable: true}, + // Malformed or unknown fields. + {optional: "shared"}, + {optional: "shared:x"}, + {optional: "shared: master:1", master: idOK{1, true}}, + {optional: "sharedx:1 unbindablex foo:7"}, + } { + i := Info{Optional: tc.optional} + check := func(name string, got, want idOK) { + if got != want { + t.Errorf("%q: %s: got %+v, want %+v", tc.optional, name, got, want) + } + } + id, ok := i.PeerGroup() + check("PeerGroup", idOK{id, ok}, tc.peerGroup) + id, ok = i.Master() + check("Master", idOK{id, ok}, tc.master) + id, ok = i.PropagateFrom() + check("PropagateFrom", idOK{id, ok}, tc.propagateFrom) + if got := i.Unbindable(); got != tc.unbindable { + t.Errorf("%q: Unbindable: got %v, want %v", tc.optional, got, tc.unbindable) + } + } +} diff --git a/mountinfo/mountinfo_unsupported.go b/mountinfo/mountinfo_unsupported.go index b4e692b7..47f3f5e5 100644 --- a/mountinfo/mountinfo_unsupported.go +++ b/mountinfo/mountinfo_unsupported.go @@ -16,3 +16,11 @@ func parseMountTable(_ FilterFunc) ([]*Info, error) { func mounted(path string) (bool, error) { return false, errNotImplemented } + +func mountOf(_ string) (*Info, error) { + return nil, errNotImplemented +} + +func submounts(_ string) ([]*Info, error) { + return nil, errNotImplemented +} diff --git a/mountinfo/mountinfo_windows.go b/mountinfo/mountinfo_windows.go index 13fad165..2c487581 100644 --- a/mountinfo/mountinfo_windows.go +++ b/mountinfo/mountinfo_windows.go @@ -1,5 +1,7 @@ package mountinfo +import "errors" + func parseMountTable(_ FilterFunc) ([]*Info, error) { // Do NOT return an error! return nil, nil @@ -8,3 +10,11 @@ func parseMountTable(_ FilterFunc) ([]*Info, error) { func mounted(_ string) (bool, error) { return false, nil } + +func mountOf(_ string) (*Info, error) { + return nil, errors.ErrUnsupported +} + +func submounts(_ string) ([]*Info, error) { + return nil, errors.ErrUnsupported +} diff --git a/mountinfo/mountof_linux.go b/mountinfo/mountof_linux.go new file mode 100644 index 00000000..2468d937 --- /dev/null +++ b/mountinfo/mountof_linux.go @@ -0,0 +1,64 @@ +package mountinfo + +import ( + "errors" + "fmt" + "os" + "runtime" + + "golang.org/x/sys/unix" +) + +func mountOf(path string) (*Info, error) { + // Make sure the mount namespace does not change in between the calls. + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + // Use AT_NO_AUTOMOUNT to be consistent with Mounted. + const flags = unix.AT_NO_AUTOMOUNT + var st unix.Statx_t + err := unix.Statx(unix.AT_FDCWD, path, flags, unix.STATX_MNT_ID_UNIQUE, &st) + if err != nil { + if !isUnsupported(err) { + return nil, &os.PathError{Op: "statx", Path: path, Err: err} + } + // No statx (or blocked by seccomp). + return mountOfByParentsSlow(path) + } + + // Fast path: statx + statmount (Linux 6.8+, all Info fields need 6.13+). + if st.Mask&unix.STATX_MNT_ID_UNIQUE != 0 { + info, err := statmount(st.Mnt_id) + if !errors.Is(err, errStatmountUnsupported) { + return info, err + } + // Get the old (non-unique) mount ID which is used in mountinfo. + err = unix.Statx(unix.AT_FDCWD, path, flags, unix.STATX_MNT_ID, &st) + if err != nil { + return nil, &os.PathError{Op: "statx", Path: path, Err: err} + } + } + + // Slower path: statx + mountinfo by mount ID (Linux 5.8+). + if st.Mask&unix.STATX_MNT_ID != 0 { + return mountOfByID(int(st.Mnt_id)) + } + + // Slowest path. + return mountOfByParentsSlow(path) +} + +// mountOfByID returns Info of a mount with a given (non-unique) mount ID. +func mountOfByID(id int) (*Info, error) { + mounts, err := GetMounts(func(m *Info) (skip, stop bool) { + return m.ID != id, m.ID == id + }) + if err != nil { + return nil, err + } + if len(mounts) == 0 { + // Unmounted since statx. + return nil, fmt.Errorf("mount ID %d: %w", id, unix.ENOENT) + } + return mounts[0], nil +} diff --git a/mountinfo/mountof_linux_test.go b/mountinfo/mountof_linux_test.go new file mode 100644 index 00000000..65ddc7f2 --- /dev/null +++ b/mountinfo/mountof_linux_test.go @@ -0,0 +1,228 @@ +package mountinfo + +import ( + "errors" + "os" + "path/filepath" + "testing" + + "golang.org/x/sys/unix" +) + +// mountOfImpls returns all implementations of mountOf to check. +// Each one takes a non-normalized path. +func mountOfImpls() map[string]func(string) (*Info, error) { + return map[string]func(string) (*Info, error){ + "MountOf": MountOf, + "byID": func(path string) (*Info, error) { + var st unix.Statx_t + if err := unix.Statx(unix.AT_FDCWD, path, unix.AT_NO_AUTOMOUNT, unix.STATX_MNT_ID, &st); err != nil { + return nil, &os.PathError{Op: "statx", Path: path, Err: err} + } + return mountOfByID(int(st.Mnt_id)) + }, + "byParents": mountOfByParentsSlow, + "MountOfNoStatmount": func(path string) (*Info, error) { + noStatmount = true + defer func() { noStatmount = false }() + return MountOf(path) + }, + } +} + +func TestMountOf(t *testing.T) { + statmountOK := true + if _, err := getMountsStatmount(func(*Info) (bool, bool) { return false, true }); err != nil { + statmountOK = false + } + + for _, tc := range testMounts { + t.Run(tc.desc, func(t *testing.T) { + path := tc.prepare(t) + + var want *Info + for name, fn := range mountOfImpls() { + info, err := fn(path) + if tc.isNotExist { + if !errors.Is(err, os.ErrNotExist) { + t.Errorf("%s: want ErrNotExist, got %v", name, err) + } + continue + } + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if name == "MountOf" && statmountOK && info.UniqueID == 0 { + t.Errorf("%s: UniqueID not set", name) + } + got := infoNoUnique(info) + if want == nil { + want = &got + } else if got != *want { + t.Errorf("%s: mismatch:\n got %+v\n want %+v", name, got, *want) + } + } + if tc.isNotExist { + return + } + norm, err := normalizePath(path) + if err != nil { + t.Fatal(err) + } + if isMount := want.Mountpoint == norm; isMount != tc.isMount { + t.Errorf("expected isMount %v, got Mountpoint %q for %q", tc.isMount, want.Mountpoint, norm) + } + }) + } +} + +// TestMountOfOvermount checks that MountOf returns the topmost mount if +// several mounts are stacked on the same mount point. +func TestMountOfOvermount(t *testing.T) { + dir := t.TempDir() + tMount(t, "tmpfs", dir, "tmpfs", 0) + tMount(t, "tmpfs", dir, "tmpfs", unix.MS_RDONLY) + file := filepath.Join(dir, "nonexistent") + + for name, fn := range mountOfImpls() { + info, err := fn(dir) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if info.Mountpoint != dir || info.Options[:2] != "ro" { + t.Errorf("%s: expected topmost (ro) mount on %s, got %+v", name, dir, info) + } + if _, err := fn(file); !errors.Is(err, os.ErrNotExist) { + t.Errorf("%s(%s): want ErrNotExist, got %v", name, file, err) + } + } +} + +// TestMountOfAllMounts checks that all MountOf implementations agree +// for all mount points in the system. +func TestMountOfAllMounts(t *testing.T) { + mounts, err := GetMounts(nil) + if err != nil { + t.Fatal(err) + } + checked := 0 + seen := map[string]bool{} + for _, m := range mounts { + mp := m.Mountpoint + if seen[mp] { + continue + } + seen[mp] = true + info, err := MountOf(mp) + if err != nil { + if errors.Is(err, os.ErrPermission) || errors.Is(err, os.ErrNotExist) { + continue + } + t.Errorf("MountOf(%q): %v", mp, err) + continue + } + if info.Mountpoint != mp { + // Mount point is shadowed by a mount on top of its parent. + t.Logf("MountOf(%q): shadowed by %q", mp, info.Mountpoint) + continue + } + for name, fn := range mountOfImpls() { + other, err := fn(mp) + if err != nil { + t.Errorf("%s(%q): %v", name, mp, err) + continue + } + if got, want := infoNoUnique(other), infoNoUnique(info); got != want { + t.Errorf("%s(%q): mismatch:\n got %+v\n want %+v", name, mp, got, want) + } + } + checked++ + } + t.Logf("checked %d mount points", checked) +} + +func BenchmarkMountOf(b *testing.B) { + path, _ := os.Getwd() + for name, fn := range mountOfImpls() { + b.Run(name, func(b *testing.B) { + for b.Loop() { + if _, err := fn(path); err != nil { + b.Fatal(err) + } + } + }) + } +} + +func TestMountOfPropagation(t *testing.T) { + makeMount := func(t *testing.T, src, fstype string, flags uintptr) string { + t.Helper() + dir := t.TempDir() + tMount(t, src, dir, fstype, flags) + return dir + } + setPropagation := func(t *testing.T, dir string, flags uintptr) { + t.Helper() + if err := unix.Mount("", dir, "", flags, ""); err != nil { + t.Fatal(&os.PathError{Op: "mount", Path: dir, Err: err}) + } + } + + shared := makeMount(t, "tmpfs", "tmpfs", 0) + setPropagation(t, shared, unix.MS_SHARED) + sharedInfo, err := MountOf(shared) + if err != nil { + t.Fatal(err) + } + group, ok := sharedInfo.PeerGroup() + if !ok { + t.Fatalf("expected %s to be shared, got %+v", shared, sharedInfo) + } + + slave := makeMount(t, shared, "", unix.MS_BIND) + setPropagation(t, slave, unix.MS_SLAVE) + + slaveShared := makeMount(t, shared, "", unix.MS_BIND) + setPropagation(t, slaveShared, unix.MS_SLAVE) + setPropagation(t, slaveShared, unix.MS_SHARED) + + unbindable := makeMount(t, "tmpfs", "tmpfs", 0) + setPropagation(t, unbindable, unix.MS_UNBINDABLE) + + private := makeMount(t, "tmpfs", "tmpfs", 0) + setPropagation(t, private, unix.MS_PRIVATE) + + for _, tc := range []struct { + desc string + path string + shared bool + master int // 0 means not a slave + unbindable bool + }{ + {desc: "shared", path: shared, shared: true}, + {desc: "slave", path: slave, master: group}, + {desc: "slave and shared", path: slaveShared, shared: true, master: group}, + {desc: "unbindable", path: unbindable, unbindable: true}, + {desc: "private", path: private}, + } { + for name, fn := range mountOfImpls() { + info, err := fn(tc.path) + if err != nil { + t.Fatalf("%s: %s: %v", tc.desc, name, err) + } + if _, ok := info.PeerGroup(); ok != tc.shared { + t.Errorf("%s: %s: PeerGroup: got %v, want %v (%q)", tc.desc, name, ok, tc.shared, info.Optional) + } + master, _ := info.Master() + if master != tc.master { + t.Errorf("%s: %s: Master: got %d, want %d (%q)", tc.desc, name, master, tc.master, info.Optional) + } + if _, ok := info.PropagateFrom(); ok { + t.Errorf("%s: %s: PropagateFrom: unexpected (%q)", tc.desc, name, info.Optional) + } + if got := info.Unbindable(); got != tc.unbindable { + t.Errorf("%s: %s: Unbindable: got %v, want %v (%q)", tc.desc, name, got, tc.unbindable, info.Optional) + } + } + } +} diff --git a/mountinfo/statmount_linux.go b/mountinfo/statmount_linux.go new file mode 100644 index 00000000..5465eca9 --- /dev/null +++ b/mountinfo/statmount_linux.go @@ -0,0 +1,249 @@ +package mountinfo + +import ( + "errors" + "runtime" + "strconv" + "strings" + + "golang.org/x/sys/unix" +) + +// errStatmountUnsupported is returned when statmount(2) can't be used to fill +// in Info (because the kernel is too old, or the syscall is blocked by seccomp). +var errStatmountUnsupported = errors.New("statmount not supported") + +// noStatmount disables the use of statmount (for testing fallback code). +var noStatmount bool + +const ( + // statmountMask is a set of statmount fields needed to fill in Info. + statmountMask = unix.STATMOUNT_SB_BASIC | unix.STATMOUNT_MNT_BASIC | + unix.STATMOUNT_PROPAGATE_FROM | unix.STATMOUNT_MNT_ROOT | + unix.STATMOUNT_MNT_POINT | unix.STATMOUNT_FS_TYPE | + unix.STATMOUNT_MNT_OPTS | unix.STATMOUNT_FS_SUBTYPE | + unix.STATMOUNT_SB_SOURCE + + // statmountAlways is a subset of statmountMask that is always set in + // the returned mask (if supported by the kernel). The rest of the bits + // are only set if the corresponding string is not empty. + statmountAlways = unix.STATMOUNT_SB_BASIC | unix.STATMOUNT_MNT_BASIC | + unix.STATMOUNT_PROPAGATE_FROM | unix.STATMOUNT_MNT_ROOT | + unix.STATMOUNT_FS_TYPE +) + +// statmount returns Info for a mount with a given unique mount ID. +// +// It returns errStatmountUnsupported if the kernel does not support +// statmount, or does not support all the fields needed to fill in Info +// (which requires Linux 6.13+). +func statmount(id uint64) (*Info, error) { + if noStatmount { + return nil, errStatmountUnsupported + } + st, err := unix.Statmount(&unix.MntIdReq{ + Id: id, + Param: statmountMask | unix.STATMOUNT_SUPPORTED_MASK, + }, 0) + if err != nil { + if isUnsupported(err) { + return nil, errStatmountUnsupported + } + return nil, err + } + if !statmountSupported(st) { + return nil, errStatmountUnsupported + } + return statmountToInfo(st), nil +} + +// isUnsupported checks if err from a syscall means it is not supported +// (or blocked by seccomp). +func isUnsupported(err error) bool { + return errors.Is(err, unix.ENOSYS) || errors.Is(err, unix.EPERM) +} + +// statmountSupported checks whether st has all the information needed to fill +// in Info. +func statmountSupported(st *unix.Statmount_t) bool { + if st.Mask&statmountAlways != statmountAlways { + return false + } + // Linux 6.15+ tells which fields it supports. + if st.Mask&unix.STATMOUNT_SUPPORTED_MASK != 0 { + return st.Supported_mask&statmountMask == statmountMask + } + // For older kernels, the presence of STATMOUNT_SB_SOURCE (which is + // non-empty for all practical purposes) means Linux 6.13+, which + // also supports STATMOUNT_MNT_OPTS and STATMOUNT_FS_SUBTYPE. + return st.Mask&unix.STATMOUNT_SB_SOURCE != 0 +} + +// statmountToInfo converts statmount(2) result to Info, so that all the +// fields are the same as if they were parsed from /proc/self/mountinfo +// (see show_mountinfo in the kernel's fs/proc_namespace.c). +func statmountToInfo(st *unix.Statmount_t) *Info { + fsType := st.Fs_type + if st.Fs_subtype != "" { + fsType += "." + st.Fs_subtype + } + return &Info{ + ID: int(st.Mnt_id_old), + Parent: int(st.Mnt_parent_id_old), + Major: int(st.Sb_dev_major), + Minor: int(st.Sb_dev_minor), + Root: st.Mnt_root, + Mountpoint: st.Mnt_point, + Options: mntAttrToOptions(st.Mnt_attr), + Optional: propagationToOptional(st), + FSType: fsType, + Source: st.Sb_source, + VFSOptions: sbOptions(st), + UniqueID: st.Mnt_id, + ParentUniqueID: st.Mnt_parent_id, + } +} + +// mntAttrToOptions converts MOUNT_ATTR_* flags to per-mount options, +// in the same format as show_vfsmnt_opts in the kernel. +func mntAttrToOptions(attr uint64) string { + var b strings.Builder + if attr&unix.MOUNT_ATTR_RDONLY != 0 { + b.WriteString("ro") + } else { + b.WriteString("rw") + } + for _, o := range []struct { + flag uint64 + str string + }{ + {unix.MOUNT_ATTR_NOSUID, ",nosuid"}, + {unix.MOUNT_ATTR_NODEV, ",nodev"}, + {unix.MOUNT_ATTR_NOEXEC, ",noexec"}, + {unix.MOUNT_ATTR_NOATIME, ",noatime"}, + {unix.MOUNT_ATTR_NODIRATIME, ",nodiratime"}, + } { + if attr&o.flag != 0 { + b.WriteString(o.str) + } + } + // MOUNT_ATTR_RELATIME is 0, so it has to be checked separately. + if attr&unix.MOUNT_ATTR__ATIME == unix.MOUNT_ATTR_RELATIME { + b.WriteString(",relatime") + } + if attr&unix.MOUNT_ATTR_NOSYMFOLLOW != 0 { + b.WriteString(",nosymfollow") + } + if attr&unix.MOUNT_ATTR_IDMAP != 0 { + b.WriteString(",idmapped") + } + return b.String() +} + +// propagationToOptional returns mount propagation information in the same +// format as optional fields of /proc/self/mountinfo. +func propagationToOptional(st *unix.Statmount_t) string { + var opts []string + if st.Mnt_propagation&unix.MS_SHARED != 0 { + opts = append(opts, "shared:"+strconv.FormatUint(st.Mnt_peer_group, 10)) + } + if st.Mnt_propagation&unix.MS_SLAVE != 0 { + opts = append(opts, "master:"+strconv.FormatUint(st.Mnt_master, 10)) + if pf := st.Propagate_from; pf != 0 && pf != st.Mnt_master { + opts = append(opts, "propagate_from:"+strconv.FormatUint(pf, 10)) + } + } + if st.Mnt_propagation&unix.MS_UNBINDABLE != 0 { + opts = append(opts, "unbindable") + } + return strings.Join(opts, " ") +} + +// sbOptions returns superblock options in the same format as the last +// field of /proc/self/mountinfo. +func sbOptions(st *unix.Statmount_t) string { + var b strings.Builder + if st.Sb_flags&unix.MS_RDONLY != 0 { + b.WriteString("ro") + } else { + b.WriteString("rw") + } + for _, o := range []struct { + flag uint32 + str string + }{ + {unix.MS_SYNCHRONOUS, ",sync"}, + {unix.MS_DIRSYNC, ",dirsync"}, + {unix.MS_LAZYTIME, ",lazytime"}, + } { + if st.Sb_flags&o.flag != 0 { + b.WriteString(o.str) + } + } + if st.Mnt_opts != "" { + b.WriteString(",") + b.WriteString(st.Mnt_opts) + } + return b.String() +} + +// listmount returns unique IDs of all mounts in the subtree of a mount with +// a given unique ID (not including the mount itself). Use [unix.LSMT_ROOT] to +// list all mounts visible to the current process. +func listmount(id uint64) ([]uint64, error) { + var ids []uint64 + buf := make([]uint64, 512) + req := unix.MntIdReq{Id: id} + for { + n, err := unix.Listmount(&req, buf, 0) + if err != nil { + if isUnsupported(err) { + return nil, errStatmountUnsupported + } + return nil, err + } + ids = append(ids, buf[:n]...) + if n < len(buf) { + return ids, nil + } + // Continue after the last returned ID. + req.Param = buf[n-1] + } +} + +// getMountsStatmount is like parseMountTable, but uses listmount(2) and +// statmount(2) instead of parsing /proc/thread-self/mountinfo. +func getMountsStatmount(filter FilterFunc) ([]*Info, error) { + // listmount and statmount work in the mount namespace of the current + // thread, so make sure it does not change while we're at it. + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + ids, err := listmount(unix.LSMT_ROOT) + if err != nil { + return nil, err + } + out := []*Info{} + for _, id := range ids { + p, err := statmount(id) + if err != nil { + if errors.Is(err, unix.ENOENT) { + // Unmounted since listmount. + continue + } + return nil, err + } + var skip, stop bool + if filter != nil { + skip, stop = filter(p) + if skip { + continue + } + } + out = append(out, p) + if stop { + break + } + } + return out, nil +} diff --git a/mountinfo/statmount_linux_test.go b/mountinfo/statmount_linux_test.go new file mode 100644 index 00000000..73844294 --- /dev/null +++ b/mountinfo/statmount_linux_test.go @@ -0,0 +1,88 @@ +package mountinfo + +import ( + "errors" + "testing" +) + +func requireStatmount(t testing.TB) { + t.Helper() + if _, err := getMountsStatmount(func(*Info) (bool, bool) { return false, true }); err != nil { + if errors.Is(err, errStatmountUnsupported) { + t.Skip("statmount not supported (need Linux 6.13+)") + } + t.Fatal(err) + } +} + +// infoNoUnique returns a copy of i with unique IDs cleared, +// so it can be compared with Info parsed from mountinfo. +func infoNoUnique(i *Info) Info { + c := *i + c.UniqueID, c.ParentUniqueID = 0, 0 + return c +} + +// TestStatmountVsMountinfo checks that getMountsStatmount returns the same +// information as parsing mountinfo. +func TestStatmountVsMountinfo(t *testing.T) { + requireStatmount(t) + + // Mounts can change between the two calls; retry a few times. + var diff []string + for range 3 { + diff = nil + mi, err := GetMounts(nil) + if err != nil { + t.Fatal(err) + } + sm, err := getMountsStatmount(nil) + if err != nil { + t.Fatal(err) + } + t.Logf("mountinfo: %d entries, statmount: %d entries", len(mi), len(sm)) + if len(mi) != len(sm) { + diff = append(diff, "number of entries differ") + } + byID := make(map[int]*Info, len(sm)) + for _, s := range sm { + if s.UniqueID == 0 || s.ParentUniqueID == 0 { + t.Errorf("statmount: unique ID not set: %+v", s) + } + byID[s.ID] = s + } + for _, m := range mi { + s, ok := byID[m.ID] + if !ok { + diff = append(diff, "missing in statmount: "+m.Mountpoint) + continue + } + if got, want := infoNoUnique(s), *m; got != want { + t.Errorf("mismatch:\n statmount: %+v\n mountinfo: %+v", got, want) + } + } + if diff == nil { + break + } + } + for _, d := range diff { + t.Error(d) + } +} + +func BenchmarkGetMountsMountinfo(b *testing.B) { + for b.Loop() { + if _, err := GetMounts(nil); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkGetMountsStatmount(b *testing.B) { + requireStatmount(b) + for b.Loop() { + if _, err := getMountsStatmount(nil); err != nil { + b.Fatal(err) + } + } +} diff --git a/mountinfo/submounts_linux.go b/mountinfo/submounts_linux.go new file mode 100644 index 00000000..941c8fd8 --- /dev/null +++ b/mountinfo/submounts_linux.go @@ -0,0 +1,102 @@ +package mountinfo + +import ( + "errors" + "os" + "runtime" + "slices" + + "golang.org/x/sys/unix" +) + +func submounts(path string) ([]*Info, error) { + // Make sure the mount namespace does not change in between the calls. + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + // Use AT_NO_AUTOMOUNT to be consistent with Mounted and MountOf. + var st unix.Statx_t + err := unix.Statx(unix.AT_FDCWD, path, unix.AT_NO_AUTOMOUNT, unix.STATX_MNT_ID_UNIQUE, &st) + if err != nil { + if !isUnsupported(err) { + return nil, &os.PathError{Op: "statx", Path: path, Err: err} + } + return submountsByPrefixSlow(path) + } + + // The fast path only works if path is a mount point. Otherwise, the + // subtree to look at is that of the parent mount (possibly all + // mounts), and parsing mountinfo is faster. + if st.Mask&unix.STATX_MNT_ID_UNIQUE != 0 && + st.Attributes_mask&unix.STATX_ATTR_MOUNT_ROOT != 0 && + st.Attributes&unix.STATX_ATTR_MOUNT_ROOT != 0 { + mounts, err := submountsStatmount(st.Mnt_id) + if !errors.Is(err, errStatmountUnsupported) { + return mounts, err + } + } + + return submountsByPrefixSlow(path) +} + +// submountsStatmount returns the mount with a given unique ID, the mounts +// stacked under it on the same mount point, and all their submounts, +// sorted by unique mount ID. +func submountsStatmount(id uint64) ([]*Info, error) { + top, err := statmount(id) + if err != nil { + return nil, err + } + + // Find the bottommost of the mounts stacked on the same mount point, + // as its subtree includes all the mounts on top of it, as well as + // those hidden by them. + out := []*Info{top} + bottom := top + for bottom.ParentUniqueID != bottom.UniqueID { + parent, err := statmount(bottom.ParentUniqueID) + if err != nil || parent.Mountpoint != top.Mountpoint { + // Note an error here is not fatal, as the parent + // mount may be inaccessible (e.g. outside of chroot). + break + } + out = append(out, parent) + bottom = parent + } + + ids, err := listmount(bottom.UniqueID) + if err != nil { + return nil, err + } + for _, id := range ids { + if slices.ContainsFunc(out, func(i *Info) bool { return i.UniqueID == id }) { + // Already have it (one of the stacked mounts). + continue + } + info, err := statmount(id) + if err != nil { + if errors.Is(err, unix.ENOENT) { + // Unmounted since listmount. + continue + } + return nil, err + } + out = append(out, info) + } + + // This is the same order as in mountinfo (since Linux 6.8). + slices.SortFunc(out, func(a, b *Info) int { + return cmpUint64(a.UniqueID, b.UniqueID) + }) + return out, nil +} + +func cmpUint64(a, b uint64) int { + switch { + case a < b: + return -1 + case a > b: + return 1 + } + return 0 +} diff --git a/mountinfo/submounts_linux_test.go b/mountinfo/submounts_linux_test.go new file mode 100644 index 00000000..e1273002 --- /dev/null +++ b/mountinfo/submounts_linux_test.go @@ -0,0 +1,172 @@ +package mountinfo + +import ( + "errors" + "os" + "path/filepath" + "testing" + + "golang.org/x/sys/unix" +) + +// submountsImpls returns all implementations of submounts to check. +func submountsImpls() map[string]func(string) ([]*Info, error) { + return map[string]func(string) ([]*Info, error){ + "Submounts": Submounts, + "SubmountsNoStatmount": func(path string) ([]*Info, error) { + noStatmount = true + defer func() { noStatmount = false }() + return Submounts(path) + }, + "byPrefix": submountsByPrefixSlow, + } +} + +// checkSubmounts checks that all submounts implementations return the same +// result for path, and returns it. If isNotExist is set, all implementations +// are expected to return ErrNotExist. +func checkSubmounts(t *testing.T, path string, isNotExist bool) []Info { + t.Helper() + var want []Info + first := true + for name, fn := range submountsImpls() { + mounts, err := fn(path) + if isNotExist { + if !errors.Is(err, os.ErrNotExist) { + t.Errorf("%s(%q): want ErrNotExist, got %v", name, path, err) + } + continue + } + if err != nil { + t.Errorf("%s(%q): %v", name, path, err) + continue + } + got := make([]Info, len(mounts)) + for i, m := range mounts { + got[i] = infoNoUnique(m) + } + if first { + want, first = got, false + continue + } + if len(got) != len(want) { + t.Errorf("%s(%q): got %d mounts, want %d:\n got %+v\n want %+v", name, path, len(got), len(want), got, want) + continue + } + for i := range got { + if got[i] != want[i] { + t.Errorf("%s(%q): mismatch at %d:\n got %+v\n want %+v", name, path, i, got[i], want[i]) + } + } + } + return want +} + +func TestSubmounts(t *testing.T) { + base := t.TempDir() + tMount(t, "tmpfs", base, "tmpfs", 0) + mkdir := func(p string) string { + t.Helper() + if err := os.MkdirAll(p, 0o700); err != nil { + t.Fatal(err) + } + return p + } + + a := mkdir(filepath.Join(base, "a")) + tMount(t, "tmpfs", a, "tmpfs", 0) + b := mkdir(filepath.Join(a, "b")) + tMount(t, "tmpfs", b, "tmpfs", 0) + // Stack another mount on a, hiding a/b. + tMount(t, "tmpfs", a, "tmpfs", 0) + // Directory bind mount. + c := mkdir(filepath.Join(base, "c")) + tMount(t, t.TempDir(), c, "", unix.MS_BIND) + // File bind mount. + f := tCreateFile(t, base) + tMount(t, f, f, "", unix.MS_BIND) + // A directory which is not a mount point, with a mount under it. + d := mkdir(filepath.Join(base, "d")) + e := mkdir(filepath.Join(d, "e")) + tMount(t, "tmpfs", e, "tmpfs", 0) + // Symlink to a. + link := filepath.Join(base, "link") + if err := os.Symlink(a, link); err != nil { + t.Fatal(err) + } + + for _, tc := range []struct { + path string + isNotExist bool + want []string // mount points, in order + }{ + {path: base, want: []string{base, a, b, a, c, f, e}}, + {path: base + "/", want: []string{base, a, b, a, c, f, e}}, + {path: a, want: []string{a, b, a}}, + {path: link, want: []string{a, b, a}}, + {path: c, want: []string{c}}, + {path: f, want: []string{f}}, + {path: d, want: []string{e}}, + {path: e, want: []string{e}}, + {path: filepath.Join(base, "nonexistent"), isNotExist: true}, + {path: filepath.Join(link, "nonexistent"), isNotExist: true}, + } { + got := checkSubmounts(t, tc.path, tc.isNotExist) + if tc.isNotExist { + continue + } + var gotMP []string + for _, m := range got { + gotMP = append(gotMP, m.Mountpoint) + } + if len(gotMP) != len(tc.want) { + t.Errorf("%s: got %q, want %q", tc.path, gotMP, tc.want) + continue + } + for i := range gotMP { + if gotMP[i] != tc.want[i] { + t.Errorf("%s: got %q, want %q", tc.path, gotMP, tc.want) + break + } + } + } +} + +// TestSubmountsAllMounts checks that all submounts implementations agree +// for all mount points in the system. +func TestSubmountsAllMounts(t *testing.T) { + mounts, err := GetMounts(nil) + if err != nil { + t.Fatal(err) + } + checked := 0 + seen := map[string]bool{} + for _, m := range mounts { + mp := m.Mountpoint + if seen[mp] || mp == "/" { + continue + } + seen[mp] = true + info, err := MountOf(mp) + if err != nil || info.Mountpoint != mp { + // Inaccessible, or shadowed by a mount on top of its parent. + continue + } + checkSubmounts(t, mp, false) + checked++ + } + t.Logf("checked %d mount points", checked) +} + +func BenchmarkSubmounts(b *testing.B) { + path, _ := os.Getwd() + for name, fn := range submountsImpls() { + b.Run(name, func(b *testing.B) { + for b.Loop() { + if _, err := fn(path); err != nil { + b.Fatal(err) + } + } + }) + } +}