• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 14554080340

19 Apr 2025 11:46AM UTC coverage: 72.101% (-0.03%) from 72.13%
14554080340

push

github

web-flow
Add two new paragraphs to coding style about header files (#37188)

296880 of 411754 relevant lines covered (72.1%)

687547.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

62.09
/src/basic/mountpoint-util.c
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.h"
9
#include "fd-util.h"
10
#include "fileio.h"
11
#include "filesystems.h"
12
#include "fs-util.h"
13
#include "log.h"
14
#include "missing_fcntl.h"
15
#include "missing_fs.h"
16
#include "missing_syscall.h"
17
#include "mkdir.h"
18
#include "mountpoint-util.h"
19
#include "nulstr-util.h"
20
#include "parse-util.h"
21
#include "path-util.h"
22
#include "stat-util.h"
23
#include "stdio-util.h"
24
#include "strv.h"
25
#include "user-util.h"
26

27
/* This is the original MAX_HANDLE_SZ definition from the kernel, when the API was introduced. We use that in place of
28
 * any more currently defined value to future-proof things: if the size is increased in the API headers, and our code
29
 * is recompiled then it would cease working on old kernels, as those refuse any sizes larger than this value with
30
 * EINVAL right-away. Hence, let's disconnect ourselves from any such API changes, and stick to the original definition
31
 * from when it was introduced. We use it as a start value only anyway (see below), and hence should be able to deal
32
 * with large file handles anyway. */
33
#define ORIGINAL_MAX_HANDLE_SZ 128
34

35
bool is_name_to_handle_at_fatal_error(int err) {
36
        /* name_to_handle_at() can return "acceptable" errors that are due to the context. For example
37
         * the file system does not support name_to_handle_at() (EOPNOTSUPP), or the syscall was blocked
38
         * (EACCES/EPERM; maybe through seccomp, because we are running inside of a container), or
39
         * the mount point is not triggered yet (EOVERFLOW, think autofs+nfs4), or some general name_to_handle_at()
40
         * flakiness (EINVAL). However other errors are not supposed to happen and therefore are considered
41
         * fatal ones. */
42

43
        assert(err < 0);
×
44

45
        if (ERRNO_IS_NEG_NOT_SUPPORTED(err))
×
46
                return false;
47
        if (ERRNO_IS_NEG_PRIVILEGE(err))
×
48
                return false;
49

50
        return !IN_SET(err, -EOVERFLOW, -EINVAL);
×
51
}
52

53
int name_to_handle_at_loop(
54
                int fd,
55
                const char *path,
56
                struct file_handle **ret_handle,
57
                int *ret_mnt_id,
58
                int flags) {
59

60
        size_t n = ORIGINAL_MAX_HANDLE_SZ;
27,197✔
61

62
        assert(fd >= 0 || fd == AT_FDCWD);
27,197✔
63
        assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH|AT_HANDLE_FID)) == 0);
27,197✔
64

65
        /* We need to invoke name_to_handle_at() in a loop, given that it might return EOVERFLOW when the specified
66
         * buffer is too small. Note that in contrast to what the docs might suggest, MAX_HANDLE_SZ is only good as a
67
         * start value, it is not an upper bound on the buffer size required.
68
         *
69
         * This improves on raw name_to_handle_at() also in one other regard: ret_handle and ret_mnt_id can be passed
70
         * as NULL if there's no interest in either. */
71

72
        for (;;) {
27,197✔
73
                _cleanup_free_ struct file_handle *h = NULL;
×
74
                int mnt_id = -1;
27,197✔
75

76
                h = malloc0(offsetof(struct file_handle, f_handle) + n);
27,197✔
77
                if (!h)
27,197✔
78
                        return -ENOMEM;
79

80
                h->handle_bytes = n;
27,197✔
81

82
                if (name_to_handle_at(fd, strempty(path), h, &mnt_id, flags) >= 0) {
54,385✔
83

84
                        if (ret_handle)
27,197✔
85
                                *ret_handle = TAKE_PTR(h);
27,197✔
86

87
                        if (ret_mnt_id)
27,197✔
88
                                *ret_mnt_id = mnt_id;
27,197✔
89

90
                        return 0;
27,197✔
91
                }
92
                if (errno != EOVERFLOW)
×
93
                        return -errno;
×
94

95
                if (!ret_handle && ret_mnt_id && mnt_id >= 0) {
×
96

97
                        /* As it appears, name_to_handle_at() fills in mnt_id even when it returns EOVERFLOW when the
98
                         * buffer is too small, but that's undocumented. Hence, let's make use of this if it appears to
99
                         * be filled in, and the caller was interested in only the mount ID an nothing else. */
100

101
                        *ret_mnt_id = mnt_id;
×
102
                        return 0;
×
103
                }
104

105
                /* If name_to_handle_at() didn't increase the byte size, then this EOVERFLOW is caused by
106
                 * something else (apparently EOVERFLOW is returned for untriggered nfs4 autofs mounts
107
                 * sometimes), not by the too small buffer. In that case propagate EOVERFLOW */
108
                if (h->handle_bytes <= n)
×
109
                        return -EOVERFLOW;
110

111
                /* The buffer was too small. Size the new buffer by what name_to_handle_at() returned. */
112
                n = h->handle_bytes;
×
113

114
                /* paranoia: check for overflow (note that .handle_bytes is unsigned only) */
115
                if (n > UINT_MAX - offsetof(struct file_handle, f_handle))
×
116
                        return -EOVERFLOW;
117
        }
