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

systemd / systemd / 14255132001

03 Apr 2025 10:15PM UTC coverage: 71.907% (-0.05%) from 71.955%
14255132001

push

github

bluca
mkosi: Fix arch build script version sed expression

Yours truly got rid of the _tag variable in the Arch Linux PKGBUILD
a while ago, so actually adapt the build script to that by changing
the pkgver= variable instead.

297094 of 413162 relevant lines covered (71.91%)

653278.23 hits per line

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

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

3
#include <errno.h>
4
#include <stdlib.h>
5
#include <sys/mount.h>
6
#include <sys/stat.h>
7
#include <sys/statvfs.h>
8
#include <unistd.h>
9
#include <linux/loop.h>
10

11
#include "alloc-util.h"
12
#include "chase.h"
13
#include "dissect-image.h"
14
#include "exec-util.h"
15
#include "extract-word.h"
16
#include "fd-util.h"
17
#include "fileio.h"
18
#include "fs-util.h"
19
#include "fstab-util.h"
20
#include "glyph-util.h"
21
#include "hashmap.h"
22
#include "initrd-util.h"
23
#include "label-util.h"
24
#include "libmount-util.h"
25
#include "missing_syscall.h"
26
#include "mkdir-label.h"
27
#include "mount-util.h"
28
#include "mountpoint-util.h"
29
#include "namespace-util.h"
30
#include "parse-util.h"
31
#include "path-util.h"
32
#include "process-util.h"
33
#include "set.h"
34
#include "sort-util.h"
35
#include "stat-util.h"
36
#include "stdio-util.h"
37
#include "string-table.h"
38
#include "string-util.h"
39
#include "strv.h"
40
#include "tmpfile-util.h"
41
#include "user-util.h"
42

43
int umount_recursive_full(const char *prefix, int flags, char **keep) {
8,747✔
44
        _cleanup_fclose_ FILE *f = NULL;
8,747✔
45
        int n = 0, r;
8,747✔
46

47
        /* Try to umount everything recursively below a directory. Also, take care of stacked mounts, and
48
         * keep unmounting them until they are gone. */
49

50
        f = fopen("/proc/self/mountinfo", "re"); /* Pin the file, in case we unmount /proc/ as part of the logic here */
8,747✔
51
        if (!f)
8,747✔
52
                return log_debug_errno(errno, "Failed to open /proc/self/mountinfo: %m");
×
53

54
        for (;;) {
45,169✔
55
                _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
18,211✔
56
                _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
26,958✔
57
                bool again = false;
26,958✔
58

59
                r = libmount_parse_mountinfo(f, &table, &iter);
26,958✔
60
                if (r < 0)
26,958✔
61
                        return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
62

63
                for (;;) {
2,835,862✔
64
                        bool shall_keep = false;
1,431,410✔
65
                        struct libmnt_fs *fs;
1,431,410✔
66
                        const char *path;
1,431,410✔
67

68
                        r = mnt_table_next_fs(table, iter, &fs);
1,431,410✔
69
                        if (r == 1)
1,431,410✔
70
                                break;
71
                        if (r < 0)
1,422,663✔
72
                                return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
73

74
                        path = mnt_fs_get_target(fs);
1,422,663✔
75
                        if (!path)
1,422,663✔
76
                                continue;
1,404,452✔
77

78
                        if (prefix && !path_startswith(path, prefix)) {
2,844,995✔
79
                                // FIXME: This is extremely noisy, we're probably doing something very wrong
80
                                // to trigger this so often, needs more investigation.
81
                                // log_trace("Not unmounting %s, outside of prefix: %s", path, prefix);
82
                                continue;
1,395,055✔
83
                        }
84

85
                        STRV_FOREACH(k, keep)
27,678✔
86
                                /* Match against anything in the path to the dirs to keep, or below the dirs to keep */
87
                                if (path_startswith(path, *k) || path_startswith(*k, path)) {
346✔
88
                                        shall_keep = true;
276✔
89
                                        break;
276✔
90
                                }
91
                        if (shall_keep) {
27,884✔
92
                                log_debug("Not unmounting %s, referenced by keep list.", path);
276✔
93
                                continue;
276✔
94
                        }
95

96
                        if (umount2(path, flags | UMOUNT_NOFOLLOW) < 0) {
27,332✔
97
                                log_debug_errno(errno, "Failed to umount %s, ignoring: %m", path);
9,121✔
98
                                continue;
9,121✔
99
                        }
100

101
                        log_trace("Successfully unmounted %s", path);
18,211✔
102

103
                        again = true;
18,211✔
104
                        n++;
18,211✔
105

106
                        break;
18,211✔
107
                }
108

109
                if (!again)
8,747✔
110
                        break;
111

112
                rewind(f);
18,211✔
113
        }
114

115
        return n;
8,747✔
116
}
117

118
#define MS_CONVERTIBLE_FLAGS (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_NOSYMFOLLOW)
119

120
static uint64_t ms_flags_to_mount_attr(unsigned long a) {
39,614✔
121
        uint64_t f = 0;
39,614✔
122

123
        if (FLAGS_SET(a, MS_RDONLY))
39,614✔
124
                f |= MOUNT_ATTR_RDONLY;
1,529✔
125

126
        if (FLAGS_SET(a, MS_NOSUID))
39,614✔
127
                f |= MOUNT_ATTR_NOSUID;
18,280✔
128

129
        if (FLAGS_SET(a, MS_NODEV))
39,614✔
130
                f |= MOUNT_ATTR_NODEV;
2✔
131

132
        if (FLAGS_SET(a, MS_NOEXEC))
39,614✔
133
                f |= MOUNT_ATTR_NOEXEC;
2✔
134

135
        if (FLAGS_SET(a, MS_NOSYMFOLLOW))
39,614✔
136
                f |= MOUNT_ATTR_NOSYMFOLLOW;
×
137

138
        return f;
39,614✔
139
}
140

141
static bool skip_mount_set_attr = false;
142

143
/* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
144
 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
145
int bind_remount_recursive_with_mountinfo(
37,216✔
146
                const char *prefix,
147
                unsigned long new_flags,
148
                unsigned long flags_mask,
149
                char **deny_list,
150
                FILE *proc_self_mountinfo) {
151

152
        _cleanup_fclose_ FILE *proc_self_mountinfo_opened = NULL;
37,216✔
153
        _cleanup_set_free_ Set *done = NULL;
37,216✔
154
        unsigned n_tries = 0;
37,216✔
155
        int r;
37,216✔
156

157
        assert(prefix);
37,216✔
158

159
        if ((flags_mask & ~MS_CONVERTIBLE_FLAGS) == 0 && strv_isempty(deny_list) && !skip_mount_set_attr) {
54,718✔
160
                /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
161

162
                if (mount_setattr(AT_FDCWD, prefix, AT_SYMLINK_NOFOLLOW|AT_RECURSIVE,
17,502✔
163
                                  &(struct mount_attr) {
17,502✔
164
                                          .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
17,502✔
165
                                          .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
17,502✔
166
                                  }, MOUNT_ATTR_SIZE_VER0) < 0) {
167

168
                        log_debug_errno(errno, "mount_setattr() failed, falling back to classic remounting: %m");
2✔
169

170
                        /* We fall through to classic behaviour if not supported (i.e. kernel < 5.12). We
171
                         * also do this for all other kinds of errors since they are so many different, and
172
                         * mount_setattr() has no graceful mode where it continues despite seeing errors one
173
                         * some mounts, but we want that. Moreover mount_setattr() only works on the mount
174
                         * point inode itself, not a non-mount point inode, and we want to support arbitrary
175
                         * prefixes here. */
176

177
                        if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
2✔
178
                                skip_mount_set_attr = true;
×
179
                } else
180
                        return 0; /* Nice, this worked! */
17,500✔
181
        }
182

183
        if (!proc_self_mountinfo) {
19,716✔
184
                r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo_opened);
3✔
185
                if (r < 0)
3✔
186
                        return r;
187

188
                proc_self_mountinfo = proc_self_mountinfo_opened;
3✔
189
        }
190

191
        /* Recursively remount a directory (and all its submounts) with desired flags (MS_READONLY,
192
         * MS_NOSUID, MS_NOEXEC). If the directory is already mounted, we reuse the mount and simply mark it
193
         * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write operation), ditto for other flags. If it
194
         * isn't we first make it one. Afterwards we apply (or remove) the flags to all submounts we can
195
         * access, too. When mounts are stacked on the same mount point we only care for each individual
196
         * "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We do
197
         * not have any effect on future submounts that might get propagated, they might be writable
198
         * etc. This includes future submounts that have been triggered via autofs. Also note that we can't
199
         * operate atomically here. Mounts established while we process the tree might or might not get
200
         * noticed and thus might or might not be covered.
201
         *
202
         * If the "deny_list" parameter is specified it may contain a list of subtrees to exclude from the
203
         * remount operation. Note that we'll ignore the deny list for the top-level path. */
204

