File: mounted_linux_test.go

package info (click to toggle)
golang-github-moby-sys 0.0~git20241107.638aa7c-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 616 kB
  • sloc: makefile: 58
file content (449 lines) | stat: -rw-r--r-- 10,348 bytes parent folder | download
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
package mountinfo

import (
	"errors"
	"net"
	"os"
	"path/filepath"
	"reflect"
	"runtime"
	"strings"
	"testing"

	"golang.org/x/sys/unix"
)

// tMount is a wrapper for unix.Mount which is used to prepare test cases.
// It skips the test case if mounting is not possible (i.e. user is not root),
// fails the test case if there is a mount error, and installs a cleanup
// handler to undo the mount.
func tMount(t *testing.T, src, dst, fstype string, flags uintptr) {
	t.Helper()
	if os.Getuid() != 0 {
		t.Skip("root required for mounting")
	}

	err := unix.Mount(src, dst, fstype, flags, "")
	if err != nil {
		t.Fatal(&os.PathError{Path: dst, Op: "mount", Err: err})
	}
	t.Cleanup(func() {
		if err := unix.Unmount(dst, unix.MNT_DETACH); err != nil {
			t.Errorf("cleanup: unmount %q failed: %v", dst, err)
		}
	})
}

func tCreateFile(t *testing.T, dir string) string {
	t.Helper()
	file, err := os.CreateTemp(dir, "file")
	if err != nil {
		t.Fatal(err)
	}
	file.Close()
	return file.Name()
}

type testMount struct {
	desc       string
	isNotExist bool
	isMount    bool
	isBind     bool
	// prepare returns a path that needs to be checked.
	// If there is an error preparing the path, the test is either skipped or failed.
	//
	// It is responsible for cleanup (by using t.Cleanup).
	prepare func(t *testing.T) string
}

