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

systemd / systemd / 19282013399

12 Nov 2025 12:00AM UTC coverage: 72.412% (+0.01%) from 72.402%
19282013399

push

github

web-flow
core/exec-credentials: port to new mount API, ensure atomicity for creds installation (#39637)

103 of 137 new or added lines in 4 files covered. (75.18%)

850 existing lines in 45 files now uncovered.

307170 of 424195 relevant lines covered (72.41%)

1105108.57 hits per line

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

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

3
#include <stdlib.h>
4
#include <sys/mount.h>
5
#include <sys/stat.h>
6
#include <unistd.h>
7

8
#include "alloc-util.h"
9
#include "chase.h"
10
#include "creds-util.h"
11
#include "dissect-image.h"
12
#include "errno-util.h"
13
#include "extract-word.h"
14
#include "fd-util.h"
15
#include "fileio.h"
16
#include "format-util.h"
17
#include "fs-util.h"
18
#include "fstab-util.h"
19
#include "glyph-util.h"
20
#include "hashmap.h"
21
#include "libmount-util.h"
22
#include "log.h"
23
#include "mkdir-label.h"
24
#include "mount-util.h"
25
#include "mountpoint-util.h"
26
#include "namespace-util.h"
27
#include "os-util.h"
28
#include "path-util.h"
29
#include "pidref.h"
30
#include "process-util.h"
31
#include "runtime-scope.h"
32
#include "set.h"
33
#include "sort-util.h"
34
#include "stat-util.h"
35
#include "string-util.h"
36
#include "strv.h"
37
#include "tmpfile-util.h"
38
#include "user-util.h"
39

40
int umount_recursive_full(const char *prefix, int flags, char **keep) {
8,219✔
41
        _cleanup_fclose_ FILE *f = NULL;
8,219✔
42
        int n = 0, r;
8,219✔
43

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

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

51
        for (;;) {
17,939✔
52
                _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
26,158✔
53
                _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
17,939✔
54
                bool again = false;
26,158✔
55

56
                r = libmount_parse_full("/proc/self/mountinfo", f, MNT_ITER_BACKWARD, &table, &iter);
26,158✔
57
                if (r < 0)
26,158✔
58
                        return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
59

60
                for (;;) {
1,515,340✔
61
                        bool shall_keep = false;
770,749✔
62
                        struct libmnt_fs *fs;
770,749✔
63
                        const char *path;
770,749✔
64

65
                        r = sym_mnt_table_next_fs(table, iter, &fs);
770,749✔
66
                        if (r == 1)
770,749✔
67
                                break;
68
                        if (r < 0)
762,530✔
69
                                return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
70

71
                        path = sym_mnt_fs_get_target(fs);
762,530✔
72
                        if (!path)
762,530✔
73
                                continue;
744,591✔
74

75
                        if (prefix && !path_startswith(path, prefix)) {
1,519,734✔
76
                                // FIXME: This is extremely noisy, we're probably doing something very wrong
77
                                // to trigger this so often, needs more investigation.
78
                                // log_trace("Not unmounting %s, outside of prefix: %s", path, prefix);
79
                                continue;
736,210✔
80
                        }
81

82
                        STRV_FOREACH(k, keep)
26,603✔
83
                                /* Match against anything in the path to the dirs to keep, or below the dirs to keep */
84
                                if (path_startswith(path, *k) || path_startswith(*k, path)) {
5,287✔
85
                                        shall_keep = true;
5,004✔
86
                                        break;
5,004✔
87
                                }
88
                        if (shall_keep) {
31,324✔
89
                                log_debug("Not unmounting %s, referenced by keep list.", path);
5,004✔
90
                                continue;
5,004✔
91
                        }
92

93
                        if (umount2(path, flags | UMOUNT_NOFOLLOW) < 0) {
21,316✔
94
                                log_debug_errno(errno, "Failed to umount %s, ignoring: %m", path);
3,377✔
95
                                continue;
3,377✔
96
                        }
97

98
                        log_trace("Successfully unmounted %s", path);
17,939✔
99

100
                        again = true;
17,939✔
101
                        n++;
17,939✔
102

103
                        break;
17,939✔
104
                }
105

106
                if (!again)
8,219✔
107
                        break;
108

109
                rewind(f);
17,939✔
110
        }
111

112
        return n;
8,219✔
113
}
114

115
#define MS_CONVERTIBLE_FLAGS (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_NOSYMFOLLOW|MS_RELATIME|MS_NOATIME|MS_STRICTATIME|MS_NODIRATIME)
116

117
static uint64_t ms_flags_to_mount_attr(unsigned long a) {
35,450✔
118
        uint64_t f = 0;
35,450✔
119

120
        if (FLAGS_SET(a, MS_RDONLY))
35,450✔
121
                f |= MOUNT_ATTR_RDONLY;
1,400✔
122

123
        if (FLAGS_SET(a, MS_NOSUID))
35,450✔
124
                f |= MOUNT_ATTR_NOSUID;
17,343✔
125

126
        if (FLAGS_SET(a, MS_NODEV))
35,450✔
127
                f |= MOUNT_ATTR_NODEV;
2,034✔
128

129
        if (FLAGS_SET(a, MS_NOEXEC))
35,450✔
130
                f |= MOUNT_ATTR_NOEXEC;
2,034✔
131

132
        if (FLAGS_SET(a, MS_NOSYMFOLLOW))
35,450✔
133
                f |= MOUNT_ATTR_NOSYMFOLLOW;
2,032✔
134

135
        if (FLAGS_SET(a, MS_RELATIME))
35,450✔
136
                f |= MOUNT_ATTR_RELATIME;
35,450✔
137

138
        if (FLAGS_SET(a, MS_NOATIME))
35,450✔
139
                f |= MOUNT_ATTR_NOATIME;
×
140

141
        if (FLAGS_SET(a, MS_STRICTATIME))
35,450✔
142
                f |= MOUNT_ATTR_STRICTATIME;
×
143

144
        if (FLAGS_SET(a, MS_NODIRATIME))
35,450✔
145
                f |= MOUNT_ATTR_NODIRATIME;
×
146

147
        return f;
35,450✔
148
}
149

150
static uint64_t ms_flags_to_mount_attr_clr(unsigned long a) {
2✔
151
        uint64_t f = 0;
2✔
152

153
        /* As per documentation, if relatime/noatime/strictatime are set, we need to clear the atime flag
154
         * too, otherwise -EINVAL will be returned by the kernel. */
155
        if (FLAGS_SET(a, MS_RELATIME))
2✔
156
                f |= MOUNT_ATTR__ATIME;
×
157

158
        if (FLAGS_SET(a, MS_NOATIME))
2✔
159
                f |= MOUNT_ATTR__ATIME;
×
160

161
        if (FLAGS_SET(a, MS_STRICTATIME))
2✔
162
                f |= MOUNT_ATTR__ATIME;
×
163

164
        return f;
2✔
165
}
166

167
static bool skip_mount_set_attr = false;
168

169
/* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
170
 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
171
int bind_remount_recursive_with_mountinfo(
31,377✔
172
                const char *prefix,
173
                unsigned long new_flags,
174
                unsigned long flags_mask,
175
                char **deny_list,
176
                FILE *proc_self_mountinfo) {
177

178
        _cleanup_fclose_ FILE *proc_self_mountinfo_opened = NULL;
31,377✔
179
        _cleanup_set_free_ Set *done = NULL;
31,377✔
180
        unsigned n_tries = 0;
31,377✔
181
        int r;
31,377✔
182

183
        assert(prefix);
31,377✔
184

185
        if ((flags_mask & ~MS_CONVERTIBLE_FLAGS) == 0 && strv_isempty(deny_list) && !skip_mount_set_attr) {
45,976✔
186
                /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
187

188
                if (mount_setattr(AT_FDCWD, prefix, AT_SYMLINK_NOFOLLOW|AT_RECURSIVE,
14,599✔
189
                                  &(struct mount_attr) {
14,599✔
190
                                          .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
14,599✔
191
                                          .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
14,599✔
192
                                  }, MOUNT_ATTR_SIZE_VER0) < 0) {
193

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

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

203
                        if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
2✔
204
                                skip_mount_set_attr = true;
×
205
                } else
206
                        return 0; /* Nice, this worked! */
14,597✔
207
        }
208

209
        if (!proc_self_mountinfo) {
16,780✔
210
                r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo_opened);
3✔
211
                if (r < 0)
3✔
212
                        return r;
213

214
                proc_self_mountinfo = proc_self_mountinfo_opened;
3✔
215
        }
216

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