205
        for (;;) {
39,436✔
206
                _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
39,436✔
207
                _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
39,436✔
208
                _cleanup_hashmap_free_ Hashmap *todo = NULL;
39,434✔
209
                bool top_autofs = false;
39,436✔
210

211
                if (n_tries++ >= 32) /* Let's not retry this loop forever */
39,436✔
212
                        return -EBUSY;
213

214
                rewind(proc_self_mountinfo);
39,436✔
215

216
                r = libmount_parse_mountinfo(proc_self_mountinfo, &table, &iter);
39,436✔
217
                if (r < 0)
39,436✔
218
                        return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
219

220
                for (;;) {
2,766,574✔
221
                        _cleanup_free_ char *d = NULL;
2,727,138✔
222
                        const char *path, *type, *opts;
2,766,574✔
223
                        unsigned long flags = 0;
2,766,574✔
224
                        struct libmnt_fs *fs;
2,766,574✔
225

226
                        r = mnt_table_next_fs(table, iter, &fs);
2,766,574✔
227
                        if (r == 1) /* EOF */
2,766,574✔
228
                                break;
229
                        if (r < 0)
2,727,138✔
230
                                return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
231

232
                        path = mnt_fs_get_target(fs);
2,727,138✔
233
                        if (!path)
2,727,138✔
234
                                continue;
×
235

236
                        if (!path_startswith(path, prefix))
2,727,138✔
237
                                continue;
2,659,325✔
238

239
                        type = mnt_fs_get_fstype(fs);
67,813✔
240
                        if (!type)
67,813✔
241
                                continue;
×
242

243
                        /* Let's ignore autofs mounts. If they aren't triggered yet, we want to avoid
244
                         * triggering them, as we don't make any guarantees for future submounts anyway. If
245
                         * they are already triggered, then we will find another entry for this. */
246
                        if (streq(type, "autofs")) {
67,813✔
247
                                top_autofs = top_autofs || path_equal(path, prefix);
6,368✔
248
                                continue;
3,184✔
249
                        }
250

251
                        if (set_contains(done, path))
64,629✔
252
                                continue;
23,323✔
253

254
                        /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
255
                         * we shall operate on. */
256
                        if (!path_equal(path, prefix)) {
41,306✔
257
                                bool deny_listed = false;
281,719✔
258

259
                                STRV_FOREACH(i, deny_list) {
281,719✔
260
                                        if (path_equal(*i, prefix))
278,115✔
261
                                                continue;
21,577✔
262

263
                                        if (!path_startswith(*i, prefix))
256,538✔
264
                                                continue;
138,483✔
265

266
                                        if (path_startswith(path, *i)) {
118,055✔
267
                                                deny_listed = true;
268
                                                log_trace("Not remounting %s deny-listed by %s, called for %s", path, *i, prefix);
269
                                                break;
270
                                        }
271
                                }
272

273
                                if (deny_listed)
21,588✔
274
                                        continue;
17,984✔
275
                        }
276

277
                        opts = mnt_fs_get_vfs_options(fs);
23,322✔
278
                        if (opts) {
23,322✔
279
                                r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
23,322✔
280
                                if (r < 0)
23,322✔
281
                                        log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
×
282
                        }
283

284
                        d = strdup(path);
23,322✔
285
                        if (!d)
23,322✔
286
                                return -ENOMEM;
287

288
                        r = hashmap_ensure_put(&todo, &path_hash_ops_free, d, ULONG_TO_PTR(flags));
23,322✔
289
                        if (r == -EEXIST)
23,322✔
290
                                /* If the same path was recorded, but with different mount flags, update it:
291
                                 * it means a mount point is overmounted, and libmount returns the "bottom" (or
292
                                 * older one) first, but we want to reapply the flags from the "top" (or newer
293
                                 * one). See: https://github.com/systemd/systemd/issues/20032
294
                                 * Note that this shouldn't really fail, as we were just told that the key
295
                                 * exists, and it's an update so we want 'd' to be freed immediately. */
296
                                r = hashmap_update(todo, d, ULONG_TO_PTR(flags));
8✔
297
                        if (r < 0)
23,322✔
298
                                return r;
299
                        if (r > 0)
23,322✔
300
                                TAKE_PTR(d);
23,280✔
301
                }
302

303
                /* Check if the top-level directory was among what we have seen so far. For that check both
304
                 * 'done' and 'todo'. Also check 'top_autofs' because if the top-level dir is an autofs we'll
305
                 * not include it in either set but will set this bool. */
306
                if (!set_contains(done, prefix) &&
39,436✔
307
                    !(top_autofs || hashmap_contains(todo, prefix))) {
19,718✔
308

309
                        /* The prefix directory itself is not yet a mount, make it one. */
310
                        r = mount_nofollow(prefix, prefix, NULL, MS_BIND|MS_REC, NULL);
2✔
311
                        if (r < 0)
2✔
312
                                return r;
313

314
                        /* Immediately rescan, so that we pick up the new mount's flags */
315
                        continue;
2✔
316
                }
317

318
                /* If we have no submounts to process anymore, we are done */
319
                if (hashmap_isempty(todo))
39,434✔
320
                        return 0;
321

322
                for (;;) {
42,997✔
323
                        unsigned long flags;
42,997✔
324
                        char *x = NULL;
42,997✔
325

326
                        /* Take the first mount from our list of mounts to still process */
327
                        flags = PTR_TO_ULONG(hashmap_steal_first_key_and_value(todo, (void**) &x));
42,997✔
328
                        if (!x)
42,997✔
329
                                break;
330

331
                        r = set_ensure_consume(&done, &path_hash_ops_free, x);
23,279✔
332
                        if (IN_SET(r, 0, -EEXIST))
23,279✔
333
                                continue; /* Already done */
222✔
334
                        if (r < 0)
23,279✔
335
                                return r;
×
336

337
                        /* Now, remount this with the new flags set, but exclude MS_RELATIME from it. (It's
338
                         * the default anyway, thus redundant, and in userns we'll get an error if we try to
339
                         * explicitly enable it) */
340
                        r = mount_nofollow(NULL, x, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
23,279✔
341
                        if (r < 0) {
23,279✔
342
                                int q;
222✔
343

344
                                /* OK, so the remount of this entry failed. We'll ultimately ignore this in
345
                                 * almost all cases (there are simply so many reasons why this can fail,
346
                                 * think autofs, NFS, FUSE, …), but let's generate useful debug messages at
347
                                 * the very least. */
348

349
                                q = path_is_mount_point(x);
222✔
350
                                if (IN_SET(q, 0, -ENOENT)) {
222✔
351
                                        /* Hmm, whaaaa? The mount point is not actually a mount point? Then
352
                                         * it is either obstructed by a later mount or somebody has been
353
                                         * racing against us and removed it. Either way the mount point
354
                                         * doesn't matter to us, let's ignore it hence. */
355
                                        log_debug_errno(r, "Mount point '%s' to remount is not a mount point anymore, ignoring remount failure: %m", x);
219✔
356
                                        continue;
219✔
357
                                }
358
                                if (q < 0) /* Any other error on this? Just log and continue */
3✔
359
                                        log_debug_errno(q, "Failed to determine whether '%s' is a mount point or not, ignoring: %m", x);
×
360

361
                                if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) == 0) { /* ignore MS_RELATIME while comparing */
3✔
362
                                        log_debug_errno(r, "Couldn't remount '%s', but the flags already match what we want, hence ignoring: %m", x);
×
363
                                        continue;
×
364
                                }
365

366
                                /* Make this fatal if this is the top-level mount */
367
                                if (path_equal(x, prefix))
3✔
368
                                        return r;
369

370
                                /* If this is not the top-level mount, then handle this gracefully: log but
371
                                 * otherwise ignore. With NFS, FUSE, autofs there are just too many reasons
372
                                 * this might fail without a chance for us to do anything about it, let's
373
                                 * hence be strict on the top-level mount and lenient on the inner ones. */
374
                                log_debug_errno(r, "Couldn't remount submount '%s' for unexpected reason, ignoring: %m", x);
3✔
375
                                continue;
3✔
376
                        }
377

378
                        log_trace("Remounted %s.", x);
23,057✔
379
                }
380
        }
381
}
382

383
int bind_remount_one_with_mountinfo(
2,304✔
384
                const char *path,
385
                unsigned long new_flags,
386
                unsigned long flags_mask,
387
                FILE *proc_self_mountinfo) {
388

389
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
2,304✔
390
        unsigned long flags = 0;
2,304✔
391
        struct libmnt_fs *fs;
2,304✔
392
        const char *opts;
2,304✔
393
        int r;
2,304✔
394

395
        assert(path);
2,304✔
396
        assert(proc_self_mountinfo);
2,304✔
397

398
        if ((flags_mask & ~MS_CONVERTIBLE_FLAGS) == 0 && !skip_mount_set_attr) {
2,304✔
399
                /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
400

401
                if (mount_setattr(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW,
2,304✔
402
                                  &(struct mount_attr) {
2,304✔
403
                                          .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
2,304✔
404
                                          .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
2,304✔
405
                                  }, MOUNT_ATTR_SIZE_VER0) < 0) {
406

407
                        log_debug_errno(errno, "mount_setattr() didn't work, falling back to classic remounting: %m");
4✔
408

409
                        if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
4✔
410
                                skip_mount_set_attr = true;
×
411
                } else
412
                        return 0; /* Nice, this worked! */
2,300✔
413
        }
414

415
        rewind(proc_self_mountinfo);
4✔
416

417
        table = mnt_new_table();
4✔
418
        if (!table)
4✔
419
                return -ENOMEM;
420

421
        r = mnt_table_parse_stream(table, proc_self_mountinfo, "/proc/self/mountinfo");
4✔
422
        if (r < 0)
4✔
423
                return r;
424

425
        fs = mnt_table_find_target(table, path, MNT_ITER_FORWARD);
4✔
426
        if (!fs) {
4✔
427
                r = access_nofollow(path, F_OK); /* Hmm, it's not in the mount table, but does it exist at all? */
4✔
428
                if (r < 0)
2✔
429
                        return r;
430

431
                return -EINVAL; /* Not a mount point we recognize */
2✔
432
        }
433

434
        opts = mnt_fs_get_vfs_options(fs);
×
435
        if (opts) {
×
436
                r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
×
437
                if (r < 0)
×
438
                        log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
×
439
        }
440

441
        r = mount_nofollow(NULL, path, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
×
442
        if (r < 0) {
×
443
                if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) != 0) /* Ignore MS_RELATIME again,
×
444
                                                                             * since kernel adds it in
445
                                                                             * everywhere, because it's the
446
                                                                             * default. */
447
                        return r;
448

449
                /* Let's handle redundant remounts gracefully */
450
                log_debug_errno(r, "Failed to remount '%s' but flags already match what we want, ignoring: %m", path);
4✔
451
        }
452

453
        return 0;
454
}
455

456
int bind_remount_one(const char *path, unsigned long new_flags, unsigned long flags_mask) {
53✔
457
        _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
53✔
458

459
        proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
53✔
460
        if (!proc_self_mountinfo)
53✔
461
                return log_debug_errno(errno, "Failed to open /proc/self/mountinfo: %m");
×
462

463
        return bind_remount_one_with_mountinfo(path, new_flags, flags_mask, proc_self_mountinfo);
53✔
464
}
465

466
static int mount_switch_root_pivot(int fd_newroot, const char *path) {
2,254✔
467
        assert(fd_newroot >= 0);
2,254✔
468
        assert(path);
2,254✔
469

470
        /* Let the kernel tuck the new root under the old one. */
471
        if (pivot_root(".", ".") < 0)
2,254✔
472
                return log_debug_errno(errno, "Failed to pivot root to new rootfs '%s': %m", path);
36✔
473

474
        /* Get rid of the old root and reveal our brand new root. (This will always operate on the top-most
475
         * mount on our cwd, regardless what our current directory actually points to.) */
476
        if (umount2(".", MNT_DETACH) < 0)
2,218✔
477
                return log_debug_errno(errno, "Failed to unmount old rootfs: %m");
×
478

479
        return 0;
480
}
481

482
static int mount_switch_root_move(int fd_newroot, const char *path) {
36✔
483
        assert(fd_newroot >= 0);
36✔
484
        assert(path);
36✔
485

486
        /* Move the new root fs */
487
        if (mount(".", "/", NULL, MS_MOVE, NULL) < 0)
36✔
488
                return log_debug_errno(errno, "Failed to move new rootfs '%s': %m", path);
×
489

490
        /* Also change root dir */
491
        if (chroot(".") < 0)
36✔
492
                return log_debug_errno(errno, "Failed to chroot to new rootfs '%s': %m", path);
×
493

494
        return 0;
495
}
496