var testMounts = []testMount{
	{
		desc:       "non-existent path",
		isNotExist: true,
		prepare: func(t *testing.T) string {
			return "/non/existent/path"
		},
	},
	{
		desc: "not mounted directory",
		prepare: func(t *testing.T) string {
			return t.TempDir()
		},
	},
	{
		desc:    "tmpfs mount",
		isMount: true,
		prepare: func(t *testing.T) string {
			mnt := t.TempDir()
			tMount(t, "tmpfs", mnt, "tmpfs", 0)
			return mnt
		},
	},
	{
		desc:    "tmpfs mount ending with a slash",
		isMount: true,
		prepare: func(t *testing.T) string {
			mnt := t.TempDir() + "/"
			tMount(t, "tmpfs", mnt, "tmpfs", 0)
			return mnt
		},
	},
	{
		desc:       "broken symlink",
		isNotExist: true,
		prepare: func(t *testing.T) string {
			link := filepath.Join(t.TempDir(), "broken-symlink")
			err := os.Symlink("/some/non/existent/dest", link)
			if err != nil {
				t.Fatal(err)
			}
			return link
		},
	},
	{
		desc: "symlink to not mounted directory",
		prepare: func(t *testing.T) string {
			tmp := t.TempDir()

			t.Helper()
			dir := filepath.Join(tmp, "dir")
			err := os.Mkdir(dir, 0o700)
			if err != nil {
				t.Fatal(err)
			}

			link := filepath.Join(tmp, "symlink")
			err = os.Symlink(dir, link)
			if err != nil {
				t.Fatal(err)
			}

			return link
		},
	},
	{
		desc:    "symlink to mounted directory",
		isMount: true,
		prepare: func(t *testing.T) string {
			tmp := t.TempDir()

			t.Helper()
			dir := filepath.Join(tmp, "dir")
			err := os.Mkdir(dir, 0o700)
			if err != nil {
				t.Fatal(err)
			}

			tMount(t, "tmpfs", dir, "tmpfs", 0)

			link := filepath.Join(tmp, "symlink")
			err = os.Symlink(dir, link)
			if err != nil {
				t.Fatal(err)
			}

			return link
		},
	},
	{
		desc:    "symlink to a file on a different filesystem",
		isMount: false,
		prepare: func(t *testing.T) string {
			tmp := t.TempDir()

			t.Helper()
			mnt := filepath.Join(tmp, "dir")
			err := os.Mkdir(mnt, 0o700)
			if err != nil {
				t.Fatal(err)
			}

			tMount(t, "tmpfs", mnt, "tmpfs", 0)
			file := tCreateFile(t, mnt)
			link := filepath.Join(tmp, "link")
			err = os.Symlink(file, link)
			if err != nil {
				t.Fatal(err)
			}

			return link
		},
	},
	{
		desc:    "path whose parent is a symlink to directory on another device",
		isMount: false,
		prepare: func(t *testing.T) string {
			tmp := t.TempDir()

			t.Helper()
			mnt := filepath.Join(tmp, "dir")
			err := os.Mkdir(mnt, 0o700)
			if err != nil {
				t.Fatal(err)
			}

			tMount(t, "tmpfs", mnt, "tmpfs", 0)
			file := tCreateFile(t, mnt)
			// Create link -> mnt under tmp dir.
			link := filepath.Join(tmp, "link")
			err = os.Symlink(filepath.Base(mnt), link)
			if err != nil {
				t.Fatal(err)
			}
			// Path to check is /<tmp>/link/file.
			return filepath.Join(link, filepath.Base(file))
		},
	},
	{
		desc:    "directory bind mounted to itself",
		isMount: true,
		isBind:  true,
		prepare: func(t *testing.T) string {
			mnt := t.TempDir()
			tMount(t, mnt, mnt, "", unix.MS_BIND)
			return mnt
		},
	},
	{
		desc:    "directory bind-mounted to other directory",
		isMount: true,
		isBind:  true,
		prepare: func(t *testing.T) string {
			mnt := t.TempDir()
			tMount(t, t.TempDir(), mnt, "", unix.MS_BIND)
			return mnt
		},
	},
	{
		desc: "not mounted file",
		prepare: func(t *testing.T) string {
			return tCreateFile(t, t.TempDir())
		},
	},
	{
		desc:    "regular file bind-mounted to itself",
		isMount: true,
		isBind:  true,
		prepare: func(t *testing.T) string {
			file := tCreateFile(t, t.TempDir())
			tMount(t, file, file, "", unix.MS_BIND)
			return file
		},
	},
	{
		desc: "not mounted socket",
		prepare: func(t *testing.T) string {
			path := filepath.Join(t.TempDir(), "sock")
			_, err := net.Listen("unix", path)
			if err != nil {
				t.Helper()
				t.Fatal(err)
			}
			return path
		},
	},
	{
		desc:    "socket bind-mounted to itself",
		isMount: true,
		isBind:  true,
		prepare: func(t *testing.T) string {
			path := filepath.Join(t.TempDir(), "sock")
			_, err := net.Listen("unix", path)
			if err != nil {
				t.Helper()
				t.Fatal(err)
			}
			tMount(t, path, path, "", unix.MS_BIND)

			return path
		},
	},
}

func requireOpenat2(t *testing.T) {
	t.Helper()
	if err := tryOpenat2(); err != nil {
		t.Skipf("openat2: %v (old kernel? need Linux 5.6+)", err)
	}
}

func tryOpenat2() error {
	fd, err := unix.Openat2(unix.AT_FDCWD, ".", &unix.OpenHow{Flags: unix.O_RDONLY})
	if err == nil {
		_ = unix.Close(fd)
	}
	return err
}

func testMountedFast(t *testing.T, path string, tc *testMount, openat2Supported bool) {
	mounted, sure, err := MountedFast(path)
	if err != nil {
		// Got an error; is it expected?
		if !(tc.isNotExist && errors.Is(err, os.ErrNotExist)) {
			t.Errorf("MountedFast: unexpected error: %v", err)
		}

		// In case of an error, sure and mounted must be false.
		if sure {
			t.Error("MountedFast: expected sure to be false on error")
		}
		if mounted {
			t.Error("MountedFast: expected mounted to be false on error")
		}

		// No more checks.
		return
	}

	if openat2Supported {
		if mounted != tc.isMount {
			t.Errorf("MountedFast: expected mounted to be %v, got %v", tc.isMount, mounted)
		}

		// No more checks.
		return
	}

	if tc.isBind {
		// For bind mounts, in case openat2 is not supported,
		// sure and mounted must be false.
		if sure {
			t.Error("MountedFast: expected sure to be false for a bind mount")
		}
		if mounted {
			t.Error("MountedFast: expected mounted to be false for a bind mount")
		}
	} else {
		if mounted != tc.isMount {
			t.Errorf("MountFast: expected mounted to be %v, got %v", tc.isMount, mounted)
		}
		if tc.isMount && !sure {
			t.Error("MountFast: expected sure to be true for normal mount")
		}
		if !tc.isMount && sure {
			t.Error("MountFast: expected sure to be false for non-mount")
		}
	}
}

func TestMountedBy(t *testing.T) {
	checked := false
	openat2Supported := false

	// List of individual implementations to check.
	toCheck := []func(string) (bool, error){mountedByMountinfo, mountedByStat}
	if tryOpenat2() == nil {
		openat2Supported = true
		toCheck = append(toCheck, mountedByOpenat2)
	}

	for _, tc := range testMounts {
		tc := tc
		t.Run(tc.desc, func(t *testing.T) {
			m := tc.prepare(t)

			// Check the public Mounted() function as a whole.
			mounted, err := Mounted(m)
			if err == nil {
				if mounted != tc.isMount {
					t.Errorf("Mounted: expected %v, got %v", tc.isMount, mounted)
				}
			} else {
				// Got an error; is it expected?
				if !(tc.isNotExist && errors.Is(err, os.ErrNotExist)) {
					t.Errorf("Mounted: unexpected error: %v", err)
				}
				// Check false is returned in error case.
				if mounted {
					t.Error("Mounted: expected false on error")
				}
			}

			// Check the public MountedFast() function as a whole.
			testMountedFast(t, m, &tc, openat2Supported)

			// Check individual mountedBy* implementations.

			// All mountedBy* functions should be called with normalized paths.
			m, err = normalizePath(m)
			if err != nil {
				if tc.isNotExist && errors.Is(err, os.ErrNotExist) {
					return
				}
				t.Fatalf("normalizePath: %v", err)
			}

			for _, fn := range toCheck {
				// Figure out function name.
				name := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()

				mounted, err = fn(m)
				if err != nil {
					t.Errorf("%s: %v", name, err)
					// Check false is returned in error case.
					if mounted {
						t.Errorf("%s: expected false on error", name)
					}
				} else if mounted != tc.isMount {
					if tc.isBind && strings.HasSuffix(name, "mountedByStat") {
						// mountedByStat can not detect bind mounts.
					} else {
						t.Errorf("%s: expected %v, got %v", name, tc.isMount, mounted)
					}
				}
				checked = true
			}
		})
	}

	if !checked {
		t.Skip("no mounts to check")
	}
}

func TestMountedByOpenat2VsMountinfo(t *testing.T) {
	requireOpenat2(t)

	mounts, err := GetMounts(nil)
	if err != nil {
		t.Fatalf("GetMounts error: %v", err)
	}

	for _, mount := range mounts {
		m := mount.Mountpoint
		if m == "/" {
			// mountedBy*() won't work for /, so skip it
			// (this special case is handled by Mounted).
			continue
		}
		mounted, err := mountedByOpenat2(m)
		if err != nil {
			if !errors.Is(err, os.ErrPermission) {
				t.Errorf("mountedByOpenat2(%q) error: %+v", m, err)
			}
		} else if !mounted {
			t.Errorf("mountedByOpenat2(%q): expected true, got false", m)
		}
	}
}

// TestMountedRoot checks that Mounted* functions always return true for root
// directory (since / is always mounted).
func TestMountedRoot(t *testing.T) {
	for _, path := range []string{
		"/",
		"/../../",
		"/tmp/..",
		strings.Repeat("../", unix.PathMax/3), // Hope $CWD is not too deep down.
	} {
		mounted, err := Mounted(path)
		if err != nil || !mounted {
			t.Errorf("Mounted(%q): expected true, <nil>; got %v, %v", path, mounted, err)
		}

		mounted, sure, err := MountedFast(path)
		if err != nil || !mounted || !sure {
			t.Errorf("MountedFast(%q): expected true, true, <nil>; got %v, %v, %v", path, mounted, sure, err)
		}
	}
}