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

systemd / systemd / 12919407857

23 Jan 2025 12:04AM UTC coverage: 71.444% (+71.3%) from 0.117%
12919407857

push

github

web-flow
core/device: do not drop backslashes in SYSTEMD_WANTS=/SYSTEMD_USER_WANTS= (#35869)

Let consider the following udev rules:
```
PROGRAM="/usr/bin/systemd-escape foo-bar-baz", ENV{SYSTEMD_WANTS}+="test1@$result.service"
PROGRAM="/usr/bin/systemd-escape aaa-bbb-ccc", ENV{SYSTEMD_WANTS}+="test2@$result.service"
```
Then, a device expectedly gains a property:
```
SYSTEMD_WANTS=test1@foo\x2dbar\x2dbaz.service test2@aaa\x2dbbb\x2dccc.service
```
After the event being processed by udevd, PID1 processes the device, the
property previously was parsed with
`extract_first_word(EXTRACT_UNQUOTE)`, then the device unit gained the
following dependencies:
```
Wants=test1@foox2dbarx2dbaz.service test2@aaax2dbbbx2dccc.service
```
So both `%i` and `%I` for the template services did not match with the
original data, and it was hard to use `systemd-escape` in `PROGRAM=`
udev rule token.

This makes the property parsed with
`extract_first_word(EXTRACT_UNQUOTE|EXTRACT_RETAIN_ESCAPE)`, hence the
device unit now gains the following dependencies:
```
Wants=test1@foo\x2dbar\x2dbaz.service test2@aaa\x2dbbb\x2dccc.service
```
and `%I` for the template services match with the original data.

Fixes a bug caused by ceed8f0c8 (v233).

Fixes #16735.
Replaces #16737 and #35768.

40 of 40 new or added lines in 2 files covered. (100.0%)

407 existing lines in 13 files now uncovered.

291321 of 407761 relevant lines covered (71.44%)

696525.16 hits per line

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

65.58
/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,861✔
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,861✔
48

49
        if (ERRNO_IS_NEG_NOT_SUPPORTED(err))
11,861✔
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(
26,847✔
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;
26,847✔
65

66
        assert(fd >= 0 || fd == AT_FDCWD);
26,847✔
67
        assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH|AT_HANDLE_FID)) == 0);
26,847✔
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 (;;) {
26,847✔
77
                _cleanup_free_ struct file_handle *h = NULL;
×
78
                int mnt_id = -1;
26,847✔
79

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

84
                h->handle_bytes = n;
26,847✔
85

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

88
                        if (ret_handle)
26,847✔
89
                                *ret_handle = TAKE_PTR(h);
26,847✔
90

91
                        if (ret_mnt_id)
26,847✔
92
                                *ret_mnt_id = mnt_id;
26,847✔
93

94
                        return 0;
26,847✔
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(
26,847✔
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;
26,847✔
132

133
        assert(fd >= 0 || fd == AT_FDCWD);
26,847✔
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);
26,847✔
140
        if (r >= 0 || is_name_to_handle_at_fatal_error(r))
26,847✔
141
                return r;
26,847✔
142

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

UNCOV
146
static int fd_fdinfo_mnt_id(int fd, const char *filename, int flags, int *ret_mnt_id) {
×
UNCOV
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)
×
UNCOV
160
                        return -errno;
×
161

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

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

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

175
        p = skip_leading_chars(p, /* bad = */ NULL);
×
UNCOV
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) {
125,269✔
182
        const char *slash, *copied;
125,269✔
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, '/');
125,269✔
191
        if (!slash)
125,269✔
192
                return filename_is_valid(s);
125,255✔
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,419✔
205
        if (a == b)
13,419✔
206
                return true;
207
        if (!a != !b)
13,419✔
208
                return false;
209
        if (a->handle_type != b->handle_type)
13,419✔
210
                return false;
211

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

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

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

222
        if (isempty(filename)) {
125,402✔
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, ".", "./"))
125,313✔
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))
125,269✔
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);
125,395✔
265

