Debian Codegraph @

mountinfo/mountinfo_linux.go

raw symbols SCIP
1 package mountinfo
2
3 import (
4 "bufio"
5 "fmt"
6 "io"
7 "os"
8 "runtime"
9 "strconv"
10 "strings"
11 "sync"
12
13 "golang.org/x/sys/unix"
14 )
15
16 // GetMountsFromReader retrieves a list of mounts from the
17 // reader provided, with an optional filter applied (use nil
18 // for no filter). This can be useful in tests or benchmarks
19 // that provide fake mountinfo data, or when a source other
20 // than /proc/thread-self/mountinfo needs to be read from.
21 //
22 // This function is Linux-specific.
23 func GetMountsFromReader(r io.Reader, filter FilterFunc) ([]*Info, error) {
24 s := bufio.NewScanner(r)
25 out := []*Info{}
26 for s.Scan() {
27 /*
28 See http://man7.org/linux/man-pages/man5/proc.5.html
29
30 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
31 (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11)
32
33 (1) mount ID: unique identifier of the mount (may be reused after umount)
34 (2) parent ID: ID of parent (or of self for the top of the mount tree)
35 (3) major:minor: value of st_dev for files on filesystem
36 (4) root: root of the mount within the filesystem
37 (5) mount point: mount point relative to the process's root
38 (6) mount options: per mount options
39 (7) optional fields: zero or more fields of the form "tag[:value]"
40 (8) separator: marks the end of the optional fields
41 (9) filesystem type: name of filesystem of the form "type[.subtype]"
42 (10) mount source: filesystem specific information or "none"
43 (11) super options: per super block options
44
45 In other words, we have:
46 * 6 mandatory fields (1)..(6)
47 * 0 or more optional fields (7)
48 * a separator field (8)
49 * 3 mandatory fields (9)..(11)
50 */
51
52 text := s.Text()
53 fields := strings.Split(text, " ")
54 numFields := len(fields)
55 if numFields < 10 {
56 // should be at least 10 fields
57 return nil, fmt.Errorf("parsing '%s' failed: not enough fields (%d)", text, numFields)
58 }
59
60 // separator field
61 sepIdx := numFields - 4
62 // In Linux <= 3.9 mounting a cifs with spaces in a share
63 // name (like "//srv/My Docs") _may_ end up having a space
64 // in the last field of mountinfo (like "unc=//serv/My Docs").
65 // Since kernel 3.10-rc1, cifs option "unc=" is ignored,
66 // so spaces should not appear.
67 //
68 // Check for a separator, and work around the spaces bug
69 for fields[sepIdx] != "-" {
70 sepIdx--
71 if sepIdx == 5 {
72 return nil, fmt.Errorf("parsing '%s' failed: missing - separator", text)
73 }
74 }
75
76 major, minor, ok := strings.Cut(fields[2], ":")
77 if !ok {
78 return nil, fmt.Errorf("parsing '%s' failed: unexpected major:minor pair %s", text, fields[2])
79 }
80
81 p := &Info{
82 ID: toInt(fields[0]),
83 Parent: toInt(fields[1]),
84 Major: toInt(major),
85 Minor: toInt(minor),
86 Root: unescape(fields[3]),
87 Mountpoint: unescape(fields[4]),
88 Options: fields[5],
89 Optional: strings.Join(fields[6:sepIdx], " "), // zero or more optional fields
90 FSType: unescape(fields[sepIdx+1]),
91 Source: unescape(fields[sepIdx+2]),
92 VFSOptions: fields[sepIdx+3],
93 }
94
95 // Run the filter after parsing all fields.
96 var skip, stop bool
97 if filter != nil {
98 skip, stop = filter(p)
99 if skip {
100 continue
101 }
102 }
103
104 out = append(out, p)
105 if stop {
106 break
107 }
108 }
109 if err := s.Err(); err != nil {
110 return nil, err
111 }
112 return out, nil
113 }
114
115 var (
116 haveProcThreadSelf bool
117 haveProcThreadSelfOnce sync.Once
118 )
119
120 func parseMountTable(filter FilterFunc) (_ []*Info, err error) {
121 haveProcThreadSelfOnce.Do(func() {
122 _, err := os.Stat("/proc/thread-self/mountinfo")
123 haveProcThreadSelf = err == nil
124 })
125
126 // We need to lock ourselves to the current OS thread in order to make sure
127 // that the thread referenced by /proc/thread-self stays alive until we
128 // finish parsing the file.
129 runtime.LockOSThread()
130 defer runtime.UnlockOSThread()
131
132 var f *os.File
133 if haveProcThreadSelf {
134 f, err = os.Open("/proc/thread-self/mountinfo")
135 } else {
136 // On pre-3.17 kernels (such as CentOS 7), we don't have
137 // /proc/thread-self/ so we need to manually construct
138 // /proc/self/task/<tid>/ as a fallback.
139 f, err = os.Open("/proc/self/task/" + strconv.Itoa(unix.Gettid()) + "/mountinfo")
140 if os.IsNotExist(err) {
141 // If /proc/self/task/... failed, it means that our active pid
142 // namespace doesn't match the pid namespace of the /proc mount. In
143 // this case we just have to make do with /proc/self, since there
144 // is no other way of figuring out our tid in a parent pid
145 // namespace on pre-3.17 kernels.
146 f, err = os.Open("/proc/self/mountinfo")
147 }
148 }
149 if err != nil {
150 return nil, err
151 }
152 defer f.Close()
153
154 return GetMountsFromReader(f, filter)
155 }
156
157 // PidMountInfo retrieves the list of mounts from a given process' mount
158 // namespace. Unless there is a need to get mounts from a mount namespace
159 // different from that of a calling process, use GetMounts.
160 //
161 // This function is Linux-specific.
162 //
163 // Deprecated: this will be removed before v1; use GetMountsFromReader with
164 // opened /proc/<pid>/mountinfo as an argument instead.
165 func PidMountInfo(pid int) ([]*Info, error) {
166 f, err := os.Open(fmt.Sprintf("/proc/%d/mountinfo", pid))
167 if err != nil {
168 return nil, err
169 }
170 defer f.Close()
171
172 return GetMountsFromReader(f, nil)
173 }
174
175 // Some characters in some mountinfo fields may be escaped using a backslash
176 // followed by a three octal digits of the character's ASCII code \NNN, where
177 // N is 0-7, for example:
178 //
179 // space -- as \040
180 // tab (aka \t) -- as \011
181 // newline (aka \n) -- as \012
182 // backslash (aka \\) -- as \134
183 // hash (aka #) -- as \043
184 //
185 // This function converts all such escape sequences back to ASCII, and returns
186 // the unescaped string.
187 func unescape(path string) string {
188 // Try to avoid copying.
189 if strings.IndexByte(path, '\\') == -1 {
190 return path
191 }
192
193 // The following code is UTF-8 transparent as it only looks for some
194 // specific characters (backslash and 0..7) with values less than
195 // utf8.RuneSelf, and everything else is passed through as is.
196 buf := make([]byte, len(path))
197 bufLen := 0
198 for i := 0; i < len(path); i++ {
199 c := path[i]
200 // Look for \NNN, i.e. a backslash followed by three octal
201 // digits. Maximum value is 177 (equals utf8.RuneSelf-1).
202 if c == '\\' && i+3 < len(path) &&
203 (path[i+1] == '0' || path[i+1] == '1') &&
204 (path[i+2] >= '0' && path[i+2] <= '7') &&
205 (path[i+3] >= '0' && path[i+3] <= '7') {
206 // Convert from ASCII to numeric values.
207 c1 := path[i+1] - '0'
208 c2 := path[i+2] - '0'
209 c3 := path[i+3] - '0'
210 // Each octal digit is three bits, thus the shift value.
211 c = c1<<6 | c2<<3 | c3
212 // We read three extra bytes of input.
213 i += 3
214 }
215 buf[bufLen] = c
216 bufLen++
217 }
218
219 return string(buf[:bufLen])
220 }
221
222 // toInt converts a string to an int, and ignores any numbers parsing errors,
223 // as there should not be any.
224 func toInt(s string) int {
225 i, _ := strconv.Atoi(s)
226 return i
227 }