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

systemd / systemd / 14895667988

07 May 2025 08:57PM UTC coverage: 72.225% (-0.007%) from 72.232%
14895667988

push

github

yuwata
network: log_link_message_debug_errno() automatically append %m if necessary

Follow-up for d28746ef5.
Fixes CID#1609753.

0 of 1 new or added line in 1 file covered. (0.0%)

20297 existing lines in 338 files now uncovered.

297407 of 411780 relevant lines covered (72.22%)

695716.85 hits per line

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

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

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

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

44
        assert(err < 0);
3,621✔
45

46
        if (ERRNO_IS_NEG_NOT_SUPPORTED(err))
3,621✔
47
                return false;
UNCOV
48
        if (ERRNO_IS_NEG_PRIVILEGE(err))
×
49
                return false;
50

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

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

61
        size_t n = ORIGINAL_MAX_HANDLE_SZ;
27,317✔
62

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

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

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

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

81
                h->handle_bytes = n;
27,317✔
82

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

85
                        if (ret_handle)
27,317✔
86
                                *ret_handle = TAKE_PTR(h);
27,317✔
87

88
                        if (ret_mnt_id)
27,317✔
89
                                *ret_mnt_id = mnt_id;
27,317✔
90

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

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

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

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

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

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

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

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

128
        int r;
27,317✔
129

130
        assert(fd >= 0 || fd == AT_FDCWD);
27,317✔
131

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

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

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

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

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

151
        if ((flags & AT_EMPTY_PATH) && isempty(filename))
×
UNCOV
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)
×
UNCOV
156
                        return -errno;
×
157

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

161
        _cleanup_free_ char *p = NULL;
×
162
        r = get_proc_field(path, "mnt_id", &p);
×
UNCOV
163
        if (r == -ENOENT)
×
164
                return -EBADF;
UNCOV
165
        if (r < 0)
×
166
                return r;
167

UNCOV
168
        return safe_atoi(p, ret_mnt_id);
×
169
}
170

171
static bool filename_possibly_with_slash_suffix(const char *s) {
79,900✔
172
        const char *slash, *copied;
79,900✔
173

174
        /* Checks whether the specified string is either file name, or a filename with a suffix of
175
         * slashes. But nothing else.
176
         *
177
         * this is OK: foo, bar, foo/, bar/, foo//, bar///
178
         * this is not OK: "", "/", "/foo", "foo/bar", ".", ".." … */
179

180
        slash = strchr(s, '/');
79,900✔
181
        if (!slash)
79,900✔
182
                return filename_is_valid(s);
79,886✔
183

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

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

190
        copied = strndupa_safe(s, slash - s);
10✔
191
        return filename_is_valid(copied);
10✔
192
}
193

194
bool file_handle_equal(const struct file_handle *a, const struct file_handle *b) {
195
        if (a == b)
13,654✔
196
                return true;
197
        if (!a != !b)
13,654✔
198
                return false;
199
        if (a->handle_type != b->handle_type)
13,654✔
200
                return false;
201

202
        return memcmp_nn(a->f_handle, a->handle_bytes, b->f_handle, b->handle_bytes) == 0;
13,640✔
203
}
204

205
int is_mount_point_at(int fd, const char *filename, int flags) {
206
        bool fd_is_self;
80,148✔
207
        int r;
80,148✔
208

209
        assert(fd >= 0 || fd == AT_FDCWD);
80,148✔
210
        assert((flags & ~AT_SYMLINK_FOLLOW) == 0);
80,148✔
211

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

224
                fd_is_self = true;
225
        } else if (STR_IN_SET(filename, ".", "./"))
79,949✔
226
                fd_is_self = true;
227
        else {
228
                /* Insist that the specified filename is actually a filename, and not a path, i.e. some inode
229
                 * further up or down the tree then immediately below the specified directory fd. */
230
                if (!filename_possibly_with_slash_suffix(filename))
79,900✔
231
                        return -EINVAL;
7✔
232

233
                fd_is_self = false;
234
        }
235

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

254
        struct statx sx = {}; /* explicitly initialize the struct to make msan silent. */
80,141✔
255
        if (statx(fd, filename,
80,141✔
256
                  at_flags_normalize_nofollow(flags) |
80,141✔
257
                  AT_NO_AUTOMOUNT |            /* don't trigger automounts – mounts are a local concept, hence no need to trigger automounts to determine STATX_ATTR_MOUNT_ROOT */
258
                  AT_STATX_DONT_SYNC,          /* don't go to the network for this – for similar reasons */
259
                  STATX_TYPE,
260
                  &sx) < 0)