266
        if (statx(fd, filename,
125,395✔
267
                  at_flags_normalize_nofollow(flags) |
125,395✔
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,615✔
273
                    !ERRNO_IS_PRIVILEGE(errno) &&     /* maybe filtered by seccomp. */
5,615✔
274
                    errno != EINVAL)                  /* glibc's fallback method returns EINVAL when AT_STATX_DONT_SYNC is set. */
275
                        return -errno;
5,615✔
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! */
119,780✔
279
                return FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
119,780✔
280

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

UNCOV
285
        r = name_to_handle_at_try_fid(fd, filename, &h, &mount_id, flags);
×
UNCOV
286
        if (r < 0) {
×
UNCOV
287
                if (is_name_to_handle_at_fatal_error(r))
×
288
                        return r;
UNCOV
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
UNCOV
300
                r = name_to_handle_at_try_fid(fd, "", &h_parent, &mount_id_parent, AT_EMPTY_PATH);
×
301
        if (r < 0) {
×
UNCOV
302
                if (is_name_to_handle_at_fatal_error(r))
×
303
                        return r;
UNCOV
304
                if (!ERRNO_IS_NOT_SUPPORTED(r))
×
UNCOV
305
                        goto fallback_fdinfo;
×
UNCOV
306
                if (nosupp)
×
307
                        /* Both the parent and the directory can't do name_to_handle_at() */
UNCOV
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. */
UNCOV
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

UNCOV
325
        return mount_id != mount_id_parent;
×
326

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

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

UNCOV
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. */
UNCOV
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) {
39,854✔
369
        _cleanup_close_ int dfd = -EBADF;
39,854✔
370
        _cleanup_free_ char *fn = NULL;
39,854✔
371

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

375
        if (path_equal(path, "/"))
39,854✔
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,
39,847✔
382
                                    CHASE_TRAIL_SLASH|(FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? 0 : CHASE_NOFOLLOW),
39,847✔
383
                                    &fn);
384
        if (dfd < 0)
39,847✔
385
                return dfd;
386

387
        return is_mount_point_at(dfd, fn, flags);
39,615✔
388
}
389

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

393
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
×
UNCOV
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))
×
UNCOV
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,574✔
404
        STRUCT_NEW_STATX_DEFINE(buf);
10,574✔
405

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

409
        if (statx(dir_fd,
21,148✔
410
                  strempty(path),
10,574✔
411
                  (isempty(path) ? AT_EMPTY_PATH : AT_SYMLINK_NOFOLLOW) |
10,574✔
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,573✔
425
                *ret = buf.nsx.stx_mnt_id;
10,573✔
426
                return 0;
10,573✔
427
        }
428

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

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

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

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

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

UNCOV
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 */
UNCOV
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) {
38✔
477
        assert(fstype);
38✔
478

479
        const FilesystemSet *fs;
38✔
480
        FOREACH_ARGUMENT(fs,
171✔
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))
152✔
486
                    return true;
19✔
487

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

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

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

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

505
bool fstype_is_ro(const char *fstype) {
2,405✔
506
        /* All Linux file systems that are necessarily read-only */
507
        return STR_IN_SET(fstype,
2,405✔
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✔
UNCOV
542
                r = mount_option_supported(fstype, "rescue=nologreplay", NULL);
×
UNCOV
543
                if (r == -EAGAIN) {
×
UNCOV
544
                        log_debug_errno(r, "Failed to check for btrfs 'rescue=nologreplay' option, assuming old kernel with 'norecovery': %m");
×
UNCOV
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) {
294✔
586
        _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
294✔
587
        int mount_id, r;
294✔
588
        char *e;
294✔
589

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

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

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

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

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

613
                if (mid != mount_id)
10,707✔
614
                        continue;
10,413✔
615

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

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

625
        return false;
227✔
626
}
627

628
static int mount_fd(
95,654✔
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);
95,654✔
636

637
        if (mount(source, FORMAT_PROC_FD_PATH(target_fd), filesystemtype, mountflags, data) < 0) {
95,654✔
638
                if (errno != ENOENT)
1,120✔
639
                        return -errno;
1,120✔
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)
555✔
644
                        return -ENOSYS;
645

646
                return -ENOENT;
555✔
647
        }
648

649
        return 0;
94,534✔
650
}
651

