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

systemd / systemd / 15232239991

24 May 2025 08:01PM UTC coverage: 72.053% (-0.02%) from 72.07%
15232239991

push

github

web-flow
docs: add man pages for sd_device_enumerator_[new,ref,unref,unrefp] (#37586)

For #20929.

299160 of 415197 relevant lines covered (72.05%)

703671.29 hits per line

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

50.0
/src/shared/mount-setup.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <sys/mount.h>
4
#include <unistd.h>
5

6
#include "alloc-util.h"
7
#include "conf-files.h"
8
#include "dev-setup.h"
9
#include "efivars.h"
10
#include "errno-util.h"
11
#include "fd-util.h"
12
#include "fileio.h"
13
#include "label-util.h"
14
#include "log.h"
15
#include "mkdir-label.h"
16
#include "mount-setup.h"
17
#include "mount-util.h"
18
#include "mountpoint-util.h"
19
#include "path-util.h"
20
#include "recurse-dir.h"
21
#include "smack-util.h"
22
#include "string-util.h"
23
#include "strv.h"
24
#include "time-util.h"
25
#include "virt.h"
26

27
typedef enum MountMode {
28
        MNT_NONE              = 0,
29
        MNT_FATAL             = 1 << 0,
30
        MNT_IN_CONTAINER      = 1 << 1,
31
        MNT_CHECK_WRITABLE    = 1 << 2,
32
        MNT_FOLLOW_SYMLINK    = 1 << 3,
33
        MNT_USRQUOTA_GRACEFUL = 1 << 4,
34
} MountMode;
35

36
typedef struct MountPoint {
37
        const char *what;
38
        const char *where;
39
        const char *type;
40
        const char *options;
41
        unsigned long flags;
42
        MountMode mode;
43
        bool (*condition_fn)(void);
44
} MountPoint;
45

46
static bool cgroupfs_recursiveprot_supported(void) {
182✔
47
        int r;
182✔
48

49
        /* Added in kernel 5.7 */
50

51
        r = mount_option_supported("cgroup2", "memory_recursiveprot", /* value = */ NULL);
182✔
52
        if (r < 0)
182✔
53
                log_debug_errno(r, "Failed to determine whether cgroupfs supports 'memory_recursiveprot' mount option, assuming not: %m");
×
54
        else if (r == 0)
182✔
55
                log_debug("'memory_recursiveprot' not supported by cgroupfs, not using mount option.");
×
56

57
        return r > 0;
182✔
58
}
59

60
int mount_cgroupfs(const char *path) {
122✔
61
        assert(path);
122✔
62

63
        /* Mount a separate cgroupfs instance, taking all options we initial set into account. This is
64
         * especially useful when cgroup namespace is *not* employed, since the kernel overrides all
65
         * previous options if a new mount is established in initial cgns (c.f.
66
         * https://github.com/torvalds/linux/blob/b69bb476dee99d564d65d418e9a20acca6f32c3f/kernel/cgroup/cgroup.c#L1984)
67
         *
68
         * The options shall be kept in sync with those in mount_table below. */
69

70
        return mount_nofollow_verbose(LOG_ERR, "cgroup2", path, "cgroup2",
122✔
71
                                      MS_NOSUID|MS_NOEXEC|MS_NODEV,
72
                                      cgroupfs_recursiveprot_supported() ? "nsdelegate,memory_recursiveprot" : "nsdelegate");
122✔
73
}
74

75
static const MountPoint mount_table[] = {
76
        { "proc",        "/proc",                     "proc",       NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
77
          MNT_FATAL|MNT_IN_CONTAINER|MNT_FOLLOW_SYMLINK },
78
        { "sysfs",       "/sys",                      "sysfs",      NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
79
          MNT_FATAL|MNT_IN_CONTAINER },
80
        { "devtmpfs",    "/dev",                      "devtmpfs",   "mode=0755" TMPFS_LIMITS_DEV,               MS_NOSUID|MS_STRICTATIME,
81
          MNT_FATAL|MNT_IN_CONTAINER },
82
        { "securityfs",  "/sys/kernel/security",      "securityfs", NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
83
          MNT_NONE                   },
84
#if ENABLE_SMACK
85
        { "smackfs",     "/sys/fs/smackfs",           "smackfs",    "smackfsdef=*",                             MS_NOSUID|MS_NOEXEC|MS_NODEV,
86
          MNT_FATAL, mac_smack_use   },
87
        { "tmpfs",       "/dev/shm",                  "tmpfs",      "mode=01777,smackfsroot=*",                 MS_NOSUID|MS_NODEV|MS_STRICTATIME,
88
          MNT_FATAL|MNT_USRQUOTA_GRACEFUL, mac_smack_use },
89
#endif
90
        { "tmpfs",       "/dev/shm",                  "tmpfs",      "mode=01777",                               MS_NOSUID|MS_NODEV|MS_STRICTATIME,
91
          MNT_FATAL|MNT_IN_CONTAINER|MNT_USRQUOTA_GRACEFUL },
92
        { "devpts",      "/dev/pts",                  "devpts",     "mode=" STRINGIFY(TTY_MODE) ",gid=" STRINGIFY(TTY_GID), MS_NOSUID|MS_NOEXEC,
93
          MNT_IN_CONTAINER           },
94
#if ENABLE_SMACK
95
        { "tmpfs",       "/run",                      "tmpfs",      "mode=0755,smackfsroot=*" TMPFS_LIMITS_RUN, MS_NOSUID|MS_NODEV|MS_STRICTATIME,
96
          MNT_FATAL, mac_smack_use   },
97
#endif
98
        { "tmpfs",       "/run",                      "tmpfs",      "mode=0755" TMPFS_LIMITS_RUN,               MS_NOSUID|MS_NODEV|MS_STRICTATIME,
99
          MNT_FATAL|MNT_IN_CONTAINER },
100
        { "cgroup2",     "/sys/fs/cgroup",            "cgroup2",    "nsdelegate,memory_recursiveprot",          MS_NOSUID|MS_NOEXEC|MS_NODEV,
101
          MNT_FATAL|MNT_IN_CONTAINER|MNT_CHECK_WRITABLE, cgroupfs_recursiveprot_supported },
102
        { "cgroup2",     "/sys/fs/cgroup",            "cgroup2",    "nsdelegate",                               MS_NOSUID|MS_NOEXEC|MS_NODEV,
103
          MNT_FATAL|MNT_IN_CONTAINER|MNT_CHECK_WRITABLE },
104
#if ENABLE_PSTORE
105
        { "pstore",      "/sys/fs/pstore",            "pstore",     NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
106
          MNT_NONE                   },
107
#endif
108
#if ENABLE_EFI
109
        { "efivarfs",    "/sys/firmware/efi/efivars", "efivarfs",   NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
110
          MNT_NONE, is_efi_boot      },
111
#endif
112
        { "bpf",         "/sys/fs/bpf",               "bpf",        "mode=0700",                                MS_NOSUID|MS_NOEXEC|MS_NODEV,
113
          MNT_NONE                   },
114
};
115

116
/* The first three entries we might need before SELinux is up. The
117
 * fourth (securityfs) is needed by IMA to load a custom policy. The
118
 * other ones we can delay until SELinux and IMA are loaded. When
119
 * SMACK is enabled we need smackfs, too, so it's a fifth one. */
120
#if ENABLE_SMACK
121
#define N_EARLY_MOUNT 5
122
#else
123
#define N_EARLY_MOUNT 4
124
#endif
125

126
assert_cc(N_EARLY_MOUNT <= ELEMENTSOF(mount_table));
127

128
bool mount_point_is_api(const char *path) {
132,183✔
129
        /* Checks if this mount point is considered "API", and hence
130
         * should be ignored */
131

132
        FOREACH_ELEMENT(i, mount_table)
1,789,294✔
133
                if (path_equal(path, i->where))
1,692,884✔
134
                        return true;
135

136
        return path_startswith(path, "/sys/fs/cgroup/");
96,410✔
137
}
138

139
bool mount_point_ignore(const char *path) {
96,398✔
140
        /* These are API file systems that might be mounted by other software, we just list them here so that
141
         * we know that we should ignore them. */
142
        FOREACH_STRING(i,
569,981✔
143
                       /* SELinux file systems */
144
                       "/sys/fs/selinux",
145
                       /* Container bind mounts */
146
                       "/dev/console",
147
                       "/proc/kmsg",
148
                       "/proc/sys",
149
                       "/proc/sys/kernel/random/boot_id")
150
                if (path_equal(path, i))
478,387✔
151
                        return true;
4,804✔
152

153
        if (path_startswith(path, "/run/host")) /* All mounts passed in from the container manager are
91,594✔
154
                                                 * something we better ignore. */
155
                return true;
7,206✔
156

157
        return false;
158
}
159

160
static int mount_one(const MountPoint *p, bool relabel) {
975✔
161
        int r, priority;
975✔
162

163
        assert(p);
975✔
164
        assert(p->what);
975✔
165
        assert(p->where);
975✔
166
        assert(p->type);
975✔
167

168
        priority = FLAGS_SET(p->mode, MNT_FATAL) ? LOG_ERR : LOG_DEBUG;
975✔
169

170
        if (p->condition_fn && !p->condition_fn())
975✔
171
                return 0;
975✔
172

173
        /* Relabel first, just in case */
174
        if (relabel)
730✔
175
                (void) label_fix(p->where, LABEL_IGNORE_ENOENT|LABEL_IGNORE_EROFS);
×
176

177
        r = path_is_mount_point_full(p->where, /* root = */ NULL, AT_SYMLINK_FOLLOW);
730✔
178
        if (r < 0 && r != -ENOENT) {
730✔
179
                log_full_errno(priority, r, "Failed to determine whether %s is a mount point: %m", p->where);
×
180
                return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
×
181
        }
182
        if (r > 0)
730✔
183
                return 0;
184

185
        if (!FLAGS_SET(p->mode, MNT_IN_CONTAINER) && detect_container() > 0)
244✔
186
                return 0;
187

188
        /* The access mode here doesn't really matter too much, since
189
         * the mounted file system will take precedence anyway. */
190
        if (relabel)
124✔
191
                (void) mkdir_p_label(p->where, 0755);
×
192
        else
193
                (void) mkdir_p(p->where, 0755);
124✔
194

195
        _cleanup_free_ char *extend_options = NULL;
124✔
196
        const char *o = p->options;
124✔
197
        if (FLAGS_SET(p->mode, MNT_USRQUOTA_GRACEFUL)) {
124✔
198
                r = mount_option_supported(p->type, "usrquota", /* value= */ NULL);
12✔
199
                if (r < 0)
12✔
200
                        log_full_errno(priority, r, "Unable to determine whether %s supports 'usrquota' mount option, assuming not: %m", p->type);
×
201
                else if (r == 0)
12✔
202
                        log_debug("Not enabling 'usrquota' on '%s' as kernel lacks support for it.", p->where);
×
203
                else {
204
                        if (!strextend_with_separator(&extend_options, ",", p->options ?: POINTER_MAX, "usrquota"))
24✔
205
                                return log_oom();
×
206

207
                        o = extend_options;
12✔
208
                }
209
        }
210

211
        log_debug("Mounting %s to %s of type %s with options %s.",
143✔
212
                  p->what,
213
                  p->where,
214
                  p->type,
215
                  o ?: "''");
216

217
        r = mount_verbose_full(priority, p->what, p->where, p->type, p->flags, o, FLAGS_SET(p->mode, MNT_FOLLOW_SYMLINK));
124✔
218
        if (r < 0)
124✔
219
                return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
×
220

221
        /* Relabel again, since we now mounted something fresh here */
222
        if (relabel)
124✔
223
                (void) label_fix(p->where, 0);
×
224

225
        if (FLAGS_SET(p->mode, MNT_CHECK_WRITABLE))
124✔
226
                if (access(p->where, W_OK) < 0) {
12✔
227
                        r = -errno;
×
228

229
                        (void) umount2(p->where, UMOUNT_NOFOLLOW);
×
230
                        (void) rmdir(p->where);
×
231

232
                        log_full_errno(priority, r, "Mount point '%s' not writable after mounting, undoing: %m", p->where);
×
233
                        return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
×
234
                }
235

236
        return 1;
237
}
238

239
static int mount_points_setup(size_t n, bool loaded_policy) {
75✔
240
        int r = 0;
75✔
241

242
        assert(n <= ELEMENTSOF(mount_table));
75✔
243

244
        FOREACH_ARRAY(mp, mount_table, n)
1,050✔
245
                RET_GATHER(r, mount_one(mp, loaded_policy));
975✔
246

247
        return r;
75✔
248
}
249

250
int mount_setup_early(void) {
15✔
251
        /* Do a minimal mount of /proc and friends to enable the most basic stuff, such as SELinux */
252
        return mount_points_setup(N_EARLY_MOUNT, /* loaded_policy= */ false);
15✔
253
}
254

255
#if HAVE_SELINUX || ENABLE_SMACK
256
static int relabel_cb(
×
257
                RecurseDirEvent event,
258
                const char *path,
259
                int dir_fd,
260
                int inode_fd,
261
                const struct dirent *de,
262
                const struct statx *sx,
263
                void *userdata) {
264

265
        switch (event) {
×
266

267
        case RECURSE_DIR_LEAVE:
268
        case RECURSE_DIR_SKIP_MOUNT:
269
                /* If we already saw this dirent when entering it or this is a dirent that on a different
270
                 * mount, don't relabel it. */
271
                return RECURSE_DIR_CONTINUE;
272

273
        case RECURSE_DIR_ENTER:
×
274
                /* /run/initramfs/ + /run/nextroot/ are static data and big, no need to dynamically relabel
275
                 * its contents at boot... */
276
                if (PATH_STARTSWITH_SET(path, "/run/initramfs", "/run/nextroot"))
×
277
                        return RECURSE_DIR_SKIP_ENTRY;
×
278

279
                _fallthrough_;
×
280

281
        default:
282
                /* Otherwise, label it, even if we had trouble stat()ing it and similar. SELinux can figure this out */
283
                (void) label_fix(path, 0);
×
284
                return RECURSE_DIR_CONTINUE;
×
285
        }
286
}
287

288
static int relabel_tree(const char *path) {
×
289
        int r;
×
290

291
        r = recurse_dir_at(AT_FDCWD, path, 0, UINT_MAX, RECURSE_DIR_ENSURE_TYPE|RECURSE_DIR_SAME_MOUNT, relabel_cb, NULL);
×
292
        if (r < 0)
×
293
                log_debug_errno(r, "Failed to recursively relabel '%s': %m", path);
×
294

295
        return r;
×
296
}
297

298
static int relabel_extra(void) {
×
299
        _cleanup_strv_free_ char **files = NULL;
×
300
        int r, c = 0;
×
301

302
        /* Support for relabelling additional files or directories after loading the policy. For this, code in the
303
         * initrd simply has to drop in *.relabel files into /run/systemd/relabel-extra.d/. We'll read all such files
304
         * expecting one absolute path by line and will relabel each (and everyone below that in case the path refers
305
         * to a directory). These drop-in files are supposed to be absolutely minimal, and do not understand comments
306
         * and such. After the operation succeeded the files are removed, and the drop-in directory as well, if
307
         * possible.
308
         */
309

310
        r = conf_files_list(&files, ".relabel", NULL,
×
311
                            CONF_FILES_FILTER_MASKED | CONF_FILES_REGULAR,
312
                            "/run/systemd/relabel-extra.d/");
313
        if (r < 0)
×
314
                return log_error_errno(r, "Failed to enumerate /run/systemd/relabel-extra.d/, ignoring: %m");
×
315

316
        STRV_FOREACH(file, files) {
×
317
                _cleanup_fclose_ FILE *f = NULL;
×
318

319
                f = fopen(*file, "re");
×
320
                if (!f) {
×
321
                        log_warning_errno(errno, "Failed to open %s, ignoring: %m", *file);
×
322
                        continue;
×
323
                }
324

325
                for (;;) {
×
326
                        _cleanup_free_ char *line = NULL;
×
327

328
                        r = read_line(f, LONG_LINE_MAX, &line);
×
329
                        if (r < 0) {
×
330
                                log_warning_errno(r, "Failed to read %s, ignoring: %m", *file);
×
331
                                break;
332
                        }
333
                        if (r == 0) /* EOF */
×
334
                                break;
335

336
                        path_simplify(line);
×
337

338
                        if (!path_is_normalized(line)) {
×
339
                                log_warning("Path to relabel is not normalized, ignoring: %s", line);
×
340
                                continue;
×
341
                        }
342

343
                        if (!path_is_absolute(line)) {
×
344
                                log_warning("Path to relabel is not absolute, ignoring: %s", line);
×
345
                                continue;
×
346
                        }
347

348
                        log_debug("Relabelling additional file/directory '%s'.", line);
×
349
                        (void) label_fix(line, 0);
×
350
                        (void) relabel_tree(line);
×
351
                        c++;
×
352
                }
353

354
                if (unlink(*file) < 0)
×
355
                        log_warning_errno(errno, "Failed to remove %s, ignoring: %m", *file);
×
356
        }
357

358
        /* Remove when we complete things. */
359
        if (rmdir("/run/systemd/relabel-extra.d") < 0 &&
×
360
            errno != ENOENT)
×
361
                log_warning_errno(errno, "Failed to remove /run/systemd/relabel-extra.d/ directory: %m");
×
362

363
        return c;
364
}
365
#endif
366

367
int mount_setup(bool loaded_policy, bool leave_propagation) {
60✔
368
        int r;
60✔
369

370
        r = mount_points_setup(ELEMENTSOF(mount_table), loaded_policy);
60✔
371
        if (r < 0)
60✔
372
                return r;
373

374
#if HAVE_SELINUX || ENABLE_SMACK
375
        /* Nodes in devtmpfs and /run need to be manually updated for
376
         * the appropriate labels, after mounting. The other virtual
377
         * API file systems like /sys and /proc do not need that, they
378
         * use the same label for all their files. */
379
        if (loaded_policy) {
60✔
380
                usec_t before_relabel, after_relabel;
×
381
                int n_extra;
×
382

383
                before_relabel = now(CLOCK_MONOTONIC);
×
384

385
                FOREACH_STRING(i, "/dev", "/dev/shm", "/run")
×
386
                        (void) relabel_tree(i);
×
387

388
                n_extra = relabel_extra();
×
389

390
                after_relabel = now(CLOCK_MONOTONIC);
×
391

392
                log_info("Relabeled /dev/, /dev/shm/, /run/%s in %s.",
×
393
                         n_extra > 0 ? ", and additional files" : "",
394
                         FORMAT_TIMESPAN(after_relabel - before_relabel, 0));
395
        }
396
#endif
397

398
        /* Create a few default symlinks, which are normally created
399
         * by udevd, but some scripts might need them before we start
400
         * udevd. */
401
        dev_setup(NULL, UID_INVALID, GID_INVALID);
60✔
402

403
        /* Mark the root directory as shared in regards to mount propagation. The kernel defaults to "private", but we
404
         * think it makes more sense to have a default of "shared" so that nspawn and the container tools work out of
405
         * the box. If specific setups need other settings they can reset the propagation mode to private if
406
         * needed. Note that we set this only when we are invoked directly by the kernel. If we are invoked by a
407
         * container manager we assume the container manager knows what it is doing (for example, because it set up
408
         * some directories with different propagation modes). */
409
        if (detect_container() <= 0 && !leave_propagation)
60✔
410
                if (mount(NULL, "/", NULL, MS_REC|MS_SHARED, NULL) < 0)
15✔
411
                        log_warning_errno(errno, "Failed to set up the root directory for shared mount propagation: %m");
×
412

413
        /* Create a few directories we always want around, Note that sd_booted() checks for /run/systemd/system, so
414
         * this mkdir really needs to stay for good, otherwise software that copied sd-daemon.c into their sources will
415
         * misdetect systemd. */
416
        (void) mkdir_label("/run/systemd", 0755);
60✔
417
        (void) mkdir_label("/run/systemd/system", 0755);
60✔
418

419
        /* Make sure there's always a place where sandboxed environments can mount root file systems they are
420
         * about to move into, even when unprivileged, without having to create a temporary one in /tmp/
421
         * (which they then have to keep track of and clean) */
422
        (void) mkdir_label("/run/systemd/mount-rootfs", 0555);
60✔
423

424
        /* Make sure we have a mount point to hide in sandboxes */
425
        (void) mkdir_label("/run/credentials", 0755);
60✔
426

427
        /* Also create /run/systemd/inaccessible nodes, so that we always have something to mount
428
         * inaccessible nodes from. If we run in a container the host might have created these for us already
429
         * in /run/host/inaccessible/. Use those if we can, since that way we likely get access to block/char
430
         * device nodes that are inaccessible, and if userns is used to nodes that are on mounts owned by a
431
         * userns outside the container and thus nicely read-only and not remountable. */
432
        if (access("/run/host/inaccessible/", F_OK) < 0) {
60✔
433
                if (errno != ENOENT)
20✔
434
                        log_debug_errno(errno, "Failed to check if /run/host/inaccessible exists, ignoring: %m");
×
435

436
                (void) make_inaccessible_nodes("/run/systemd", UID_INVALID, GID_INVALID);
20✔
437
        } else
438
                (void) symlink("../host/inaccessible", "/run/systemd/inaccessible");
40✔
439

440
        return 0;
441
}
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