118
}
119

120
int name_to_handle_at_try_fid(
121
                int fd,
122
                const char *path,
123
                struct file_handle **ret_handle,
124
                int *ret_mnt_id,
125
                int flags) {
126

127
        int r;
27,197✔
128

129
        assert(fd >= 0 || fd == AT_FDCWD);
27,197✔
130

131
        /* First issues name_to_handle_at() with AT_HANDLE_FID. If this fails and this is not a fatal error
132
         * we'll try without the flag, in order to support older kernels that didn't have AT_HANDLE_FID
133
         * (i.e. older than Linux 6.5). */
134

135
        r = name_to_handle_at_loop(fd, path, ret_handle, ret_mnt_id, flags | AT_HANDLE_FID);
27,197✔
136
        if (r >= 0 || is_name_to_handle_at_fatal_error(r))
27,197✔
137
                return r;
27,197✔
138

139
        return name_to_handle_at_loop(fd, path, ret_handle, ret_mnt_id, flags & ~AT_HANDLE_FID);
×
140
}
141

142
static int fd_fdinfo_mnt_id(int fd, const char *filename, int flags, int *ret_mnt_id) {
×
143
        char path[STRLEN("/proc/self/fdinfo/") + DECIMAL_STR_MAX(int)];
×
144
        _cleanup_free_ char *fdinfo = NULL;
×
145
        _cleanup_close_ int subfd = -EBADF;
×
146
        int r;
×
147

148
        assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH)) == 0);
×
149
        assert(ret_mnt_id);
×
150

151
        if ((flags & AT_EMPTY_PATH) && isempty(filename))
×
152
                xsprintf(path, "/proc/self/fdinfo/%i", fd);
×
153
        else {
154
                subfd = openat(fd, filename, O_CLOEXEC|O_PATH|(flags & AT_SYMLINK_FOLLOW ? 0 : O_NOFOLLOW));
×
155
                if (subfd < 0)
×
156
                        return -errno;
×
157

158
                xsprintf(path, "/proc/self/fdinfo/%i", subfd);
×
159
        }
160

161
        r = read_full_virtual_file(path, &fdinfo, NULL);
×
162
        if (r == -ENOENT)
×
163
                return proc_fd_enoent_errno();
×
164
        if (r < 0)
×
165
                return r;
166

167
        char *p = find_line_startswith(fdinfo, "mnt_id:");
×
168
        if (!p)
×
169
                return -EBADMSG;
170

171
        p = skip_leading_chars(p, /* bad = */ NULL);
×
172
        p[strcspn(p, WHITESPACE)] = 0;
×
173

174
        return safe_atoi(p, ret_mnt_id);
×
175
}
176

177
static bool filename_possibly_with_slash_suffix(const char *s) {
79,663✔
178
        const char *slash, *copied;
79,663✔
179

180
        /* Checks whether the specified string is either file name, or a filename with a suffix of
181
         * slashes. But nothing else.
182
         *
183
         * this is OK: foo, bar, foo/, bar/, foo//, bar///
184
         * this is not OK: "", "/", "/foo", "foo/bar", ".", ".." … */
185

186
        slash = strchr(s, '/');
79,663✔
187
        if (!slash)
79,663✔
188
                return filename_is_valid(s);
79,649✔
189

190
        if (slash - s > PATH_MAX) /* We want to allocate on the stack below, hence do a size check first */
14✔
191
                return false;
192

193
        if (slash[strspn(slash, "/")] != 0) /* Check that the suffix consist only of one or more slashes */
14✔
194
                return false;
195

196
        copied = strndupa_safe(s, slash - s);
10✔
197
        return filename_is_valid(copied);
10✔
198
}
199