261
                return -errno;
3,809✔
262

263
        if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT)) /* yay! */
76,332✔
264
                return FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
76,332✔
265

266
        _cleanup_free_ struct file_handle *h = NULL, *h_parent = NULL;
×
267
        int mount_id = -1, mount_id_parent = -1;
×
UNCOV
268
        bool nosupp = false;
×
269

270
        r = name_to_handle_at_try_fid(fd, filename, &h, &mount_id, flags);
×
271
        if (r < 0) {
×
UNCOV
272
                if (is_name_to_handle_at_fatal_error(r))
×
273
                        return r;
274
                if (!ERRNO_IS_NOT_SUPPORTED(r))
×
UNCOV
275
                        goto fallback_fdinfo;
×
276

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

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

295
                /* The parent can't do name_to_handle_at() but the directory we are
296
                 * interested in can?  If so, it must be a mount point. */
297
                return 1;
298
        }
299

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

305
        /* If the file handle for the directory we are interested in and its parent are identical,
306
         * we assume this is the root directory, which is a mount point. */
UNCOV
307
        if (file_handle_equal(h_parent, h))
×
308
                return 1;
309

UNCOV
310
        return mount_id != mount_id_parent;
×
311

312
fallback_fdinfo:
×
313
        r = fd_fdinfo_mnt_id(fd, filename, flags, &mount_id);
×
UNCOV
314
        if (r < 0)
×
315
                return r;
316

317
        if (fd_is_self)
×
UNCOV
318
                r = fd_fdinfo_mnt_id(fd, "..", 0, &mount_id_parent); /* can't work for non-directories 😢 */
×
319
        else
320
                r = fd_fdinfo_mnt_id(fd, "", AT_EMPTY_PATH, &mount_id_parent);
×
UNCOV
321
        if (r < 0)
×
322
                return r;
323

UNCOV
324
        if (mount_id != mount_id_parent)
×
325
                return 1;
326

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

UNCOV
331
        struct stat a, b;
×
332

333
        /* yay for fstatat() taking a different set of flags than the other _at() above */
334
        if (fstatat(fd, filename, &a, at_flags_normalize_nofollow(flags)) < 0)
×
UNCOV
335
                return -errno;
×
336

337
        if (fd_is_self)
×
UNCOV
338
                r = fstatat(fd, "..", &b, 0);
×
339
        else
340
                r = fstatat(fd, "", &b, AT_EMPTY_PATH);
×
341
        if (r < 0)
×
UNCOV
342
                return -errno;
×
343

344
        /* A directory with same device and inode as its parent must be the root directory. Otherwise
345
         * not a mount point.
346
         *
347
         * NB: we avoid inode_same_at() here because it internally attempts name_to_handle_at_try_fid() first,
348
         * which is redundant. */
UNCOV
349
        return stat_inode_same(&a, &b);
×
350
}
351

352
/* flags can be AT_SYMLINK_FOLLOW or 0 */
353
int path_is_mount_point_full(const char *path, const char *root, int flags) {
354
        _cleanup_close_ int dfd = -EBADF;
26,466✔
355
        _cleanup_free_ char *fn = NULL;
26,466✔
356

357
        assert(path);
26,466✔
358
        assert((flags & ~AT_SYMLINK_FOLLOW) == 0);
26,466✔
359

360
        if (path_equal(path, "/"))
26,466✔
361
                return 1;
362

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

372
        return is_mount_point_at(dfd, fn, flags);
26,266✔
373
}
374

375
int path_get_mnt_id_at_fallback(int dir_fd, const char *path, int *ret) {
UNCOV
376
        int r;
×
377

378
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
×
UNCOV
379
        assert(ret);
×
380

381
        r = name_to_handle_at_loop(dir_fd, path, NULL, ret, isempty(path) ? AT_EMPTY_PATH : 0);
×
382
        if (r >= 0 || is_name_to_handle_at_fatal_error(r))
×
UNCOV
383
                return r;
×
384

UNCOV
385
        return fd_fdinfo_mnt_id(dir_fd, path, isempty(path) ? AT_EMPTY_PATH : 0, ret);
×
386
}
387