231
        for (;;) {
33,562✔
232
                _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
33,562✔
233
                _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
33,562✔
234
                _cleanup_hashmap_free_ Hashmap *todo = NULL;
33,560✔
235
                bool top_autofs = false;
33,562✔
236

237
                if (n_tries++ >= 32) /* Let's not retry this loop forever */
33,562✔
238
                        return -EBUSY;
239

240
                rewind(proc_self_mountinfo);
33,562✔
241

242
                r = libmount_parse_mountinfo(proc_self_mountinfo, &table, &iter);
33,562✔
243
                if (r < 0)
33,562✔
244
                        return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
245

246
                for (;;) {
2,352,268✔
247
                        _cleanup_free_ char *d = NULL;
2,318,706✔
248
                        const char *path, *type, *opts;
2,352,268✔
249
                        unsigned long flags = 0;
2,352,268✔
250
                        struct libmnt_fs *fs;
2,352,268✔
251

252
                        r = sym_mnt_table_next_fs(table, iter, &fs);
2,352,268✔
253
                        if (r == 1) /* EOF */
2,352,268✔
254
                                break;
255
                        if (r < 0)
2,318,706✔
256
                                return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
257

258
                        path = sym_mnt_fs_get_target(fs);
2,318,706✔
259
                        if (!path)
2,318,706✔
260
                                continue;
×
261

262
                        if (!path_startswith(path, prefix))
2,318,706✔
263
                                continue;
2,258,095✔
264

265
                        type = sym_mnt_fs_get_fstype(fs);
60,611✔
266
                        if (!type)
60,611✔
267
                                continue;
×
268

269
                        /* Let's ignore autofs mounts. If they aren't triggered yet, we want to avoid
270
                         * triggering them, as we don't make any guarantees for future submounts anyway. If
271
                         * they are already triggered, then we will find another entry for this. */
272
                        if (streq(type, "autofs")) {
60,611✔
273
                                top_autofs = top_autofs || path_equal(path, prefix);
4,956✔
274
                                continue;
2,478✔
275
                        }
276

277
                        if (set_contains(done, path))
58,133✔
278
                                continue;
20,690✔
279

280
                        /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
281
                         * we shall operate on. */
282
                        if (!path_equal(path, prefix)) {
37,443✔
283
                                bool deny_listed = false;
263,348✔
284

285
                                STRV_FOREACH(i, deny_list) {
263,348✔
286
                                        if (path_equal(*i, prefix))
259,439✔
287
                                                continue;
20,650✔
288

289
                                        if (!path_startswith(*i, prefix))
238,789✔
290
                                                continue;
131,498✔
291

292
                                        if (path_startswith(path, *i)) {
107,291✔
293
                                                deny_listed = true;
294
                                                log_trace("Not remounting %s deny-listed by %s, called for %s", path, *i, prefix);
295
                                                break;
296
                                        }
297
                                }
298

299
                                if (deny_listed)
20,661✔
300
                                        continue;
16,752✔
301
                        }
302

303
                        opts = sym_mnt_fs_get_vfs_options(fs);
20,691✔
304
                        if (opts) {
20,691✔
305
                                r = sym_mnt_optstr_get_flags(opts, &flags, sym_mnt_get_builtin_optmap(MNT_LINUX_MAP));
20,691✔
306
                                if (r < 0)
20,691✔
307
                                        log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
×
308
                        }
309

310
                        d = strdup(path);
20,691✔
311
                        if (!d)
20,691✔
312
                                return -ENOMEM;
313

314
                        r = hashmap_ensure_put(&todo, &path_hash_ops_free, d, ULONG_TO_PTR(flags));
20,691✔
315
                        if (r == -EEXIST)
20,691✔
316
                                /* If the same path was recorded, but with different mount flags, update it:
317
                                 * it means a mount point is overmounted, and libmount returns the "bottom" (or
318
                                 * older one) first, but we want to reapply the flags from the "top" (or newer
319
                                 * one). See: https://github.com/systemd/systemd/issues/20032
320
                                 * Note that this shouldn't really fail, as we were just told that the key
321
                                 * exists, and it's an update so we want 'd' to be freed immediately. */
322
                                r = hashmap_update(todo, d, ULONG_TO_PTR(flags));
9✔
323
                        if (r < 0)
20,691✔
324
                                return r;
325
                        if (r > 0)
20,691✔
326
                                TAKE_PTR(d);
20,648✔
327
                }
328

329
                /* Check if the top-level directory was among what we have seen so far. For that check both
330
                 * 'done' and 'todo'. Also check 'top_autofs' because if the top-level dir is an autofs we'll
331
                 * not include it in either set but will set this bool. */
332
                if (!set_contains(done, prefix) &&
33,562✔
333
                    !(top_autofs || hashmap_contains(todo, prefix))) {
16,782✔
334

335
                        /* The prefix directory itself is not yet a mount, make it one. */
336
                        r = mount_nofollow(prefix, prefix, NULL, MS_BIND|MS_REC, NULL);
2✔
337
                        if (r < 0)
2✔
338
                                return r;
339

340
                        /* Immediately rescan, so that we pick up the new mount's flags */
341
                        continue;
2✔
342
                }
343

344
                /* If we have no submounts to process anymore, we are done */
345
                if (hashmap_isempty(todo))
33,560✔
346
                        return 0;
347

348
                for (;;) {
37,427✔
349
                        unsigned long flags;
37,427✔
350
                        char *x = NULL;
37,427✔
351

352
                        /* Take the first mount from our list of mounts to still process */
353
                        flags = PTR_TO_ULONG(hashmap_steal_first_key_and_value(todo, (void**) &x));
37,427✔
354
                        if (!x)
37,427✔
355
                                break;
356

357
                        r = set_ensure_consume(&done, &path_hash_ops_free, x);
20,647✔
358
                        if (IN_SET(r, 0, -EEXIST))
20,647✔
359
                                continue; /* Already done */
287✔
360
                        if (r < 0)
20,647✔
361
                                return r;
×
362

363
                        /* Now, remount this with the new flags set, but exclude MS_RELATIME from it. (It's
364
                         * the default anyway, thus redundant, and in userns we'll get an error if we try to
365
                         * explicitly enable it) */
366
                        r = mount_nofollow(NULL, x, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
20,647✔
367
                        if (r < 0) {
20,647✔
368
                                int q;
287✔
369

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

375
                                q = path_is_mount_point(x);
287✔
376
                                if (IN_SET(q, 0, -ENOENT)) {
287✔
377
                                        /* Hmm, whaaaa? The mount point is not actually a mount point? Then
378
                                         * it is either obstructed by a later mount or somebody has been
379
                                         * racing against us and removed it. Either way the mount point
380
                                         * doesn't matter to us, let's ignore it hence. */
381
                                        log_debug_errno(r, "Mount point '%s' to remount is not a mount point anymore, ignoring remount failure: %m", x);
283✔
382
                                        continue;
283✔
383
                                }
384
                                if (q < 0) /* Any other error on this? Just log and continue */
4✔
385
                                        log_debug_errno(q, "Failed to determine whether '%s' is a mount point or not, ignoring: %m", x);
×
386

387
                                if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) == 0) { /* ignore MS_RELATIME while comparing */
4✔
388
                                        log_debug_errno(r, "Couldn't remount '%s', but the flags already match what we want, hence ignoring: %m", x);
×
389
                                        continue;
×
390
                                }
391

392
                                /* Make this fatal if this is the top-level mount */
393
                                if (path_equal(x, prefix))
4✔
394
                                        return r;
395

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

404
                        log_trace("Remounted %s.", x);
20,360✔
405
                }
406
        }
407
}
408

409
int bind_remount_one_with_mountinfo(
2,109✔
410
                const char *path,
411
                unsigned long new_flags,
412
                unsigned long flags_mask,
413
                FILE *proc_self_mountinfo) {
414

415
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
×
416
        unsigned long flags = 0;
2,109✔
417
        struct libmnt_fs *fs;
2,109✔
418
        const char *opts;
2,109✔
419
        int r;
2,109✔
420

421
        assert(path);
2,109✔
422
        assert(proc_self_mountinfo);
2,109✔
423

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

427
                if (mount_setattr(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW,
2,109✔
428
                                  &(struct mount_attr) {
2,109✔
429
                                          .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
2,109✔
430
                                          .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
2,109✔
431
                                  }, MOUNT_ATTR_SIZE_VER0) < 0) {
432

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

435
                        if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
4✔
436
                                skip_mount_set_attr = true;
×
437
                } else
438
                        return 0; /* Nice, this worked! */
2,105✔
439
        }
440

441
        rewind(proc_self_mountinfo);
4✔
442

443
        r = dlopen_libmount();
4✔
444
        if (r < 0)
4✔
445
                return r;
446

447
        table = sym_mnt_new_table();
4✔
448
        if (!table)
4✔
449
                return -ENOMEM;
450

451
        r = sym_mnt_table_parse_stream(table, proc_self_mountinfo, "/proc/self/mountinfo");
4✔
452
        if (r < 0)
4✔
453
                return r;
454

455
        fs = sym_mnt_table_find_target(table, path, MNT_ITER_FORWARD);
4✔
456
        if (!fs) {
4✔
457
                r = access_nofollow(path, F_OK); /* Hmm, it's not in the mount table, but does it exist at all? */
4✔
458
                if (r < 0)
4✔
459
                        return r;
460

461
                return -EINVAL; /* Not a mount point we recognize */
2✔
462
        }
463

464
        opts = sym_mnt_fs_get_vfs_options(fs);
×
465
        if (opts) {
×
466
                r = sym_mnt_optstr_get_flags(opts, &flags, sym_mnt_get_builtin_optmap(MNT_LINUX_MAP));
×
467
                if (r < 0)
×
468
                        log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
×
469
        }
470

471
        r = mount_nofollow(NULL, path, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
×
472
        if (r < 0) {
×
473
                if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) != 0) /* Ignore MS_RELATIME again,
×
474
                                                                             * since kernel adds it in
475
                                                                             * everywhere, because it's the
476
                                                                             * default. */
477
                        return r;
478

479
                /* Let's handle redundant remounts gracefully */
480
                log_debug_errno(r, "Failed to remount '%s' but flags already match what we want, ignoring: %m", path);
2,109✔
481
        }
482

483
        return 0;
484
}
485

486
int bind_remount_one(const char *path, unsigned long new_flags, unsigned long flags_mask) {
57✔
487
        _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
57✔
488

489
        proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
57✔
490
        if (!proc_self_mountinfo)
57✔
491
                return log_debug_errno(errno, "Failed to open %s: %m", "/proc/self/mountinfo");
×
492

493
        return bind_remount_one_with_mountinfo(path, new_flags, flags_mask, proc_self_mountinfo);
57✔
494
}
495

496
static int mount_switch_root_pivot(int fd_newroot, const char *path) {
2,229✔
497
        assert(fd_newroot >= 0);
2,229✔
498
        assert(path);
2,229✔
499

500
        /* Let the kernel tuck the new root under the old one. */
501
        if (pivot_root(".", ".") < 0)
2,229✔
502
                return log_debug_errno(errno, "Failed to pivot root to new rootfs '%s': %m", path);
×
503

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

509
        return 0;
510
}
511

512
static int mount_switch_root_move(int fd_newroot, const char *path) {
×
513
        assert(fd_newroot >= 0);
×
514
        assert(path);
×
515

516
        /* Move the new root fs */
517
        if (mount(".", "/", NULL, MS_MOVE, NULL) < 0)
×
518
                return log_debug_errno(errno, "Failed to move new rootfs '%s': %m", path);
×
519

520
        /* Also change root dir */
521
        if (chroot(".") < 0)
×
522
                return log_debug_errno(errno, "Failed to chroot to new rootfs '%s': %m", path);
×
523

524
        return 0;
525
}
526