200
bool file_handle_equal(const struct file_handle *a, const struct file_handle *b) {
201
        if (a == b)
13,594✔
202
                return true;
203
        if (!a != !b)
13,594✔
204
                return false;
205
        if (a->handle_type != b->handle_type)
13,594✔
206
                return false;
207

208
        return memcmp_nn(a->f_handle, a->handle_bytes, b->f_handle, b->handle_bytes) == 0;
13,580✔
209
}
210

211
int is_mount_point_at(int fd, const char *filename, int flags) {
212
        bool fd_is_self;
79,911✔
213
        int r;
79,911✔
214

215
        assert(fd >= 0 || fd == AT_FDCWD);
79,911✔
216
        assert((flags & ~AT_SYMLINK_FOLLOW) == 0);
79,911✔
217

218
        if (isempty(filename)) {
79,911✔
219
                if (fd == AT_FDCWD)
199✔
220
                        filename = ".";
221
                else {
222
                        /* If the file name is empty we'll see if the specified 'fd' is a mount point.
223
                         * That's only supported by statx(), or if the inode specified via 'fd' refers to a
224
                         * directory. Otherwise, we'll have to fail (ENOTDIR), because we have no kernel API
225
                         * to query the information we need. */
226
                        flags |= AT_EMPTY_PATH;
197✔
227
                        filename = "";
197✔
228
                }
229

230
                fd_is_self = true;
231
        } else if (STR_IN_SET(filename, ".", "./"))
79,712✔
232
                fd_is_self = true;
233
        else {
234
                /* Insist that the specified filename is actually a filename, and not a path, i.e. some inode
235
                 * further up or down the tree then immediately below the specified directory fd. */
236
                if (!filename_possibly_with_slash_suffix(filename))
79,663✔
237
                        return -EINVAL;
7✔
238

239
                fd_is_self = false;
240
        }
241

242
        /* First we will try statx()' STATX_ATTR_MOUNT_ROOT attribute, which is our ideal API, available
243
         * since kernel 5.8.
244
         *
245
         * If that fails, our second try is the name_to_handle_at() syscall, which tells us the mount id and
246
         * an opaque file "handle". It is not supported everywhere though (kernel compile-time option, not
247
         * all file systems are hooked up). If it works the mount id is usually good enough to tell us
248
         * whether something is a mount point.
249
         *
250
         * If that didn't work we will try to read the mount id from /proc/self/fdinfo/<fd>. This is almost
251
         * as good as name_to_handle_at(), however, does not return the opaque file handle. The opaque file
252
         * handle is pretty useful to detect the root directory, which we should always consider a mount
253
         * point. Hence we use this only as fallback.
254
         *
255
         * Note that traditionally the check is done via fstat()-based st_dev comparisons. However, various
256
         * file systems don't guarantee same st_dev across single fs anymore, e.g. unionfs exposes file systems
257
         * with a variety of st_dev reported. Also, btrfs subvolumes have different st_dev, even though
258
         * they aren't real mounts of their own. */
259

260
        struct statx sx = {}; /* explicitly initialize the struct to make msan silent. */
79,904✔
261
        if (statx(fd, filename,
79,904✔
262
                  at_flags_normalize_nofollow(flags) |
79,904✔
263
                  AT_NO_AUTOMOUNT |            /* don't trigger automounts – mounts are a local concept, hence no need to trigger automounts to determine STATX_ATTR_MOUNT_ROOT */
264
                  AT_STATX_DONT_SYNC,          /* don't go to the network for this – for similar reasons */
265
                  STATX_TYPE,
266
                  &sx) < 0)
267
                return -errno;
3,792✔
268

269
        if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT)) /* yay! */
76,112✔
270
                return FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
76,112✔
271

272
        _cleanup_free_ struct file_handle *h = NULL, *h_parent = NULL;
×
273
        int mount_id = -1, mount_id_parent = -1;
×
274
        bool nosupp = false;
×
275

276
        r = name_to_handle_at_try_fid(fd, filename, &h, &mount_id, flags);
×
277
        if (r < 0) {
×
278
                if (is_name_to_handle_at_fatal_error(r))
×
279
                        return r;
280
                if (!ERRNO_IS_NOT_SUPPORTED(r))
×
281
                        goto fallback_fdinfo;
×
282

283
                /* This file system does not support name_to_handle_at(), hence let's see if the upper fs
284
                 * supports it (in which case it is a mount point), otherwise fall back to the fdinfo logic. */
285
                nosupp = true;
286
        }
287

288
        if (fd_is_self)
×
289
                r = name_to_handle_at_try_fid(fd, "..", &h_parent, &mount_id_parent, 0); /* can't work for non-directories 😢 */
×
290
        else
291
                r = name_to_handle_at_try_fid(fd, "", &h_parent, &mount_id_parent, AT_EMPTY_PATH);
