aboutsummaryrefslogtreecommitdiffhomepage
path: root/vfs/mountinfo.go
blob: 3c9e65ca64451ffca4350afb7fe19a67b5a7bf65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// Package vfs provides bindings and iterators over proc_pid_mountinfo(5).
package vfs

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"iter"
	"slices"
	"strconv"
	"strings"
	"syscall"
)

const (
	MS_NOSYMFOLLOW = 0x100
)

var (
	ErrMountInfoFields = errors.New("unexpected field count")
	ErrMountInfoEmpty  = errors.New("unexpected empty field")
	ErrMountInfoDevno  = errors.New("bad maj:min field")
	ErrMountInfoSep    = errors.New("bad optional fields separator")
)

// A DecoderError describes a nonrecoverable error decoding a mountinfo stream.
type DecoderError struct {
	Op   string
	Line int
	Err  error
}

func (e *DecoderError) Unwrap() error { return e.Err }
func (e *DecoderError) Error() string {
	var s string

	var numError *strconv.NumError
	switch {
	case errors.As(e.Err, &numError) && numError != nil:
		s = "numeric field " + strconv.Quote(numError.Num) + " " + numError.Err.Error()

	default:
		s = e.Err.Error()
	}

	var atLine string
	if e.Line >= 0 {
		atLine = " at line " + strconv.Itoa(e.Line)
	}
	return e.Op + " mountinfo" + atLine + ": " + s
}

type (
	// A MountInfoDecoder reads and decodes proc_pid_mountinfo(5) entries from
	// an input stream.
	MountInfoDecoder struct {
		s *bufio.Scanner
		m *MountInfo

		current  *MountInfo
		parseErr error
		curLine  int
		complete bool
	}

	// MountInfo represents the contents of a proc_pid_mountinfo(5) document.
	MountInfo struct {
		Next *MountInfo
		MountInfoEntry
	}

	// MountInfoEntry represents a proc_pid_mountinfo(5) entry.
	MountInfoEntry struct {
		// mount ID: a unique ID for the mount (may be reused after umount(2)).
		ID int `json:"id"`
		// parent ID: the ID of the parent mount (or of self for the root of
		// this mount namespace's mount tree).
		Parent int `json:"parent"`
		// major:minor: the value of st_dev for files on this filesystem (see stat(2)).
		Devno DevT `json:"devno"`
		// root: the pathname of the directory in the filesystem which forms the
		// root of this mount.
		Root string `json:"root"`
		// mount point: the pathname of the mount point relative to the
		// process's root directory.
		Target string `json:"target"`
		// mount options: per-mount options (see mount(2)).
		VfsOptstr string `json:"vfs_optstr"`
		// optional fields: zero or more fields of the form "tag[:value]"; see below.
		// separator: the end of the optional fields is marked by a single hyphen.
		OptFields []string `json:"opt_fields"`
		// filesystem type: the filesystem type in the form "type[.subtype]".
		FsType string `json:"fstype"`
		// mount source: filesystem-specific information or "none".
		Source string `json:"source"`
		// super options: per-superblock options (see mount(2)).
		FsOptstr string `json:"fs_optstr"`
	}

	DevT [2]int
)

// Flags interprets VfsOptstr and returns the resulting flags and unmatched options.
func (e *MountInfoEntry) Flags() (flags uintptr, unmatched []string) {
	for s := range strings.SplitSeq(e.VfsOptstr, ",") {
		switch s {
		case "rw":
		case "ro":
			flags |= syscall.MS_RDONLY
		case "nosuid":
			flags |= syscall.MS_NOSUID
		case "nodev":
			flags |= syscall.MS_NODEV
		case "noexec":
			flags |= syscall.MS_NOEXEC
		case "nosymfollow":
			flags |= MS_NOSYMFOLLOW
		case "noatime":
			flags |= syscall.MS_NOATIME
		case "nodiratime":
			flags |= syscall.MS_NODIRATIME
		case "relatime":
			flags |= syscall.MS_RELATIME
		default:
			unmatched = append(unmatched, s)
		}
	}
	return
}

// NewMountInfoDecoder returns a new decoder that reads from r.
//
// The decoder introduces its own buffering and may read data from r beyond the
// mountinfo entries requested.
func NewMountInfoDecoder(r io.Reader) *MountInfoDecoder {
	return &MountInfoDecoder{s: bufio.NewScanner(r)}
}

func (d *MountInfoDecoder) Decode(v **MountInfo) (err error) {
	for d.scan() {
	}
	err = d.Err()
	if err == nil {
		*v = d.m
	}
	return
}