388
int path_get_mnt_id_at(int dir_fd, const char *path, int *ret) {
389
        struct statx sx;
6,252✔
390

391
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
6,252✔
392
        assert(ret);
6,252✔
393

394
        if (statx(dir_fd,
12,504✔
395
                  strempty(path),
6,252✔
396
                  (isempty(path) ? AT_EMPTY_PATH : AT_SYMLINK_NOFOLLOW) |
6,252✔
397
                  AT_NO_AUTOMOUNT |    /* don't trigger automounts, mnt_id is a local concept */
398
                  AT_STATX_DONT_SYNC,  /* don't go to the network, mnt_id is a local concept */
399
                  STATX_MNT_ID,
400
                  &sx) < 0)
401
                return -errno;
1✔
402

403
        if (FLAGS_SET(sx.stx_mask, STATX_MNT_ID)) {
6,251✔
404
                *ret = sx.stx_mnt_id;
6,251✔
405
                return 0;
6,251✔
406
        }
407

UNCOV
408
        return path_get_mnt_id_at_fallback(dir_fd, path, ret);
×
409
}
410

411
bool fstype_is_network(const char *fstype) {
412
        const char *x;
2,050✔
413

414
        x = startswith(fstype, "fuse.");
2,050✔
415
        if (x)
2,050✔
UNCOV
416
                fstype = x;
×
417

418
        if (nulstr_contains(filesystem_sets[FILESYSTEM_SET_NETWORK].value, fstype))
2,050✔
419
                return true;
2,050✔
420

421
        /* Filesystems not present in the internal database */
422
        return STR_IN_SET(fstype,
2,046✔
423
                          "davfs",
424
                          "glusterfs",
425
                          "lustre",
426
                          "sshfs");
427
}
428

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

455
bool fstype_is_api_vfs(const char *fstype) {
456
        assert(fstype);
59✔
457

458
        const FilesystemSet *fs;
59✔
459
        FOREACH_ARGUMENT(fs,
267✔
460
                         filesystem_sets + FILESYSTEM_SET_BASIC_API,
461
                         filesystem_sets + FILESYSTEM_SET_AUXILIARY_API,
462
                         filesystem_sets + FILESYSTEM_SET_PRIVILEGED_API,
463
                         filesystem_sets + FILESYSTEM_SET_TEMPORARY)
464
                if (nulstr_contains(fs->value, fstype))
236✔
465
                    return true;
28✔
466

467
        /* Filesystems not present in the internal database */
468
        return STR_IN_SET(fstype,
31✔
469
                          "autofs",
470
                          "cpuset",
471
                          "devtmpfs");
472
}
473

474
bool fstype_is_blockdev_backed(const char *fstype) {
475
        const char *x;
29✔
476

477
        x = startswith(fstype, "fuse.");
29✔
478
        if (x)
29✔
UNCOV
479
                fstype = x;
×
480

481
        return !streq(fstype, "9p") && !fstype_is_network(fstype) && !fstype_is_api_vfs(fstype);
29✔
482
}
483

484
bool fstype_is_ro(const char *fstype) {
485
        /* All Linux file systems that are necessarily read-only */
486
        return STR_IN_SET(fstype,
2,786✔
487
                          "DM_verity_hash",
488
                          "cramfs",
489
                          "erofs",
490
                          "iso9660",
491
                          "squashfs");
492
}
493

494
bool fstype_can_discard(const char *fstype) {
495
        assert(fstype);
4✔
496

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

502
        /* On new kernels we can just ask the kernel */
503
        return mount_option_supported(fstype, "discard", NULL) > 0;
3✔
504
}
505

506
const char* fstype_norecovery_option(const char *fstype) {
507
        int r;
162✔
508

509
        assert(fstype);
162✔
510

511
        /* Use a curated list as first check, to avoid calling fsopen() which might load kmods, which might
512
         * not be allowed in our MAC context. */
513
        if (STR_IN_SET(fstype, "ext3", "ext4", "xfs"))
162✔
514
                return "norecovery";
17✔
515

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

532
        /* On new kernels we can just ask the kernel */
533
        return mount_option_supported(fstype, "norecovery", NULL) > 0 ? "norecovery" : NULL;
145✔
534
}
535