×
292
        if (r < 0) {
×
293
                if (is_name_to_handle_at_fatal_error(r))
×
294
                        return r;
295
                if (!ERRNO_IS_NOT_SUPPORTED(r))
×
296
                        goto fallback_fdinfo;
×
297
                if (nosupp)
×
298
                        /* Both the parent and the directory can't do name_to_handle_at() */
299
                        goto fallback_fdinfo;
×
300

301
                /* The parent can't do name_to_handle_at() but the directory we are
302
                 * interested in can?  If so, it must be a mount point. */
303
                return 1;
304
        }
305

306
        /* The parent can do name_to_handle_at() but the directory we are interested in can't? If
307
         * so, it must be a mount point. */
308
        if (nosupp)
×
309
                return 1;
310

311
        /* If the file handle for the directory we are interested in and its parent are identical,
312
         * we assume this is the root directory, which is a mount point. */
313
        if (file_handle_equal(h_parent, h))
×
314
                return 1;
315

316
        return mount_id != mount_id_parent;
×
317

318
fallback_fdinfo:
×
319
        r = fd_fdinfo_mnt_id(fd, filename, flags, &mount_id);
×
320
        if (r < 0)
×
321
                return r;
322

323
        if (fd_is_self)
×
324
                r = fd_fdinfo_mnt_id(fd, "..", 0, &mount_id_parent); /* can't work for non-directories 😢 */
×
325
        else
326
                r = fd_fdinfo_mnt_id(fd, "", AT_EMPTY_PATH, &mount_id_parent);
×
327
        if (r < 0)
×
328
                return r;
329

330
        if (mount_id != mount_id_parent)
×
331
                return 1;
332

333
        /* Hmm, so, the mount ids are the same. This leaves one special case though for the root file
334
         * system. For that, let's see if the parent directory has the same inode as we are interested
335
         * in. */
336

337
        struct stat a, b;
×
338

339
        /* yay for fstatat() taking a different set of flags than the other _at() above */
340
        if (fstatat(fd, filename, &a, at_flags_normalize_nofollow(flags)) < 0)
×
341
                return -errno;
×
342

343
        if (fd_is_self)
×
344
                r = fstatat(fd, "..", &b, 0);
×
345
        else
346
                r = fstatat(fd, "", &b, AT_EMPTY_PATH);
×
347
        if (r < 0)
×
348
                return -errno;
×
349

350
        /* A directory with same device and inode as its parent must be the root directory. Otherwise
351
         * not a mount point.
352
         *
353
         * NB: we avoid inode_same_at() here because it internally attempts name_to_handle_at_try_fid() first,
354
         * which is redundant. */
355
        return stat_inode_same(&a, &b);
×
356
}
357

358
/* flags can be AT_SYMLINK_FOLLOW or 0 */
359
int path_is_mount_point_full(const char *path, const char *root, int flags) {
360
        _cleanup_close_ int dfd = -EBADF;
26,238✔
361
        _cleanup_free_ char *fn = NULL;
26,238✔
362

363
        assert(path);
26,238✔
364
        assert((flags & ~AT_SYMLINK_FOLLOW) == 0);
26,238✔
365

366
        if (path_equal(path, "/"))
26,238✔
367
                return 1;
368

369
        /* we need to resolve symlinks manually, we can't just rely on is_mount_point_at() to do that for us;
370
         * if we have a structure like /bin -> /usr/bin/ and /usr is a mount point, then the parent that we
371
         * look at needs to be /usr, not /. */
372
        dfd = chase_and_open_parent(path, root,
26,231✔
373
                                    CHASE_TRAIL_SLASH|(FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? 0 : CHASE_NOFOLLOW),
26,231✔
374
                                    &fn);
375
        if (dfd < 0)
26,231✔
376
                return dfd;
377

378
        return is_mount_point_at(dfd, fn, flags);
26,038✔
379
}
380

381
int path_get_mnt_id_at_fallback(int dir_fd, const char *path, int *ret) {
382
        int r;
×
383

384
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
×
385
        assert(ret);
×
386

387
        r = name_to_handle_at_loop(dir_fd, path, NULL, ret, isempty(path) ? AT_EMPTY_PATH : 0);
×
388
        if (r >= 0 || is_name_to_handle_at_fatal_error(r))
×
389
                return r;
×
390

391
        return fd_fdinfo_mnt_id(dir_fd, path, isempty(path) ? AT_EMPTY_PATH : 0, ret);
×
392
}
393

