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

systemd / systemd / 13339601146

14 Feb 2025 08:02PM UTC coverage: 71.699% (-0.1%) from 71.823%
13339601146

push

github

web-flow
mkosi: Fix mkosi.clangd (#36387)

- Add missing '--' delimiter
- Use the new BuildSubdirectory JSON field to figure out the build
  subdirectory.
- Remove the /usr/include path mapping for now. This means we can't
  jump into system headers anymore if they don't exist on the host,
  we can find a way to add this back later if it turns out to be
  crucial.

293171 of 408891 relevant lines covered (71.7%)

715519.06 hits per line

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

65.48
/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
#if WANT_LINUX_FS_H
7
#include <linux/fs.h>
8
#endif
9

10
#include "alloc-util.h"
11
#include "chase.h"
12
#include "fd-util.h"
13
#include "fileio.h"
14
#include "filesystems.h"
15
#include "fs-util.h"
16
#include "missing_fcntl.h"
17
#include "missing_fs.h"
18
#include "missing_mount.h"
19
#include "missing_stat.h"
20
#include "missing_syscall.h"
21
#include "mkdir.h"
22
#include "mountpoint-util.h"
23
#include "nulstr-util.h"
24
#include "parse-util.h"
25
#include "path-util.h"
26
#include "stat-util.h"
27
#include "stdio-util.h"
28
#include "strv.h"
29
#include "user-util.h"
30

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

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

47
        assert(err < 0);
11,751✔
48

49
        if (ERRNO_IS_NEG_NOT_SUPPORTED(err))
11,751✔
50
                return false;
51
        if (ERRNO_IS_NEG_PRIVILEGE(err))
×
52
                return false;
53

54
        return !IN_SET(err, -EOVERFLOW, -EINVAL);
×
55
}
56

57
int name_to_handle_at_loop(
27,181✔
58
                int fd,
59
                const char *path,
60
                struct file_handle **ret_handle,
61
                int *ret_mnt_id,
62
                int flags) {
63

64
        size_t n = ORIGINAL_MAX_HANDLE_SZ;
27,181✔
65

66
        assert(fd >= 0 || fd == AT_FDCWD);
27,181✔
67
        assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH|AT_HANDLE_FID)) == 0);
27,181✔
68

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

76
        for (;;) {
27,181✔
77
                _cleanup_free_ struct file_handle *h = NULL;
×
78
                int mnt_id = -1;
27,181✔
79

80
                h = malloc0(offsetof(struct file_handle, f_handle) + n);
27,181✔
81
                if (!h)
27,181✔
82
                        return -ENOMEM;
83

84
                h->handle_bytes = n;
27,181✔
85

86
                if (name_to_handle_at(fd, strempty(path), h, &mnt_id, flags) >= 0) {
54,353✔
87

88
                        if (ret_handle)
27,181✔
89
                                *ret_handle = TAKE_PTR(h);
27,181✔
90

91
                        if (ret_mnt_id)
27,181✔
92
                                *ret_mnt_id = mnt_id;
27,181✔
93

94
                        return 0;
27,181✔
95
                }
96
                if (errno != EOVERFLOW)
×
97
                        return -errno;
×
98

99
                if (!ret_handle && ret_mnt_id && mnt_id >= 0) {
×
100

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

105
                        *ret_mnt_id = mnt_id;
×
106
                        return 0;
×
107
                }
108

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

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

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

124
int name_to_handle_at_try_fid(
27,181✔
125
                int fd,
126
                const char *path,
127
                struct file_handle **ret_handle,
128
                int *ret_mnt_id,
129
                int flags) {
130

131
        int r;
27,181✔
132

133
        assert(fd >= 0 || fd == AT_FDCWD);
27,181✔
134

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

139
        r = name_to_handle_at_loop(fd, path, ret_handle, ret_mnt_id, flags | AT_HANDLE_FID);
27,181✔
140
        if (r >= 0 || is_name_to_handle_at_fatal_error(r))
27,181✔
141
                return r;
27,181✔
142

143
        return name_to_handle_at_loop(fd, path, ret_handle, ret_mnt_id, flags & ~AT_HANDLE_FID);
×
144
}
145

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

152
        assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH)) == 0);
×
153
        assert(ret_mnt_id);
×
154

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

162
                xsprintf(path, "/proc/self/fdinfo/%i", subfd);
×
163
        }
164

165
        r = read_full_virtual_file(path, &fdinfo, NULL);