497
int mount_switch_root_full(const char *path, unsigned long mount_propagation_flag, bool force_ms_move) {
2,256✔
498
        _cleanup_close_ int fd_newroot = -EBADF;
2,256✔
499
        int r, is_current_root;
2,256✔
500

501
        assert(path);
2,256✔
502
        assert(mount_propagation_flag_is_valid(mount_propagation_flag));
2,256✔
503

504
        fd_newroot = open(path, O_PATH|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
2,256✔
505
        if (fd_newroot < 0)
2,256✔
506
                return log_debug_errno(errno, "Failed to open new rootfs '%s': %m", path);
×
507

508
        is_current_root = path_is_root_at(fd_newroot, NULL);
2,256✔
509
        if (is_current_root < 0)
2,256✔
510
                return log_debug_errno(is_current_root, "Failed to determine if target dir is our root already: %m");
×
511

512
        /* Change into the new rootfs. */
513
        if (fchdir(fd_newroot) < 0)
2,256✔
514
                return log_debug_errno(errno, "Failed to chdir into new rootfs '%s': %m", path);
×
515

516
        /* Make this a NOP if we are supposed to switch to our current root fs. After all, both pivot_root()
517
         * and MS_MOVE don't like that. */
518
        if (!is_current_root) {
2,256✔
519
                if (!force_ms_move) {
2,254✔
520
                        r = mount_switch_root_pivot(fd_newroot, path);
2,254✔
521
                        if (r < 0) {
2,254✔
522
                                log_debug_errno(r, "Failed to pivot into new rootfs '%s', will try to use MS_MOVE instead: %m", path);
36✔
523
                                force_ms_move = true;
524
                        }
525
                }
526
                if (force_ms_move) {
527
                        /* Failed to pivot_root() fallback to MS_MOVE. For example, this may happen if the rootfs is
528
                         * an initramfs in which case pivot_root() isn't supported. */
529
                        r = mount_switch_root_move(fd_newroot, path);
36✔
530
                        if (r < 0)
36✔
531
                                return log_debug_errno(r, "Failed to switch to new rootfs '%s' with MS_MOVE: %m", path);
×
532
                }
533
        }
534

535
        log_debug("Successfully switched root to '%s'.", path);
2,256✔
536

537
        /* Finally, let's establish the requested propagation flags. */
538
        if (mount_propagation_flag == 0)
2,256✔
539
                return 0;
540

541
        if (mount(NULL, ".", NULL, mount_propagation_flag | MS_REC, NULL) < 0)
271✔
542
                return log_debug_errno(errno, "Failed to turn new rootfs '%s' into %s mount: %m",
×
543
                                       mount_propagation_flag_to_string(mount_propagation_flag), path);
544

545
        return 0;
546
}
547

548
int repeat_unmount(const char *path, int flags) {
15✔
549
        bool done = false;
15✔
550

551
        assert(path);
15✔
552

553
        /* If there are multiple mounts on a mount point, this
554
         * removes them all */
555

556
        for (;;) {
30✔
557
                if (umount2(path, flags) < 0) {
30✔
558

559
                        if (errno == EINVAL)
15✔
560
                                return done;
15✔
561

562
                        return -errno;
×
563
                }
564

565
                done = true;
566
        }
567
}
568

569
int mode_to_inaccessible_node(
4,789✔
570
                const char *runtime_dir,
571
                mode_t mode,
572
                char **ret) {
573

574
        /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
575
         * during early boot by PID 1. In some cases we lacked the privs to create the character and block
576
         * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
577
         * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
578
         * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
579
         * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
580
         * file nodes, and that's the most important thing that matters.
581
         *
582
         * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
583
         * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
584

585
        _cleanup_free_ char *d = NULL;
4,789✔
586
        const char *node;
4,789✔
587

588
        assert(ret);
4,789✔
589

590
        if (!runtime_dir)
4,789✔
591
                runtime_dir = "/run";
4✔
592

593
        if (S_ISLNK(mode))
4,789✔
594
                return -EINVAL;
595

596
        node = inode_type_to_string(mode);
4,789✔
597
        if (!node)
4,789✔
598
                return -EINVAL;
599

600
        d = path_join(runtime_dir, "systemd/inaccessible", node);
4,789✔
601
        if (!d)
4,789✔
602
                return -ENOMEM;
603

604
        /* On new kernels unprivileged users are permitted to create 0:0 char device nodes (because they also
605
         * act as whiteout inode for overlayfs), but no other char or block device nodes. On old kernels no
606
         * device node whatsoever may be created by unprivileged processes. Hence, if the caller asks for the
607
         * inaccessible block device node let's see if the block device node actually exists, and if not,
608
         * fall back to the character device node. From there fall back to the socket device node. This means
609
         * in the best case we'll get the right device node type — but if not we'll hopefully at least get a
610
         * device node at all. */
611

612
        if (S_ISBLK(mode) &&
4,789✔
613
            access(d, F_OK) < 0 && errno == ENOENT) {
×
614
                free(d);
×
615
                d = path_join(runtime_dir, "/systemd/inaccessible/chr");
×
616
                if (!d)
×
617
                        return -ENOMEM;
618
        }
619

620
        if (IN_SET(mode & S_IFMT, S_IFBLK, S_IFCHR) &&
5,234✔
621
            access(d, F_OK) < 0 && errno == ENOENT) {
445✔
622
                free(d);
×
623
                d = path_join(runtime_dir, "/systemd/inaccessible/sock");
×
624
                if (!d)
×
625
                        return -ENOMEM;
626
        }
627

628
        *ret = TAKE_PTR(d);
4,789✔
629
        return 0;
4,789✔
630
}
631

632
int mount_flags_to_string(unsigned long flags, char **ret) {
51,530✔
633
        static const struct {
51,530✔
634
                unsigned long flag;
635
                const char *name;
636
        } map[] = {
637
                { .flag = MS_RDONLY,      .name = "MS_RDONLY",      },
638
                { .flag = MS_NOSUID,      .name = "MS_NOSUID",      },
639
                { .flag = MS_NODEV,       .name = "MS_NODEV",       },
640
                { .flag = MS_NOEXEC,      .name = "MS_NOEXEC",      },
641
                { .flag = MS_SYNCHRONOUS, .name = "MS_SYNCHRONOUS", },
642
                { .flag = MS_REMOUNT,     .name = "MS_REMOUNT",     },
643
                { .flag = MS_MANDLOCK,    .name = "MS_MANDLOCK",    },
644
                { .flag = MS_DIRSYNC,     .name = "MS_DIRSYNC",     },
645
                { .flag = MS_NOSYMFOLLOW, .name = "MS_NOSYMFOLLOW", },
646
                { .flag = MS_NOATIME,     .name = "MS_NOATIME",     },
647
                { .flag = MS_NODIRATIME,  .name = "MS_NODIRATIME",  },
648
                { .flag = MS_BIND,        .name = "MS_BIND",        },
649
                { .flag = MS_MOVE,        .name = "MS_MOVE",        },
650
                { .flag = MS_REC,         .name = "MS_REC",         },
651
                { .flag = MS_SILENT,      .name = "MS_SILENT",      },
652
                { .flag = MS_POSIXACL,    .name = "MS_POSIXACL",    },
653
                { .flag = MS_UNBINDABLE,  .name = "MS_UNBINDABLE",  },
654
                { .flag = MS_PRIVATE,     .name = "MS_PRIVATE",     },
655
                { .flag = MS_SLAVE,       .name = "MS_SLAVE",       },
656
                { .flag = MS_SHARED,      .name = "MS_SHARED",      },
657
                { .flag = MS_RELATIME,    .name = "MS_RELATIME",    },
658
                { .flag = MS_KERNMOUNT,   .name = "MS_KERNMOUNT",   },
659
                { .flag = MS_I_VERSION,   .name = "MS_I_VERSION",   },
660
                { .flag = MS_STRICTATIME, .name = "MS_STRICTATIME", },
661
                { .flag = MS_LAZYTIME,    .name = "MS_LAZYTIME",    },
662
        };
663
        _cleanup_free_ char *str = NULL;
51,530✔
664

665
        assert(ret);
51,530✔
666

667
        FOREACH_ELEMENT(entry, map)
1,339,780✔
668
                if (flags & entry->flag) {
1,288,250✔
669
                        if (!strextend_with_separator(&str, "|", entry->name))
122,676✔
670
                                return -ENOMEM;
671
                        flags &= ~entry->flag;
122,676✔
672
                }
673

674
        if (!str || flags != 0)
51,530✔
675
                if (strextendf_with_separator(&str, "|", "%lx", flags) < 0)
153✔
676
                        return -ENOMEM;
677

678
        *ret = TAKE_PTR(str);
51,530✔
679
        return 0;
51,530✔
680
}
681

682
int mount_verbose_full(
51,500✔
683
                int error_log_level,
684
                const char *what,
685
                const char *where,
686
                const char *type,
687
                unsigned long flags,
688
                const char *options,
689
                bool follow_symlink) {
690

691
        _cleanup_free_ char *fl = NULL, *o = NULL;
51,500✔
692
        unsigned long f;
51,500✔
693
        int r;
51,500✔
694

695
        r = mount_option_mangle(options, flags, &f, &o);
51,500✔
696
        if (r < 0)
51,500✔
697
                return log_full_errno(error_log_level, r,
×
698
                                      "Failed to mangle mount options %s: %m",
699
                                      strempty(options));
700

701
        (void) mount_flags_to_string(f, &fl);
51,500✔
702

703
        if (FLAGS_SET(f, MS_REMOUNT|MS_BIND))
51,500✔
704
                log_debug("Changing mount flags %s (%s \"%s\")...",
11,795✔
705
                          where, strnull(fl), strempty(o));
706
        else if (f & MS_REMOUNT)
45,602✔
707
                log_debug("Remounting superblock %s (%s \"%s\")...",
46✔
708
                          where, strnull(fl), strempty(o));
709
        else if (f & (MS_SHARED|MS_PRIVATE|MS_SLAVE|MS_UNBINDABLE))
45,556✔
710
                log_debug("Changing mount propagation %s (%s \"%s\")",
6,682✔
711
                          where, strnull(fl), strempty(o));
712
        else if (f & MS_BIND)
42,215✔
713
                log_debug("Bind-mounting %s on %s (%s \"%s\")...",
59,375✔
714
                          what, where, strnull(fl), strempty(o));
715
        else if (f & MS_MOVE)
12,464✔
716
                log_debug("Moving mount %s %s %s (%s \"%s\")...",
7,670✔
717
                          what, glyph(GLYPH_ARROW_RIGHT), where, strnull(fl), strempty(o));
718
        else
719
                log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
10,109✔
720
                          strna(what), strna(type), where, strnull(fl), strempty(o));
721

722
        if (follow_symlink)
51,500✔
723
                r = RET_NERRNO(mount(what, where, type, f, o));
51,867✔
724
        else
725
                r = mount_nofollow(what, where, type, f, o);
46,406✔
726
        if (r < 0)
46,773✔
727
                return log_full_errno(error_log_level, r,
9,486✔
728
                                      "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
729
                                      strna(what), strna(type), where, strnull(fl), strempty(o));
730
        return 0;
731
}
732