527
int mount_switch_root_full(const char *path, unsigned long mount_propagation_flag, bool force_ms_move) {
2,231✔
528
        _cleanup_close_ int fd_newroot = -EBADF;
2,231✔
529
        int r, is_current_root;
2,231✔
530

531
        assert(path);
2,231✔
532
        assert(mount_propagation_flag_is_valid(mount_propagation_flag));
2,231✔
533

534
        fd_newroot = open(path, O_PATH|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
2,231✔
535
        if (fd_newroot < 0)
2,231✔
536
                return log_debug_errno(errno, "Failed to open new rootfs '%s': %m", path);
×
537

538
        is_current_root = path_is_root_at(fd_newroot, NULL);
2,231✔
539
        if (is_current_root < 0)
2,231✔
540
                return log_debug_errno(is_current_root, "Failed to determine if target dir is our root already: %m");
×
541

542
        /* Change into the new rootfs. */
543
        if (fchdir(fd_newroot) < 0)
2,231✔
544
                return log_debug_errno(errno, "Failed to chdir into new rootfs '%s': %m", path);
×
545

546
        /* Make this a NOP if we are supposed to switch to our current root fs. After all, both pivot_root()
547
         * and MS_MOVE don't like that. */
548
        if (!is_current_root) {
2,231✔
549
                if (!force_ms_move) {
2,229✔
550
                        r = mount_switch_root_pivot(fd_newroot, path);
2,229✔
551
                        if (r < 0) {
2,229✔
552
                                log_debug_errno(r, "Failed to pivot into new rootfs '%s', will try to use MS_MOVE instead: %m", path);
×
553
                                force_ms_move = true;
554
                        }
555
                }
556
                if (force_ms_move) {
557
                        /* Failed to pivot_root() fallback to MS_MOVE. For example, this may happen if the rootfs is
558
                         * an initramfs in which case pivot_root() isn't supported. */
559
                        r = mount_switch_root_move(fd_newroot, path);
×
560
                        if (r < 0)
×
561
                                return log_debug_errno(r, "Failed to switch to new rootfs '%s' with MS_MOVE: %m", path);
×
562
                }
563
        }
564

565
        log_debug("Successfully switched root to '%s'.", path);
2,231✔
566

567
        /* Finally, let's establish the requested propagation flags. */
568
        if (mount_propagation_flag == 0)
2,231✔
569
                return 0;
570

571
        if (mount(NULL, ".", NULL, mount_propagation_flag | MS_REC, NULL) < 0)
241✔
572
                return log_debug_errno(errno, "Failed to turn new rootfs '%s' into %s mount: %m",
×
573
                                       mount_propagation_flag_to_string(mount_propagation_flag), path);
574

575
        return 0;
576
}
577

578
int repeat_unmount(const char *path, int flags) {
17✔
579
        bool done = false;
17✔
580

581
        assert(path);
17✔
582

583
        /* If there are multiple mounts on a mount point, this
584
         * removes them all */
585

586
        for (;;) {
34✔
587
                if (umount2(path, flags) < 0) {
34✔
588

589
                        if (errno == EINVAL)
17✔
590
                                return done;
17✔
591

592
                        return -errno;
×
593
                }
594

595
                done = true;
596
        }
597
}
598

599
int mode_to_inaccessible_node(
4,621✔
600
                const char *runtime_dir,
601
                mode_t mode,
602
                char **ret) {
603

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

615
        _cleanup_free_ char *d = NULL;
4,621✔
616
        const char *node;
4,621✔
617

618
        assert(ret);
4,621✔
619

620
        if (!runtime_dir)
4,621✔
621
                runtime_dir = "/run";
4✔
622

623
        if (S_ISLNK(mode))
4,621✔
624
                return -EINVAL;
625

626
        node = inode_type_to_string(mode);
4,621✔
627
        if (!node)
4,621✔
628
                return -EINVAL;
629

630
        d = path_join(runtime_dir, "systemd/inaccessible", node);
4,621✔
631
        if (!d)
4,621✔
632
                return -ENOMEM;
633

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

642
        if (S_ISBLK(mode) &&
4,621✔
643
            access(d, F_OK) < 0 && errno == ENOENT) {
×
644
                free(d);
×
645
                d = path_join(runtime_dir, "/systemd/inaccessible/chr");
×
646
                if (!d)
×
647
                        return -ENOMEM;
648
        }
649

650
        if (IN_SET(mode & S_IFMT, S_IFBLK, S_IFCHR) &&
5,149✔
651
            access(d, F_OK) < 0 && errno == ENOENT) {
528✔
652
                free(d);
×
653
                d = path_join(runtime_dir, "/systemd/inaccessible/sock");
×
654
                if (!d)
×
655
                        return -ENOMEM;
656
        }
657

658
        *ret = TAKE_PTR(d);
4,621✔
659
        return 0;
4,621✔
660
}
661

662
int mount_flags_to_string(unsigned long flags, char **ret) {
38,101✔
663
        static const struct {
38,101✔
664
                unsigned long flag;
665
                const char *name;
666
        } map[] = {
667
                { .flag = MS_RDONLY,      .name = "MS_RDONLY",      },
668
                { .flag = MS_NOSUID,      .name = "MS_NOSUID",      },
669
                { .flag = MS_NODEV,       .name = "MS_NODEV",       },
670
                { .flag = MS_NOEXEC,      .name = "MS_NOEXEC",      },
671
                { .flag = MS_SYNCHRONOUS, .name = "MS_SYNCHRONOUS", },
672
                { .flag = MS_REMOUNT,     .name = "MS_REMOUNT",     },
673
                { .flag = MS_MANDLOCK,    .name = "MS_MANDLOCK",    },
674
                { .flag = MS_DIRSYNC,     .name = "MS_DIRSYNC",     },
675
                { .flag = MS_NOSYMFOLLOW, .name = "MS_NOSYMFOLLOW", },
676
                { .flag = MS_NOATIME,     .name = "MS_NOATIME",     },
677
                { .flag = MS_NODIRATIME,  .name = "MS_NODIRATIME",  },
678
                { .flag = MS_BIND,        .name = "MS_BIND",        },
679
                { .flag = MS_MOVE,        .name = "MS_MOVE",        },
680
                { .flag = MS_REC,         .name = "MS_REC",         },
681
                { .flag = MS_SILENT,      .name = "MS_SILENT",      },
682
                { .flag = MS_POSIXACL,    .name = "MS_POSIXACL",    },
683
                { .flag = MS_UNBINDABLE,  .name = "MS_UNBINDABLE",  },
684
                { .flag = MS_PRIVATE,     .name = "MS_PRIVATE",     },
685
                { .flag = MS_SLAVE,       .name = "MS_SLAVE",       },
686
                { .flag = MS_SHARED,      .name = "MS_SHARED",      },
687
                { .flag = MS_RELATIME,    .name = "MS_RELATIME",    },
688
                { .flag = MS_KERNMOUNT,   .name = "MS_KERNMOUNT",   },
689
                { .flag = MS_I_VERSION,   .name = "MS_I_VERSION",   },
690
                { .flag = MS_STRICTATIME, .name = "MS_STRICTATIME", },
691
                { .flag = MS_LAZYTIME,    .name = "MS_LAZYTIME",    },
692
        };
693
        _cleanup_free_ char *str = NULL;
38,101✔
694

695
        assert(ret);
38,101✔
696

697
        FOREACH_ELEMENT(entry, map)
990,626✔
698
                if (flags & entry->flag) {
952,525✔
699
                        if (!strextend_with_separator(&str, "|", entry->name))
86,057✔
700
                                return -ENOMEM;
701
                        flags &= ~entry->flag;
86,057✔
702
                }
703

704
        if (!str || flags != 0)
38,101✔
705
                if (strextendf_with_separator(&str, "|", "%lx", flags) < 0)
144✔
706
                        return -ENOMEM;
707

708
        *ret = TAKE_PTR(str);
38,101✔
709
        return 0;
38,101✔
710
}
711

712
int mount_verbose_full(
38,071✔
713
                int error_log_level,
714
                const char *what,
715
                const char *where,
716
                const char *type,
717
                unsigned long flags,
718
                const char *options,
719
                bool follow_symlink) {
720

721
        _cleanup_free_ char *fl = NULL, *o = NULL;
38,071✔
722
        unsigned long f;
38,071✔
723
        int r;
38,071✔
724

725
        r = mount_option_mangle(options, flags, &f, &o);
38,071✔
726
        if (r < 0)
38,071✔
727
                return log_full_errno(error_log_level, r,
×
728
                                      "Failed to mangle mount options %s: %m",
729
                                      strempty(options));
730

731
        (void) mount_flags_to_string(f, &fl);
38,071✔
732

733
        if (FLAGS_SET(f, MS_REMOUNT|MS_BIND))
38,071✔
734
                log_debug("Changing mount flags %s (%s \"%s\")...",
7,129✔
735
                          where, strnull(fl), strempty(o));
736
        else if (f & MS_REMOUNT)
34,506✔
737
                log_debug("Remounting superblock %s (%s \"%s\")...",
4✔
738
                          where, strnull(fl), strempty(o));
739
        else if (f & (MS_SHARED|MS_PRIVATE|MS_SLAVE|MS_UNBINDABLE))
34,502✔
740
                log_debug("Changing mount propagation %s (%s \"%s\")",
2,674✔
741
                          where, strnull(fl), strempty(o));
742
        else if (f & MS_BIND)
33,165✔
743
                log_debug("Bind-mounting %s on %s (%s \"%s\")...",
50,490✔
744
                          what, where, strnull(fl), strempty(o));
745
        else if (f & MS_MOVE)
7,910✔
746
                log_debug("Moving mount %s %s %s (%s \"%s\")...",
3,382✔
747
                          what, glyph(GLYPH_ARROW_RIGHT), where, strnull(fl), strempty(o));
748
        else
749
                log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
7,603✔
750
                          strna(what), strna(type), where, strnull(fl), strempty(o));
751

752
        if (follow_symlink)
38,071✔
753
                r = RET_NERRNO(mount(what, where, type, f, o));
38,472✔
754
        else
755
                r = mount_nofollow(what, where, type, f, o);
32,832✔
756
        if (r < 0)
33,233✔
757
                return log_full_errno(error_log_level, r,
8,993✔
758
                                      "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
759
                                      strna(what), strna(type), where, strnull(fl), strempty(o));
760
        return 0;
761
}
762

763
int umount_verbose(
550✔
764
                int error_log_level,
765
                const char *where,
766
                int flags) {
767

768
        assert(where);
550✔
769

770
        log_debug("Unmounting '%s'...", where);
550✔
771

772
        if (umount2(where, flags) < 0)
550✔
773
                return log_full_errno(error_log_level, errno, "Failed to unmount '%s': %m", where);
97✔
774

775
        return 0;
776
}
777

778
int umountat_detach_verbose(
238✔
779
                int error_log_level,
780
                int fd,
781
                const char *where) {
782

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

786
        assert(fd >= 0 || fd == AT_FDCWD);
238✔
787

788
        /* If neither fd nor path are specified take this as reference to the cwd */
789
        if (fd == AT_FDCWD && isempty(where))
238✔
790
                return umount_verbose(error_log_level, ".", MNT_DETACH|UMOUNT_NOFOLLOW);
238✔
791

792
        /* If we don't actually take the fd into consideration for this operation shortcut things, so that we
793
         * don't have to open the inode */
794
        if (fd == AT_FDCWD || path_is_absolute(where))
238✔
795
                return umount_verbose(error_log_level, where, MNT_DETACH|UMOUNT_NOFOLLOW);
×
796

797
        _cleanup_free_ char *prefix = NULL;
476✔
798
        const char *p;
238✔
799
        if (fd_get_path(fd, &prefix) < 0)
238✔
800
                p = "<fd>"; /* if we can't get the path, return something vaguely useful */
801
        else
802
                p = prefix;
238✔
803
        _cleanup_free_ char *joined = isempty(where) ? strdup(p) : path_join(p, where);
610✔
804

805
        log_debug("Unmounting '%s'...", strna(joined));
238✔
806

807
        _cleanup_close_ int inode_fd = -EBADF;
238✔
808
        int mnt_fd;
238✔
809
        if (isempty(where))
238✔
810
                mnt_fd = fd;
811
        else {
812
                inode_fd = openat(fd, where, O_PATH|O_CLOEXEC|O_NOFOLLOW);
134✔
813
                if (inode_fd < 0)
134✔
814
                        return log_full_errno(error_log_level, errno, "Failed to pin '%s': %m", strna(joined));
×
815

816
                mnt_fd = inode_fd;
817
        }
818

819
        if (umount2(FORMAT_PROC_FD_PATH(mnt_fd), MNT_DETACH) < 0)
238✔
820
                return log_full_errno(error_log_level, errno, "Failed to unmount '%s': %m", strna(joined));
15✔
821

822
        return 0;
223✔
823
}
824