×
166
        if (r == -ENOENT)
×
167
                return proc_fd_enoent_errno();
×
168
        if (r < 0)
×
169
                return r;
170

171
        char *p = find_line_startswith(fdinfo, "mnt_id:");
×
172
        if (!p)
×
173
                return -EBADMSG;
174

175
        p = skip_leading_chars(p, /* bad = */ NULL);
×
176
        p[strcspn(p, WHITESPACE)] = 0;
×
177

178
        return safe_atoi(p, ret_mnt_id);
×
179
}
180

181
static bool filename_possibly_with_slash_suffix(const char *s) {
128,135✔
182
        const char *slash, *copied;
128,135✔
183

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

190
        slash = strchr(s, '/');
128,135✔
191
        if (!slash)
128,135✔
192
                return filename_is_valid(s);
128,121✔
193

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

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

200
        copied = strndupa_safe(s, slash - s);
10✔
201
        return filename_is_valid(copied);
10✔
202
}
203

204
bool file_handle_equal(const struct file_handle *a, const struct file_handle *b) {
13,586✔
205
        if (a == b)
13,586✔
206
                return true;
207
        if (!a != !b)
13,586✔
208
                return false;
209
        if (a->handle_type != b->handle_type)
13,586✔
210
                return false;
211

212
        return memcmp_nn(a->f_handle, a->handle_bytes, b->f_handle, b->handle_bytes) == 0;
13,572✔
213
}
214

215
int is_mount_point_at(int fd, const char *filename, int flags) {
128,272✔
216
        bool fd_is_self;
128,272✔
217
        int r;
128,272✔
218

219
        assert(fd >= 0 || fd == AT_FDCWD);
128,272✔
220
        assert((flags & ~AT_SYMLINK_FOLLOW) == 0);
128,272✔
221

222
        if (isempty(filename)) {
128,272✔
223
                if (fd == AT_FDCWD)
89✔
224
                        filename = ".";
225
                else {
226
                        /* If the file name is empty we'll see if the specified 'fd' is a mount point.
227
                         * That's only supported if the kernel supports statx(), or if the inode specified
228
                         * via 'fd' refers to a directory. Otherwise, we'll have to fail (ENOTDIR), because
229
                         * we have no kernel API to query the information we need. */
230
                        flags |= AT_EMPTY_PATH;
87✔
231
                        filename = "";
87✔
232
                }
233

234
                fd_is_self = true;
235
        } else if (STR_IN_SET(filename, ".", "./"))
128,183✔
236
                fd_is_self = true;
237
        else {
238
                /* Insist that the specified filename is actually a filename, and not a path, i.e. some inode
239
                 * further up or down the tree then immediately below the specified directory fd. */
240
                if (!filename_possibly_with_slash_suffix(filename))
128,135✔
241
                        return -EINVAL;
7✔
242

243
                fd_is_self = false;
244
        }
245

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

264
        STRUCT_STATX_DEFINE(sx);
128,265✔
265

266
        if (statx(fd, filename,
128,265✔
267
                  at_flags_normalize_nofollow(flags) |
128,265✔
268
                  AT_NO_AUTOMOUNT |            /* don't trigger automounts – mounts are a local concept, hence no need to trigger automounts to determine STATX_ATTR_MOUNT_ROOT */
269
                  AT_STATX_DONT_SYNC,          /* don't go to the network for this – for similar reasons */
270
                  STATX_TYPE,
271
                  &sx) < 0) {
272
                if (!ERRNO_IS_NOT_SUPPORTED(errno) && /* statx() is not supported by the kernel. */
5,758✔
273
                    !ERRNO_IS_PRIVILEGE(errno) &&     /* maybe filtered by seccomp. */
5,758✔
274
                    errno != EINVAL)                  /* glibc's fallback method returns EINVAL when AT_STATX_DONT_SYNC is set. */
275
                        return -errno;
5,758✔
276

277
                /* If statx() is not available or forbidden, fall back to name_to_handle_at() below */
278
        } else if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT)) /* yay! */
122,507✔
279
                return FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
122,507✔
280

281
        _cleanup_free_ struct file_handle *h = NULL, *h_parent = NULL;
×
282
        int mount_id = -1, mount_id_parent = -1;
×
283
        bool nosupp = false;
×
284

285
        r = name_to_handle_at_try_fid(fd, filename, &h, &mount_id, flags);