733
int umount_verbose(
506✔
734
                int error_log_level,
735
                const char *where,
736
                int flags) {
737

738
        assert(where);
506✔
739

740
        log_debug("Unmounting '%s'...", where);
506✔
741

742
        if (umount2(where, flags) < 0)
506✔
743
                return log_full_errno(error_log_level, errno, "Failed to unmount '%s': %m", where);
81✔
744

745
        return 0;
746
}
747

748
int umountat_detach_verbose(
220✔
749
                int error_log_level,
750
                int fd,
751
                const char *where) {
752

753
        /* Similar to umountat_verbose(), but goes by fd + path. This implies MNT_DETACH, since to do this we
754
         * must pin the inode in question via an fd. */
755

756
        assert(fd >= 0 || fd == AT_FDCWD);
220✔
757

758
        /* If neither fd nor path are specified take this as reference to the cwd */
759
        if (fd == AT_FDCWD && isempty(where))
220✔
760
                return umount_verbose(error_log_level, ".", MNT_DETACH|UMOUNT_NOFOLLOW);
220✔
761

762
        /* If we don't actually take the fd into consideration for this operation shortcut things, so that we
763
         * don't have to open the inode */
764
        if (fd == AT_FDCWD || path_is_absolute(where))
220✔
765
                return umount_verbose(error_log_level, where, MNT_DETACH|UMOUNT_NOFOLLOW);
×
766

767
        _cleanup_free_ char *prefix = NULL;
440✔
768
        const char *p;
220✔
769
        if (fd_get_path(fd, &prefix) < 0)
220✔
770
                p = "<fd>"; /* if we can't get the path, return something vaguely useful */
771
        else
772
                p = prefix;
220✔
773
        _cleanup_free_ char *joined = isempty(where) ? strdup(p) : path_join(p, where);
559✔
774

775
        log_debug("Unmounting '%s'...", strna(joined));
220✔
776

777
        _cleanup_close_ int inode_fd = -EBADF;
220✔
778
        int mnt_fd;
220✔
779
        if (isempty(where))
220✔
780
                mnt_fd = fd;
781
        else {
782
                inode_fd = openat(fd, where, O_PATH|O_CLOEXEC|O_NOFOLLOW);
119✔
783
                if (inode_fd < 0)
119✔
784
                        return log_full_errno(error_log_level, errno, "Failed to pin '%s': %m", strna(joined));
×
785

786
                mnt_fd = inode_fd;
787
        }
788

789
        if (umount2(FORMAT_PROC_FD_PATH(mnt_fd), MNT_DETACH) < 0)
220✔
790
                return log_full_errno(error_log_level, errno, "Failed to unmount '%s': %m", strna(joined));
9✔
791

792
        return 0;
211✔
793
}
794

795
int mount_exchange_graceful(int fsmount_fd, const char *dest, bool mount_beneath) {
16✔
796
        int r;
16✔
797

798
        assert(fsmount_fd >= 0);
16✔
799
        assert(dest);
16✔
800

801
        /* First, try to mount beneath an existing mount point, and if that works, umount the old mount,
802
         * which is now at the top. This will ensure we can atomically replace a mount. Note that this works
803
         * also in the case where there are submounts down the tree. Mount propagation is allowed but
804
         * restricted to layouts that don't end up propagation the new mount on top of the mount stack.  If
805
         * this is not supported (minimum kernel v6.5), or if there is no mount on the mountpoint, we get
806
         * -EINVAL and then we fallback to normal mounting. */
807

808
        r = RET_NERRNO(move_mount(fsmount_fd, /* from_path = */ "",
26✔
809
                                  /* to_fd = */ -EBADF, dest,
810
                                  MOVE_MOUNT_F_EMPTY_PATH | (mount_beneath ? MOVE_MOUNT_BENEATH : 0)));
811
        if (mount_beneath) {
16✔
812
                if (r >= 0) /* Mounting beneath worked! Now unmount the upper mount. */
6✔
813
                        return umount_verbose(LOG_DEBUG, dest, UMOUNT_NOFOLLOW|MNT_DETACH);
2✔
814

815
                if (r == -EINVAL) { /* Fallback if mount_beneath is not supported */
4✔
816
                        log_debug_errno(r,
4✔
817
                                        "Cannot mount beneath '%s', falling back to overmount: %m",
818
                                        dest);
819
                        return mount_exchange_graceful(fsmount_fd, dest, /* mount_beneath = */ false);
4✔
820
                }
821
        }
822

823
        return r;
824
}
825

826
int mount_option_mangle(
51,572✔
827
                const char *options,
828
                unsigned long mount_flags,
829
                unsigned long *ret_mount_flags,
830
                char **ret_remaining_options) {
831

832
        const struct libmnt_optmap *map;
51,572✔
833
        _cleanup_free_ char *ret = NULL;
51,572✔
834
        int r;
51,572✔
835

836
        /* This extracts mount flags from the mount options, and stores
837
         * non-mount-flag options to '*ret_remaining_options'.
838
         * E.g.,
839
         * "rw,nosuid,nodev,relatime,size=1630748k,mode=0700,uid=1000,gid=1000"
840
         * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
841
         * "size=1630748k,mode=0700,uid=1000,gid=1000".
842
         * See more examples in test-mount-util.c.
843
         *
844
         * If 'options' does not contain any non-mount-flag options,
845
         * then '*ret_remaining_options' is set to NULL instead of empty string.
846
         * The validity of options stored in '*ret_remaining_options' is not checked.
847
         * If 'options' is NULL, this just copies 'mount_flags' to *ret_mount_flags. */
848

849
        assert(ret_mount_flags);
51,572✔
850
        assert(ret_remaining_options);
51,572✔
851

852
        map = mnt_get_builtin_optmap(MNT_LINUX_MAP);
51,572✔
853
        if (!map)
51,572✔
854
                return -EINVAL;
855

856
        for (const char *p = options;;) {
51,572✔
857
                _cleanup_free_ char *word = NULL;
25,079✔
858
                const struct libmnt_optmap *ent;
76,650✔
859

860
                r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
76,650✔
861
                if (r < 0)
76,650✔
862
                        return r;
863
                if (r == 0)
76,649✔
864
                        break;
865

866
                for (ent = map; ent->name; ent++) {
1,050,693✔
867
                        /* All entries in MNT_LINUX_MAP do not take any argument.
868
                         * Thus, ent->name does not contain "=" or "[=]". */
869
                        if (!streq(word, ent->name))
1,025,706✔
870
                                continue;
1,025,615✔
871

872
                        if (!(ent->mask & MNT_INVERT))
91✔
873
                                mount_flags |= ent->id;
82✔
874
                        else
875
                                mount_flags &= ~ent->id;
9✔
876

877
                        break;
878
                }
879

880
                /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
881
                if (!ent->name &&
50,065✔
882
                    !startswith_no_case(word, "x-") &&
49,972✔
883
                    !strextend_with_separator(&ret, ",", word))
24,985✔
884
                        return -ENOMEM;
885
        }
886

887
        *ret_mount_flags = mount_flags;
51,571✔
888
        *ret_remaining_options = TAKE_PTR(ret);
51,571✔
889

890
        return 0;
51,571✔
891
}
892

893
static int mount_in_namespace_legacy(
×
894
                const char *chased_src_path,
895
                int chased_src_fd,
896
                struct stat *chased_src_st,
897
                const char *propagate_path,
898
                const char *incoming_path,
899
                const char *dest,
900
                int pidns_fd,
901
                int mntns_fd,
902
                int root_fd,
903
                MountInNamespaceFlags flags,
904
                const MountOptions *options,
905
                const ImagePolicy *image_policy) {
906

907
        _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
×
908
        char mount_slave[] = "/tmp/propagate.XXXXXX", *mount_tmp, *mount_outside, *p;
×
909
        bool mount_slave_created = false, mount_slave_mounted = false,
×
910
                mount_tmp_created = false, mount_tmp_mounted = false,
×
911
                mount_outside_created = false, mount_outside_mounted = false;
×
912
        pid_t child;
×
913
        int r;
×
914

915
        assert(chased_src_path);
×
916
        assert(chased_src_fd >= 0);
×
917
        assert(chased_src_st);
×
918
        assert(propagate_path);
×
919
        assert(incoming_path);
×
920
        assert(dest);
×
921
        assert(pidns_fd >= 0);
×
922
        assert(mntns_fd >= 0);
×
923
        assert(root_fd >= 0);
×
924
        assert(!options || (flags & MOUNT_IN_NAMESPACE_IS_IMAGE));
×
925

926
        p = strjoina(propagate_path, "/");
×
927
        r = access_nofollow(p, F_OK);
×
928
        if (r < 0)
×
929
                return log_debug_errno(r == -ENOENT ? SYNTHETIC_ERRNO(EOPNOTSUPP) : r, "Target does not allow propagation of mount points");
×
930

931
        /* Our goal is to install a new bind mount into the container,
932
           possibly read-only. This is irritatingly complex
933
           unfortunately, currently.
934

935
           First, we start by creating a private playground in /tmp,
936
           that we can mount MS_SLAVE. (Which is necessary, since
937
           MS_MOVE cannot be applied to mounts with MS_SHARED parent
938
           mounts.) */
939

940
        if (!mkdtemp(mount_slave))
×
941
                return log_debug_errno(errno, "Failed to create playground %s: %m", mount_slave);
×
942

943
        mount_slave_created = true;
×
944

945
        r = mount_nofollow_verbose(LOG_DEBUG, mount_slave, mount_slave, NULL, MS_BIND, NULL);
×
946
        if (r < 0)
×
947
                goto finish;
×
948

949
        mount_slave_mounted = true;
×
950

951
        r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_slave, NULL, MS_SLAVE, NULL);
×
952
        if (r < 0)
×
953
                goto finish;
×
954

955
        /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
956
        mount_tmp = strjoina(mount_slave, "/mount");
×
957
        r = make_mount_point_inode_from_mode(AT_FDCWD, mount_tmp, (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) ? S_IFDIR : chased_src_st->st_mode, 0700);
×
958
        if (r < 0) {
×
959
                log_debug_errno(r, "Failed to create temporary mount point %s: %m", mount_tmp);
×
960
                goto finish;
×
961
        }
962

963
        mount_tmp_created = true;
×
964

965
        if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE)
×
966
                r = verity_dissect_and_mount(
×
967
                                chased_src_fd,
968
                                chased_src_path,
969
                                mount_tmp,
970
                                options,
971
                                image_policy,
972
                                /* image_filter= */ NULL,
973
                                /* extension_release_data= */ NULL,
974
                                /* verity= */ NULL,
975
                                /* ret_image= */ NULL);
976
        else
977
                r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(chased_src_fd), mount_tmp, NULL, MS_BIND, NULL);
×
978
        if (r < 0)
×
979
                goto finish;