825
int mount_exchange_graceful(int fsmount_fd, const char *dest, bool mount_beneath) {
27✔
826
        int r;
27✔
827

828
        assert(fsmount_fd >= 0);
27✔
829
        assert(dest);
27✔
830

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

838
        r = RET_NERRNO(move_mount(fsmount_fd, /* from_path = */ "",
39✔
839
                                  /* to_fd = */ -EBADF, dest,
840
                                  MOVE_MOUNT_F_EMPTY_PATH | (mount_beneath ? MOVE_MOUNT_BENEATH : 0)));
841
        if (mount_beneath) {
27✔
842
                if (r >= 0) /* Mounting beneath worked! Now unmount the upper mount. */
15✔
843
                        return umount_verbose(LOG_DEBUG, dest, UMOUNT_NOFOLLOW|MNT_DETACH);
11✔
844

845
                if (r == -EINVAL) { /* Fallback if mount_beneath is not supported */
4✔
846
                        log_debug_errno(r,
4✔
847
                                        "Cannot mount beneath '%s', falling back to overmount: %m",
848
                                        dest);
849
                        return mount_exchange_graceful(fsmount_fd, dest, /* mount_beneath = */ false);
4✔
850
                }
851
        }
852

853
        return r;
854
}
855

856
int mount_option_mangle(
38,143✔
857
                const char *options,
858
                unsigned long mount_flags,
859
                unsigned long *ret_mount_flags,
860
                char **ret_remaining_options) {
861

862
        const struct libmnt_optmap *map;
38,143✔
863
        _cleanup_free_ char *ret = NULL;
38,143✔
864
        int r;
38,143✔
865

866
        /* This extracts mount flags from the mount options, and stores
867
         * non-mount-flag options to '*ret_remaining_options'.
868
         * E.g.,
869
         * "rw,nosuid,nodev,relatime,size=1630748k,mode=0700,uid=1000,gid=1000"
870
         * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
871
         * "size=1630748k,mode=0700,uid=1000,gid=1000".
872
         * See more examples in test-mount-util.c.
873
         *
874
         * If 'options' does not contain any non-mount-flag options,
875
         * then '*ret_remaining_options' is set to NULL instead of empty string.
876
         * The validity of options stored in '*ret_remaining_options' is not checked.
877
         * If 'options' is NULL, this just copies 'mount_flags' to *ret_mount_flags. */
878

879
        assert(ret_mount_flags);
38,143✔
880
        assert(ret_remaining_options);
38,143✔
881

882
        r = dlopen_libmount();
38,143✔
883
        if (r < 0)
38,143✔
884
                return r;
885

886
        map = sym_mnt_get_builtin_optmap(MNT_LINUX_MAP);
38,143✔
887
        if (!map)
38,143✔
888
                return -EINVAL;
889

890
        for (const char *p = options;;) {
38,143✔
891
                _cleanup_free_ char *word = NULL;
15,971✔
892
                const struct libmnt_optmap *ent;
54,113✔
893

894
                r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
54,113✔
895
                if (r < 0)
54,113✔
896
                        return r;
897
                if (r == 0)
54,112✔
898
                        break;
899

900
                for (ent = map; ent->name; ent++) {
667,957✔
901
                        /* All entries in MNT_LINUX_MAP do not take any argument.
902
                         * Thus, ent->name does not contain "=" or "[=]". */
903
                        if (!streq(word, ent->name))
652,088✔
904
                                continue;
651,987✔
905

906
                        if (!(ent->mask & MNT_INVERT))
101✔
907
                                mount_flags |= ent->id;
92✔
908
                        else
909
                                mount_flags &= ~ent->id;
9✔
910

911
                        break;
912
                }
913

914
                /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
915
                if (!ent->name &&
31,839✔
916
                    !startswith_no_case(word, "x-") &&
31,736✔
917
                    !strextend_with_separator(&ret, ",", word))
15,867✔
918
                        return -ENOMEM;
919
        }
920

921
        *ret_mount_flags = mount_flags;
38,142✔
922
        *ret_remaining_options = TAKE_PTR(ret);
38,142✔
923

924
        return 0;
38,142✔
925
}
926

927
static int mount_in_namespace_legacy(
×
928
                const char *chased_src_path,
929
                int chased_src_fd,
930
                struct stat *chased_src_st,
931
                const char *propagate_path,
932
                const char *incoming_path,
933
                const char *dest,
934
                int pidns_fd,
935
                int mntns_fd,
936
                int root_fd,
937
                MountInNamespaceFlags flags,
938
                const MountOptions *options,
939
                const ImagePolicy *image_policy) {
940

941
        _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
×
942
        char mount_slave[] = "/tmp/propagate.XXXXXX", *mount_tmp, *mount_outside, *p;
×
943
        bool mount_slave_created = false, mount_slave_mounted = false,
×
944
                mount_tmp_created = false, mount_tmp_mounted = false,
×
945
                mount_outside_created = false, mount_outside_mounted = false;
×
946
        pid_t child;
×
947
        int r;
×
948

949
        assert(chased_src_path);
×
950
        assert(chased_src_fd >= 0);
×
951
        assert(chased_src_st);
×
952
        assert(propagate_path);
×
953
        assert(incoming_path);
×
954
        assert(dest);
×
955
        assert(pidns_fd >= 0);
×
956
        assert(mntns_fd >= 0);
×
957
        assert(root_fd >= 0);
×
958
        assert(!options || (flags & MOUNT_IN_NAMESPACE_IS_IMAGE));
×
959

960
        p = strjoina(propagate_path, "/");
×
961
        r = access_nofollow(p, F_OK);
×
962
        if (r < 0)
×
963
                return log_debug_errno(r == -ENOENT ? SYNTHETIC_ERRNO(EOPNOTSUPP) : r, "Target does not allow propagation of mount points");
×
964

965
        /* Our goal is to install a new bind mount into the container,
966
           possibly read-only. This is irritatingly complex
967
           unfortunately, currently.
968

969
           First, we start by creating a private playground in /tmp,
970
           that we can mount MS_SLAVE. (Which is necessary, since
971
           MS_MOVE cannot be applied to mounts with MS_SHARED parent
972
           mounts.) */
973

974
        if (!mkdtemp(mount_slave))
×
975
                return log_debug_errno(errno, "Failed to create playground %s: %m", mount_slave);
×
976

977
        mount_slave_created = true;
×
978

979
        r = mount_nofollow_verbose(LOG_DEBUG, mount_slave, mount_slave, NULL, MS_BIND, NULL);
×
980
        if (r < 0)
×
981
                goto finish;
×
982

983
        mount_slave_mounted = true;
×
984

985
        r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_slave, NULL, MS_SLAVE, NULL);
×
986
        if (r < 0)
×
987
                goto finish;
×
988

989
        /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
990
        mount_tmp = strjoina(mount_slave, "/mount");
×
991
        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);
×
992
        if (r < 0) {
×
993
                log_debug_errno(r, "Failed to create temporary mount point %s: %m", mount_tmp);
×
994
                goto finish;
×
995
        }
996

997
        mount_tmp_created = true;
×
998

999
        if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE)
×
1000
                r = verity_dissect_and_mount(
×
1001
                                chased_src_fd,
1002
                                chased_src_path,
1003
                                mount_tmp,
1004
                                options,
1005
                                image_policy,
1006
                                /* image_filter= */ NULL,
1007
                                /* extension_release_data= */ NULL,
1008
                                /* required_class= */ _IMAGE_CLASS_INVALID,
1009
                                /* verity= */ NULL,
1010
                                RUNTIME_SCOPE_SYSTEM,
1011
                                /* ret_image= */ NULL);
1012
        else
1013
                r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(chased_src_fd), mount_tmp, NULL, MS_BIND, NULL);
×
1014
        if (r < 0)
×
1015
                goto finish;
×
1016

1017
        mount_tmp_mounted = true;
×
1018

1019
        /* Third, we remount the new bind mount read-only if requested. */
1020
        if (flags & MOUNT_IN_NAMESPACE_READ_ONLY) {
×
1021
                r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_tmp, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
×
1022
                if (r < 0)
×
1023
                        goto finish;
×
1024
        }
1025

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

1029
        mount_outside = strjoina(propagate_path, "/XXXXXX");
×
1030
        if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
1031
                r = mkdtemp(mount_outside) ? 0 : -errno;
×
1032
        else {
1033
                r = mkostemp_safe(mount_outside);
×
1034
                safe_close(r);
×
1035
        }
1036
        if (r < 0) {
×
1037
                log_debug_errno(r, "Cannot create propagation file or directory %s: %m", mount_outside);
×
1038
                goto finish;
×
1039
        }
1040

1041
        mount_outside_created = true;
×
1042

1043
        r = mount_nofollow_verbose(LOG_DEBUG, mount_tmp, mount_outside, NULL, MS_MOVE, NULL);
×
1044
        if (r < 0)
×
1045
                goto finish;
×
1046

1047
        mount_outside_mounted = true;
×
1048
        mount_tmp_mounted = false;
×
1049

1050
        if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
1051
                (void) rmdir(mount_tmp);
×
1052
        else
1053
                (void) unlink(mount_tmp);
×
1054
        mount_tmp_created = false;
×
1055

1056
        (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
×
1057
        mount_slave_mounted = false;
×
1058

1059
        (void) rmdir(mount_slave);
×
1060
        mount_slave_created = false;
×
1061

1062
        if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0) {
×
1063
                log_debug_errno(errno, "Failed to create pipe: %m");
×
1064
                goto finish;
×
1065
        }
1066

1067
        r = namespace_fork(
×
1068
                        "(sd-bindmnt)",
1069
                        "(sd-bindmnt-inner)",
1070
                        /* except_fds= */ NULL,
1071
                        /* n_except_fds= */ 0,
1072
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
1073
                        pidns_fd,
1074
                        mntns_fd,
1075
                        /* netns_fd= */ -EBADF,
1076
                        /* userns_fd= */ -EBADF,
1077
                        root_fd,
1078
                        &child);
1079
        if (r < 0)
×
1080
                goto finish;