// Entries returns an iterator over mountinfo entries.
func (d *MountInfoDecoder) Entries() iter.Seq[*MountInfoEntry] {
	return func(yield func(*MountInfoEntry) bool) {
		for cur := d.m; cur != nil; cur = cur.Next {
			if !yield(&cur.MountInfoEntry) {
				return
			}
		}
		for d.scan() {
			if !yield(&d.current.MountInfoEntry) {
				return
			}
		}
	}
}

func (d *MountInfoDecoder) Err() error {
	if err := d.s.Err(); err != nil {
		return &DecoderError{"scan", d.curLine, err}
	}
	if d.parseErr != nil {
		return &DecoderError{"parse", d.curLine, d.parseErr}
	}
	return nil
}

func (d *MountInfoDecoder) scan() bool {
	if d.complete {
		return false
	}
	if !d.s.Scan() {
		d.complete = true
		return false
	}

	m := new(MountInfo)
	if err := parseMountInfoLine(d.s.Text(), &m.MountInfoEntry); err != nil {
		d.parseErr = err
		d.complete = true
		return false
	}

	if d.current == nil {
		d.m = m
		d.current = d.m
	} else {
		d.current.Next = m
		d.current = d.current.Next
	}
	d.curLine++
	return true
}

func parseMountInfoLine(s string, ent *MountInfoEntry) error {
	// prevent proceeding with misaligned fields due to optional fields
	f := strings.Split(s, " ")
	if len(f) < 10 {
		return ErrMountInfoFields
	}

	// 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
	// (1)(2)(3)   (4)   (5)      (6)      (7)   (8) (9)   (10)         (11)

	// (1) id
	if id, err := strconv.Atoi(f[0]); err != nil { // 0
		return err
	} else {
		ent.ID = id
	}

	// (2) parent
	if parent, err := strconv.Atoi(f[1]); err != nil { // 1
		return err
	} else {
		ent.Parent = parent
	}

	// (3) maj:min
	if n, err := fmt.Sscanf(f[2], "%d:%d", &ent.Devno[0], &ent.Devno[1]); err != nil {
		return err
	} else if n != 2 {
		// unreachable
		return ErrMountInfoDevno
	}

	// (4) mountroot
	ent.Root = Unmangle(f[3])
	if ent.Root == "" {
		return ErrMountInfoEmpty
	}

	// (5) target
	ent.Target = Unmangle(f[4])
	if ent.Target == "" {
		return ErrMountInfoEmpty
	}

	// (6) vfs options (fs-independent)
	ent.VfsOptstr = Unmangle(f[5])
	if ent.VfsOptstr == "" {
		return ErrMountInfoEmpty
	}

	// (7) optional fields, terminated by " - "
	i := len(f) - 4
	ent.OptFields = f[6:i]

	// (8) optional fields end marker
	if f[i] != "-" {
		return ErrMountInfoSep
	}
	i++

	// (9) FS type
	ent.FsType = Unmangle(f[i])
	if ent.FsType == "" {
		return ErrMountInfoEmpty
	}
	i++

	// (10) source -- maybe empty string
	ent.Source = Unmangle(f[i])
	i++

	// (11) fs options (fs specific)
	ent.FsOptstr = Unmangle(f[i])

	return nil
}

// EqualWithIgnore compares to [MountInfoEntry] values, ignoring fields that
// compare equal to ignore.
func (e *MountInfoEntry) EqualWithIgnore(want *MountInfoEntry, ignore string) bool {
	return (e.ID == want.ID || want.ID == -1) &&
		(e.Parent == want.Parent || want.Parent == -1) &&
		(e.Devno == want.Devno || (want.Devno[0] == -1 && want.Devno[1] == -1)) &&
		(e.Root == want.Root || want.Root == ignore) &&
		(e.Target == want.Target || want.Target == ignore) &&
		(e.VfsOptstr == want.VfsOptstr || want.VfsOptstr == ignore) &&
		(slices.Equal(e.OptFields, want.OptFields) || (len(want.OptFields) == 1 && want.OptFields[0] == ignore)) &&
		(e.FsType == want.FsType || want.FsType == ignore) &&
		(e.Source == want.Source || want.Source == ignore) &&
		(e.FsOptstr == want.FsOptstr || want.FsOptstr == ignore)
}

// String returns a user-facing representation of a [MountInfoEntry]. It fits
// roughly into the mountinfo format, but without mangling.
func (e *MountInfoEntry) String() string {
	return fmt.Sprintf("%d %d %d:%d %s %s %s %s %s %s %s",
		e.ID, e.Parent, e.Devno[0], e.Devno[1], e.Root, e.Target, e.VfsOptstr,
		strings.Join(append(e.OptFields, "-"), " "), e.FsType, e.Source, e.FsOptstr)
}