536
bool fstype_can_fmask_dmask(const char *fstype) {
537
        assert(fstype);
57✔
538

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

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

552
        return STR_IN_SET(fstype,
1✔
553
                          "adfs",
554
                          "exfat",
555
                          "fat",
556
                          "hfs",
557
                          "hpfs",
558
                          "iso9660",
559
                          "msdos",
560
                          "ntfs",
561
                          "vfat");
562
}
563

564
int dev_is_devtmpfs(void) {
565
        _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
249✔
566
        int mount_id, r;
249✔
567
        char *e;
249✔
568

569
        r = path_get_mnt_id("/dev", &mount_id);
249✔
570
        if (r < 0)
249✔
571
                return r;
572

573
        r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo);
249✔
574
        if (r == -ENOENT)
249✔
UNCOV
575
                return proc_mounted() > 0 ? -ENOENT : -ENOSYS;
×
576
        if (r < 0)
249✔
577
                return r;
578

579
        for (;;) {
11,137✔
580
                _cleanup_free_ char *line = NULL;
10,903✔
581
                int mid;
11,137✔
582

583
                r = read_line(proc_self_mountinfo, LONG_LINE_MAX, &line);
11,137✔
584
                if (r < 0)
11,137✔
585
                        return r;
586
                if (r == 0)
11,137✔
587
                        break;
588

589
                if (sscanf(line, "%i", &mid) != 1)
10,903✔
UNCOV
590
                        continue;
×
591

592
                if (mid != mount_id)
10,903✔
593
                        continue;
10,654✔
594

595
                e = strstrafter(line, " - ");
249✔
596
                if (!e)
249✔
UNCOV
597
                        continue;
×
598

599
                /* accept any name that starts with the currently expected type */
600
                if (startswith(e, "devtmpfs"))
249✔
601
                        return true;
602
        }
603

604
        return false;
234✔
605
}
606

607
static int mount_fd(
66,125✔
608
                const char *source,
609
                int target_fd,
610
                const char *filesystemtype,
611
                unsigned long mountflags,
612
                const void *data) {
613

614
        assert(target_fd >= 0);
66,125✔
615

616
        if (mount(source, FORMAT_PROC_FD_PATH(target_fd), filesystemtype, mountflags, data) < 0) {
66,125✔
617
                if (errno != ENOENT)
991✔
618
                        return -errno;
991✔
619

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

625
                return -ENOENT;
490✔
626
        }
627

628
        return 0;
65,134✔
629
}
630

631
int mount_nofollow(
632
                const char *source,
633
                const char *target,
634
                const char *filesystemtype,
635
                unsigned long mountflags,
636
                const void *data) {
637

638
        _cleanup_close_ int fd = -EBADF;
67,579✔
639

640
        assert(target);
67,579✔
641

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

651
        fd = open(target, O_PATH|O_CLOEXEC|O_NOFOLLOW);
67,579✔
652
        if (fd < 0)
67,579✔
653
                return -errno;
1,454✔
654

655
        return mount_fd(source, fd, filesystemtype, mountflags, data);
66,125✔
656
}
657

658
const char* mount_propagation_flag_to_string(unsigned long flags) {
659

660
        switch (flags & (MS_SHARED|MS_SLAVE|MS_PRIVATE)) {
9✔
661
        case 0:
662
                return "";
663
        case MS_SHARED:
1✔
664
                return "shared";
1✔
665
        case MS_SLAVE:
1✔
666
                return "slave";
1✔
667
        case MS_PRIVATE:
3✔
668
                return "private";
3✔
669
        }
670

UNCOV
671
        return NULL;
×
672
}
673

674
int mount_propagation_flag_from_string(const char *name, unsigned long *ret) {
675

676
        if (isempty(name))
8✔
677
                *ret = 0;
2✔
678
        else if (streq(name, "shared"))
6✔
679
                *ret = MS_SHARED;
1✔
680
        else if (streq(name, "slave"))
5✔
681
                *ret = MS_SLAVE;
1✔
682
        else if (streq(name, "private"))
4✔
683
                *ret = MS_PRIVATE;
2✔
684
        else
685
                return -EINVAL;
686
        return 0;
687
}
688

689
bool mount_propagation_flag_is_valid(unsigned long flag) {
690
        return IN_SET(flag, 0, MS_SHARED, MS_PRIVATE, MS_SLAVE);
2,215✔
691
}
692