×
286
        if (r < 0) {
×
287
                if (is_name_to_handle_at_fatal_error(r))
×
288
                        return r;
289
                if (!ERRNO_IS_NOT_SUPPORTED(r))
×
290
                        goto fallback_fdinfo;
×
291

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

297
        if (fd_is_self)
×
298
                r = name_to_handle_at_try_fid(fd, "..", &h_parent, &mount_id_parent, 0); /* can't work for non-directories 😢 */
×
299
        else
300
                r = name_to_handle_at_try_fid(fd, "", &h_parent, &mount_id_parent, AT_EMPTY_PATH);
×
301
        if (r < 0) {
×
302
                if (is_name_to_handle_at_fatal_error(r))
×
303
                        return r;
304
                if (!ERRNO_IS_NOT_SUPPORTED(r))
×
305
                        goto fallback_fdinfo;
×
306
                if (nosupp)
×
307
                        /* Both the parent and the directory can't do name_to_handle_at() */
308
                        goto fallback_fdinfo;
×
309

310
                /* The parent can't do name_to_handle_at() but the directory we are
311
                 * interested in can?  If so, it must be a mount point. */
312
                return 1;
313
        }
314

315
        /* The parent can do name_to_handle_at() but the directory we are interested in can't? If
316
         * so, it must be a mount point. */
317
        if (nosupp)
×
318
                return 1;
319

320
        /* If the file handle for the directory we are interested in and its parent are identical,
321
         * we assume this is the root directory, which is a mount point. */
322
        if (file_handle_equal(h_parent, h))
×
323
                return 1;
324

325
        return mount_id != mount_id_parent;
×
326

327
fallback_fdinfo:
×
328
        r = fd_fdinfo_mnt_id(fd, filename, flags, &mount_id);
×
329
        if (r < 0)
×
330
                return r;
331

332
        if (fd_is_self)
×
333
                r = fd_fdinfo_mnt_id(fd, "..", 0, &mount_id_parent); /* can't work for non-directories 😢 */
×
334
        else
335
                r = fd_fdinfo_mnt_id(fd, "", AT_EMPTY_PATH, &mount_id_parent);
×
336
        if (r < 0)
×
337
                return r;
338

339
        if (mount_id != mount_id_parent)
×
340
                return 1;
341

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

346
        struct stat a, b;
×
347

348
        /* yay for fstatat() taking a different set of flags than the other _at() above */
349
        if (fstatat(fd, filename, &a, at_flags_normalize_nofollow(flags)) < 0)
×
350
                return -errno;
×
351

352
        if (fd_is_self)
×
353
                r = fstatat(fd, "..", &b, 0);
×
354
        else
355
                r = fstatat(fd, "", &b, AT_EMPTY_PATH);
×
356
        if (r < 0)
×
357
                return -errno;
×
358

359
        /* A directory with same device and inode as its parent must be the root directory. Otherwise
360
         * not a mount point.
361
         *
362
         * NB: we avoid inode_same_at() here because it internally attempts name_to_handle_at_try_fid() first,
363
         * which is redundant. */
364
        return stat_inode_same(&a, &b);
×
365
}
366

367
/* flags can be AT_SYMLINK_FOLLOW or 0 */
368
int path_is_mount_point_full(const char *path, const char *root, int flags) {
40,694✔
369
        _cleanup_close_ int dfd = -EBADF;
40,694✔
370
        _cleanup_free_ char *fn = NULL;
40,694✔
371

372
        assert(path);
40,694✔
373
        assert((flags & ~AT_SYMLINK_FOLLOW) == 0);
40,694✔
374

375
        if (path_equal(path, "/"))
40,694✔
376
                return 1;
377

378
        /* we need to resolve symlinks manually, we can't just rely on is_mount_point_at() to do that for us;
379
         * if we have a structure like /bin -> /usr/bin/ and /usr is a mount point, then the parent that we
380
         * look at needs to be /usr, not /. */
381
        dfd = chase_and_open_parent(path, root,
40,687✔
382
                                    CHASE_TRAIL_SLASH|(FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? 0 : CHASE_NOFOLLOW),
40,687✔
383
                                    &fn);
384
        if (dfd < 0)
40,687✔
385
                return dfd;
386

387
        return is_mount_point_at(dfd, fn, flags);
40,439✔
388
}
389