×
980

981
        mount_tmp_mounted = true;
×
982

983
        /* Third, we remount the new bind mount read-only if requested. */
984
        if (flags & MOUNT_IN_NAMESPACE_READ_ONLY) {
×
985
                r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_tmp, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
×
986
                if (r < 0)
×
987
                        goto finish;
×
988
        }
989

990
        /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
991
         * right-away. */
992

993
        mount_outside = strjoina(propagate_path, "/XXXXXX");
×
994
        if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
995
                r = mkdtemp(mount_outside) ? 0 : -errno;
×
996
        else {
997
                r = mkostemp_safe(mount_outside);
×
998
                safe_close(r);
×
999
        }
1000
        if (r < 0) {
×
1001
                log_debug_errno(r, "Cannot create propagation file or directory %s: %m", mount_outside);
×
1002
                goto finish;
×
1003
        }
1004

1005
        mount_outside_created = true;
×
1006

1007
        r = mount_nofollow_verbose(LOG_DEBUG, mount_tmp, mount_outside, NULL, MS_MOVE, NULL);
×
1008
        if (r < 0)
×
1009
                goto finish;
×
1010

1011
        mount_outside_mounted = true;
×
1012
        mount_tmp_mounted = false;
×
1013

1014
        if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
1015
                (void) rmdir(mount_tmp);
×
1016
        else
1017
                (void) unlink(mount_tmp);
×
1018
        mount_tmp_created = false;
×
1019

1020
        (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
×
1021
        mount_slave_mounted = false;
×
1022

1023
        (void) rmdir(mount_slave);
×
1024
        mount_slave_created = false;
×
1025

1026
        if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0) {
×
1027
                log_debug_errno(errno, "Failed to create pipe: %m");
×
1028
                goto finish;
×
1029
        }
1030

1031
        r = namespace_fork(
×
1032
                        "(sd-bindmnt)",
1033
                        "(sd-bindmnt-inner)",
1034
                        /* except_fds= */ NULL,
1035
                        /* n_except_fds= */ 0,
1036
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
1037
                        pidns_fd,
1038
                        mntns_fd,
1039
                        /* netns_fd= */ -EBADF,
1040
                        /* userns_fd= */ -EBADF,
1041
                        root_fd,
1042
                        &child);
1043
        if (r < 0)
×
1044
                goto finish;
×
1045
        if (r == 0) {
×
1046
                _cleanup_free_ char *mount_outside_fn = NULL, *mount_inside = NULL;
×
1047

1048
                errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
×
1049

1050
                _cleanup_close_ int dest_fd = -EBADF;
×
1051
                _cleanup_free_ char *dest_fn = NULL;
×
1052
                r = chase(dest, /* root= */ NULL, CHASE_PARENT|CHASE_EXTRACT_FILENAME|((flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) ? CHASE_MKDIR_0755 : 0), &dest_fn, &dest_fd);
×
1053
                if (r < 0)
×
1054
                        log_debug_errno(r, "Failed to pin parent directory of mount '%s', ignoring: %m", dest);
×
1055
                else if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) {
×
1056
                        r = make_mount_point_inode_from_mode(dest_fd, dest_fn, (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) ? S_IFDIR : chased_src_st->st_mode, 0700);
×
1057
                        if (r < 0)
×
1058
                                log_debug_errno(r, "Failed to make mount point inode of mount '%s', ignoring: %m", dest);
×
1059
                }
1060

1061
                /* Fifth, move the mount to the right place inside */
1062
                r = path_extract_filename(mount_outside, &mount_outside_fn);
×
1063
                if (r < 0) {
×
1064
                        log_debug_errno(r, "Failed to extract filename from propagation file or directory '%s': %m", mount_outside);
×
1065
                        report_errno_and_exit(errno_pipe_fd[1], r);
×
1066
                }
1067

1068
                mount_inside = path_join(incoming_path, mount_outside_fn);
×
1069
                if (!mount_inside)
×
1070
                        report_errno_and_exit(errno_pipe_fd[1], log_oom_debug());
×
1071

1072
                r = mount_nofollow_verbose(LOG_DEBUG, mount_inside, dest_fd >= 0 ? FORMAT_PROC_FD_PATH(dest_fd) : dest, /* fstype= */ NULL, MS_MOVE, /* options= */ NULL);
×
1073
                if (r < 0)
×
1074
                        report_errno_and_exit(errno_pipe_fd[1], r);
×
1075

1076
                _exit(EXIT_SUCCESS);
×
1077
        }
1078

1079
        errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
×
1080

1081
        r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
×
1082
        if (r < 0) {
×
1083
                log_debug_errno(r, "Failed to wait for child: %m");
×
1084
                goto finish;
×
1085
        }
1086
        if (r != EXIT_SUCCESS) {
×
1087
                if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
×
1088
                        log_debug_errno(r, "Failed to mount: %m");
×
1089
                else
1090
                        log_debug("Child failed.");
×
1091
                goto finish;
×
1092
        }
1093

1094
finish:
×
1095
        if (mount_outside_mounted)
×
1096
                (void) umount_verbose(LOG_DEBUG, mount_outside, UMOUNT_NOFOLLOW);
×
1097
        if (mount_outside_created) {
×
1098
                if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
1099
                        (void) rmdir(mount_outside);
×
1100
                else
1101
                        (void) unlink(mount_outside);
×
1102
        }
1103

1104
        if (mount_tmp_mounted)
×
1105
                (void) umount_verbose(LOG_DEBUG, mount_tmp, UMOUNT_NOFOLLOW);
×
1106
        if (mount_tmp_created) {
×
1107
                if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
1108
                        (void) rmdir(mount_tmp);
×
1109
                else
1110
                        (void) unlink(mount_tmp);
×
1111
        }
1112

1113
        if (mount_slave_mounted)
×
1114
                (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
×
1115
        if (mount_slave_created)
×
1116
                (void) rmdir(mount_slave);
×
1117

1118
        return r;
×
1119
}
1120

1121
static int mount_in_namespace(
6✔
1122
                const PidRef *target,
1123
                const char *propagate_path,
1124
                const char *incoming_path,
1125
                const char *src,
1126
                const char *dest,
1127
                MountInNamespaceFlags flags,
1128
                const MountOptions *options,
1129
                const ImagePolicy *image_policy) {
1130

1131
        _cleanup_close_ int mntns_fd = -EBADF, root_fd = -EBADF, pidns_fd = -EBADF, chased_src_fd = -EBADF;
18✔
1132
        _cleanup_free_ char *chased_src_path = NULL;
6✔
1133
        struct stat st;
6✔
1134
        int r;
6✔
1135

1136
        assert(propagate_path);
6✔
1137
        assert(incoming_path);
6✔
1138
        assert(src);
6✔
1139
        assert(dest);
6✔
1140
        assert((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || (!options && !image_policy));
6✔
1141

1142
        if (!pidref_is_set(target))
12✔
1143
                return -ESRCH;
1144

1145
        r = pidref_namespace_open(target, &pidns_fd, &mntns_fd, /* ret_netns_fd = */ NULL, /* ret_userns_fd = */ NULL, &root_fd);
6✔
1146
        if (r < 0)
6✔
1147
                return log_debug_errno(r, "Failed to retrieve FDs of the target process' namespace: %m");
×
1148

1149
        r = is_our_namespace(mntns_fd, NAMESPACE_MOUNT);
6✔
1150
        if (r < 0)
6✔
1151
                return log_debug_errno(r, "Failed to determine if mount namespaces are equal: %m");
×
1152
        /* We can't add new mounts at runtime if the process wasn't started in a namespace */
1153
        if (r > 0)
6✔
1154
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to activate bind mount in target, not running in a mount namespace.");
×
1155

1156
        r = chase(src, NULL, 0, &chased_src_path, &chased_src_fd);
6✔
1157
        if (r < 0)
6✔
1158
                return log_debug_errno(r, "Failed to resolve source path '%s': %m", src);
×
1159
        log_debug("Chased source path '%s': %s", src, chased_src_path);
6✔
1160

1161
        if (fstat(chased_src_fd, &st) < 0)
6✔
1162
                return log_debug_errno(errno, "Failed to stat() resolved source path '%s': %m", src);
×
1163
        if (S_ISLNK(st.st_mode)) /* This shouldn't really happen, given that we just chased the symlinks above, but let's better be safe… */
6✔
1164
                return log_debug_errno(SYNTHETIC_ERRNO(ELOOP), "Source path '%s' can't be a symbolic link.", src);
×
1165

1166
        if (!mount_new_api_supported()) /* Fallback if we can't use the new mount API */
6✔
1167
                return mount_in_namespace_legacy(
×
1168
                                chased_src_path,
1169
                                chased_src_fd,
1170
                                &st,
1171
                                propagate_path,
1172
                                incoming_path,
1173
                                dest,
1174
                                pidns_fd,
1175
                                mntns_fd,
1176
                                root_fd,
1177
                                flags,
1178
                                options,
1179
                                image_policy);
1180

1181
        _cleanup_(dissected_image_unrefp) DissectedImage *img = NULL;
×
1182
        _cleanup_close_ int new_mount_fd = -EBADF;
6✔
1183
        _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
6✔
1184
        pid_t child;
6✔
1185

1186
        if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) {
6✔
1187
                r = verity_dissect_and_mount(
2✔
1188
                                chased_src_fd,
1189
                                chased_src_path,
1190
                                /* dest= */ NULL,
1191
                                options,
1192
                                image_policy,
1193
                                /* image_filter= */ NULL,
1194
                                /* extension_release_data= */ NULL,
1195
                                /* verity= */ NULL,
1196
                                &img);
1197
                if (r < 0)
2✔
1198
                        return log_debug_errno(r,
×
1199
                                               "Failed to dissect and mount image '%s': %m",
1200
                                               chased_src_path);
1201
        } else {
1202
                new_mount_fd = open_tree(
4✔
1203
                                chased_src_fd,
1204
                                "",
1205
                                OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH);
1206
                if (new_mount_fd < 0)
4✔
1207
                        return log_debug_errno(
×
1208
                                        errno,
1209
                                        "Failed to open mount source '%s': %m",
1210
                                        chased_src_path);
1211

1212
                if ((flags & MOUNT_IN_NAMESPACE_READ_ONLY) && mount_setattr(new_mount_fd, "", AT_EMPTY_PATH,
4✔
1213
                                               &(struct mount_attr) {
×
1214
                                                       .attr_set = MOUNT_ATTR_RDONLY,
1215
                                               }, MOUNT_ATTR_SIZE_VER0) < 0)
1216
                        return log_debug_errno(errno,
×
1217
                                               "Failed to set mount for '%s' to read only: %m",
1218
                                               chased_src_path);
1219
        }
1220

1221
        if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0)
6✔
1222
                return log_debug_errno(errno, "Failed to create pipe: %m");
×
1223