394
int path_get_mnt_id_at(int dir_fd, const char *path, int *ret) {
395
        struct statx sx;
6,197✔
396

397
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
6,197✔
398
        assert(ret);
6,197✔
399

400
        if (statx(dir_fd,
12,394✔
401
                  strempty(path),
6,197✔
402
                  (isempty(path) ? AT_EMPTY_PATH : AT_SYMLINK_NOFOLLOW) |
6,197✔
403
                  AT_NO_AUTOMOUNT |    /* don't trigger automounts, mnt_id is a local concept */
404
                  AT_STATX_DONT_SYNC,  /* don't go to the network, mnt_id is a local concept */
405
                  STATX_MNT_ID,
406
                  &sx) < 0)
407
                return -errno;
1✔
408

409
        if (FLAGS_SET(sx.stx_mask, STATX_MNT_ID)) {
6,196✔
410
                *ret = sx.stx_mnt_id;
6,196✔
411
                return 0;
6,196✔
412
        }
413

414
        return path_get_mnt_id_at_fallback(dir_fd, path, ret);
×
415
}
416

417
bool fstype_is_network(const char *fstype) {
418
        const char *x;
2,016✔
419

420
        x = startswith(fstype, "fuse.");
2,016✔
421
        if (x)
2,016✔
422
                fstype = x;
×
423

424
        if (nulstr_contains(filesystem_sets[FILESYSTEM_SET_NETWORK].value, fstype))
2,016✔
425
                return true;
2,016✔
426

427
        /* Filesystems not present in the internal database */
428
        return STR_IN_SET(fstype,
2,012✔
429
                          "davfs",
430
                          "glusterfs",
431
                          "lustre",
432
                          "sshfs");
433
}
434

435
bool fstype_needs_quota(const char *fstype) {
436
       /* 1. quotacheck needs to be run for some filesystems after they are mounted
437
        *    if the filesystem was not unmounted cleanly.
438
        * 2. You may need to run quotaon to enable quota usage tracking and/or
439
        *    enforcement.
440
        * ext2     - needs 1) and 2)
441
        * ext3     - needs 2) if configured using usrjquota/grpjquota mount options
442
        * ext4     - needs 1) if created without journal, needs 2) if created without QUOTA
443
        *            filesystem feature
444
        * reiserfs - needs 2).
445
        * jfs      - needs 2)
446
        * f2fs     - needs 2) if configured using usrjquota/grpjquota/prjjquota mount options
447
        * xfs      - nothing needed
448
        * gfs2     - nothing needed
449
        * ocfs2    - nothing needed
450
        * btrfs    - nothing needed
451
        * for reference see filesystem and quota manpages */
452
        return STR_IN_SET(fstype,
×
453
                          "ext2",
454
                          "ext3",
455
                          "ext4",
456
                          "reiserfs",
457
                          "jfs",
458
                          "f2fs");
459
}
460

461
bool fstype_is_api_vfs(const char *fstype) {
462
        assert(fstype);
59✔
463

464
        const FilesystemSet *fs;
59✔
465
        FOREACH_ARGUMENT(fs,
267✔
466
                         filesystem_sets + FILESYSTEM_SET_BASIC_API,
467
                         filesystem_sets + FILESYSTEM_SET_AUXILIARY_API,
468
                         filesystem_sets + FILESYSTEM_SET_PRIVILEGED_API,
469
                         filesystem_sets + FILESYSTEM_SET_TEMPORARY)
470
                if (nulstr_contains(fs->value, fstype))
236✔
471
                    return true;
28✔
472

473
        /* Filesystems not present in the internal database */
474
        return STR_IN_SET(fstype,
31✔
475
                          "autofs",
476
                          "cpuset",
477
                          "devtmpfs");
478
}
479

480
bool fstype_is_blockdev_backed(const char *fstype) {
481
        const char *x;
29✔
482

483
        x = startswith(fstype, "fuse.");
29✔
484
        if (x)
29✔
485
                fstype = x;
×
486

487
        return !streq(fstype, "9p") && !fstype_is_network(fstype) && !fstype_is_api_vfs(fstype);
29✔
488
}
489

490
bool fstype_is_ro(const char *fstype) {
491
        /* All Linux file systems that are necessarily read-only */
492
        return STR_IN_SET(fstype,
2,785✔
493
                          "DM_verity_hash",
494
                          "cramfs",
495
                          "erofs",
496
                          "iso9660",
497
                          "squashfs");
498
}
499

500
bool fstype_can_discard(const char *fstype) {
501
        assert(fstype);
4✔
502

503
        /* Use a curated list as first check, to avoid calling fsopen() which might load kmods, which might
504
         * not be allowed in our MAC context. */
505
        if (STR_IN_SET(fstype, "btrfs", "f2fs", "ext4", "vfat", "xfs"))
4✔
506
                return true;
1✔
507

508
        /* On new kernels we can just ask the kernel */
509
        return mount_option_supported(fstype, "discard", NULL) > 0;
3✔
510
}
511

