1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <sys/mount.h>
6 
7 #include "alloc-util.h"
8 #include "chase-symlinks.h"
9 #include "fd-util.h"
10 #include "fileio.h"
11 #include "filesystems.h"
12 #include "fs-util.h"
13 #include "missing_stat.h"
14 #include "missing_syscall.h"
15 #include "mkdir.h"
16 #include "mountpoint-util.h"
17 #include "nulstr-util.h"
18 #include "parse-util.h"
19 #include "path-util.h"
20 #include "stat-util.h"
21 #include "stdio-util.h"
22 #include "strv.h"
23 #include "user-util.h"
24 
25 /* This is the original MAX_HANDLE_SZ definition from the kernel, when the API was introduced. We use that in place of
26  * any more currently defined value to future-proof things: if the size is increased in the API headers, and our code
27  * is recompiled then it would cease working on old kernels, as those refuse any sizes larger than this value with
28  * EINVAL right-away. Hence, let's disconnect ourselves from any such API changes, and stick to the original definition
29  * from when it was introduced. We use it as a start value only anyway (see below), and hence should be able to deal
30  * with large file handles anyway. */
31 #define ORIGINAL_MAX_HANDLE_SZ 128
32 
name_to_handle_at_loop(int fd,const char * path,struct file_handle ** ret_handle,int * ret_mnt_id,int flags)33 int name_to_handle_at_loop(
34                 int fd,
35                 const char *path,
36                 struct file_handle **ret_handle,
37                 int *ret_mnt_id,
38                 int flags) {
39 
40         _cleanup_free_ struct file_handle *h = NULL;
41         size_t n = ORIGINAL_MAX_HANDLE_SZ;
42 
43         assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH)) == 0);
44 
45         /* We need to invoke name_to_handle_at() in a loop, given that it might return EOVERFLOW when the specified
46          * buffer is too small. Note that in contrast to what the docs might suggest, MAX_HANDLE_SZ is only good as a
47          * start value, it is not an upper bound on the buffer size required.
48          *
49          * This improves on raw name_to_handle_at() also in one other regard: ret_handle and ret_mnt_id can be passed
50          * as NULL if there's no interest in either. */
51 
52         for (;;) {
53                 int mnt_id = -1;
54 
55                 h = malloc0(offsetof(struct file_handle, f_handle) + n);
56                 if (!h)
57                         return -ENOMEM;
58 
59                 h->handle_bytes = n;
60 
61                 if (name_to_handle_at(fd, path, h, &mnt_id, flags) >= 0) {
62 
63                         if (ret_handle)
64                                 *ret_handle = TAKE_PTR(h);
65 
66                         if (ret_mnt_id)
67                                 *ret_mnt_id = mnt_id;
68 
69                         return 0;
70                 }
71                 if (errno != EOVERFLOW)
72                         return -errno;
73 
74                 if (!ret_handle && ret_mnt_id && mnt_id >= 0) {
75 
76                         /* As it appears, name_to_handle_at() fills in mnt_id even when it returns EOVERFLOW when the
77                          * buffer is too small, but that's undocumented. Hence, let's make use of this if it appears to
78                          * be filled in, and the caller was interested in only the mount ID an nothing else. */
79 
80                         *ret_mnt_id = mnt_id;
81                         return 0;
82                 }
83 
84                 /* If name_to_handle_at() didn't increase the byte size, then this EOVERFLOW is caused by something
85                  * else (apparently EOVERFLOW is returned for untriggered nfs4 mounts sometimes), not by the too small
86                  * buffer. In that case propagate EOVERFLOW */
87                 if (h->handle_bytes <= n)
88                         return -EOVERFLOW;
89 
90                 /* The buffer was too small. Size the new buffer by what name_to_handle_at() returned. */
91                 n = h->handle_bytes;
92                 if (offsetof(struct file_handle, f_handle) + n < n) /* check for addition overflow */
93                         return -EOVERFLOW;
94 
95                 h = mfree(h);
96         }
97 }
98 
fd_fdinfo_mnt_id(int fd,const char * filename,int flags,int * ret_mnt_id)99 static int fd_fdinfo_mnt_id(int fd, const char *filename, int flags, int *ret_mnt_id) {
100         char path[STRLEN("/proc/self/fdinfo/") + DECIMAL_STR_MAX(int)];
101         _cleanup_free_ char *fdinfo = NULL;
102         _cleanup_close_ int subfd = -1;
103         char *p;
104         int r;
105 
106         assert(ret_mnt_id);
107         assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH)) == 0);
108 
109         if ((flags & AT_EMPTY_PATH) && isempty(filename))
110                 xsprintf(path, "/proc/self/fdinfo/%i", fd);
111         else {
112                 subfd = openat(fd, filename, O_CLOEXEC|O_PATH|(flags & AT_SYMLINK_FOLLOW ? 0 : O_NOFOLLOW));
113                 if (subfd < 0)
114                         return -errno;
115 
116                 xsprintf(path, "/proc/self/fdinfo/%i", subfd);
117         }
118 
119         r = read_full_virtual_file(path, &fdinfo, NULL);
120         if (r == -ENOENT) /* The fdinfo directory is a relatively new addition */
121                 return -EOPNOTSUPP;
122         if (r < 0)
123                 return r;
124 
125         p = startswith(fdinfo, "mnt_id:");
126         if (!p) {
127                 p = strstr(fdinfo, "\nmnt_id:");
128                 if (!p) /* The mnt_id field is a relatively new addition */
129                         return -EOPNOTSUPP;
130 
131                 p += 8;
132         }
133 
134         p += strspn(p, WHITESPACE);
135         p[strcspn(p, WHITESPACE)] = 0;
136 
137         return safe_atoi(p, ret_mnt_id);
138 }
139 
filename_possibly_with_slash_suffix(const char * s)140 static bool filename_possibly_with_slash_suffix(const char *s) {
141         const char *slash, *copied;
142 
143         /* Checks whether the specified string is either file name, or a filename with a suffix of
144          * slashes. But nothing else.
145          *
146          * this is OK: foo, bar, foo/, bar/, foo//, bar///
147          * this is not OK: "", "/", "/foo", "foo/bar", ".", ".." … */
148 
149         slash = strchr(s, '/');
150         if (!slash)
151                 return filename_is_valid(s);
152 
153         if (slash - s > PATH_MAX) /* We want to allocate on the stack below, hence do a size check first */
154                 return false;
155 
156         if (slash[strspn(slash, "/")] != 0) /* Check that the suffix consist only of one or more slashes */
157                 return false;
158 
159         copied = strndupa_safe(s, slash - s);
160         return filename_is_valid(copied);
161 }
162 
is_name_to_handle_at_fatal_error(int err)163 static bool is_name_to_handle_at_fatal_error(int err) {
164         /* name_to_handle_at() can return "acceptable" errors that are due to the context. For
165          * example the kernel does not support name_to_handle_at() at all (ENOSYS), or the syscall
166          * was blocked (EACCES/EPERM; maybe through seccomp, because we are running inside of a
167          * container), or the mount point is not triggered yet (EOVERFLOW, think nfs4), or some
168          * general name_to_handle_at() flakiness (EINVAL). However other errors are not supposed to
169          * happen and therefore are considered fatal ones. */
170 
171         assert(err < 0);
172 
173         return !IN_SET(err, -EOPNOTSUPP, -ENOSYS, -EACCES, -EPERM, -EOVERFLOW, -EINVAL);
174 }
175 
fd_is_mount_point(int fd,const char * filename,int flags)176 int fd_is_mount_point(int fd, const char *filename, int flags) {
177         _cleanup_free_ struct file_handle *h = NULL, *h_parent = NULL;
178         int mount_id = -1, mount_id_parent = -1;
179         bool nosupp = false, check_st_dev = true;
180         STRUCT_STATX_DEFINE(sx);
181         struct stat a, b;
182         int r;
183 
184         assert(fd >= 0);
185         assert(filename);
186         assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH)) == 0);
187 
188         /* Insist that the specified filename is actually a filename, and not a path, i.e. some inode further
189          * up or down the tree then immediately below the specified directory fd. */
190         if (!filename_possibly_with_slash_suffix(filename))
191                 return -EINVAL;
192 
193         /* First we will try statx()' STATX_ATTR_MOUNT_ROOT attribute, which is our ideal API, available
194          * since kernel 5.8.
195          *
196          * If that fails, our second try is the name_to_handle_at() syscall, which tells us the mount id and
197          * an opaque file "handle". It is not supported everywhere though (kernel compile-time option, not
198          * all file systems are hooked up). If it works the mount id is usually good enough to tell us
199          * whether something is a mount point.
200          *
201          * If that didn't work we will try to read the mount id from /proc/self/fdinfo/<fd>. This is almost
202          * as good as name_to_handle_at(), however, does not return the opaque file handle. The opaque file
203          * handle is pretty useful to detect the root directory, which we should always consider a mount
204          * point. Hence we use this only as fallback. Exporting the mnt_id in fdinfo is a pretty recent
205          * kernel addition.
206          *
207          * As last fallback we do traditional fstat() based st_dev comparisons. This is how things were
208          * traditionally done, but unionfs breaks this since it exposes file systems with a variety of st_dev
209          * reported. Also, btrfs subvolumes have different st_dev, even though they aren't real mounts of
210          * their own. */
211 
212         if (statx(fd, filename, (FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? 0 : AT_SYMLINK_NOFOLLOW) |
213                                 (flags & AT_EMPTY_PATH) |
214                                 AT_NO_AUTOMOUNT, STATX_TYPE, &sx) < 0) {
215                 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
216                         return -errno;
217 
218                 /* If statx() is not available or forbidden, fall back to name_to_handle_at() below */
219         } else if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT)) /* yay! */
220                 return FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
221         else if (FLAGS_SET(sx.stx_mask, STATX_TYPE) && S_ISLNK(sx.stx_mode))
222                 return false; /* symlinks are never mount points */
223 
224         r = name_to_handle_at_loop(fd, filename, &h, &mount_id, flags);
225         if (r < 0) {
226                 if (is_name_to_handle_at_fatal_error(r))
227                         return r;
228                 if (r != -EOPNOTSUPP)
229                         goto fallback_fdinfo;
230 
231                 /* This kernel or file system does not support name_to_handle_at(), hence let's see
232                  * if the upper fs supports it (in which case it is a mount point), otherwise fall
233                  * back to the traditional stat() logic */
234                 nosupp = true;
235         }
236 
237         r = name_to_handle_at_loop(fd, "", &h_parent, &mount_id_parent, AT_EMPTY_PATH);
238         if (r < 0) {
239                 if (is_name_to_handle_at_fatal_error(r))
240                         return r;
241                 if (r != -EOPNOTSUPP)
242                         goto fallback_fdinfo;
243                 if (nosupp)
244                         /* Both the parent and the directory can't do name_to_handle_at() */
245                         goto fallback_fdinfo;
246 
247                 /* The parent can't do name_to_handle_at() but the directory we are
248                  * interested in can?  If so, it must be a mount point. */
249                 return 1;
250         }
251 
252         /* The parent can do name_to_handle_at() but the directory we are interested in can't? If
253          * so, it must be a mount point. */
254         if (nosupp)
255                 return 1;
256 
257         /* If the file handle for the directory we are interested in and its parent are identical,
258          * we assume this is the root directory, which is a mount point. */
259 
260         if (h->handle_bytes == h_parent->handle_bytes &&
261             h->handle_type == h_parent->handle_type &&
262             memcmp(h->f_handle, h_parent->f_handle, h->handle_bytes) == 0)
263                 return 1;
264 
265         return mount_id != mount_id_parent;
266 
267 fallback_fdinfo:
268         r = fd_fdinfo_mnt_id(fd, filename, flags, &mount_id);
269         if (IN_SET(r, -EOPNOTSUPP, -EACCES, -EPERM))
270                 goto fallback_fstat;
271         if (r < 0)
272                 return r;
273 
274         r = fd_fdinfo_mnt_id(fd, "", AT_EMPTY_PATH, &mount_id_parent);
275         if (r < 0)
276                 return r;
277 
278         if (mount_id != mount_id_parent)
279                 return 1;
280 
281         /* Hmm, so, the mount ids are the same. This leaves one special case though for the root file
282          * system. For that, let's see if the parent directory has the same inode as we are interested
283          * in. Hence, let's also do fstat() checks now, too, but avoid the st_dev comparisons, since they
284          * aren't that useful on unionfs mounts. */
285         check_st_dev = false;
286 
287 fallback_fstat:
288         /* yay for fstatat() taking a different set of flags than the other _at() above */
289         if (flags & AT_SYMLINK_FOLLOW)
290                 flags &= ~AT_SYMLINK_FOLLOW;
291         else
292                 flags |= AT_SYMLINK_NOFOLLOW;
293         if (fstatat(fd, filename, &a, flags) < 0)
294                 return -errno;
295         if (S_ISLNK(a.st_mode)) /* Symlinks are never mount points */
296                 return false;
297 
298         if (fstatat(fd, "", &b, AT_EMPTY_PATH) < 0)
299                 return -errno;
300 
301         /* A directory with same device and inode as its parent? Must be the root directory */
302         if (stat_inode_same(&a, &b))
303                 return 1;
304 
305         return check_st_dev && (a.st_dev != b.st_dev);
306 }
307 
308 /* flags can be AT_SYMLINK_FOLLOW or 0 */
path_is_mount_point(const char * t,const char * root,int flags)309 int path_is_mount_point(const char *t, const char *root, int flags) {
310         _cleanup_free_ char *canonical = NULL;
311         _cleanup_close_ int fd = -1;
312         int r;
313 
314         assert(t);
315         assert((flags & ~AT_SYMLINK_FOLLOW) == 0);
316 
317         if (path_equal(t, "/"))
318                 return 1;
319 
320         /* we need to resolve symlinks manually, we can't just rely on
321          * fd_is_mount_point() to do that for us; if we have a structure like
322          * /bin -> /usr/bin/ and /usr is a mount point, then the parent that we
323          * look at needs to be /usr, not /. */
324         if (flags & AT_SYMLINK_FOLLOW) {
325                 r = chase_symlinks(t, root, CHASE_TRAIL_SLASH, &canonical, NULL);
326                 if (r < 0)
327                         return r;
328 
329                 t = canonical;
330         }
331 
332         fd = open_parent(t, O_PATH|O_CLOEXEC, 0);
333         if (fd < 0)
334                 return fd;
335 
336         return fd_is_mount_point(fd, last_path_component(t), flags);
337 }
338 
path_get_mnt_id(const char * path,int * ret)339 int path_get_mnt_id(const char *path, int *ret) {
340         STRUCT_NEW_STATX_DEFINE(buf);
341         int r;
342 
343         if (statx(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT, STATX_MNT_ID, &buf.sx) < 0) {
344                 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
345                         return -errno;
346 
347                 /* Fall back to name_to_handle_at() and then fdinfo if statx is not supported or we lack
348                  * privileges */
349 
350         } else if (FLAGS_SET(buf.nsx.stx_mask, STATX_MNT_ID)) {
351                 *ret = buf.nsx.stx_mnt_id;
352                 return 0;
353         }
354 
355         r = name_to_handle_at_loop(AT_FDCWD, path, NULL, ret, 0);
356         if (r == 0 || is_name_to_handle_at_fatal_error(r))
357                 return r;
358 
359         return fd_fdinfo_mnt_id(AT_FDCWD, path, 0, ret);
360 }
361 
fstype_is_network(const char * fstype)362 bool fstype_is_network(const char *fstype) {
363         const char *x;
364 
365         x = startswith(fstype, "fuse.");
366         if (x)
367                 fstype = x;
368 
369         if (nulstr_contains(filesystem_sets[FILESYSTEM_SET_NETWORK].value, fstype))
370                 return true;
371 
372         /* Filesystems not present in the internal database */
373         return STR_IN_SET(fstype,
374                           "davfs",
375                           "glusterfs",
376                           "lustre",
377                           "sshfs");
378 }
379 
fstype_is_api_vfs(const char * fstype)380 bool fstype_is_api_vfs(const char *fstype) {
381         const FilesystemSet *fs;
382 
383         FOREACH_POINTER(fs,
384                 filesystem_sets + FILESYSTEM_SET_BASIC_API,
385                 filesystem_sets + FILESYSTEM_SET_AUXILIARY_API,
386                 filesystem_sets + FILESYSTEM_SET_PRIVILEGED_API,
387                 filesystem_sets + FILESYSTEM_SET_TEMPORARY)
388             if (nulstr_contains(fs->value, fstype))
389                     return true;
390 
391         /* Filesystems not present in the internal database */
392         return STR_IN_SET(fstype,
393                           "autofs",
394                           "cpuset",
395                           "devtmpfs");
396 }
397 
fstype_is_blockdev_backed(const char * fstype)398 bool fstype_is_blockdev_backed(const char *fstype) {
399         const char *x;
400 
401         x = startswith(fstype, "fuse.");
402         if (x)
403                 fstype = x;
404 
405         return !streq(fstype, "9p") && !fstype_is_network(fstype) && !fstype_is_api_vfs(fstype);
406 }
407 
fstype_is_ro(const char * fstype)408 bool fstype_is_ro(const char *fstype) {
409         /* All Linux file systems that are necessarily read-only */
410         return STR_IN_SET(fstype,
411                           "DM_verity_hash",
412                           "cramfs",
413                           "erofs",
414                           "iso9660",
415                           "squashfs");
416 }
417 
fstype_can_discard(const char * fstype)418 bool fstype_can_discard(const char *fstype) {
419         return STR_IN_SET(fstype,
420                           "btrfs",
421                           "f2fs",
422                           "ext4",
423                           "vfat",
424                           "xfs");
425 }
426 
fstype_can_uid_gid(const char * fstype)427 bool fstype_can_uid_gid(const char *fstype) {
428 
429         /* All file systems that have a uid=/gid= mount option that fixates the owners of all files and directories,
430          * current and future. */
431 
432         return STR_IN_SET(fstype,
433                           "adfs",
434                           "exfat",
435                           "fat",
436                           "hfs",
437                           "hpfs",
438                           "iso9660",
439                           "msdos",
440                           "ntfs",
441                           "vfat");
442 }
443 
dev_is_devtmpfs(void)444 int dev_is_devtmpfs(void) {
445         _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
446         int mount_id, r;
447         char *e;
448 
449         r = path_get_mnt_id("/dev", &mount_id);
450         if (r < 0)
451                 return r;
452 
453         r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo);
454         if (r < 0)
455                 return r;
456 
457         for (;;) {
458                 _cleanup_free_ char *line = NULL;
459                 int mid;
460 
461                 r = read_line(proc_self_mountinfo, LONG_LINE_MAX, &line);
462                 if (r < 0)
463                         return r;
464                 if (r == 0)
465                         break;
466 
467                 if (sscanf(line, "%i", &mid) != 1)
468                         continue;
469 
470                 if (mid != mount_id)
471                         continue;
472 
473                 e = strstr(line, " - ");
474                 if (!e)
475                         continue;
476 
477                 /* accept any name that starts with the currently expected type */
478                 if (startswith(e + 3, "devtmpfs"))
479                         return true;
480         }
481 
482         return false;
483 }
484 
mount_propagation_flags_to_string(unsigned long flags)485 const char *mount_propagation_flags_to_string(unsigned long flags) {
486 
487         switch (flags & (MS_SHARED|MS_SLAVE|MS_PRIVATE)) {
488         case 0:
489                 return "";
490         case MS_SHARED:
491                 return "shared";
492         case MS_SLAVE:
493                 return "slave";
494         case MS_PRIVATE:
495                 return "private";
496         }
497 
498         return NULL;
499 }
500 
mount_propagation_flags_from_string(const char * name,unsigned long * ret)501 int mount_propagation_flags_from_string(const char *name, unsigned long *ret) {
502 
503         if (isempty(name))
504                 *ret = 0;
505         else if (streq(name, "shared"))
506                 *ret = MS_SHARED;
507         else if (streq(name, "slave"))
508                 *ret = MS_SLAVE;
509         else if (streq(name, "private"))
510                 *ret = MS_PRIVATE;
511         else
512                 return -EINVAL;
513         return 0;
514 }
515