1224
        r = namespace_fork("(sd-bindmnt)",
6✔
1225
                           "(sd-bindmnt-inner)",
1226
                           /* except_fds= */ NULL,
1227
                           /* n_except_fds= */ 0,
1228
                           FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
1229
                           pidns_fd,
1230
                           mntns_fd,
1231
                           /* netns_fd= */ -EBADF,
1232
                           /* userns_fd= */ -EBADF,
1233
                           root_fd,
1234
                           &child);
1235
        if (r < 0)
12✔
1236
                return log_debug_errno(r, "Failed to fork off mount helper into namespace: %m");
×
1237
        if (r == 0) {
12✔
1238
                errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
6✔
1239

1240
                _cleanup_close_ int dest_fd = -EBADF;
×
1241
                _cleanup_free_ char *dest_fn = NULL;
×
1242
                r = chase(dest, /* root= */ NULL, CHASE_PARENT|CHASE_EXTRACT_FILENAME|((flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) ? CHASE_MKDIR_0755 : 0), &dest_fn, &dest_fd);
6✔
1243
                if (r < 0)
6✔
1244
                        report_errno_and_exit(errno_pipe_fd[1], r);
×
1245

1246
                if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY)
6✔
1247
                        (void) make_mount_point_inode_from_mode(dest_fd, dest_fn, img ? S_IFDIR : st.st_mode, 0700);
6✔
1248

1249
                if (img) {
6✔
1250
                        DissectImageFlags f =
2✔
1251
                                DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE |
1252
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
1253

1254
                        if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY)
2✔
1255
                                f |= DISSECT_IMAGE_MKDIR;
2✔
1256

1257
                        if (flags & MOUNT_IN_NAMESPACE_READ_ONLY)
2✔
1258
                                f |= DISSECT_IMAGE_READ_ONLY;
×
1259

1260
                        r = dissected_image_mount(
2✔
1261
                                        img,
1262
                                        dest,
1263
                                        /* uid_shift= */ UID_INVALID,
1264
                                        /* uid_range= */ UID_INVALID,
1265
                                        /* userns_fd= */ -EBADF,
1266
                                        f);
1267
                } else
1268
                        r = mount_exchange_graceful(new_mount_fd, dest, /* mount_beneath= */ true);
4✔
1269

1270
                report_errno_and_exit(errno_pipe_fd[1], r);
6✔
1271
        }
1272

1273
        errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
6✔
1274

1275
        r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
6✔
1276
        if (r < 0)
6✔
1277
                return log_debug_errno(r, "Failed to wait for child: %m");
×
1278
        if (r != EXIT_SUCCESS) {
6✔
1279
                if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
×
1280
                        return log_debug_errno(r, "Failed to mount into namespace: %m");
×
1281

1282
                return log_debug_errno(SYNTHETIC_ERRNO(EPROTO), "Child failed.");
×
1283
        }
1284

1285
        return 0;
1286
}
1287

1288
int bind_mount_in_namespace(
4✔
1289
                const PidRef *target,
1290
                const char *propagate_path,
1291
                const char *incoming_path,
1292
                const char *src,
1293
                const char *dest,
1294
                MountInNamespaceFlags flags) {
1295

1296
        return mount_in_namespace(target,
8✔
1297
                                  propagate_path,
1298
                                  incoming_path,
1299
                                  src,
1300
                                  dest,
1301
                                  flags & ~MOUNT_IN_NAMESPACE_IS_IMAGE,
4✔
1302
                                  /* options = */ NULL,
1303
                                  /* image_policy = */ NULL);
1304
}
1305

1306
int mount_image_in_namespace(
2✔
1307
                const PidRef *target,
1308
                const char *propagate_path,
1309
                const char *incoming_path,
1310
                const char *src,
1311
                const char *dest,
1312
                MountInNamespaceFlags flags,
1313
                const MountOptions *options,
1314
                const ImagePolicy *image_policy) {
1315

1316
        return mount_in_namespace(target,
4✔
1317
                                  propagate_path,
1318
                                  incoming_path,
1319
                                  src,
1320
                                  dest,
1321
                                  flags | MOUNT_IN_NAMESPACE_IS_IMAGE,
2✔
1322
                                  options,
1323
                                  image_policy);
1324
}
1325

1326
int make_mount_point(const char *path) {
23✔
1327
        int r;
23✔
1328

1329
        assert(path);
23✔
1330

1331
        /* If 'path' is already a mount point, does nothing and returns 0. If it is not it makes it one, and returns 1. */
1332

1333
        r = path_is_mount_point(path);
23✔
1334
        if (r < 0)
23✔
1335
                return log_debug_errno(r, "Failed to determine whether '%s' is a mount point: %m", path);
×
1336
        if (r > 0)
23✔
1337
                return 0;
1338

1339
        r = mount_nofollow_verbose(LOG_DEBUG, path, path, NULL, MS_BIND|MS_REC, NULL);
9✔
1340
        if (r < 0)
9✔
1341
                return r;
×
1342

1343
        return 1;
1344
}
1345

1346
int fd_make_mount_point(int fd) {
11✔
1347
        int r;
11✔
1348

1349
        assert(fd >= 0);
11✔
1350

1351
        r = is_mount_point_at(fd, NULL, 0);
11✔
1352
        if (r < 0)
11✔
1353
                return log_debug_errno(r, "Failed to determine whether file descriptor is a mount point: %m");
×
1354
        if (r > 0)
11✔
1355
                return 0;
1356

1357
        r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(fd), FORMAT_PROC_FD_PATH(fd), NULL, MS_BIND|MS_REC, NULL);
1✔
1358
        if (r < 0)
1✔
1359
                return r;
×
1360

1361
        return 1;
1362
}
1363

1364
int make_userns(uid_t uid_shift,
88✔
1365
                uid_t uid_range,
1366
                uid_t source_owner,
1367
                uid_t dest_owner,
1368
                RemountIdmapping idmapping) {
1369

1370
        _cleanup_close_ int userns_fd = -EBADF;
88✔
1371
        _cleanup_free_ char *line = NULL;
88✔
1372
        uid_t source_base = 0;
88✔
1373

1374
        /* Allocates a userns file descriptor with the mapping we need. For this we'll fork off a child
1375
         * process whose only purpose is to give us a new user namespace. It's killed when we got it. */
1376

1377
        if (!userns_shift_range_valid(uid_shift, uid_range))
88✔
1378
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid UID range for user namespace.");
×
1379

1380
        switch (idmapping) {
88✔
1381

1382
        case REMOUNT_IDMAPPING_FOREIGN_WITH_HOST_ROOT:
2✔
1383
                source_base = FOREIGN_UID_BASE;
2✔
1384
                _fallthrough_;
86✔
1385

1386
        case REMOUNT_IDMAPPING_NONE:
86✔
1387
        case REMOUNT_IDMAPPING_HOST_ROOT:
1388

1389
                if (asprintf(&line,
86✔
1390
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
1391
                             source_base, uid_shift, uid_range) < 0)
1392
                        return log_oom_debug();
×
1393

1394
                /* If requested we'll include an entry in the mapping so that the host root user can make
1395
                 * changes to the uidmapped mount like it normally would. Specifically, we'll map the user
1396
                 * with UID_MAPPED_ROOT on the backing fs to UID 0. This is useful, since nspawn code wants
1397
                 * to create various missing inodes in the OS tree before booting into it, and this becomes
1398
                 * very easy and straightforward to do if it can just do it under its own regular UID. Note
1399
                 * that in that case the container's runtime uidmap (i.e. the one the container payload
1400
                 * processes run in) will leave this UID unmapped, i.e. if we accidentally leave files owned
1401
                 * by host root in the already uidmapped tree around they'll show up as owned by 'nobody',
1402
                 * which is safe. (Of course, we shouldn't leave such inodes around, but always chown() them
1403
                 * to the container's own UID range, but it's good to have a safety net, in case we
1404
                 * forget it.) */
1405
                if (idmapping == REMOUNT_IDMAPPING_HOST_ROOT)
86✔
1406
                        if (strextendf(&line,
84✔
1407
                                       UID_FMT " " UID_FMT " " UID_FMT "\n",
1408
                                       UID_MAPPED_ROOT, (uid_t) 0u, (uid_t) 1u) < 0)
1409
                                return log_oom_debug();
×
1410

1411
                break;
1412

1413
        case REMOUNT_IDMAPPING_HOST_OWNER:
×
1414
                /* Remap the owner of the bind mounted directory to the root user within the container. This
1415
                 * way every file written by root within the container to the bind-mounted directory will
1416
                 * be owned by the original user from the host. All other users will remain unmapped. */
1417
                if (asprintf(&line,
×
1418
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
1419
                             source_owner, uid_shift, (uid_t) 1u) < 0)
1420
                        return log_oom_debug();
×
1421
                break;
1422

1423
        case REMOUNT_IDMAPPING_HOST_OWNER_TO_TARGET_OWNER:
2✔
1424
                /* Remap the owner of the bind mounted directory to the owner of the target directory
1425
                 * within the container. This way every file written by target directory owner within the
1426
                 * container to the bind-mounted directory will be owned by the original host user.
1427
                 * All other users will remain unmapped. */
1428
                if (asprintf(&line,
2✔
1429
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
1430
                             source_owner, dest_owner, (uid_t) 1u) < 0)
1431
                        return log_oom_debug();
×
1432
                break;
1433

1434
        default:
×
1435
                assert_not_reached();
×
1436
        }
1437

1438
        /* We always assign the same UID and GID ranges */
1439
        userns_fd = userns_acquire(line, line, /* setgroups_deny= */ true);
88✔
1440
        if (userns_fd < 0)
88✔
1441
                return log_debug_errno(userns_fd, "Failed to acquire new userns: %m");
×
1442

1443
        return TAKE_FD(userns_fd);
1444
}
1445

1446
int remount_idmap_fd(
99✔
1447
                char **paths,
1448
                int userns_fd,
1449
                uint64_t extra_mount_attr_set) {
1450

1451
        int r;
99✔
1452

1453
        assert(userns_fd >= 0);
99✔
1454

1455
        /* This remounts all specified paths with the specified userns as idmap. It will do so in the
1456
         * order specified in the strv: the expectation is that the top-level directories are at the
1457
         * beginning, and nested directories in the right, so that the tree can be built correctly from left
1458
         * to right. */
1459

1460
        size_t n = strv_length(paths);
99✔
1461
        if (n == 0) /* Nothing to do? */
99✔
1462
                return 0;
99✔
1463

1464
        int *mount_fds = NULL;
99✔
1465
        size_t n_mounts_fds = 0;
99✔
1466

1467
        mount_fds = new(int, n);
99✔
1468
        if (!mount_fds)
99✔
1469
                return log_oom_debug();
×
1470

1471
        CLEANUP_ARRAY(mount_fds, n_mounts_fds, close_many_and_free);
99✔
1472

1473
        for (size_t i = 0; i < n; i++) {
196✔
1474
                int mntfd;
99✔
1475

1476
                /* Clone the mount point */
1477
                mntfd = mount_fds[n_mounts_fds] = open_tree(-EBADF, paths[i], OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
99✔
1478
                if (mount_fds[n_mounts_fds] < 0)
99✔
1479
                        return log_debug_errno(errno, "Failed to open tree of mounted filesystem '%s': %m", paths[i]);
×
1480

1481
                n_mounts_fds++;
99✔
1482

1483
                /* Set the user namespace mapping attribute on the cloned mount point */
1484
                if (mount_setattr(mntfd, "", AT_EMPTY_PATH,
99✔
1485
                                  &(struct mount_attr) {
99✔
1486
                                          .attr_set = MOUNT_ATTR_IDMAP | extra_mount_attr_set,
99✔
1487
                                          .userns_fd = userns_fd,
1488
                                  }, sizeof(struct mount_attr)) < 0)
1489
                        return log_debug_errno(errno, "Failed to change bind mount attributes for clone of '%s': %m", paths[i]);
2✔
1490
        }
1491

1492
        for (size_t i = n; i > 0; i--) { /* Unmount the paths right-to-left */
194✔
1493
                /* Remove the old mount points now that we have a idmapped mounts as replacement for all of them */
1494
                r = umount_verbose(LOG_DEBUG, paths[i-1], UMOUNT_NOFOLLOW);
97✔
1495
                if (r < 0)
97✔
1496
                        return r;
1497
        }
1498

1499
        for (size_t i = 0; i < n; i++) { /* Mount the replacement mounts left-to-right */
194✔
1500
                /* And place the cloned version in its place */
1501
                log_debug("Mounting idmapped fs to '%s'", paths[i]);
97✔
1502
                if (move_mount(mount_fds[i], "", -EBADF, paths[i], MOVE_MOUNT_F_EMPTY_PATH) < 0)
97✔
1503
                        return log_debug_errno(errno, "Failed to attach UID mapped mount to '%s': %m", paths[i]);
×
1504
        }
1505

1506
        return 0;
1507
}
1508

1509
int remount_idmap(
86✔
1510
                char **p,
1511
                uid_t uid_shift,
1512
                uid_t uid_range,
1513
                uid_t source_owner,
1514
                uid_t dest_owner,
1515
                RemountIdmapping idmapping) {
1516

1517
        _cleanup_close_ int userns_fd = -EBADF;
86✔
1518

1519
        userns_fd = make_userns(uid_shift, uid_range, source_owner, dest_owner, idmapping);
86✔
1520
        if (userns_fd < 0)
86✔
1521
                return userns_fd;
1522

1523
        return remount_idmap_fd(p, userns_fd, /* extra_mount_attr_set= */ 0);
86✔
1524
}
1525

1526
static void sub_mount_clear(SubMount *s) {
5,272✔
1527
        assert(s);
5,272✔
1528

1529
        s->path = mfree(s->path);
5,272✔
1530
        s->mount_fd = safe_close(s->mount_fd);
5,272✔
1531
}
5,272✔
1532

1533
void sub_mount_array_free(SubMount *s, size_t n) {
1,237✔
1534
        assert(s || n == 0);
1,237✔
1535

1536
        for (size_t i = 0; i < n; i++)
5,768✔
1537
                sub_mount_clear(s + i);
4,531✔
1538

1539
        free(s);
1,237✔
1540
}
1,237✔
1541

1542
static int sub_mount_compare(const SubMount *a, const SubMount *b) {
6,560✔
1543
        assert(a);
6,560✔
1544
        assert(b);
6,560✔
1545
        assert(a->path);
6,560✔
1546
        assert(b->path);
6,560✔
1547

1548
        return path_compare(a->path, b->path);
6,560✔
1549
}
1550

1551
static void sub_mount_drop(SubMount *s, size_t n) {
1,779✔
1552
        assert(s || n == 0);
1,779✔
1553

1554
        for (size_t m = 0, i = 1; i < n; i++) {
5,073✔
1555
                if (path_startswith(s[i].path, s[m].path))
3,294✔
1556
                        sub_mount_clear(s + i);
741✔
1557
                else
1558
                        m = i;
1559
        }
1560
}
1,779✔
1561

1562
int get_sub_mounts(const char *prefix, SubMount **ret_mounts, size_t *ret_n_mounts) {
1,779✔
1563

1564
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
1,779✔
1565
        _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
1,779✔
1566
        SubMount *mounts = NULL;
1,779✔
1567
        size_t n = 0;
1,779✔
1568
        int r;
1,779✔
1569

1570
        CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1,779✔
1571

1572
        assert(prefix);
1,779✔
1573
        assert(ret_mounts);
1,779✔
1574
        assert(ret_n_mounts);
1,779✔
1575

1576
        r = libmount_parse_mountinfo(/* source = */ NULL, &table, &iter);
1,779✔
1577
        if (r < 0)
1,779✔
1578
                return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
1579

1580
        for (;;) {
89,240✔
1581
                _cleanup_close_ int mount_fd = -EBADF;
87,461✔
1582
                _cleanup_free_ char *p = NULL;
89,240✔
1583
                struct libmnt_fs *fs;
89,240✔
1584
                const char *path;
89,240✔
1585
                int id1, id2;
89,240✔
1586

1587
                r = mnt_table_next_fs(table, iter, &fs);
89,240✔
1588
                if (r == 1)
89,240✔
1589
                        break; /* EOF */
1590
                if (r < 0)
87,461✔
1591
                        return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
1592

1593
                path = mnt_fs_get_target(fs);
87,461✔
1594
                if (!path)
87,461✔
1595
                        continue;
×
1596

1597
                if (isempty(path_startswith(path, prefix)))
87,461✔
1598
                        continue;
82,194✔
1599

1600
                id1 = mnt_fs_get_id(fs);
5,267✔
1601
                r = path_get_mnt_id(path, &id2);
5,267✔
1602
                if (r < 0) {
5,267✔
1603
                        log_debug_errno(r, "Failed to get mount ID of '%s', ignoring: %m", path);
×
1604
                        continue;
×
1605
                }
1606
                if (id1 != id2) {
5,267✔
1607
                        /* The path may be hidden by another over-mount or already remounted. */
1608
                        log_debug("The mount IDs of '%s' obtained by libmount and path_get_mnt_id() are different (%i vs %i), ignoring.",
736✔
1609
                                  path, id1, id2);
1610
                        continue;
736✔
1611
                }
1612

1613
                mount_fd = open(path, O_CLOEXEC|O_PATH);
4,531✔
1614
                if (mount_fd < 0) {
4,531✔
1615
                        if (errno == ENOENT) /* The path may be hidden by another over-mount or already unmounted. */
×
1616
                                continue;
×
1617

1618
                        return log_debug_errno(errno, "Failed to open subtree of mounted filesystem '%s': %m", path);
×
1619
                }
1620

1621
                p = strdup(path);
4,531✔
1622
                if (!p)
4,531✔
1623
                        return log_oom_debug();
×
1624

1625
                if (!GREEDY_REALLOC(mounts, n + 1))
4,531✔
1626
                        return log_oom_debug();
×
1627

1628
                mounts[n++] = (SubMount) {
4,531✔
1629
                        .path = TAKE_PTR(p),
4,531✔
1630
                        .mount_fd = TAKE_FD(mount_fd),
4,531✔
1631
                };
1632
        }
1633

1634
        typesafe_qsort(mounts, n, sub_mount_compare);
1,779✔
1635
        sub_mount_drop(mounts, n);
1,779✔
1636

1637
        *ret_mounts = TAKE_PTR(mounts);
1,779✔
1638
        *ret_n_mounts = n;
1,779✔
1639
        return 0;
1,779✔
1640
}
1641

1642
int bind_mount_submounts(
1,241✔
1643
                const char *source,
1644
                const char *target) {
1645

1646
        SubMount *mounts = NULL;
1,241✔
1647
        size_t n = 0;
1,241✔
1648
        int ret = 0, r;
1,241✔
1649

1650
        /* Bind mounts all child mounts of 'source' to 'target'. Useful when setting up a new procfs instance
1651
         * with new mount options to copy the original submounts over. */
1652

1653
        assert(source);
1,241✔
1654
        assert(target);
1,241✔
1655

1656
        CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1,241✔
1657

1658
        r = get_sub_mounts(source, &mounts, &n);
1,241✔
1659
        if (r < 0)
1,241✔
1660
                return r;
1661

1662
        FOREACH_ARRAY(m, mounts, n) {
5,768✔
1663
                _cleanup_free_ char *t = NULL;
4,527✔
1664
                const char *suffix;
4,527✔
1665

1666
                if (isempty(m->path))
4,527✔
1667
                        continue;
741✔
1668

1669
                assert_se(suffix = path_startswith(m->path, source));
3,786✔
1670

1671
                t = path_join(target, suffix);
3,786✔
1672
                if (!t)
3,786✔
1673
                        return -ENOMEM;
×
1674

1675
                r = path_is_mount_point(t);
3,786✔
1676
                if (r < 0) {
3,786✔
1677
                        log_debug_errno(r, "Failed to detect if '%s' already is a mount point, ignoring: %m", t);
9✔
1678
                        continue;
9✔
1679
                }
1680
                if (r > 0) {
3,777✔
1681
                        log_debug("Not bind mounting '%s' from '%s' to '%s', since there's already a mountpoint.", suffix, source, target);
×
1682
                        continue;
×
1683
                }
1684

1685
                r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(m->mount_fd), t, NULL, MS_BIND|MS_REC, NULL);
3,777✔
1686
                if (r < 0 && ret == 0)
3,777✔
1687
                        ret = r;
367✔
1688
        }
1689

1690
        return ret;
1691
}
1692

1693
int make_mount_point_inode_from_mode(int dir_fd, const char *dest, mode_t source_mode, mode_t target_mode) {
980✔
1694
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
980✔
1695
        assert(dest);
980✔
1696

1697
        if (S_ISDIR(source_mode))
980✔
1698
                return mkdirat_label(dir_fd, dest, target_mode & 07777);
963✔
1699
        else
1700
                return RET_NERRNO(mknodat(dir_fd, dest, S_IFREG|(target_mode & 07666), 0)); /* Mask off X bit */
18✔
1701
}
1702

1703
int make_mount_point_inode_from_path(const char *source, const char *dest, mode_t access_mode) {
834✔
1704
        struct stat st;
834✔
1705

1706
        assert(source);
834✔
1707
        assert(dest);
834✔
1708

1709
        if (stat(source, &st) < 0)
834✔
1710
                return -errno;
×
1711

1712
        return make_mount_point_inode_from_mode(AT_FDCWD, dest, st.st_mode, access_mode);
834✔
1713
}
1714

1715
int trigger_automount_at(int dir_fd, const char *path) {
380✔
1716
        _cleanup_free_ char *nested = NULL;
760✔
1717

1718
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
380✔
1719

1720
        nested = path_join(path, "a");
380✔
1721
        if (!nested)
380✔
1722
                return -ENOMEM;
1723

1724
        (void) faccessat(dir_fd, nested, F_OK, 0);
380✔
1725

1726
        return 0;
380✔
1727
}
1728

1729
unsigned long credentials_fs_mount_flags(bool ro) {
3,870✔
1730
        /* A tight set of mount flags for credentials mounts */
1731
        return MS_NODEV|MS_NOEXEC|MS_NOSUID|ms_nosymfollow_supported()|(ro ? MS_RDONLY : 0);
3,870✔
1732
}
1733

1734
int mount_credentials_fs(const char *path, size_t size, bool ro) {
1,935✔
1735
        _cleanup_free_ char *opts = NULL;
1,935✔
1736
        int r, noswap_supported;
1,935✔
1737

1738
        /* Mounts a file system we can place credentials in, i.e. with tight access modes right from the
1739
         * beginning, and ideally swapping turned off. In order of preference:
1740
         *
1741
         *      1. tmpfs if it supports "noswap"
1742
         *      2. ramfs
1743
         *      3. tmpfs if it doesn't support "noswap"
1744
         */
1745

1746
        noswap_supported = mount_option_supported("tmpfs", "noswap", NULL); /* Check explicitly to avoid kmsg noise */
1,935✔
1747
        if (noswap_supported > 0) {
1,935✔
1748
                _cleanup_free_ char *noswap_opts = NULL;
1,934✔
1749

1750
                if (asprintf(&noswap_opts, "mode=0700,nr_inodes=1024,size=%zu,noswap", size) < 0)
1,934✔
1751
                        return -ENOMEM;
1752

1753
                /* Best case: tmpfs with noswap (needs kernel >= 6.3) */
1754

1755
                r = mount_nofollow_verbose(
1,934✔
1756
                                LOG_DEBUG,
1757
                                "tmpfs",
1758
                                path,
1759
                                "tmpfs",
1760
                                credentials_fs_mount_flags(ro),
1761
                                noswap_opts);
1762
                if (r >= 0)
1,934✔
1763
                        return r;
1764
        }
1765

1766
        r = mount_nofollow_verbose(
1✔
1767
                        LOG_DEBUG,
1768
                        "ramfs",
1769
                        path,
1770
                        "ramfs",
1771
                        credentials_fs_mount_flags(ro),
1772
                        "mode=0700");
1773
        if (r >= 0)
1✔
1774
                return r;
1775

1776
        if (asprintf(&opts, "mode=0700,nr_inodes=1024,size=%zu", size) < 0)
1✔
1777
                return -ENOMEM;
1778

1779
        return mount_nofollow_verbose(
1,935✔
1780
                        LOG_DEBUG,
1781
                        "tmpfs",
1782
                        path,
1783
                        "tmpfs",
1784
                        credentials_fs_mount_flags(ro),
1785
                        opts);
1786
}
1787

1788
int make_fsmount(
2✔
1789
                int error_log_level,
1790
                const char *what,
1791
                const char *type,
1792
                unsigned long flags,
1793
                const char *options,
1794
                int userns_fd) {
1795

1796
        _cleanup_close_ int fs_fd = -EBADF, mnt_fd = -EBADF;
2✔
1797
        _cleanup_free_ char *o = NULL;
2✔
1798
        unsigned long f;
2✔
1799
        int r;
2✔
1800

1801
        assert(type);
2✔
1802
        assert(what);
2✔
1803

1804
        r = mount_option_mangle(options, flags, &f, &o);
2✔
1805
        if (r < 0)
2✔
1806
                return log_full_errno(
×
1807
                                error_log_level, r, "Failed to mangle mount options %s: %m",
1808
                                strempty(options));
1809

1810
        if (DEBUG_LOGGING) {
2✔
1811
                _cleanup_free_ char *fl = NULL;
2✔
1812
                (void) mount_flags_to_string(f, &fl);
2✔
1813

1814
                log_debug("Creating mount fd for %s (%s) (%s \"%s\")...",
4✔
1815
                        strna(what), strna(type), strnull(fl), strempty(o));
1816
        }
1817

1818
        fs_fd = fsopen(type, FSOPEN_CLOEXEC);
2✔
1819
        if (fs_fd < 0)
2✔
1820
                return log_full_errno(error_log_level, errno, "Failed to open superblock for \"%s\": %m", type);
×
1821

1822
        if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "source", what, 0) < 0)
2✔
1823
                return log_full_errno(error_log_level, errno, "Failed to set mount source for \"%s\" to \"%s\": %m", type, what);
×
1824

1825
        if (FLAGS_SET(f, MS_RDONLY))
2✔
1826
                if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, "ro", NULL, 0) < 0)
2✔
1827
                        return log_full_errno(error_log_level, errno, "Failed to set read only mount flag for \"%s\": %m", type);
×
1828

1829
        for (const char *p = o;;) {
2✔
1830
                _cleanup_free_ char *word = NULL;
×
1831
                char *eq;
2✔
1832

1833
                r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
2✔
1834
                if (r < 0)
2✔
1835
                        return log_full_errno(error_log_level, r, "Failed to parse mount option string \"%s\": %m", o);
×
1836
                if (r == 0)
2✔
1837
                        break;
1838

1839
                eq = strchr(word, '=');
×
1840
                if (eq) {
×
1841
                        *eq = 0;
×
1842
                        eq++;
×
1843

1844
                        if (fsconfig(fs_fd, FSCONFIG_SET_STRING, word, eq, 0) < 0)
×
1845
                                return log_full_errno(error_log_level, errno, "Failed to set mount option \"%s=%s\" for \"%s\": %m", word, eq, type);
×
1846
                } else {
1847
                        if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, word, NULL, 0) < 0)
×
1848
                                return log_full_errno(error_log_level, errno, "Failed to set mount flag \"%s\" for \"%s\": %m", word, type);
×
1849
                }
1850
        }
1851

1852
        if (fsconfig(fs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) < 0)
2✔
1853
                return log_full_errno(error_log_level, errno, "Failed to realize fs fd for \"%s\" (\"%s\"): %m", what, type);
×
1854

1855
        mnt_fd = fsmount(fs_fd, FSMOUNT_CLOEXEC, 0);
2✔
1856
        if (mnt_fd < 0)
2✔
1857
                return log_full_errno(error_log_level, errno, "Failed to create mount fd for \"%s\" (\"%s\"): %m", what, type);
×
1858

1859
        if (mount_setattr(mnt_fd, "", AT_EMPTY_PATH|AT_RECURSIVE,
2✔
1860
                          &(struct mount_attr) {
4✔
1861
                                  .attr_set = ms_flags_to_mount_attr(f) | (userns_fd >= 0 ? MOUNT_ATTR_IDMAP : 0),
4✔
1862
                                  .userns_fd = userns_fd,
1863
                          }, MOUNT_ATTR_SIZE_VER0) < 0)
1864
                return log_full_errno(error_log_level,
×
1865
                                      errno,
1866
                                      "Failed to set mount flags for \"%s\" (\"%s\"): %m",
1867
                                      what,
1868
                                      type);
1869

1870
        return TAKE_FD(mnt_fd);
2✔
1871
}
1872

1873
char* umount_and_unlink_and_free(char *p) {
1✔
1874
        if (!p)
1✔
1875
                return NULL;
1✔
1876

1877
        PROTECT_ERRNO;
2✔
1878
        (void) umount2(p, 0);
1✔
1879
        (void) unlink(p);
1✔
1880
        return mfree(p);
1✔
1881
}
1882

1883
static int path_get_mount_info_at(
615✔
1884
                int dir_fd,
1885
                const char *path,
1886
                char **ret_fstype,
1887
                char **ret_options) {
1888

1889
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
615✔
1890
        _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
615✔
1891
        int r, mnt_id;
615✔
1892

1893
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
615✔
1894

1895
        r = path_get_mnt_id_at(dir_fd, path, &mnt_id);
615✔
1896
        if (r < 0)
615✔
1897
                return log_debug_errno(r, "Failed to get mount ID: %m");
×
1898

1899
        /* When getting options is requested, we also need to parse utab, otherwise userspace options like
1900
         * "_netdev" will be lost. */
1901
        if (ret_options)
615✔
1902
                r = libmount_parse_with_utab(&table, &iter);
615✔
1903
        else
1904
                r = libmount_parse_mountinfo(/* source = */ NULL, &table, &iter);
×
1905
        if (r < 0)
615✔
1906
                return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
1907

1908
        for (;;) {
2,827✔
1909
                struct libmnt_fs *fs;
1,721✔
1910

1911
                r = mnt_table_next_fs(table, iter, &fs);
1,721✔
1912
                if (r == 1)
1,721✔
1913
                        break; /* EOF */
1914
                if (r < 0)
1,721✔
1915
                        return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
615✔
1916

1917
                if (mnt_fs_get_id(fs) != mnt_id)
1,721✔
1918
                        continue;
1,106✔
1919

1920
                _cleanup_free_ char *fstype = NULL, *options = NULL;
615✔
1921

1922
                if (ret_fstype) {
615✔
1923
                        fstype = strdup(strempty(mnt_fs_get_fstype(fs)));
615✔
1924
                        if (!fstype)
615✔
1925
                                return log_oom_debug();
×
1926
                }
1927

1928
                if (ret_options) {
615✔
1929
                        options = strdup(strempty(mnt_fs_get_options(fs)));
615✔
1930
                        if (!options)
615✔
1931
                                return log_oom_debug();
×
1932
                }
1933

1934
                if (ret_fstype)
615✔
1935
                        *ret_fstype = TAKE_PTR(fstype);
615✔
1936
                if (ret_options)
615✔
1937
                        *ret_options = TAKE_PTR(options);
615✔
1938

1939
                return 0;
1940
        }
1941

1942
        return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Cannot find mount ID %i from /proc/self/mountinfo.", mnt_id);
615✔
1943
}
1944

1945
int path_is_network_fs_harder_at(int dir_fd, const char *path) {
633✔
1946
        _cleanup_close_ int fd = -EBADF;
633✔
1947
        int r;
633✔
1948

1949
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
633✔
1950

1951
        fd = xopenat(dir_fd, path, O_PATH | O_CLOEXEC | O_NOFOLLOW);
633✔
1952
        if (fd < 0)
633✔
1953
                return fd;
1954

1955
        r = fd_is_network_fs(fd);
615✔
1956
        if (r != 0)
615✔
1957
                return r;
1958

1959
        _cleanup_free_ char *fstype = NULL, *options = NULL;
615✔
1960
        r = path_get_mount_info_at(fd, /* path = */ NULL, &fstype, &options);
615✔
1961
        if (r < 0)
615✔
1962
                return r;
1963

1964
        if (fstype_is_network(fstype))
615✔
1965
                return true;
1966

1967
        if (fstab_test_option(options, "_netdev\0"))
615✔
1968
                return true;
×
1969

1970
        return false;
1971
}
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