512
const char* fstype_norecovery_option(const char *fstype) {
513
        int r;
163✔
514

515
        assert(fstype);
163✔
516

517
        /* Use a curated list as first check, to avoid calling fsopen() which might load kmods, which might
518
         * not be allowed in our MAC context. */
519
        if (STR_IN_SET(fstype, "ext3", "ext4", "xfs"))
163✔
520
                return "norecovery";
17✔
521

522
        /* btrfs dropped support for the "norecovery" option in 6.8
523
         * (https://github.com/torvalds/linux/commit/a1912f712188291f9d7d434fba155461f1ebef66) and replaced
524
         * it with rescue=nologreplay, so we check for the new name first and fall back to checking for the
525
         * old name if the new name doesn't work. */
526
        if (streq(fstype, "btrfs")) {
146✔
527
                r = mount_option_supported(fstype, "rescue=nologreplay", NULL);
×
528
                if (r == -EAGAIN) {
×
529
                        log_debug_errno(r, "Failed to check for btrfs 'rescue=nologreplay' option, assuming old kernel with 'norecovery': %m");
×
530
                        return "norecovery";
×
531
                }
532
                if (r < 0)
×
533
                        log_debug_errno(r, "Failed to check for btrfs 'rescue=nologreplay' option, assuming it is not supported: %m");
×
534
                if (r > 0)
×
535
                        return "rescue=nologreplay";
536
        }
537

538
        /* On new kernels we can just ask the kernel */
539
        return mount_option_supported(fstype, "norecovery", NULL) > 0 ? "norecovery" : NULL;
146✔
540
}
541

542
bool fstype_can_fmask_dmask(const char *fstype) {
543
        assert(fstype);
57✔
544

545
        /* Use a curated list as first check, to avoid calling fsopen() which might load kmods, which might
546
         * not be allowed in our MAC context. If we don't know ourselves, on new kernels we can just ask the
547
         * kernel. */
548
        return streq(fstype, "vfat") || (mount_option_supported(fstype, "fmask", "0177") > 0 && mount_option_supported(fstype, "dmask", "0077") > 0);
57✔
549
}
550

551
bool fstype_can_uid_gid(const char *fstype) {
552
        /* All file systems that have a uid=/gid= mount option that fixates the owners of all files and
553
         * directories, current and future. Note that this does *not* ask the kernel via
554
         * mount_option_supported() here because the uid=/gid= setting of various file systems mean different
555
         * things: some apply it only to the root dir inode, others to all inodes in the file system. Thus we
556
         * maintain the curated list below. 😢 */
557

558
        return STR_IN_SET(fstype,
1✔
559
                          "adfs",
560
                          "exfat",
561
                          "fat",
562
                          "hfs",
563
                          "hpfs",
564
                          "iso9660",
565
                          "msdos",
566
                          "ntfs",
567
                          "vfat");
568
}
569

570
int dev_is_devtmpfs(void) {
571
        _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
249✔
572
        int mount_id, r;
249✔
573
        char *e;
249✔
574

575
        r = path_get_mnt_id("/dev", &mount_id);
249✔
576
        if (r < 0)
249✔
577
                return r;
578

579
        r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo);
249✔
580
        if (r == -ENOENT)
249✔
581
                return proc_mounted() > 0 ? -ENOENT : -ENOSYS;
×
582
        if (r < 0)
249✔
583
                return r;
584

585
        for (;;) {
11,256✔
586
                _cleanup_free_ char *line = NULL;
11,022✔
587
                int mid;
11,256✔
588

589
                r = read_line(proc_self_mountinfo, LONG_LINE_MAX, &line);
11,256✔
590
                if (r < 0)
11,256✔
591
                        return r;
592
                if (r == 0)
11,256✔
593
                        break;
594

595
                if (sscanf(line, "%i", &mid) != 1)
11,022✔
596
                        continue;
×
597

598
                if (mid != mount_id)
11,022✔
599
                        continue;
10,773✔
600

601
                e = strstrafter(line, " - ");
249✔
602
                if (!e)
249✔
603
                        continue;
×
604

605
                /* accept any name that starts with the currently expected type */
606
                if (startswith(e, "devtmpfs"))
249✔
607
                        return true;
608
        }
609

610
        return false;
234✔
611
}
612