×
1081
        if (r == 0) {
×
1082
                _cleanup_free_ char *mount_outside_fn = NULL, *mount_inside = NULL;
×
1083

1084
                errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
×
1085

1086
                _cleanup_close_ int dest_fd = -EBADF;
×
1087
                _cleanup_free_ char *dest_fn = NULL;
×
1088
                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);
×
1089
                if (r < 0)
×
1090
                        log_debug_errno(r, "Failed to pin parent directory of mount '%s', ignoring: %m", dest);
×
1091
                else if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) {
×
1092
                        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);
×
1093
                        if (r < 0)
×
1094
                                log_debug_errno(r, "Failed to make mount point inode of mount '%s', ignoring: %m", dest);
×
1095
                }
1096

1097
                /* Fifth, move the mount to the right place inside */
1098
                r = path_extract_filename(mount_outside, &mount_outside_fn);
×
1099
                if (r < 0) {
×
1100
                        log_debug_errno(r, "Failed to extract filename from propagation file or directory '%s': %m", mount_outside);
×
1101
                        report_errno_and_exit(errno_pipe_fd[1], r);
×
1102
                }
1103

1104
                mount_inside = path_join(incoming_path, mount_outside_fn);
×
1105
                if (!mount_inside)
×
1106
                        report_errno_and_exit(errno_pipe_fd[1], log_oom_debug());
×
1107

1108
                r = mount_nofollow_verbose(LOG_DEBUG, mount_inside, dest_fd >= 0 ? FORMAT_PROC_FD_PATH(dest_fd) : dest, /* fstype= */ NULL, MS_MOVE, /* options= */ NULL);
×
1109
                if (r < 0)
×
1110
                        report_errno_and_exit(errno_pipe_fd[1], r);
×
1111

1112
                _exit(EXIT_SUCCESS);
×
1113
        }
1114

1115
        errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
×
1116

1117
        r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
×
1118
        if (r < 0) {
×
1119
                log_debug_errno(r, "Failed to wait for child: %m");
×
1120
                goto finish;
×
1121
        }
1122
        if (r != EXIT_SUCCESS) {
×
1123
                if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
×
1124
                        log_debug_errno(r, "Failed to mount: %m");
×
1125
                else
1126
                        log_debug("Child failed.");
×
1127
                goto finish;
×
1128
        }
1129

1130
finish:
×
1131
        if (mount_outside_mounted)
×
1132
                (void) umount_verbose(LOG_DEBUG, mount_outside, UMOUNT_NOFOLLOW);
×
1133
        if (mount_outside_created) {
×
1134
                if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
1135
                        (void) rmdir(mount_outside);
×
1136
                else
1137
                        (void) unlink(mount_outside);
×
1138
        }
1139

1140
        if (mount_tmp_mounted)
×
1141
                (void) umount_verbose(LOG_DEBUG, mount_tmp, UMOUNT_NOFOLLOW);
×
1142
        if (mount_tmp_created) {
×
1143
                if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
1144
                        (void) rmdir(mount_tmp);
×
1145
                else
1146
                        (void) unlink(mount_tmp);
×
1147
        }
1148

1149
        if (mount_slave_mounted)
×
1150
                (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
×
1151
        if (mount_slave_created)
×
1152
                (void) rmdir(mount_slave);
×
1153

1154
        return r;
×
1155
}
1156

1157
static int mount_in_namespace(
6✔
1158
                const PidRef *target,
1159
                const char *propagate_path,
1160
                const char *incoming_path,
1161
                const char *src,
1162
                const char *dest,
1163
                MountInNamespaceFlags flags,
1164
                const MountOptions *options,
1165
                const ImagePolicy *image_policy) {
1166

1167
        _cleanup_close_ int mntns_fd = -EBADF, root_fd = -EBADF, pidns_fd = -EBADF, chased_src_fd = -EBADF;
18✔
1168
        _cleanup_free_ char *chased_src_path = NULL;
6✔
1169
        struct stat st;
6✔
1170
        int r;
6✔
1171

1172
        assert(propagate_path);
6✔
1173
        assert(incoming_path);
6✔
1174
        assert(src);
6✔
1175
        assert(dest);
6✔
1176
        assert((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || (!options && !image_policy));
6✔
1177

1178
        if (!pidref_is_set(target))
12✔
1179
                return -ESRCH;
1180

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

1185
        r = is_our_namespace(mntns_fd, NAMESPACE_MOUNT);
6✔
1186
        if (r < 0)
6✔
1187
                return log_debug_errno(r, "Failed to determine if mount namespaces are equal: %m");
×
1188
        /* We can't add new mounts at runtime if the process wasn't started in a namespace */
1189
        if (r > 0)
6✔
1190
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to activate bind mount in target, not running in a mount namespace.");
×
1191

1192
        r = chase(src, NULL, 0, &chased_src_path, &chased_src_fd);
6✔
1193
        if (r < 0)
6✔
1194
                return log_debug_errno(r, "Failed to resolve source path '%s': %m", src);
×
1195
        log_debug("Chased source path '%s': %s", src, chased_src_path);
6✔
1196

1197
        if (fstat(chased_src_fd, &st) < 0)
6✔
1198
                return log_debug_errno(errno, "Failed to stat() resolved source path '%s': %m", src);
×
1199
        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✔
1200
                return log_debug_errno(SYNTHETIC_ERRNO(ELOOP), "Source path '%s' can't be a symbolic link.", src);
×
1201

1202
        if (!mount_new_api_supported()) /* Fallback if we can't use the new mount API */
6✔
1203
                return mount_in_namespace_legacy(
×
1204
                                chased_src_path,
1205
                                chased_src_fd,
1206
                                &st,
1207
                                propagate_path,
1208
                                incoming_path,
1209
                                dest,
1210
                                pidns_fd,
1211
                                mntns_fd,
1212
                                root_fd,
1213
                                flags,
1214
                                options,
1215
                                image_policy);
1216

1217
        _cleanup_(dissected_image_unrefp) DissectedImage *img = NULL;
×
1218
        _cleanup_close_ int new_mount_fd = -EBADF;
6✔
1219
        _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
6✔
1220
        pid_t child;
6✔
1221

1222
        if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) {
6✔
1223
                r = verity_dissect_and_mount(
2✔
1224
                                chased_src_fd,
1225
                                chased_src_path,
1226
                                /* dest= */ NULL,
1227
                                options,
1228
                                image_policy,
1229
                                /* image_filter= */ NULL,
1230
                                /* extension_release_data= */ NULL,
1231
                                /* required_class= */ _IMAGE_CLASS_INVALID,
1232
                                /* verity= */ NULL,
1233
                                RUNTIME_SCOPE_SYSTEM,
1234
                                &img);
1235
                if (r < 0)
2✔
1236
                        return log_debug_errno(r,
×
1237
                                               "Failed to dissect and mount image '%s': %m",
1238
                                               chased_src_path);
1239
        } else {
1240
                new_mount_fd = open_tree(
4✔
1241
                                chased_src_fd,
1242
                                "",
1243
                                OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH);
1244
                if (new_mount_fd < 0)
4✔
1245
                        return log_debug_errno(
×
1246
                                        errno,
1247
                                        "Failed to open mount source '%s': %m",
1248
                                        chased_src_path);
1249

1250
                if ((flags & MOUNT_IN_NAMESPACE_READ_ONLY) && mount_setattr(new_mount_fd, "", AT_EMPTY_PATH,
4✔
1251
                                               &(struct mount_attr) {
×
1252
                                                       .attr_set = MOUNT_ATTR_RDONLY,
1253
                                               }, MOUNT_ATTR_SIZE_VER0) < 0)
1254
                        return log_debug_errno(errno,
×
1255
                                               "Failed to set mount for '%s' to read only: %m",
1256
                                               chased_src_path);
1257
        }
1258

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

1262
        r = namespace_fork("(sd-bindmnt)",
6✔
1263
                           "(sd-bindmnt-inner)",
1264
                           /* except_fds= */ NULL,
1265
                           /* n_except_fds= */ 0,
1266
                           FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
1267
                           pidns_fd,
1268
                           mntns_fd,
1269
                           /* netns_fd= */ -EBADF,
1270
                           /* userns_fd= */ -EBADF,
1271
                           root_fd,
1272
                           &child);
1273
        if (r < 0)
12✔
1274
                return log_debug_errno(r, "Failed to fork off mount helper into namespace: %m");
×
1275
        if (r == 0) {
12✔
1276
                errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
6✔
1277

1278
                _cleanup_close_ int dest_fd = -EBADF;
×
1279
                _cleanup_free_ char *dest_fn = NULL;
×
1280
                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✔
1281
                if (r < 0)
6✔
1282
                        report_errno_and_exit(errno_pipe_fd[1], r);
×
1283

1284
                if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY)
6✔
1285
                        (void) make_mount_point_inode_from_mode(dest_fd, dest_fn, img ? S_IFDIR : st.st_mode, 0700);
6✔
1286

1287
                if (img) {
6✔
1288
                        DissectImageFlags f =
2✔
1289
                                DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE |
1290
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
1291

1292
                        if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY)
2✔
1293
                                f |= DISSECT_IMAGE_MKDIR;
2✔
1294

1295
                        if (flags & MOUNT_IN_NAMESPACE_READ_ONLY)
2✔
1296
                                f |= DISSECT_IMAGE_READ_ONLY;
×
1297

1298
                        r = dissected_image_mount(
2✔
1299
                                        img,
1300
                                        dest,
1301
                                        /* uid_shift= */ UID_INVALID,
1302
                                        /* uid_range= */ UID_INVALID,
1303
                                        /* userns_fd= */ -EBADF,
1304
                                        f);
1305
                } else
1306
                        r = mount_exchange_graceful(new_mount_fd, dest, /* mount_beneath= */ true);
4✔
1307

1308
                report_errno_and_exit(errno_pipe_fd[1], r);
6✔
1309
        }
1310

1311
        errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
6✔
1312

1313
        r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
6✔
1314
        if (r < 0)
6✔
1315
                return log_debug_errno(r, "Failed to wait for child: %m");
×
1316
        if (r != EXIT_SUCCESS) {
6✔
1317
                if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
×
1318
                        return log_debug_errno(r, "Failed to mount into namespace: %m");
×
1319

1320
                return log_debug_errno(SYNTHETIC_ERRNO(EPROTO), "Child failed.");
×
1321
        }
1322

1323
        return 0;
1324
}
1325

1326
int bind_mount_in_namespace(
4✔
1327
                const PidRef *target,
1328
                const char *propagate_path,
1329
                const char *incoming_path,
1330
                const char *src,
1331
                const char *dest,
1332
                MountInNamespaceFlags flags) {
1333

1334
        return mount_in_namespace(target,
8✔
1335
                                  propagate_path,
1336
                                  incoming_path,
1337
                                  src,
1338
                                  dest,
1339
                                  flags & ~MOUNT_IN_NAMESPACE_IS_IMAGE,
4✔
1340
                                  /* options = */ NULL,
1341
                                  /* image_policy = */ NULL);
1342
}
1343

1344
int mount_image_in_namespace(
2✔
1345
                const PidRef *target,
1346
                const char *propagate_path,
1347
                const char *incoming_path,
1348
                const char *src,
1349
                const char *dest,
1350
                MountInNamespaceFlags flags,
1351
                const MountOptions *options,
1352
                const ImagePolicy *image_policy) {
1353

1354
        return mount_in_namespace(target,
4✔
1355
                                  propagate_path,
1356
                                  incoming_path,
1357
                                  src,
1358
                                  dest,
1359
                                  flags | MOUNT_IN_NAMESPACE_IS_IMAGE,
2✔
1360
                                  options,
1361
                                  image_policy);
1362
}
1363

1364
int make_mount_point(const char *path) {
30✔
1365
        int r;
30✔
1366

1367
        assert(path);
30✔
1368

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

1371
        r = path_is_mount_point(path);
30✔
1372
        if (r < 0)
30✔
1373
                return log_debug_errno(r, "Failed to determine whether '%s' is a mount point: %m", path);
×
1374
        if (r > 0)
30✔
1375
                return 0;
1376

1377
        r = mount_nofollow_verbose(LOG_DEBUG, path, path, NULL, MS_BIND|MS_REC, NULL);
14✔
1378
        if (r < 0)
14✔
1379
                return r;
×
1380

1381
        return 1;
1382
}
1383

1384
int fd_make_mount_point(int fd) {
13✔
1385
        int r;
13✔
1386

1387
        assert(fd >= 0);
13✔
1388

1389
        r = is_mount_point_at(fd, NULL, 0);
13✔
1390
        if (r < 0)
13✔
1391
                return log_debug_errno(r, "Failed to determine whether file descriptor is a mount point: %m");
×
1392
        if (r > 0)
13✔
1393
                return 0;
1394

1395
        r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(fd), FORMAT_PROC_FD_PATH(fd), NULL, MS_BIND|MS_REC, NULL);
1✔
1396
        if (r < 0)
1✔
1397
                return r;
×
1398

1399
        return 1;
1400
}
1401

1402
int make_userns(uid_t uid_shift,
130✔
1403
                uid_t uid_range,
1404
                uid_t source_owner,
1405
                uid_t dest_owner,
1406
                RemountIdmapping idmapping) {
1407

1408
        _cleanup_close_ int userns_fd = -EBADF;
130✔
1409
        _cleanup_free_ char *line = NULL;
130✔
1410
        uid_t source_base = 0;
130✔
1411

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

1415
        if (!userns_shift_range_valid(uid_shift, uid_range))
130✔
1416
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid UID range for user namespace.");
×
1417

1418
        switch (idmapping) {
130✔
1419

1420
        case REMOUNT_IDMAPPING_FOREIGN_WITH_HOST_ROOT:
2✔
1421
                source_base = FOREIGN_UID_BASE;
2✔
1422
                _fallthrough_;
92✔
1423

1424
        case REMOUNT_IDMAPPING_NONE:
92✔
1425
        case REMOUNT_IDMAPPING_HOST_ROOT:
1426

1427
                if (asprintf(&line,
92✔
1428
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
1429
                             source_base, uid_shift, uid_range) < 0)
1430
                        return log_oom_debug();
×
1431

1432
                /* If requested we'll include an entry in the mapping so that the host root user can make
1433
                 * changes to the uidmapped mount like it normally would. Specifically, we'll map the user
1434
                 * with UID_MAPPED_ROOT on the backing fs to UID 0. This is useful, since nspawn code wants
1435
                 * to create various missing inodes in the OS tree before booting into it, and this becomes
1436
                 * very easy and straightforward to do if it can just do it under its own regular UID. Note
1437
                 * that in that case the container's runtime uidmap (i.e. the one the container payload
1438
                 * processes run in) will leave this UID unmapped, i.e. if we accidentally leave files owned
1439
                 * by host root in the already uidmapped tree around they'll show up as owned by 'nobody',
1440
                 * which is safe. (Of course, we shouldn't leave such inodes around, but always chown() them
1441
                 * to the container's own UID range, but it's good to have a safety net, in case we
1442
                 * forget it.) */
1443
                if (idmapping == REMOUNT_IDMAPPING_HOST_ROOT)
92✔
1444
                        if (strextendf(&line,
90✔
1445
                                       UID_FMT " " UID_FMT " " UID_FMT "\n",
1446
                                       UID_MAPPED_ROOT, (uid_t) 0u, (uid_t) 1u) < 0)
1447
                                return log_oom_debug();
×
1448

1449
                break;
1450

1451
        case REMOUNT_IDMAPPING_HOST_OWNER:
6✔
1452
                /* Remap the owner of the bind mounted directory to the root user within the container. This
1453
                 * way every file written by root within the container to the bind-mounted directory will
1454
                 * be owned by the original user from the host. All other users will remain unmapped. */
1455
                if (asprintf(&line,
6✔
1456
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
1457
                             source_owner, uid_shift, (uid_t) 1u) < 0)
1458
                        return log_oom_debug();
×
1459
                break;
1460

1461
        case REMOUNT_IDMAPPING_HOST_OWNER_TO_TARGET_OWNER:
32✔
1462
                /* Remap the owner of the bind mounted directory to the owner of the target directory
1463
                 * within the container. This way every file written by target directory owner within the
1464
                 * container to the bind-mounted directory will be owned by the original host user.
1465
                 * All other users will remain unmapped. */
1466
                if (asprintf(&line,
32✔
1467
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
1468
                             source_owner, dest_owner, (uid_t) 1u) < 0)
1469
                        return log_oom_debug();
×
1470
                break;
1471

1472
        default:
×
1473
                assert_not_reached();
×
1474
        }
1475

1476
        /* We always assign the same UID and GID ranges */
1477
        userns_fd = userns_acquire(line, line, /* setgroups_deny= */ true);
130✔
1478
        if (userns_fd < 0)
130✔
1479
                return log_debug_errno(userns_fd, "Failed to acquire new userns: %m");
×
1480

1481
        return TAKE_FD(userns_fd);
1482
}
1483

1484
int open_tree_attr_with_fallback(int dir_fd, const char *path, unsigned flags, struct mount_attr *attr) {
179✔
1485
        _cleanup_close_ int fd = -EBADF;
179✔
1486

1487
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
179✔
1488
        assert(attr);
179✔
1489

1490
        if (isempty(path)) {
179✔
1491
                path = "";
×
1492
                flags |= AT_EMPTY_PATH;
×
1493
        }
1494

1495
        fd = open_tree_attr(dir_fd, path, flags, attr, sizeof(struct mount_attr));
179✔
1496
        if (fd >= 0)
179✔
1497
                return TAKE_FD(fd);
179✔
1498
        if (!ERRNO_IS_NOT_SUPPORTED(errno))
15✔
1499
                return log_debug_errno(errno, "Failed to open tree and set mount attributes: %m");
2✔
1500

1501
        if (attr->attr_clr & MOUNT_ATTR_IDMAP)
13✔
1502
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Cannot clear idmap from mount without open_tree_attr()");
×
1503

1504
        fd = open_tree(dir_fd, path, flags);
13✔
1505
        if (fd < 0)
13✔
1506
                return log_debug_errno(errno, "Failed to open tree: %m");
×
1507

1508
        if (mount_setattr(fd, "", AT_EMPTY_PATH | (flags & AT_RECURSIVE), attr, sizeof(struct mount_attr)) < 0)
13✔
1509
                return log_debug_errno(errno, "Failed to change mount attributes: %m");
×
1510

1511
        return TAKE_FD(fd);
1512
}
1513

1514
int open_tree_try_drop_idmap(int dir_fd, const char *path, unsigned flags) {
38✔
1515
        /* Tries to drop MOUNT_ATTR_IDMAP while calling open_tree_attr(), but if that doesn't work just uses
1516
         * a regular open_tree() */
1517

1518
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
38✔
1519

1520
        if (isempty(path)) {
38✔
1521
                path = "";
×
1522
                flags |= AT_EMPTY_PATH;
×
1523
        }
1524

1525
        _cleanup_close_ int fd = open_tree_attr_with_fallback(
38✔
1526
                        dir_fd,
1527
                        path,
1528
                        flags,
1529
                        &(struct mount_attr) {
38✔
1530
                                .attr_clr = MOUNT_ATTR_IDMAP,
1531
                        });
1532
        if (fd < 0) {
38✔
1533
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(fd))
×
1534
                        return log_debug_errno(fd, "Failed to clear idmap of directory with open_tree_attr(): %m");
×
1535

1536
                log_debug_errno(fd, "Failed to clear idmap with open_tree_attr(), retrying open_tree() without clearing idmap: %m");
×
1537

1538
                fd = RET_NERRNO(open_tree(dir_fd, path, flags));
×
1539
                if (fd < 0)
×
1540
                        return log_debug_errno(fd, "Both open_tree() and open_tree_attr() failed, giving up: %m");
×
1541

1542
                log_debug("open_tree() without clearing idmap worked.");
×
1543
                return TAKE_FD(fd);
×
1544
        }
1545

1546
        log_debug("Successfully acquired mount fd with cleared idmap.");
38✔
1547
        return TAKE_FD(fd);
1548
}
1549

1550
int remount_idmap_fd(
141✔
1551
                char **paths,
1552
                int userns_fd,
1553
                uint64_t extra_mount_attr_set) {
1554

1555
        int r;
141✔
1556

1557
        assert(userns_fd >= 0);
141✔
1558

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

1564
        size_t n = strv_length(paths);
141✔
1565
        if (n == 0) /* Nothing to do? */
141✔
1566
                return 0;
141✔
1567

1568
        int *mount_fds = NULL;
141✔
1569
        size_t n_mounts_fds = 0;
141✔
1570

1571
        mount_fds = new(int, n);
141✔
1572
        if (!mount_fds)
141✔
1573
                return log_oom_debug();
×
1574

1575
        CLEANUP_ARRAY(mount_fds, n_mounts_fds, close_many_and_free);
141✔
1576

1577
        for (size_t i = 0; i < n; i++) {
280✔
1578
                /* Clone the mount point and et the user namespace mapping attribute on the cloned mount point. */
1579
                mount_fds[n_mounts_fds] = open_tree_attr_with_fallback(
282✔
1580
                                AT_FDCWD,
1581
                                paths[i],
141✔
1582
                                OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC,
1583
                                &(struct mount_attr) {
141✔
1584
                                          .attr_set = MOUNT_ATTR_IDMAP | extra_mount_attr_set,
141✔
1585
                                          .userns_fd = userns_fd,
1586
                                });
1587
                if (mount_fds[n_mounts_fds] < 0)
141✔
1588
                        return mount_fds[n_mounts_fds];
2✔
1589

1590
                n_mounts_fds++;
139✔
1591
        }
1592

1593
        for (size_t i = n; i > 0; i--) { /* Unmount the paths right-to-left */
278✔
1594
                /* Remove the old mount points now that we have a idmapped mounts as replacement for all of them */
1595
                r = umount_verbose(LOG_DEBUG, paths[i-1], UMOUNT_NOFOLLOW);
139✔
1596
                if (r < 0)
139✔
1597
                        return r;
1598
        }
1599

1600
        for (size_t i = 0; i < n; i++) { /* Mount the replacement mounts left-to-right */
278✔
1601
                /* And place the cloned version in its place */
1602
                log_debug("Mounting idmapped fs to '%s'", paths[i]);
139✔
1603
                if (move_mount(mount_fds[i], "", -EBADF, paths[i], MOVE_MOUNT_F_EMPTY_PATH) < 0)
139✔
1604
                        return log_debug_errno(errno, "Failed to attach UID mapped mount to '%s': %m", paths[i]);
×
1605
        }
1606

1607
        return 0;
1608
}
1609