693
bool mount_new_api_supported(void) {
694
        static int cache = -1;
6,013✔
695
        int r;
6,013✔
696

697
        if (cache >= 0)
6,013✔
698
                return cache;
1,604✔
699

700
        /* This is the newer API among the ones we use, so use it as boundary */
701
        r = RET_NERRNO(mount_setattr(-EBADF, NULL, 0, NULL, 0));
4,409✔
702
        if (r == 0 || ERRNO_IS_NOT_SUPPORTED(r)) /* This should return an error if it is working properly */
4,409✔
UNCOV
703
                return (cache = false);
×
704

705
        return (cache = true);
4,409✔
706
}
707

708
unsigned long ms_nosymfollow_supported(void) {
709
        _cleanup_close_ int fsfd = -EBADF, mntfd = -EBADF;
4,860✔
710
        static int cache = -1;
4,860✔
711

712
        /* Returns MS_NOSYMFOLLOW if it is supported, zero otherwise. */
713

714
        if (cache >= 0)
4,860✔
715
                return cache ? MS_NOSYMFOLLOW : 0;
2,532✔
716

717
        if (!mount_new_api_supported())
2,328✔
UNCOV
718
                goto not_supported;
×
719

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

723
        fsfd = fsopen("tmpfs", FSOPEN_CLOEXEC);
2,328✔
724
        if (fsfd < 0) {
2,328✔
725
                if (ERRNO_IS_NOT_SUPPORTED(errno))
2✔
UNCOV
726
                        goto not_supported;
×
727

728
                log_debug_errno(errno, "Failed to open superblock context for tmpfs: %m");
2✔
729
                return 0;
2✔
730
        }
731

732
        if (fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) < 0) {
2,326✔
733
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
UNCOV
734
                        goto not_supported;
×
735

736
                log_debug_errno(errno, "Failed to create tmpfs superblock: %m");
×
UNCOV
737
                return 0;
×
738
        }
739

740
        mntfd = fsmount(fsfd, FSMOUNT_CLOEXEC, 0);
2,326✔
741
        if (mntfd < 0) {
2,326✔
742
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
UNCOV
743
                        goto not_supported;
×
744

745
                log_debug_errno(errno, "Failed to turn superblock fd into mount fd: %m");
×
UNCOV
746
                return 0;
×
747
        }
748

749
        if (mount_setattr(mntfd, "", AT_EMPTY_PATH|AT_RECURSIVE,
2,326✔
750
                          &(struct mount_attr) {
2,326✔
751
                                  .attr_set = MOUNT_ATTR_NOSYMFOLLOW,
752
                          }, sizeof(struct mount_attr)) < 0) {
753
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
UNCOV
754
                        goto not_supported;
×
755

756
                log_debug_errno(errno, "Failed to set MOUNT_ATTR_NOSYMFOLLOW mount attribute: %m");
×
UNCOV
757
                return 0;
×
758
        }
759

760
        cache = true;
2,326✔
761
        return MS_NOSYMFOLLOW;
2,326✔
762

763
not_supported:
×
764
        cache = false;
×
UNCOV
765
        return 0;
×
766
}
767

768
int mount_option_supported(const char *fstype, const char *key, const char *value) {
769
        _cleanup_close_ int fd = -EBADF;
3,618✔
770
        int r;
3,618✔
771

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

775
        assert(fstype);
3,618✔
776
        assert(key);
3,618✔
777

778
        fd = fsopen(fstype, FSOPEN_CLOEXEC);
3,618✔
779
        if (fd < 0)
3,618✔
780
                return log_debug_errno(errno, "Failed to open superblock context for '%s': %m", fstype);
1✔
781

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

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

800
        if (value)
3,617✔
801
                r = fsconfig(fd, FSCONFIG_SET_STRING, key, value, 0);
872✔
802
        else
803
                r = fsconfig(fd, FSCONFIG_SET_FLAG, key, NULL, 0);
2,745✔
804
        if (r < 0) {
3,617✔
805
                if (errno == EINVAL)
193✔
806
                        return false; /* EINVAL means option not supported. */
807

UNCOV
808
                return log_debug_errno(errno, "Failed to set '%s%s%s' on '%s' superblock context: %m",
×
809
                                       key, value ? "=" : "", strempty(value), fstype);
810
        }
811

812
        return true; /* works! */
813
}
814

815
bool path_below_api_vfs(const char *p) {
816
        assert(p);
9,319✔
817

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