613
static int mount_fd(
65,921✔
614
                const char *source,
615
                int target_fd,
616
                const char *filesystemtype,
617
                unsigned long mountflags,
618
                const void *data) {
619

620
        assert(target_fd >= 0);
65,921✔
621

622
        if (mount(source, FORMAT_PROC_FD_PATH(target_fd), filesystemtype, mountflags, data) < 0) {
65,921✔
623
                if (errno != ENOENT)
991✔
624
                        return -errno;
991✔
625

626
                /* ENOENT can mean two things: either that the source is missing, or that /proc/ isn't
627
                 * mounted. Check for the latter to generate better error messages. */
628
                if (proc_mounted() == 0)
490✔
629
                        return -ENOSYS;
630

631
                return -ENOENT;
490✔
632
        }
633

634
        return 0;
64,930✔
635
}
636

637
int mount_nofollow(
638
                const char *source,
639
                const char *target,
640
                const char *filesystemtype,
641
                unsigned long mountflags,
642
                const void *data) {
643

644
        _cleanup_close_ int fd = -EBADF;
67,364✔
645

646
        assert(target);
67,364✔
647

648
        /* In almost all cases we want to manipulate the mount table without following symlinks, hence
649
         * mount_nofollow() is usually the way to go. The only exceptions are environments where /proc/ is
650
         * not available yet, since we need /proc/self/fd/ for this logic to work. i.e. during the early
651
         * initialization of namespacing/container stuff where /proc is not yet mounted (and maybe even the
652
         * fs to mount) we can only use traditional mount() directly.
653
         *
654
         * Note that this disables following only for the final component of the target, i.e symlinks within
655
         * the path of the target are honoured, as are symlinks in the source path everywhere. */
656

657
        fd = open(target, O_PATH|O_CLOEXEC|O_NOFOLLOW);
67,364✔
658
        if (fd < 0)
67,364✔
659
                return -errno;
1,443✔
660

661
        return mount_fd(source, fd, filesystemtype, mountflags, data);
65,921✔
662
}
663

664
const char* mount_propagation_flag_to_string(unsigned long flags) {
665

666
        switch (flags & (MS_SHARED|MS_SLAVE|MS_PRIVATE)) {
9✔
667
        case 0:
668
                return "";
669
        case MS_SHARED:
1✔
670
                return "shared";
1✔
671
        case MS_SLAVE:
1✔
672
                return "slave";
1✔
673
        case MS_PRIVATE:
3✔
674
                return "private";
3✔
675
        }
676

677
        return NULL;
×
678
}
679

680
int mount_propagation_flag_from_string(const char *name, unsigned long *ret) {
681

682
        if (isempty(name))
8✔
683
                *ret = 0;
2✔
684
        else if (streq(name, "shared"))
6✔
685
                *ret = MS_SHARED;
1✔
686
        else if (streq(name, "slave"))
5✔
687
                *ret = MS_SLAVE;
1✔
688
        else if (streq(name, "private"))
4✔
689
                *ret = MS_PRIVATE;
2✔
690
        else
691
                return -EINVAL;
692
        return 0;
693
}
694

695
bool mount_propagation_flag_is_valid(unsigned long flag) {
696
        return IN_SET(flag, 0, MS_SHARED, MS_PRIVATE, MS_SLAVE);
2,210✔
697
}
698

699
bool mount_new_api_supported(void) {
700
        static int cache = -1;
5,995✔
701
        int r;
5,995✔
702

703
        if (cache >= 0)
5,995✔
704
                return cache;
1,601✔
705

706
        /* This is the newer API among the ones we use, so use it as boundary */
707
        r = RET_NERRNO(mount_setattr(-EBADF, NULL, 0, NULL, 0));
4,394✔
708
        if (r == 0 || ERRNO_IS_NOT_SUPPORTED(r)) /* This should return an error if it is working properly */
4,394✔
709
                return (cache = false);
×
710

711
        return (cache = true);
4,394✔
712
}
713

714
unsigned long ms_nosymfollow_supported(void) {
715
        _cleanup_close_ int fsfd = -EBADF, mntfd = -EBADF;
4,838✔
716
        static int cache = -1;
4,838✔
717

718
        /* Returns MS_NOSYMFOLLOW if it is supported, zero otherwise. */
719

720
        if (cache >= 0)
4,838✔
721
                return cache ? MS_NOSYMFOLLOW : 0;
2,521✔
722

723
        if (!mount_new_api_supported())
2,317✔
724
                goto not_supported;
×
725

726
        /* Checks if MS_NOSYMFOLLOW is supported (which was added in 5.10). We use the new mount API's
727
         * mount_setattr() call for that, which was added in 5.12, which is close enough. */
728

729
        fsfd = fsopen("tmpfs", FSOPEN_CLOEXEC);
2,317✔
730
        if (fsfd < 0) {
2,317✔
731
                if (ERRNO_IS_NOT_SUPPORTED(errno))
2✔
732
                        goto not_supported;
×
733

734
                log_debug_errno(errno, "Failed to open superblock context for tmpfs: %m");
2✔
735
                return 0;
2✔
736
        }
737

738
        if (fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) < 0) {
2,315✔
739
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
740
                        goto not_supported;
×
741

742
                log_debug_errno(errno, "Failed to create tmpfs superblock: %m");
×
743
                return 0;
×
744
        }