390
int path_get_mnt_id_at_fallback(int dir_fd, const char *path, int *ret) {
×
391
        int r;
×
392

393
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
×
394
        assert(ret);
×
395

396
        r = name_to_handle_at_loop(dir_fd, path, NULL, ret, isempty(path) ? AT_EMPTY_PATH : 0);
×
397
        if (r >= 0 || is_name_to_handle_at_fatal_error(r))
×
398
                return r;
×
399

400
        return fd_fdinfo_mnt_id(dir_fd, path, isempty(path) ? AT_EMPTY_PATH : 0, ret);
×
401
}
402

403
int path_get_mnt_id_at(int dir_fd, const char *path, int *ret) {
10,823✔
404
        STRUCT_NEW_STATX_DEFINE(buf);
10,823✔
405

406
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
10,823✔
407
        assert(ret);
10,823✔
408

409
        if (statx(dir_fd,
21,646✔
410
                  strempty(path),
10,823✔
411
                  (isempty(path) ? AT_EMPTY_PATH : AT_SYMLINK_NOFOLLOW) |
10,823✔
412
                  AT_NO_AUTOMOUNT |    /* don't trigger automounts, mnt_id is a local concept */
413
                  AT_STATX_DONT_SYNC,  /* don't go to the network, mnt_id is a local concept */
414
                  STATX_MNT_ID,
415
                  &buf.sx) < 0) {
416
                if (!ERRNO_IS_NOT_SUPPORTED(errno) && /* statx() is not supported by the kernel. */
1✔
417
                    !ERRNO_IS_PRIVILEGE(errno) &&     /* maybe filtered by seccomp. */
1✔
418
                    errno != EINVAL)                  /* glibc's fallback method returns EINVAL when AT_STATX_DONT_SYNC is set. */
419
                        return -errno;
1✔
420

421
                /* Fall back to name_to_handle_at() and then fdinfo if statx is not supported or we lack
422
                 * privileges */
423

424
        } else if (FLAGS_SET(buf.nsx.stx_mask, STATX_MNT_ID)) {
10,822✔
425
                *ret = buf.nsx.stx_mnt_id;
10,822✔
426
                return 0;
10,822✔
427
        }
428

429
        return path_get_mnt_id_at_fallback(dir_fd, path, ret);
×
430
}
431

432
bool fstype_is_network(const char *fstype) {
2,031✔
433
        const char *x;
2,031✔
434

435
        x = startswith(fstype, "fuse.");
2,031✔
436
        if (x)
2,031✔
437
                fstype = x;
×
438

439
        if (nulstr_contains(filesystem_sets[FILESYSTEM_SET_NETWORK].value, fstype))
2,031✔
440
                return true;
2,031✔
441

442
        /* Filesystems not present in the internal database */
443
        return STR_IN_SET(fstype,
2,027✔
444
                          "davfs",
445
                          "glusterfs",
446
                          "lustre",
447
                          "sshfs");
448
}
449

450
bool fstype_needs_quota(const char *fstype) {
×
451
       /* 1. quotacheck needs to be run for some filesystems after they are mounted
452
        *    if the filesystem was not unmounted cleanly.
453
        * 2. You may need to run quotaon to enable quota usage tracking and/or
454
        *    enforcement.
455
        * ext2     - needs 1) and 2)
456
        * ext3     - needs 2) if configured using usrjquota/grpjquota mount options
457
        * ext4     - needs 1) if created without journal, needs 2) if created without QUOTA
458
        *            filesystem feature
459
        * reiserfs - needs 2).
460
        * jfs      - needs 2)
461
        * f2fs     - needs 2) if configured using usrjquota/grpjquota/prjjquota mount options
462
        * xfs      - nothing needed
463
        * gfs2     - nothing needed
464
        * ocfs2    - nothing needed
465
        * btrfs    - nothing needed
466
        * for reference see filesystem and quota manpages */
467
        return STR_IN_SET(fstype,
×
468
                          "ext2",
469
                          "ext3",
470
                          "ext4",
471
                          "reiserfs",
472
                          "jfs",
473
                          "f2fs");
474
}
475

476
bool fstype_is_api_vfs(const char *fstype) {
40✔
477
        assert(fstype);
40✔
478

479
        const FilesystemSet *fs;
40✔
480
        FOREACH_ARGUMENT(fs,
181✔
481
                         filesystem_sets + FILESYSTEM_SET_BASIC_API,
482
                         filesystem_sets + FILESYSTEM_SET_AUXILIARY_API,
483
                         filesystem_sets + FILESYSTEM_SET_PRIVILEGED_API,
484
                         filesystem_sets + FILESYSTEM_SET_TEMPORARY)
485
                if (nulstr_contains(fs->value, fstype))
160✔
486
                    return true;
19✔
487

488
        /* Filesystems not present in the internal database */
489
        return STR_IN_SET(fstype,
21✔
490
                          "autofs",
491
                          "cpuset",
492
                          "devtmpfs");
493
}
494

495
bool fstype_is_blockdev_backed(const char *fstype) {
10✔
496
        const char *x;
10✔
497

498
        x = startswith(fstype, "fuse.");
10✔
499
        if (x)
10✔
500
                fstype = x;
×
501

502
        return !streq(fstype, "9p") && !fstype_is_network(fstype) && !fstype_is_api_vfs(fstype);
10✔
503
}
504

505
bool fstype_is_ro(const char *fstype) {
2,406✔
506
        /* All Linux file systems that are necessarily read-only */
507
        return STR_IN_SET(fstype,
2,406✔
508
                          "DM_verity_hash",
509
                          "cramfs",
510
                          "erofs",
511
                          "iso9660",
512
                          "squashfs");
513
}
514

515
bool fstype_can_discard(const char *fstype) {
4✔
516
        assert(fstype);
4✔
517

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

523
        /* On new kernels we can just ask the kernel */
524
        return mount_option_supported(fstype, "discard", NULL) > 0;
3✔
525
}
526

527
const char* fstype_norecovery_option(const char *fstype) {
156✔
528
        int r;
156✔
529

530
        assert(fstype);
156✔
531

532
        /* Use a curated list as first check, to avoid calling fsopen() which might load kmods, which might
533
         * not be allowed in our MAC context. */
534
        if (STR_IN_SET(fstype, "ext3", "ext4", "xfs"))
156✔
535
                return "norecovery";
11✔
536

537
        /* btrfs dropped support for the "norecovery" option in 6.8
538
         * (https://github.com/torvalds/linux/commit/a1912f712188291f9d7d434fba155461f1ebef66) and replaced
539
         * it with rescue=nologreplay, so we check for the new name first and fall back to checking for the
540
         * old name if the new name doesn't work. */
541
        if (streq(fstype, "btrfs")) {
145✔
542
                r = mount_option_supported(fstype, "rescue=nologreplay", NULL);
×
543
                if (r == -EAGAIN) {
×
544
                        log_debug_errno(r, "Failed to check for btrfs 'rescue=nologreplay' option, assuming old kernel with 'norecovery': %m");
×
545
                        return "norecovery";
×
546
                }
547
                if (r < 0)
×
548
                        log_debug_errno(r, "Failed to check for btrfs 'rescue=nologreplay' option, assuming it is not supported: %m");
×
549
                if (r > 0)
×
550
                        return "rescue=nologreplay";
551
        }
552

553
        /* On new kernels we can just ask the kernel */
554
        return mount_option_supported(fstype, "norecovery", NULL) > 0 ? "norecovery" : NULL;
145✔
555
}
556

557
bool fstype_can_fmask_dmask(const char *fstype) {
56✔
558
        assert(fstype);
56✔
559

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

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

573
        return STR_IN_SET(fstype,
1✔
574
                          "adfs",
575
                          "exfat",
576
                          "fat",
577
                          "hfs",
578
                          "hpfs",
579
                          "iso9660",
580
                          "msdos",
581
                          "ntfs",
582
                          "vfat");
583
}
584

585
int dev_is_devtmpfs(void) {
298✔
586
        _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
298✔
587
        int mount_id, r;
298✔
588
        char *e;
298✔
589

590
        r = path_get_mnt_id("/dev", &mount_id);
298✔
591
        if (r < 0)
298✔
592
                return r;
593

594
        r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo);
298✔
595
        if (r == -ENOENT)
298✔
596
                return proc_mounted() > 0 ? -ENOENT : -ENOSYS;
×
597
        if (r < 0)
298✔
598
                return r;
599

600
        for (;;) {
11,098✔
601
                _cleanup_free_ char *line = NULL;
10,867✔
602
                int mid;
11,098✔
603

604
                r = read_line(proc_self_mountinfo, LONG_LINE_MAX, &line);
11,098✔
605
                if (r < 0)
11,098✔
606
                        return r;
607
                if (r == 0)
11,098✔
608
                        break;
609

610
                if (sscanf(line, "%i", &mid) != 1)
10,867✔
611
                        continue;
×
612

613
                if (mid != mount_id)
10,867✔
614
                        continue;
10,569✔
615

616
                e = strstrafter(line, " - ");
298✔
617
                if (!e)
298✔
618
                        continue;
×
619

620
                /* accept any name that starts with the currently expected type */
621
                if (startswith(e, "devtmpfs"))
298✔
622
                        return true;
623
        }
624

625
        return false;
231✔
626
}
627

628
static int mount_fd(
97,313✔
629
                const char *source,
630
                int target_fd,
631
                const char *filesystemtype,
632
                unsigned long mountflags,
633
                const void *data) {
634

635
        assert(target_fd >= 0);
97,313✔
636

637
        if (mount(source, FORMAT_PROC_FD_PATH(target_fd), filesystemtype, mountflags, data) < 0) {
97,313✔
638
                if (errno != ENOENT)
1,190✔
639
                        return -errno;
1,190✔
640

641
                /* ENOENT can mean two things: either that the source is missing, or that /proc/ isn't
642
                 * mounted. Check for the latter to generate better error messages. */
643
                if (proc_mounted() == 0)
590✔
644
                        return -ENOSYS;
645

646
                return -ENOENT;
590✔
647
        }
648

649
        return 0;
96,123✔
650
}
651

652
int mount_nofollow(
98,819✔
653
                const char *source,
654
                const char *target,
655
                const char *filesystemtype,
656
                unsigned long mountflags,
657
                const void *data) {
658

659
        _cleanup_close_ int fd = -EBADF;
98,819✔
660

661
        assert(target);
98,819✔
662

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

672
        fd = open(target, O_PATH|O_CLOEXEC|O_NOFOLLOW);
98,819✔
673
        if (fd < 0)
98,819✔
674
                return -errno;
1,506✔
675

676
        return mount_fd(source, fd, filesystemtype, mountflags, data);
97,313✔
677
}
678

679
const char* mount_propagation_flag_to_string(unsigned long flags) {
9✔
680

681
        switch (flags & (MS_SHARED|MS_SLAVE|MS_PRIVATE)) {
9✔
682
        case 0:
683
                return "";
684
        case MS_SHARED:
1✔
685
                return "shared";
1✔
686
        case MS_SLAVE:
1✔
687
                return "slave";
1✔
688
        case MS_PRIVATE:
3✔
689
                return "private";
3✔
690
        }
691

692
        return NULL;
×
693
}
694

695
int mount_propagation_flag_from_string(const char *name, unsigned long *ret) {
8✔
696

697
        if (isempty(name))
8✔
698
                *ret = 0;
2✔
699
        else if (streq(name, "shared"))
6✔
700
                *ret = MS_SHARED;
1✔
701
        else if (streq(name, "slave"))
5✔
702
                *ret = MS_SLAVE;
1✔
703
        else if (streq(name, "private"))
4✔
704
                *ret = MS_PRIVATE;
2✔
705
        else
706
                return -EINVAL;
707
        return 0;
708
}
709

710
bool mount_propagation_flag_is_valid(unsigned long flag) {
2,812✔
711
        return IN_SET(flag, 0, MS_SHARED, MS_PRIVATE, MS_SLAVE);
2,812✔
712
}
713

714
bool mount_new_api_supported(void) {
6,888✔
715
        static int cache = -1;
6,888✔
716
        int r;
6,888✔
717

718
        if (cache >= 0)
6,888✔
719
                return cache;
1,753✔
720

721
        /* This is the newer API among the ones we use, so use it as boundary */
722
        r = RET_NERRNO(mount_setattr(-EBADF, NULL, 0, NULL, 0));
5,135✔
723
        if (r == 0 || ERRNO_IS_NOT_SUPPORTED(r)) /* This should return an error if it is working properly */
5,135✔
724
                return (cache = false);
×
725

726
        return (cache = true);
5,135✔
727
}
728