652
int mount_nofollow(
97,129✔
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;
97,129✔
660

661
        assert(target);
97,129✔
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);
97,129✔
673
        if (fd < 0)
97,129✔
674
                return -errno;
1,475✔
675

676
        return mount_fd(source, fd, filesystemtype, mountflags, data);
95,654✔
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,777✔
711
        return IN_SET(flag, 0, MS_SHARED, MS_PRIVATE, MS_SLAVE);
2,777✔
712
}
713

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

718
        if (cache >= 0)
6,772✔
719
                return cache;
1,738✔
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,034✔
723
        if (r == 0 || ERRNO_IS_NOT_SUPPORTED(r)) /* This should return an error if it is working properly */
5,034✔
724
                return (cache = false);
×
725

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

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

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

735
        if (cache >= 0)
5,937✔
736
                return cache ? MS_NOSYMFOLLOW : 0;
3,093✔
737

738
        if (!mount_new_api_supported())
2,844✔
UNCOV
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,844✔
745
        if (fsfd < 0) {
2,844✔
746
                if (ERRNO_IS_NOT_SUPPORTED(errno))
2✔
UNCOV
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,842✔
UNCOV
754
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
755
                        goto not_supported;
×
756

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

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

UNCOV
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,842✔
771
                          &(struct mount_attr) {
2,842✔
772
                                  .attr_set = MOUNT_ATTR_NOSYMFOLLOW,
773
                          }, sizeof(struct mount_attr)) < 0) {
UNCOV
774
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
UNCOV
775
                        goto not_supported;
×
776

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

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

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

789
int mount_option_supported(const char *fstype, const char *key, const char *value) {
4,574✔
790
        _cleanup_close_ int fd = -EBADF;
4,574✔
791
        int r;
4,574✔
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,574✔
797
        assert(key);
4,574✔
798

799
        fd = fsopen(fstype, FSOPEN_CLOEXEC);
4,574✔
800
        if (fd < 0) {
4,574✔
801
                if (ERRNO_IS_NOT_SUPPORTED(errno))
1✔
802
                        return -EAGAIN;  /* new mount API not available → don't know */
803

804
                return log_debug_errno(errno, "Failed to open superblock context for '%s': %m", fstype);
1✔
805
        }
806

807
        /* Various file systems have not been converted to the new mount API yet. For such file systems
808
         * fsconfig() with FSCONFIG_SET_STRING/FSCONFIG_SET_FLAG never fail. Which sucks, because we want to
809
         * use it for testing support, after all. Let's hence do a check if the file system got converted yet
810
         * first. */
811
        if (fsconfig(fd, FSCONFIG_SET_FD, "adefinitelynotexistingmountoption", NULL, fd) < 0) {
4,573✔
812
                /* If FSCONFIG_SET_FD is not supported for the fs, then the file system was not converted to
813
                 * the new mount API yet. If it returns EINVAL the mount option doesn't exist, but the fstype
814
                 * is converted. */
815
                if (errno == EOPNOTSUPP)
4,573✔
816
                        return -EAGAIN; /* FSCONFIG_SET_FD not supported on the fs, hence not converted to new mount API → don't know */
817
                if (errno != EINVAL)
4,571✔
UNCOV
818
                        return log_debug_errno(errno, "Failed to check if file system has been converted to new mount API: %m");
×
819

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

825
        if (value)
4,571✔
826
                r = fsconfig(fd, FSCONFIG_SET_STRING, key, value, 0);
1,258✔
827
        else
828
                r = fsconfig(fd, FSCONFIG_SET_FLAG, key, NULL, 0);
3,313✔
829
        if (r < 0) {
4,571✔
830
                if (errno == EINVAL)
183✔
831
                        return false; /* EINVAL means option not supported. */
832

UNCOV
833
                return log_debug_errno(errno, "Failed to set '%s%s%s' on '%s' superblock context: %m",
×
834
                                       key, value ? "=" : "", strempty(value), fstype);
835
        }
836

837
        return true; /* works! */
838
}
839

840
bool path_below_api_vfs(const char *p) {
7,487✔
841
        assert(p);
7,487✔
842

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