745

746
        mntfd = fsmount(fsfd, FSMOUNT_CLOEXEC, 0);
2,315✔
747
        if (mntfd < 0) {
2,315✔
748
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
749
                        goto not_supported;
×
750

751
                log_debug_errno(errno, "Failed to turn superblock fd into mount fd: %m");
×
752
                return 0;
×
753
        }
754

755
        if (mount_setattr(mntfd, "", AT_EMPTY_PATH|AT_RECURSIVE,
2,315✔
756
                          &(struct mount_attr) {
2,315✔
757
                                  .attr_set = MOUNT_ATTR_NOSYMFOLLOW,
758
                          }, sizeof(struct mount_attr)) < 0) {
759
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
760
                        goto not_supported;
×
761

762
                log_debug_errno(errno, "Failed to set MOUNT_ATTR_NOSYMFOLLOW mount attribute: %m");
×
763
                return 0;
×
764
        }
765

766
        cache = true;
2,315✔
767
        return MS_NOSYMFOLLOW;
2,315✔
768

769
not_supported:
×
770
        cache = false;
×
771
        return 0;
×
772
}
773

774
int mount_option_supported(const char *fstype, const char *key, const char *value) {
775
        _cleanup_close_ int fd = -EBADF;
3,611✔
776
        int r;
3,611✔
777

778
        /* Checks if the specified file system supports a mount option. Returns > 0 if it supports it, == 0 if
779
         * it does not. Return -EAGAIN if we can't determine it. And any other error otherwise. */
780

781
        assert(fstype);
3,611✔
782
        assert(key);
3,611✔
783

784
        fd = fsopen(fstype, FSOPEN_CLOEXEC);
3,611✔
785
        if (fd < 0)
3,611✔
786
                return log_debug_errno(errno, "Failed to open superblock context for '%s': %m", fstype);
1✔
787

788
        /* Various file systems support fs context only in recent kernels (e.g. btrfs). For older kernels
789
         * fsconfig() with FSCONFIG_SET_STRING/FSCONFIG_SET_FLAG never fail. Which sucks, because we want to
790
         * use it for testing support, after all. Let's hence do a check if the file system got converted yet
791
         * first. */
792
        if (fsconfig(fd, FSCONFIG_SET_FD, "adefinitelynotexistingmountoption", NULL, fd) < 0) {
3,610✔
793
                /* If FSCONFIG_SET_FD is not supported for the fs, then the file system was not converted to
794
                 * the new mount API yet. If it returns EINVAL the mount option doesn't exist, but the fstype
795
                 * is converted. */
796
                if (errno == EOPNOTSUPP)
3,610✔
797
                        return -EAGAIN; /* fs not converted to new mount API → don't know */
798
                if (errno != EINVAL)
3,608✔
799
                        return log_debug_errno(errno, "Failed to check if file system '%s' has been converted to new mount API: %m", fstype);
×
800

801
                /* So FSCONFIG_SET_FD worked, but the option didn't exist (we got EINVAL), this means the fs
802
                 * is converted. Let's now ask the actual question we wonder about. */
803
        } else
804
                return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "FSCONFIG_SET_FD worked unexpectedly for '%s', whoa!", fstype);
×
805

806
        if (value)
3,608✔
807
                r = fsconfig(fd, FSCONFIG_SET_STRING, key, value, 0);
875✔
808
        else
809
                r = fsconfig(fd, FSCONFIG_SET_FLAG, key, NULL, 0);
2,733✔
810
        if (r < 0) {
3,608✔
811
                if (errno == EINVAL)
192✔
812
                        return false; /* EINVAL means option not supported. */
813

814
                return log_debug_errno(errno, "Failed to set '%s%s%s' on '%s' superblock context: %m",
×
815
                                       key, value ? "=" : "", strempty(value), fstype);
816
        }
817

818
        return true; /* works! */
819
}
820

821
bool path_below_api_vfs(const char *p) {
822
        assert(p);
9,207✔
823

824
        /* API VFS are either directly mounted on any of these three paths, or below it. */
825
        return PATH_STARTSWITH_SET(p, "/dev", "/sys", "/proc");
9,207✔
826
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc