Debian Codegraph @

filesystem/mountpoint.go

raw
1 /*
2 * mountpoint.go - Contains all the functionality for finding mountpoints and
3 * using UUIDs to refer to them. Specifically, we can find the mountpoint of a
4 * path, get info about a mountpoint, and find mountpoints with a specific UUID.
5 *
6 * Copyright 2017 Google Inc.
7 * Author: Joe Richey ([email protected])
8 *
9 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
10 * use this file except in compliance with the License. You may obtain a copy of
11 * the License at
12 *
13 * http://www.apache.org/licenses/LICENSE-2.0
14 *
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18 * License for the specific language governing permissions and limitations under
19 * the License.
20 */
21
22 package filesystem
23
24 import (
25 "bufio"
26 "fmt"
27 "io"
28 "log"
29 "os"
30 "path/filepath"
31 "sort"
32 "strconv"
33 "strings"
34 "sync"
35
36 "github.com/pkg/errors"
37 )
38
39 var (
40 // These maps hold data about the state of the system's filesystems.
41 //
42 // They only contain one Mount per filesystem, even if there are
43 // additional bind mounts, since we want to store fscrypt metadata in
44 // only one place per filesystem. When it is ambiguous which Mount
45 // should be used for a filesystem, mountsByDevice will contain an
46 // explicit nil entry, and mountsByPath won't contain an entry.
47 mountsByDevice map[DeviceNumber]*Mount
48 mountsByPath map[string]*Mount
49 // Used to make the mount functions thread safe
50 mountMutex sync.Mutex
51 // True if the maps have been successfully initialized.
52 mountsInitialized bool
53 // Supported tokens for filesystem links
54 uuidToken = "UUID"
55 pathToken = "PATH"
56 // Location to perform UUID lookup
57 uuidDirectory = "/dev/disk/by-uuid"
58 )
59
60 // Unescape octal-encoded escape sequences in a string from the mountinfo file.
61 // The kernel encodes the ' ', '\t', '\n', and '\\' bytes this way. This
62 // function exactly inverts what the kernel does, including by preserving
63 // invalid UTF-8.
64 func unescapeString(str string) string {
65 var sb strings.Builder
66 for i := 0; i < len(str); i++ {
67 b := str[i]
68 if b == '\\' && i+3 < len(str) {
69 if parsed, err := strconv.ParseInt(str[i+1:i+4], 8, 8); err == nil {
70 b = uint8(parsed)
71 i += 3
72 }
73 }
74 sb.WriteByte(b)
75 }
76 return sb.String()
77 }
78
79 // EscapeString is the reverse of unescapeString. Use this to avoid injecting
80 // spaces or newlines into output that uses these characters as separators.
81 func EscapeString(str string) string {
82 var sb strings.Builder
83 for _, b := range []byte(str) {
84 switch b {
85 case ' ', '\t', '\n', '\\':
86 sb.WriteString(fmt.Sprintf("\\%03o", b))
87 default:
88 sb.WriteByte(b)
89 }
90 }
91 return sb.String()
92 }
93
94 func getDeviceName(num DeviceNumber, mountSource string) string {
95 // When possible, get the device name via the device number rather than
96 // use the mount source field directly. This is necessary to handle a
97 // rootfs that was mounted via the kernel command line, since mountinfo
98 // always shows /dev/root for that.
99 linkPath := fmt.Sprintf("/sys/dev/block/%v", num)
100 if target, err := os.Readlink(linkPath); err == nil {
101 derivedDeviceName := fmt.Sprintf("/dev/%s", filepath.Base(target))
102 if _, err := os.Stat(derivedDeviceName); err == nil {
103 return derivedDeviceName
104 }
105 }
106 // Sysfs is not mounted or is incomplete, or the device nodes are not in
107 // the standard location. Fall back to using the mount source field if
108 // it looks like a path.
109 if strings.HasPrefix(mountSource, "/") {
110 return mountSource
111 }
112 return ""
113 }
114
115 // Parse one line of /proc/self/mountinfo.
116 //
117 // The line contains the following space-separated fields:
118 //
119 // [0] mount ID
120 // [1] parent ID
121 // [2] major:minor
122 // [3] root
123 // [4] mount point
124 // [5] mount options
125 // [6...n-1] optional field(s)
126 // [n] separator
127 // [n+1] filesystem type
128 // [n+2] mount source
129 // [n+3] super options
130 //
131 // For more details, see https://www.kernel.org/doc/Documentation/filesystems/proc.txt
132 func parseMountInfoLine(line string) *Mount {
133 fields := strings.Split(line, " ")
134 if len(fields) < 10 {
135 return nil
136 }
137
138 // Count the optional fields. In case new fields are appended later,
139 // don't simply assume that n == len(fields) - 4.
140 n := 6
141 for fields[n] != "-" {
142 n++
143 if n >= len(fields) {
144 return nil
145 }
146 }
147 if n+3 >= len(fields) {
148 return nil
149 }
150
151 var mnt *Mount = &Mount{}
152 var err error
153 mnt.DeviceNumber, err = newDeviceNumberFromString(fields[2])
154 if err != nil {
155 return nil
156 }
157 mnt.Subtree = unescapeString(fields[3])
158 mnt.Path = unescapeString(fields[4])
159 for _, opt := range strings.Split(fields[5], ",") {
160 if opt == "ro" {
161 mnt.ReadOnly = true
162 }
163 }
164 mnt.FilesystemType = unescapeString(fields[n+1])
165 mnt.Device = getDeviceName(mnt.DeviceNumber, unescapeString(fields[n+2]))
166 return mnt
167 }
168
169 type mountpointTreeNode struct {
170 mount *Mount
171 parent *mountpointTreeNode
172 children []*mountpointTreeNode
173 }
174
175 func addUncontainedSubtreesRecursive(dst map[string]bool,
176 node *mountpointTreeNode, allUncontainedSubtrees map[string]bool) {
177 if allUncontainedSubtrees[node.mount.Subtree] {
178 dst[node.mount.Subtree] = true
179 }
180 for _, child := range node.children {
181 addUncontainedSubtreesRecursive(dst, child, allUncontainedSubtrees)
182 }
183 }
184
185 // findMainMount finds the "main" Mount of a filesystem. The "main" Mount is
186 // where the filesystem's fscrypt metadata is stored.
187 //
188 // Normally, there is just one Mount and it's of the entire filesystem
189 // (mnt.Subtree == "/"). But in general, the filesystem might be mounted in
190 // multiple places, including "bind mounts" where mnt.Subtree != "/". Also, the
191 // filesystem might have a combination of read-write and read-only mounts.
192 //
193 // To handle most cases, we could just choose a mount with mnt.Subtree == "/",
194 // preferably a read-write mount. However, that doesn't work in containers
195 // where the "/" subtree might not be mounted. Here's a real-world example:
196 //
197 // mnt.Subtree mnt.Path
198 // ----------- --------
199 // /var/lib/lxc/base/rootfs /
200 // /var/cache/pacman/pkg /var/cache/pacman/pkg
201 // /srv/repo/x86_64 /srv/http/x86_64
202 //
203 // In this case, all mnt.Subtree are independent. To handle this case, we must
204 // choose the Mount whose mnt.Path contains the others, i.e. the first one.
205 // Note: the fscrypt metadata won't be usable from outside the container since
206 // it won't be at the real root of the filesystem, but that may be acceptable.
207 //
208 // However, we can't look *only* at mnt.Path, since in some cases mnt.Subtree is
209 // needed to correctly handle bind mounts. For example, in the following case,
210 // the first Mount should be chosen:
211 //
212 // mnt.Subtree mnt.Path
213 // ----------- --------
214 // /foo /foo
215 // /foo/dir /dir
216 //
217 // To solve this, we divide the mounts into non-overlapping trees of mnt.Path.
218 // Then, we choose one of these trees which contains (exactly or via path
219 // prefix) *all* mnt.Subtree. We then return the root of this tree. In both
220 // the above examples, this algorithm returns the first Mount.
221 func findMainMount(filesystemMounts []*Mount) *Mount {
222 // Index this filesystem's mounts by path. Note: paths are unique here,
223 // since non-last mounts were already excluded earlier.
224 //
225 // Also build the set of all mounted subtrees.
226 filesystemMountsByPath := make(map[string]*mountpointTreeNode)
227 allSubtrees := make(map[string]bool)
228 for _, mnt := range filesystemMounts {
229 filesystemMountsByPath[mnt.Path] = &mountpointTreeNode{mount: mnt}
230 allSubtrees[mnt.Subtree] = true
231 }
232
233 // Divide the mounts into non-overlapping trees of mountpoints.
234 for path, mntNode := range filesystemMountsByPath {
235 for path != "/" && mntNode.parent == nil {
236 path = filepath.Dir(path)
237 if parent := filesystemMountsByPath[path]; parent != nil {
238 mntNode.parent = parent
239 parent.children = append(parent.children, mntNode)
240 }
241 }
242 }
243
244 // Build the set of mounted subtrees that aren't contained in any other
245 // mounted subtree.
246 allUncontainedSubtrees := make(map[string]bool)
247 for subtree := range allSubtrees {
248 contained := false
249 for t := subtree; t != "/" && !contained; {
250 t = filepath.Dir(t)
251 contained = allSubtrees[t]
252 }
253 if !contained {
254 allUncontainedSubtrees[subtree] = true
255 }
256 }
257
258 // Select the root of a mountpoint tree whose mounted subtrees contain
259 // *all* mounted subtrees. Equivalently, select a mountpoint tree in
260 // which every uncontained subtree is mounted.
261 var mainMount *Mount
262 for _, mntNode := range filesystemMountsByPath {
263 mnt := mntNode.mount
264 if mntNode.parent != nil {
265 continue
266 }
267 uncontainedSubtrees := make(map[string]bool)
268 addUncontainedSubtreesRecursive(uncontainedSubtrees, mntNode, allUncontainedSubtrees)
269 if len(uncontainedSubtrees) != len(allUncontainedSubtrees) {
270 continue
271 }
272 // If there's more than one eligible mount, they should have the
273 // same Subtree. Otherwise it's ambiguous which one to use.
274 if mainMount != nil && mainMount.Subtree != mnt.Subtree {
275 log.Printf("Unsupported case: %q (%v) has multiple non-overlapping mounts. This filesystem will be ignored!",
276 mnt.Device, mnt.DeviceNumber)
277 return nil
278 }
279 // Prefer a read-write mount to a read-only one.
280 if mainMount == nil || mainMount.ReadOnly {
281 mainMount = mnt
282 }
283 }
284 return mainMount
285 }
286
287 // This is separate from loadMountInfo() only for unit testing.
288 func readMountInfo(r io.Reader) error {
289 mountsByDevice = make(map[DeviceNumber]*Mount)
290 mountsByPath = make(map[string]*Mount)
291 allMountsByDevice := make(map[DeviceNumber][]*Mount)
292 allMountsByPath := make(map[string]*Mount)
293
294 scanner := bufio.NewScanner(r)
295 for scanner.Scan() {
296 line := scanner.Text()
297 mnt := parseMountInfoLine(line)
298 if mnt == nil {
299 log.Printf("ignoring invalid mountinfo line %q", line)
300 continue
301 }
302
303 // We can only use mountpoints that are directories for fscrypt.
304 if !isDir(mnt.Path) {
305 log.Printf("ignoring mountpoint %q because it is not a directory", mnt.Path)
306 continue
307 }
308
309 // Note this overrides the info if we have seen the mountpoint
310 // earlier in the file. This is correct behavior because the
311 // mountpoints are listed in mount order.
312 allMountsByPath[mnt.Path] = mnt
313 }
314 // For each filesystem, choose a "main" Mount and discard any additional
315 // bind mounts. fscrypt only cares about the main Mount, since it's
316 // where the fscrypt metadata is stored. Store all the main Mounts in
317 // mountsByDevice and mountsByPath so that they can be found later.
318 for _, mnt := range allMountsByPath {
319 allMountsByDevice[mnt.DeviceNumber] =
320 append(allMountsByDevice[mnt.DeviceNumber], mnt)
321 }
322 for deviceNumber, filesystemMounts := range allMountsByDevice {
323 mnt := findMainMount(filesystemMounts)
324 mountsByDevice[deviceNumber] = mnt // may store an explicit nil entry
325 if mnt != nil {
326 mountsByPath[mnt.Path] = mnt
327 }
328 }
329 return nil
330 }
331
332 // loadMountInfo populates the Mount mappings by parsing /proc/self/mountinfo.
333 // It returns an error if the Mount mappings cannot be populated.
334 func loadMountInfo() error {
335 if !mountsInitialized {
336 file, err := os.Open("/proc/self/mountinfo")
337 if err != nil {
338 return err
339 }
340 defer file.Close()
341 if err := readMountInfo(file); err != nil {
342 return err
343 }
344 mountsInitialized = true
345 }
346 return nil
347 }
348
349 func filesystemLacksMainMountError(deviceNumber DeviceNumber) error {
350 return errors.Errorf("Device %q (%v) lacks a \"main\" mountpoint in the current mount namespace, so it's ambiguous where to store the fscrypt metadata.",
351 getDeviceName(deviceNumber, ""), deviceNumber)
352 }
353
354 // AllFilesystems lists all mounted filesystems ordered by path to their "main"
355 // Mount. Use CheckSetup() to see if they are set up for use with fscrypt.
356 func AllFilesystems() ([]*Mount, error) {
357 mountMutex.Lock()
358 defer mountMutex.Unlock()
359 if err := loadMountInfo(); err != nil {
360 return nil, err
361 }
362
363 mounts := make([]*Mount, 0, len(mountsByPath))
364 for _, mount := range mountsByPath {
365 mounts = append(mounts, mount)
366 }
367
368 sort.Sort(PathSorter(mounts))
369 return mounts, nil
370 }
371
372 // UpdateMountInfo updates the filesystem mountpoint maps with the current state
373 // of the filesystem mountpoints. Returns error if the initialization fails.
374 func UpdateMountInfo() error {
375 mountMutex.Lock()
376 defer mountMutex.Unlock()
377 mountsInitialized = false
378 return loadMountInfo()
379 }
380
381 // FindMount returns the main Mount object for the filesystem which contains the
382 // file at the specified path. An error is returned if the path is invalid or if
383 // we cannot load the required mount data. If a mount has been updated since the
384 // last call to one of the mount functions, run UpdateMountInfo to see changes.
385 func FindMount(path string) (*Mount, error) {
386 mountMutex.Lock()
387 defer mountMutex.Unlock()
388 if err := loadMountInfo(); err != nil {
389 return nil, err
390 }
391 // First try to find the mount by the number of the containing device.
392 deviceNumber, err := getNumberOfContainingDevice(path)
393 if err != nil {
394 return nil, err
395 }
396 mnt, ok := mountsByDevice[deviceNumber]
397 if ok {
398 if mnt == nil {
399 return nil, filesystemLacksMainMountError(deviceNumber)
400 }
401 return mnt, nil
402 }
403 // The mount couldn't be found by the number of the containing device.
404 // Fall back to walking up the directory hierarchy and checking for a
405 // mount at each directory path. This is necessary for btrfs, where
406 // files report a different st_dev from the /proc/self/mountinfo entry.
407 curPath, err := canonicalizePath(path)
408 if err != nil {
409 return nil, err
410 }
411 for {
412 mnt := mountsByPath[curPath]
413 if mnt != nil {
414 return mnt, nil
415 }
416 // Move to the parent directory unless we have reached the root.
417 parent := filepath.Dir(curPath)
418 if parent == curPath {
419 return nil, errors.Errorf("couldn't find mountpoint containing %q", path)
420 }
421 curPath = parent
422 }
423 }
424
425 // GetMount is like FindMount, except GetMount also returns an error if the path
426 // doesn't name the same file as the filesystem's "main" Mount. For example, if
427 // a filesystem is fully mounted at "/mnt" and if "/mnt/a" exists, then
428 // FindMount("/mnt/a") will succeed whereas GetMount("/mnt/a") will fail. This
429 // is true even if "/mnt/a" is a bind mount of part of the same filesystem.
430 func GetMount(mountpoint string) (*Mount, error) {
431 mnt, err := FindMount(mountpoint)
432 if err != nil {
433 return nil, &ErrNotAMountpoint{mountpoint}
434 }
435 // Check whether 'mountpoint' names the same directory as 'mnt.Path'.
436 // Use os.SameFile() (i.e., compare inode numbers) rather than compare
437 // canonical paths, since filesystems may be mounted in multiple places.
438 fi1, err := os.Stat(mountpoint)
439 if err != nil {
440 return nil, err
441 }
442 fi2, err := os.Stat(mnt.Path)
443 if err != nil {
444 return nil, err
445 }
446 if !os.SameFile(fi1, fi2) {
447 return nil, &ErrNotAMountpoint{mountpoint}
448 }
449 return mnt, nil
450 }
451
452 func uuidToDeviceNumber(uuid string) (DeviceNumber, error) {
453 uuidSymlinkPath := filepath.Join(uuidDirectory, uuid)
454 return getDeviceNumber(uuidSymlinkPath)
455 }
456
457 func deviceNumberToMount(deviceNumber DeviceNumber) (*Mount, bool) {
458 mountMutex.Lock()
459 defer mountMutex.Unlock()
460 if err := loadMountInfo(); err != nil {
461 log.Print(err)
462 return nil, false
463 }
464 mnt, ok := mountsByDevice[deviceNumber]
465 return mnt, ok
466 }
467
468 // getMountFromLink returns the main Mount, if any, for the filesystem which the
469 // given link points to. The link should contain a series of token-value pairs
470 // (<token>=<value>), one per line. The supported tokens are "UUID" and "PATH".
471 // If the UUID is present and it works, then it is used; otherwise, PATH is used
472 // if it is present. (The fallback from UUID to PATH will keep the link working
473 // if the UUID of the target filesystem changes but its mountpoint doesn't.)
474 //
475 // If a mount has been updated since the last call to one of the mount
476 // functions, make sure to run UpdateMountInfo first.
477 func getMountFromLink(link string) (*Mount, error) {
478 // Parse the link.
479 uuid := ""
480 path := ""
481 lines := strings.Split(link, "\n")
482 for _, line := range lines {
483 line := strings.TrimSpace(line)
484 if line == "" {
485 continue
486 }
487 pair := strings.Split(line, "=")
488 if len(pair) != 2 {
489 log.Printf("ignoring invalid line in filesystem link file: %q", line)
490 continue
491 }
492 token := pair[0]
493 value := pair[1]
494 switch token {
495 case uuidToken:
496 uuid = value
497 case pathToken:
498 path = value
499 default:
500 log.Printf("ignoring unknown link token %q", token)
501 }
502 }
503 // At least one of UUID and PATH must be present.
504 if uuid == "" && path == "" {
505 return nil, &ErrFollowLink{link, errors.Errorf("invalid filesystem link file")}
506 }
507
508 // Try following the UUID.
509 errMsg := ""
510 if uuid != "" {
511 deviceNumber, err := uuidToDeviceNumber(uuid)
512 if err == nil {
513 mnt, ok := deviceNumberToMount(deviceNumber)
514 if mnt != nil {
515 log.Printf("resolved filesystem link using UUID %q", uuid)
516 return mnt, nil
517 }
518 if ok {
519 return nil, &ErrFollowLink{link, filesystemLacksMainMountError(deviceNumber)}
520 }
521 log.Printf("cannot find filesystem with UUID %q", uuid)
522 } else {
523 log.Printf("cannot find filesystem with UUID %q: %v", uuid, err)
524 }
525 errMsg += fmt.Sprintf("cannot find filesystem with UUID %q", uuid)
526 if path != "" {
527 log.Printf("falling back to using mountpoint path instead of UUID")
528 }
529 }
530 // UUID didn't work. As a fallback, try the mountpoint path.
531 if path != "" {
532 mnt, err := GetMount(path)
533 if mnt != nil {
534 log.Printf("resolved filesystem link using mountpoint path %q", path)
535 return mnt, nil
536 }
537 log.Print(err)
538 if errMsg == "" {
539 errMsg = fmt.Sprintf("cannot find filesystem with main mountpoint %q", path)
540 } else {
541 errMsg += fmt.Sprintf(" or main mountpoint %q", path)
542 }
543 }
544 // No method worked; return an error.
545 return nil, &ErrFollowLink{link, errors.New(errMsg)}
546 }
547
548 func (mnt *Mount) getFilesystemUUID() (string, error) {
549 dirEntries, err := os.ReadDir(uuidDirectory)
550 if err != nil {
551 return "", err
552 }
553 for _, dirEntry := range dirEntries {
554 fileInfo, err := dirEntry.Info()
555 if err != nil {
556 continue
557 }
558 if fileInfo.Mode()&os.ModeSymlink == 0 {
559 continue // Only interested in UUID symlinks
560 }
561 uuid := fileInfo.Name()
562 deviceNumber, err := uuidToDeviceNumber(uuid)
563 if err != nil {
564 log.Print(err)
565 continue
566 }
567 if mnt.DeviceNumber == deviceNumber {
568 return uuid, nil
569 }
570 }
571 return "", errors.Errorf("cannot determine UUID of device %q (%v)",
572 mnt.Device, mnt.DeviceNumber)
573 }
574
575 // makeLink creates the contents of a link file which will point to the given
576 // filesystem. This will normally be a string of the form
577 // "UUID=<uuid>\nPATH=<path>\n". If the UUID cannot be determined, the UUID
578 // portion will be omitted.
579 func makeLink(mnt *Mount) (string, error) {
580 uuid, err := mnt.getFilesystemUUID()
581 if err != nil {
582 // The UUID could not be determined. This happens for btrfs
583 // filesystems, as the device number found via
584 // /dev/disk/by-uuid/* for btrfs filesystems differs from the
585 // actual device number of the mounted filesystem. Just rely
586 // entirely on the fallback to mountpoint path.
587 log.Print(err)
588 return fmt.Sprintf("%s=%s\n", pathToken, mnt.Path), nil
589 }
590 return fmt.Sprintf("%s=%s\n%s=%s\n", uuidToken, uuid, pathToken, mnt.Path), nil
591 }