729
unsigned long ms_nosymfollow_supported(void) {
6,077✔
730
        _cleanup_close_ int fsfd = -EBADF, mntfd = -EBADF;
6,077✔
731
        static int cache = -1;
6,077✔
732

733
        /* Returns MS_NOSYMFOLLOW if it is supported, zero otherwise. */
734

735
        if (cache >= 0)
6,077✔
736
                return cache ? MS_NOSYMFOLLOW : 0;
3,169✔
737

738
        if (!mount_new_api_supported())
2,908✔
739
                goto not_supported;
×
740

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

744
        fsfd = fsopen("tmpfs", FSOPEN_CLOEXEC);
2,908✔
745
        if (fsfd < 0) {
2,908✔
746
                if (ERRNO_IS_NOT_SUPPORTED(errno))
2✔
747
                        goto not_supported;
×
748

749
                log_debug_errno(errno, "Failed to open superblock context for tmpfs: %m");
2✔
750
                return 0;
2✔
751
        }
752

753
        if (fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) < 0) {
2,906✔
754
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
755
                        goto not_supported;
×
756

757
                log_debug_errno(errno, "Failed to create tmpfs superblock: %m");
×
758
                return 0;
×
759
        }
760

761
        mntfd = fsmount(fsfd, FSMOUNT_CLOEXEC, 0);
2,906✔
762
        if (mntfd < 0) {
2,906✔
763
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
764
                        goto not_supported;
×
765

766
                log_debug_errno(errno, "Failed to turn superblock fd into mount fd: %m");
×
767
                return 0;
×
768
        }
769

770
        if (mount_setattr(mntfd, "", AT_EMPTY_PATH|AT_RECURSIVE,
2,906✔
771
                          &(struct mount_attr) {
2,906✔
772
                                  .attr_set = MOUNT_ATTR_NOSYMFOLLOW,
773
                          }, sizeof(struct mount_attr)) < 0) {
774
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
775
                        goto not_supported;
×
776

777
                log_debug_errno(errno, "Failed to set MOUNT_ATTR_NOSYMFOLLOW mount attribute: %m");
×
778
                return 0;
×
779
        }
780

781
        cache = true;
2,906✔
782
        return MS_NOSYMFOLLOW;
2,906✔
783

784
not_supported:
×
785
        cache = false;
×
786
        return 0;
×
787
}
788

789
int mount_option_supported(const char *fstype, const char *key, const char *value) {
4,666✔
790
        _cleanup_close_ int fd = -EBADF;
4,666✔
791
        int r;
4,666✔
792

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

796
        assert(fstype);
4,666✔
797
        assert(key);
4,666✔
798

799
        fd = fsopen(fstype, FSOPEN_CLOEXEC);
4,666✔
800
        if (fd < 0)
4,666✔
801
                return log_debug_errno(errno, "Failed to open superblock context for '%s': %m", fstype);
1✔
802

803
        /* Various file systems support fs context only in recent kernels (e.g. btrfs). For older kernels
804
         * fsconfig() with FSCONFIG_SET_STRING/FSCONFIG_SET_FLAG never fail. Which sucks, because we want to
805
         * use it for testing support, after all. Let's hence do a check if the file system got converted yet
806
         * first. */
807
        if (fsconfig(fd, FSCONFIG_SET_FD, "adefinitelynotexistingmountoption", NULL, fd) < 0) {
4,665✔
808
                /* If FSCONFIG_SET_FD is not supported for the fs, then the file system was not converted to
809
                 * the new mount API yet. If it returns EINVAL the mount option doesn't exist, but the fstype
810
                 * is converted. */
811
                if (errno == EOPNOTSUPP)
4,665✔
812
                        return -EAGAIN; /* fs not converted to new mount API → don't know */
813
                if (errno != EINVAL)
4,663✔
814
                        return log_debug_errno(errno, "Failed to check if file system '%s' has been converted to new mount API: %m", fstype);
×
815

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

821
        if (value)
4,663✔
822
                r = fsconfig(fd, FSCONFIG_SET_STRING, key, value, 0);
1,272✔
823
        else
824
                r = fsconfig(fd, FSCONFIG_SET_FLAG, key, NULL, 0);
3,391✔
825
        if (r < 0) {
4,663✔
826
                if (errno == EINVAL)
191✔
827
                        return false; /* EINVAL means option not supported. */
828

829
                return log_debug_errno(errno, "Failed to set '%s%s%s' on '%s' superblock context: %m",
×
830
                                       key, value ? "=" : "", strempty(value), fstype);
831
        }
832

833
        return true; /* works! */
834
}
835

836
bool path_below_api_vfs(const char *p) {
7,689✔
837
        assert(p);
7,689✔
838

839
        /* API VFS are either directly mounted on any of these three paths, or below it. */
840
        return PATH_STARTSWITH_SET(p, "/dev", "/sys", "/proc");
7,689✔
841
}
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