1610
int remount_idmap(
128✔
1611
                char **p,
1612
                uid_t uid_shift,
1613
                uid_t uid_range,
1614
                uid_t source_owner,
1615
                uid_t dest_owner,
1616
                RemountIdmapping idmapping) {
1617

1618
        _cleanup_close_ int userns_fd = -EBADF;
128✔
1619

1620
        userns_fd = make_userns(uid_shift, uid_range, source_owner, dest_owner, idmapping);
128✔
1621
        if (userns_fd < 0)
128✔
1622
                return userns_fd;
1623

1624
        return remount_idmap_fd(p, userns_fd, /* extra_mount_attr_set= */ 0);
128✔
1625
}
1626

1627
static void sub_mount_clear(SubMount *s) {
5,623✔
1628
        assert(s);
5,623✔
1629

1630
        s->path = mfree(s->path);
5,623✔
1631
        s->mount_fd = safe_close(s->mount_fd);
5,623✔
1632
}
5,623✔
1633

1634
void sub_mount_array_free(SubMount *s, size_t n) {
1,197✔
1635
        assert(s || n == 0);
1,197✔
1636

1637
        for (size_t i = 0; i < n; i++)
6,011✔
1638
                sub_mount_clear(s + i);
4,814✔
1639

1640
        free(s);
1,197✔
1641
}
1,197✔
1642

1643
static int sub_mount_compare(const SubMount *a, const SubMount *b) {
7,215✔
1644
        assert(a);
7,215✔
1645
        assert(b);
7,215✔
1646
        assert(a->path);
7,215✔
1647
        assert(b->path);
7,215✔
1648

1649
        return path_compare(a->path, b->path);
7,215✔
1650
}
1651

1652
static void sub_mount_drop(SubMount *s, size_t n) {
1,815✔
1653
        assert(s || n == 0);
1,815✔
1654

1655
        for (size_t m = 0, i = 1; i < n; i++) {
5,432✔
1656
                if (path_startswith(s[i].path, s[m].path))
3,617✔
1657
                        sub_mount_clear(s + i);
809✔
1658
                else
1659
                        m = i;
1660
        }
1661
}
1,815✔
1662

1663
int get_sub_mounts(const char *prefix, SubMount **ret_mounts, size_t *ret_n_mounts) {
1,815✔
1664

1665
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
1,815✔
1666
        _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
1,815✔
1667
        SubMount *mounts = NULL;
1,815✔
1668
        size_t n = 0;
1,815✔
1669
        int r;
1,815✔
1670

1671
        CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1,815✔
1672

1673
        assert(prefix);
1,815✔
1674
        assert(ret_mounts);
1,815✔
1675
        assert(ret_n_mounts);
1,815✔
1676

1677
        r = libmount_parse_mountinfo(/* source = */ NULL, &table, &iter);
1,815✔
1678
        if (r < 0)
1,815✔
1679
                return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
1680

1681
        for (;;) {
92,894✔
1682
                _cleanup_close_ int mount_fd = -EBADF;
91,079✔
1683
                _cleanup_free_ char *p = NULL;
92,894✔
1684
                struct libmnt_fs *fs;
92,894✔
1685
                const char *path;
92,894✔
1686
                int id1, id2;
92,894✔
1687

1688
                r = sym_mnt_table_next_fs(table, iter, &fs);
92,894✔
1689
                if (r == 1)
92,894✔
1690
                        break; /* EOF */
1691
                if (r < 0)
91,079✔
1692
                        return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
1693

1694
                path = sym_mnt_fs_get_target(fs);
91,079✔
1695
                if (!path)
91,079✔
1696
                        continue;
×
1697

1698
                if (isempty(path_startswith(path, prefix)))
91,079✔
1699
                        continue;
85,461✔
1700

1701
                id1 = sym_mnt_fs_get_id(fs);
5,618✔
1702
                r = path_get_mnt_id(path, &id2);
5,618✔
1703
                if (r < 0) {
5,618✔
1704
                        log_debug_errno(r, "Failed to get mount ID of '%s', ignoring: %m", path);
×
1705
                        continue;
×
1706
                }
1707
                if (id1 != id2) {
5,618✔
1708
                        /* The path may be hidden by another over-mount or already remounted. */
1709
                        log_debug("The mount IDs of '%s' obtained by libmount and path_get_mnt_id() are different (%i vs %i), ignoring.",
804✔
1710
                                  path, id1, id2);
1711
                        continue;
804✔
1712
                }
1713

1714
                mount_fd = open(path, O_CLOEXEC|O_PATH);
4,814✔
1715
                if (mount_fd < 0) {
4,814✔
1716
                        if (errno == ENOENT) /* The path may be hidden by another over-mount or already unmounted. */
×
1717
                                continue;
×
1718

1719
                        return log_debug_errno(errno, "Failed to open subtree of mounted filesystem '%s': %m", path);
×
1720
                }
1721

1722
                p = strdup(path);
4,814✔
1723
                if (!p)
4,814✔
1724
                        return log_oom_debug();
×
1725

1726
                if (!GREEDY_REALLOC(mounts, n + 1))
4,814✔
1727
                        return log_oom_debug();
×
1728

1729
                mounts[n++] = (SubMount) {
4,814✔
1730
                        .path = TAKE_PTR(p),
4,814✔
1731
                        .mount_fd = TAKE_FD(mount_fd),
4,814✔
1732
                };
1733
        }
1734

1735
        typesafe_qsort(mounts, n, sub_mount_compare);
1,815✔
1736
        sub_mount_drop(mounts, n);
1,815✔
1737

1738
        *ret_mounts = TAKE_PTR(mounts);
1,815✔
1739
        *ret_n_mounts = n;
1,815✔
1740
        return 0;
1,815✔
1741
}
1742

1743
int bind_mount_submounts(
1,205✔
1744
                const char *source,
1745
                const char *target) {
1746

1747
        SubMount *mounts = NULL;
1,205✔
1748
        size_t n = 0;
1,205✔
1749
        int ret = 0, r;
1,205✔
1750

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

1754
        assert(source);
1,205✔
1755
        assert(target);
1,205✔
1756

1757
        CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1,205✔
1758

1759
        r = get_sub_mounts(source, &mounts, &n);
1,205✔
1760
        if (r < 0)
1,205✔
1761
                return r;
1762

1763
        FOREACH_ARRAY(m, mounts, n) {
6,015✔
1764
                _cleanup_free_ char *t = NULL;
4,810✔
1765
                const char *suffix;
4,810✔
1766

1767
                if (isempty(m->path))
4,810✔
1768
                        continue;
809✔
1769

1770
                assert_se(suffix = path_startswith(m->path, source));
4,001✔
1771

1772
                t = path_join(target, suffix);
4,001✔
1773
                if (!t)
4,001✔
1774
                        return -ENOMEM;
×
1775

1776
                r = path_is_mount_point(t);
4,001✔
1777
                if (r < 0) {
4,001✔
1778
                        log_debug_errno(r, "Failed to detect if '%s' already is a mount point, ignoring: %m", t);
11✔
1779
                        continue;
11✔
1780
                }
1781
                if (r > 0) {
3,990✔
1782
                        log_debug("Not bind mounting '%s' from '%s' to '%s', since there's already a mountpoint.", suffix, source, target);
×
1783
                        continue;
×
1784
                }
1785

1786
                r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(m->mount_fd), t, NULL, MS_BIND|MS_REC, NULL);
3,990✔
1787
                if (r < 0 && ret == 0)
3,990✔
1788
                        ret = r;
401✔
1789
        }
1790

1791
        return ret;
1792
}
1793

1794
int make_mount_point_inode_from_mode(int dir_fd, const char *dest, mode_t source_mode, mode_t target_mode) {
923✔
1795
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
923✔
1796
        assert(dest);
923✔
1797

1798
        if (S_ISDIR(source_mode))
923✔
1799
                return mkdirat_label(dir_fd, dest, target_mode & 07777);
896✔
1800
        else
1801
                return RET_NERRNO(mknodat(dir_fd, dest, S_IFREG|(target_mode & 07666), 0)); /* Mask off X bit */
28✔
1802
}
1803

1804
int make_mount_point_inode_from_path(const char *source, const char *dest, mode_t access_mode) {
751✔
1805
        struct stat st;
751✔
1806

1807
        assert(source);
751✔
1808
        assert(dest);
751✔
1809

1810
        if (stat(source, &st) < 0)
751✔
1811
                return -errno;
×
1812

1813
        return make_mount_point_inode_from_mode(AT_FDCWD, dest, st.st_mode, access_mode);
751✔
1814
}
1815

1816
int trigger_automount_at(int dir_fd, const char *path) {
449✔
1817
        _cleanup_free_ char *nested = NULL;
898✔
1818

1819
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
449✔
1820

1821
        nested = path_join(path, "a");
449✔
1822
        if (!nested)
449✔
1823
                return -ENOMEM;
1824

1825
        (void) faccessat(dir_fd, nested, F_OK, 0);
449✔
1826

1827
        return 0;
449✔
1828
}
1829

1830
unsigned long credentials_fs_mount_flags(bool ro) {
2,049✔
1831
        /* A tight set of mount flags for credentials mounts */
1832
        return MS_NODEV|MS_NOEXEC|MS_NOSUID|ms_nosymfollow_supported()|(ro ? MS_RDONLY : 0);
2,049✔
1833
}
1834

1835
int fsmount_credentials_fs(int *ret_fsfd) {
2,036✔
1836
        _cleanup_close_ int fs_fd = -EBADF;
2,036✔
1837
        char size_str[DECIMAL_STR_MAX(uint64_t)];
2,036✔
1838

1839
        /* Mounts a file system we can place credentials in, i.e. with tight access modes right from the
1840
         * beginning, and ideally swapping turned off. In order of preference:
1841
         *
1842
         *      1. tmpfs if it supports "noswap" (needs kernel >= 6.3)
1843
         *      2. ramfs
1844
         *      3. tmpfs without "noswap"
1845
         */
1846

1847
        fs_fd = fsopen("tmpfs", FSOPEN_CLOEXEC);
2,036✔
1848
        if (fs_fd < 0)
2,036✔
1849
                return -errno;
4✔
1850

1851
        if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "nr_inodes", "1024", 0) < 0)
2,032✔
NEW
1852
                return -errno;
×
1853

1854
        xsprintf(size_str, "%" PRIu64, CREDENTIALS_TOTAL_SIZE_MAX);
2,032✔
1855
        if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "size", size_str, 0) < 0)
2,032✔
NEW
1856
                return -errno;
×
1857

1858
        if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, "noswap", NULL, 0) < 0) {
2,032✔
NEW
1859
                if (errno != EINVAL)
×
NEW
1860
                        return -errno;
×
1861

NEW
1862
                int ramfs_fd = fsopen("ramfs", FSOPEN_CLOEXEC);
×
NEW
1863
                if (ramfs_fd >= 0)
×
NEW
1864
                        close_and_replace(fs_fd, ramfs_fd);
×
1865
        }
1866

1867
        if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "mode", "0700", 0) < 0)
2,032✔
NEW
1868
                return -errno;
×
1869

1870
        if (fsconfig(fs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) < 0)
2,032✔
NEW
1871
                return -errno;
×
1872

1873
        int mfd = fsmount(fs_fd, FSMOUNT_CLOEXEC,
6,096✔
1874
                          ms_flags_to_mount_attr(credentials_fs_mount_flags(/* ro = */ false)));
2,032✔
1875
        if (mfd < 0)
2,032✔
NEW
1876
                return -errno;
×
1877

1878
        if (ret_fsfd)
2,032✔
1879
                *ret_fsfd = TAKE_FD(fs_fd);
2,018✔
1880

1881
        return mfd;
1882
}
1883

1884
int mount_credentials_fs(const char *path) {
14✔
1885
        _cleanup_close_ int mfd = -EBADF;
14✔
1886

1887
        assert(path);
14✔
1888

1889
        mfd = fsmount_credentials_fs(/* ret_fsfd = */ NULL);
14✔
1890
        if (mfd < 0)
14✔
1891
                return mfd;
1892

1893
        return RET_NERRNO(move_mount(mfd, "", AT_FDCWD, path, MOVE_MOUNT_F_EMPTY_PATH));
14✔
1894
}
1895

1896
int make_fsmount(
2✔
1897
                int error_log_level,
1898
                const char *what,
1899
                const char *type,
1900
                unsigned long flags,
1901
                const char *options,
1902
                int userns_fd) {
1903

1904
        _cleanup_close_ int fs_fd = -EBADF, mnt_fd = -EBADF;
2✔
1905
        _cleanup_free_ char *o = NULL;
2✔
1906
        unsigned long f;
2✔
1907
        int r;
2✔
1908

1909
        assert(type);
2✔
1910
        assert(what);
2✔
1911

1912
        r = mount_option_mangle(options, flags, &f, &o);
2✔
1913
        if (r < 0)
2✔
1914
                return log_full_errno(
×
1915
                                error_log_level, r, "Failed to mangle mount options %s: %m",
1916
                                strempty(options));
1917

1918
        if (DEBUG_LOGGING) {
2✔
1919
                _cleanup_free_ char *fl = NULL;
2✔
1920
                (void) mount_flags_to_string(f, &fl);
2✔
1921

1922
                log_debug("Creating mount fd for %s (%s) (%s \"%s\")...",
4✔
1923
                        strna(what), strna(type), strnull(fl), strempty(o));
1924
        }
1925

1926
        fs_fd = fsopen(type, FSOPEN_CLOEXEC);
2✔
1927
        if (fs_fd < 0)
2✔
1928
                return log_full_errno(error_log_level, errno, "Failed to open superblock for \"%s\": %m", type);
×
1929

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

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

1937
        for (const char *p = o;;) {
2✔
1938
                _cleanup_free_ char *word = NULL;
×
1939
                char *eq;
2✔
1940

1941
                r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
2✔
1942
                if (r < 0)
2✔
1943
                        return log_full_errno(error_log_level, r, "Failed to parse mount option string \"%s\": %m", o);
×
1944
                if (r == 0)
2✔
1945
                        break;
1946

1947
                eq = strchr(word, '=');
×
1948
                if (eq) {
×
1949
                        *eq = 0;
×
1950
                        eq++;
×
1951

1952
                        if (fsconfig(fs_fd, FSCONFIG_SET_STRING, word, eq, 0) < 0)
×
1953
                                return log_full_errno(error_log_level, errno, "Failed to set mount option \"%s=%s\" for \"%s\": %m", word, eq, type);
×
1954
                } else {
1955
                        if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, word, NULL, 0) < 0)
×
1956
                                return log_full_errno(error_log_level, errno, "Failed to set mount flag \"%s\" for \"%s\": %m", word, type);
×
1957
                }
1958
        }
1959

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

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

1967
        struct mount_attr ma = {
4✔
1968
                .attr_clr = ms_flags_to_mount_attr_clr(f),
2✔
1969
                .attr_set = ms_flags_to_mount_attr(f) | (userns_fd >= 0 ? MOUNT_ATTR_IDMAP : 0),
2✔
1970
                .userns_fd = userns_fd,
1971
        };
1972
        if (ma.attr_set != 0 && mount_setattr(mnt_fd, "", AT_EMPTY_PATH|AT_RECURSIVE, &ma, MOUNT_ATTR_SIZE_VER0) < 0)
2✔
1973
                return log_full_errno(error_log_level,
×
1974
                                      errno,
1975
                                      "Failed to set mount flags for \"%s\" (\"%s\"): %m",
1976
                                      what,
1977
                                      type);
1978

1979
        return TAKE_FD(mnt_fd);
1980
}
1981

1982
char* umount_and_rmdir_and_free(char *p) {
158✔
1983
        if (!p)
158✔
1984
                return NULL;
158✔
1985

1986
        PROTECT_ERRNO;
×
1987
        (void) umount_recursive(p, 0);
158✔
1988
        (void) rmdir(p);
158✔
1989
        return mfree(p);
158✔
1990
}
1991

1992
char* umount_and_free(char *p) {
44✔
1993
        if (!p)
44✔
1994
                return NULL;
44✔
1995

1996
        PROTECT_ERRNO;
×
1997
        (void) umount_recursive(p, 0);
44✔
1998
        return mfree(p);
44✔
1999
}
2000

2001
char* umount_and_unlink_and_free(char *p) {
1✔
2002
        if (!p)
1✔
2003
                return NULL;
1✔
2004

2005
        PROTECT_ERRNO;
2✔
2006
        (void) umount2(p, 0);
1✔
2007
        (void) unlink(p);
1✔
2008
        return mfree(p);
1✔
2009
}
2010

2011
int path_get_mount_info_at(
779✔
2012
                int dir_fd,
2013
                const char *path,
2014
                char **ret_fstype,
2015
                char **ret_options,
2016
                char **ret_source) {
2017

2018
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
779✔
2019
        _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
779✔
2020
        int r, mnt_id;
779✔
2021

2022
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
779✔
2023

2024
        r = path_get_mnt_id_at(dir_fd, path, &mnt_id);
779✔
2025
        if (r < 0)
779✔
2026
                return log_debug_errno(r, "Failed to get mount ID: %m");
×
2027

2028
        /* When getting options is requested, we also need to parse utab, otherwise userspace options like
2029
         * "_netdev" will be lost. */
2030
        if (ret_options)
779✔
2031
                r = libmount_parse_with_utab(&table, &iter);
769✔
2032
        else
2033
                r = libmount_parse_mountinfo(/* source = */ NULL, &table, &iter);
10✔
2034
        if (r < 0)
779✔
2035
                return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
2036

2037
        for (;;) {
4,951✔
2038
                struct libmnt_fs *fs;
2,865✔
2039

2040
                r = sym_mnt_table_next_fs(table, iter, &fs);
2,865✔
2041
                if (r == 1)
2,865✔
2042
                        break; /* EOF */
2043
                if (r < 0)
2,865✔
2044
                        return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
779✔
2045

2046
                if (sym_mnt_fs_get_id(fs) != mnt_id)
2,865✔
2047
                        continue;
2,086✔
2048

2049
                _cleanup_free_ char *fstype = NULL, *options = NULL, *source = NULL;
779✔
2050

2051
                if (ret_fstype) {
779✔
2052
                        fstype = strdup(strempty(sym_mnt_fs_get_fstype(fs)));
769✔
2053
                        if (!fstype)
769✔
2054
                                return log_oom_debug();
×
2055
                }
2056

2057
                if (ret_options) {
779✔
2058
                        options = strdup(strempty(sym_mnt_fs_get_options(fs)));
769✔
2059
                        if (!options)
769✔
2060
                                return log_oom_debug();
×
2061
                }
2062

2063
                if (ret_source) {
779✔
2064
                        source = strdup(strempty(sym_mnt_fs_get_source(fs)));
10✔
2065
                        if (!source)
10✔
2066
                                return log_oom_debug();
×
2067
                }
2068

2069
                if (ret_fstype)
779✔
2070
                        *ret_fstype = TAKE_PTR(fstype);
769✔
2071
                if (ret_options)
779✔
2072
                        *ret_options = TAKE_PTR(options);
769✔
2073
                if (ret_source)
779✔
2074
                        *ret_source = TAKE_PTR(source);
10✔
2075

2076
                return 0;
2077
        }
2078

2079
        return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Cannot find mount ID %i from /proc/self/mountinfo.", mnt_id);
×
2080
}
2081

2082
int path_is_network_fs_harder_at(int dir_fd, const char *path) {
799✔
2083
        _cleanup_close_ int fd = -EBADF;
799✔
2084
        int r;
799✔
2085

2086
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
799✔
2087

2088
        fd = xopenat(dir_fd, path, O_PATH | O_CLOEXEC | O_NOFOLLOW);
799✔
2089
        if (fd < 0)
799✔
2090
                return fd;
2091

2092
        r = fd_is_network_fs(fd);
769✔
2093
        if (r != 0)
769✔
2094
                return r;
2095

2096
        _cleanup_free_ char *fstype = NULL, *options = NULL;
769✔
2097
        r = path_get_mount_info_at(fd, /* path = */ NULL, &fstype, &options, /* ret_source = */ NULL);
769✔
2098
        if (r < 0)
769✔
2099
                return r;
2100

2101
        if (fstype_is_network(fstype))
769✔
2102
                return true;
2103

2104
        if (fstab_test_option(options, "_netdev\0"))
769✔
2105
                return true;
×
2106

2107
        return false;
2108
}
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