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

systemd / systemd / 18578253386

16 Oct 2025 06:50PM UTC coverage: 72.363% (+0.3%) from 72.072%
18578253386

push

github

web-flow
core/mount: properly handle REMOUNTING_* states in mount_stop() (#39269)

5 of 9 new or added lines in 1 file covered. (55.56%)

3694 existing lines in 74 files now uncovered.

304611 of 420946 relevant lines covered (72.36%)

1092905.84 hits per line

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

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

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

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

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

50
        for (;;) {
17,357✔
51
                _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
25,461✔
52
                _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
17,357✔
53
                bool again = false;
25,461✔
54

55
                r = libmount_parse_mountinfo(f, &table, &iter);
25,461✔
56
                if (r < 0)
25,461✔
UNCOV
57
                        return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
58

59
                for (;;) {
2,777,029✔
60
                        bool shall_keep = false;
1,401,245✔
61
                        struct libmnt_fs *fs;
1,401,245✔
62
                        const char *path;
1,401,245✔
63

64
                        r = sym_mnt_table_next_fs(table, iter, &fs);
1,401,245✔
65
                        if (r == 1)
1,401,245✔
66
                                break;
67
                        if (r < 0)
1,393,141✔
UNCOV
68
                                return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
69

70
                        path = sym_mnt_fs_get_target(fs);
1,393,141✔
71
                        if (!path)
1,393,141✔
72
                                continue;
1,375,784✔
73

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

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

92
                        if (umount2(path, flags | UMOUNT_NOFOLLOW) < 0) {
25,963✔
93
                                log_debug_errno(errno, "Failed to umount %s, ignoring: %m", path);
8,606✔
94
                                continue;
8,606✔
95
                        }
96

97
                        log_trace("Successfully unmounted %s", path);
17,357✔
98

99
                        again = true;
17,357✔
100
                        n++;
17,357✔
101

102
                        break;
17,357✔
103
                }
104

105
                if (!again)
8,104✔
106
                        break;
107

108
                rewind(f);
17,357✔
109
        }
110

111
        return n;
8,104✔
112
}
113

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

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

119
        if (FLAGS_SET(a, MS_RDONLY))
35,006✔
120
                f |= MOUNT_ATTR_RDONLY;
1,360✔
121

122
        if (FLAGS_SET(a, MS_NOSUID))
35,006✔
123
                f |= MOUNT_ATTR_NOSUID;
16,145✔
124

125
        if (FLAGS_SET(a, MS_NODEV))
35,006✔
126
                f |= MOUNT_ATTR_NODEV;
2✔
127

128
        if (FLAGS_SET(a, MS_NOEXEC))
35,006✔
129
                f |= MOUNT_ATTR_NOEXEC;
2✔
130

131
        if (FLAGS_SET(a, MS_NOSYMFOLLOW))
35,006✔
UNCOV
132
                f |= MOUNT_ATTR_NOSYMFOLLOW;
×
133

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

137
        if (FLAGS_SET(a, MS_NOATIME))
35,006✔
UNCOV
138
                f |= MOUNT_ATTR_NOATIME;
×
139

140
        if (FLAGS_SET(a, MS_STRICTATIME))
35,006✔
UNCOV
141
                f |= MOUNT_ATTR_STRICTATIME;
×
142

143
        if (FLAGS_SET(a, MS_NODIRATIME))
35,006✔
UNCOV
144
                f |= MOUNT_ATTR_NODIRATIME;
×
145

146
        return f;
35,006✔
147
}
148

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

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

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

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

163
        return f;
2✔
164
}
165

166
static bool skip_mount_set_attr = false;
167

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

177
        _cleanup_fclose_ FILE *proc_self_mountinfo_opened = NULL;
33,850✔
178
        _cleanup_set_free_ Set *done = NULL;
33,850✔
179
        unsigned n_tries = 0;
33,850✔
180
        int r;
33,850✔
181

182
        assert(prefix);
33,850✔
183

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

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

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

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

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

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

213
                proc_self_mountinfo = proc_self_mountinfo_opened;
3✔
214
        }
215

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

230
        for (;;) {
36,831✔
231
                _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
36,831✔
232
                _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
36,831✔
233
                _cleanup_hashmap_free_ Hashmap *todo = NULL;
36,829✔
234
                bool top_autofs = false;
36,831✔
235

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

239
                rewind(proc_self_mountinfo);
36,831✔
240

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

245
                for (;;) {
2,608,604✔
246
                        _cleanup_free_ char *d = NULL;
2,571,773✔
247
                        const char *path, *type, *opts;
2,608,604✔
248
                        unsigned long flags = 0;
2,608,604✔
249
                        struct libmnt_fs *fs;
2,608,604✔
250

251
                        r = sym_mnt_table_next_fs(table, iter, &fs);
2,608,604✔
252
                        if (r == 1) /* EOF */
2,608,604✔
253
                                break;
254
                        if (r < 0)
2,571,773✔
UNCOV
255
                                return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
256

257
                        path = sym_mnt_fs_get_target(fs);
2,571,773✔
258
                        if (!path)
2,571,773✔
UNCOV
259
                                continue;
×
260

261
                        if (!path_startswith(path, prefix))
2,571,773✔
262
                                continue;
2,508,317✔
263

264
                        type = sym_mnt_fs_get_fstype(fs);
63,456✔
265
                        if (!type)
63,456✔
UNCOV
266
                                continue;
×
267

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

276
                        if (set_contains(done, path))
60,978✔
277
                                continue;
22,275✔
278

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

284
                                STRV_FOREACH(i, deny_list) {
267,836✔
285
                                        if (path_equal(*i, prefix))
263,977✔
286
                                                continue;
20,276✔
287

288
                                        if (!path_startswith(*i, prefix))
243,701✔
289
                                                continue;
137,314✔
290

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

298
                                if (deny_listed)
20,287✔
299
                                        continue;
16,428✔
300
                        }
301

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

309
                        d = strdup(path);
22,275✔
310
                        if (!d)
22,275✔
311
                                return -ENOMEM;
312

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

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

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

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

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

347
                for (;;) {
40,646✔
348
                        unsigned long flags;
40,646✔
349
                        char *x = NULL;
40,646✔
350

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

356
                        r = set_ensure_consume(&done, &path_hash_ops_free, x);
22,231✔
357
                        if (IN_SET(r, 0, -EEXIST))
22,231✔
358
                                continue; /* Already done */
270✔
359
                        if (r < 0)
22,231✔
UNCOV
360
                                return r;
×
361

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

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

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

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

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

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

403
                        log_trace("Remounted %s.", x);
21,961✔
404
                }
405
        }
406
}
407

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

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

420
        assert(path);
2,064✔
421
        assert(proc_self_mountinfo);
2,064✔
422

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

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

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

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

440
        rewind(proc_self_mountinfo);
4✔
441

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

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

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

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

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

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

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

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

482
        return 0;
483
}
484

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

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

492
        return bind_remount_one_with_mountinfo(path, new_flags, flags_mask, proc_self_mountinfo);
53✔
493
}
494

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

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

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

508
        return 0;
509
}
510

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

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

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

523
        return 0;
524
}
525

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

530
        assert(path);
2,204✔
531
        assert(mount_propagation_flag_is_valid(mount_propagation_flag));
2,204✔
532

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

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

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

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

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

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

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

574
        return 0;
575
}
576

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

580
        assert(path);
17✔
581

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

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

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

UNCOV
591
                        return -errno;
×
592
                }
593

594
                done = true;
595
        }
596
}
597

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

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

614
        _cleanup_free_ char *d = NULL;
4,560✔
615
        const char *node;
4,560✔
616

617
        assert(ret);
4,560✔
618

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

622
        if (S_ISLNK(mode))
4,560✔
623
                return -EINVAL;
624

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

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

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

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

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

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

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

694
        assert(ret);
47,666✔
695

696
        FOREACH_ELEMENT(entry, map)
1,239,316✔
697
                if (flags & entry->flag) {
1,191,650✔
698
                        if (!strextend_with_separator(&str, "|", entry->name))
115,283✔
699
                                return -ENOMEM;
700
                        flags &= ~entry->flag;
115,283✔
701
                }
702

703
        if (!str || flags != 0)
47,666✔
704
                if (strextendf_with_separator(&str, "|", "%lx", flags) < 0)
136✔
705
                        return -ENOMEM;
706

707
        *ret = TAKE_PTR(str);
47,666✔
708
        return 0;
47,666✔
709
}
710

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

720
        _cleanup_free_ char *fl = NULL, *o = NULL;
47,636✔
721
        unsigned long f;
47,636✔
722
        int r;
47,636✔
723

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

730
        (void) mount_flags_to_string(f, &fl);
47,636✔
731

732
        if (FLAGS_SET(f, MS_REMOUNT|MS_BIND))
47,636✔
733
                log_debug("Changing mount flags %s (%s \"%s\")...",
11,131✔
734
                          where, strnull(fl), strempty(o));
735
        else if (f & MS_REMOUNT)
42,070✔
736
                log_debug("Remounting superblock %s (%s \"%s\")...",
4✔
737
                          where, strnull(fl), strempty(o));
738
        else if (f & (MS_SHARED|MS_PRIVATE|MS_SLAVE|MS_UNBINDABLE))
42,066✔
739
                log_debug("Changing mount propagation %s (%s \"%s\")",
6,656✔
740
                          where, strnull(fl), strempty(o));
741
        else if (f & MS_BIND)
38,738✔
742
                log_debug("Bind-mounting %s on %s (%s \"%s\")...",
53,767✔
743
                          what, where, strnull(fl), strempty(o));
744
        else if (f & MS_MOVE)
11,842✔
745
                log_debug("Moving mount %s %s %s (%s \"%s\")...",
7,358✔
746
                          what, glyph(GLYPH_ARROW_RIGHT), where, strnull(fl), strempty(o));
747
        else
748
                log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
9,534✔
749
                          strna(what), strna(type), where, strnull(fl), strempty(o));
750

751
        if (follow_symlink)
47,636✔
752
                r = RET_NERRNO(mount(what, where, type, f, o));
48,027✔
753
        else
754
                r = mount_nofollow(what, where, type, f, o);
42,480✔
755
        if (r < 0)
42,871✔
756
                return log_full_errno(error_log_level, r,
9,305✔
757
                                      "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
758
                                      strna(what), strna(type), where, strnull(fl), strempty(o));
759
        return 0;
760
}
761

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

767
        assert(where);
525✔
768

769
        log_debug("Unmounting '%s'...", where);
525✔
770

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

774
        return 0;
775
}
776

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

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

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

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

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

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

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

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

815
                mnt_fd = inode_fd;
816
        }
817

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

821
        return 0;
223✔
822
}
823

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

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

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

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

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

852
        return r;
853
}
854

855
int mount_option_mangle(
47,708✔
856
                const char *options,
857
                unsigned long mount_flags,
858
                unsigned long *ret_mount_flags,
859
                char **ret_remaining_options) {
860

861
        const struct libmnt_optmap *map;
47,708✔
862
        _cleanup_free_ char *ret = NULL;
47,708✔
863
        int r;
47,708✔
864

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

878
        assert(ret_mount_flags);
47,708✔
879
        assert(ret_remaining_options);
47,708✔
880

881
        r = dlopen_libmount();
47,708✔
882
        if (r < 0)
47,708✔
883
                return r;
884

885
        map = sym_mnt_get_builtin_optmap(MNT_LINUX_MAP);
47,708✔
886
        if (!map)
47,708✔
887
                return -EINVAL;
888

889
        for (const char *p = options;;) {
47,708✔
890
                _cleanup_free_ char *word = NULL;
23,689✔
891
                const struct libmnt_optmap *ent;
71,396✔
892

893
                r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
71,396✔
894
                if (r < 0)
71,396✔
895
                        return r;
896
                if (r == 0)
71,395✔
897
                        break;
898

899
                for (ent = map; ent->name; ent++) {
992,313✔
900
                        /* All entries in MNT_LINUX_MAP do not take any argument.
901
                         * Thus, ent->name does not contain "=" or "[=]". */
902
                        if (!streq(word, ent->name))
968,716✔
903
                                continue;
968,625✔
904

905
                        if (!(ent->mask & MNT_INVERT))
91✔
906
                                mount_flags |= ent->id;
82✔
907
                        else
908
                                mount_flags &= ~ent->id;
9✔
909

910
                        break;
911
                }
912

913
                /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
914
                if (!ent->name &&
47,285✔
915
                    !startswith_no_case(word, "x-") &&
47,192✔
916
                    !strextend_with_separator(&ret, ",", word))
23,595✔
917
                        return -ENOMEM;
918
        }
919

920
        *ret_mount_flags = mount_flags;
47,707✔
921
        *ret_remaining_options = TAKE_PTR(ret);
47,707✔
922

923
        return 0;
47,707✔
924
}
925

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

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

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

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

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

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

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

UNCOV
976
        mount_slave_created = true;
×
977

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

UNCOV
982
        mount_slave_mounted = true;
×
983

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

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

UNCOV
996
        mount_tmp_created = true;
×
997

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

UNCOV
1016
        mount_tmp_mounted = true;
×
1017

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

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

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

1040
        mount_outside_created = true;
×
1041

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

UNCOV
1046
        mount_outside_mounted = true;
×
1047
        mount_tmp_mounted = false;
×
1048

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

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

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

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

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

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

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

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

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

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

UNCOV
1111
                _exit(EXIT_SUCCESS);
×
1112
        }
1113

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

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

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

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

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

UNCOV
1153
        return r;
×
1154
}
1155

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1322
        return 0;
1323
}
1324

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

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

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

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

1363
int make_mount_point(const char *path) {
27✔
1364
        int r;
27✔
1365

1366
        assert(path);
27✔
1367

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

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

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

1380
        return 1;
1381
}
1382

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

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

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

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

1398
        return 1;
1399
}
1400

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

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

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

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

1417
        switch (idmapping) {
130✔
1418

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

1423
        case REMOUNT_IDMAPPING_NONE:
92✔
1424
        case REMOUNT_IDMAPPING_HOST_ROOT:
1425

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

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

1448
                break;
1449

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

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

UNCOV
1471
        default:
×
UNCOV
1472
                assert_not_reached();
×
1473
        }
1474

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

1480
        return TAKE_FD(userns_fd);
1481
}
1482

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

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

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

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

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

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

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

1510
        return TAKE_FD(fd);
1511
}
1512

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

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

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

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

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

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

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

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

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

1554
        int r;
141✔
1555

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

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

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

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

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

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

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

1589
                n_mounts_fds++;
139✔
1590
        }
1591

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

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

1606
        return 0;
1607
}
1608

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

1617
        _cleanup_close_ int userns_fd = -EBADF;
128✔
1618

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

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

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

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

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

1636
        for (size_t i = 0; i < n; i++)
5,903✔
1637
                sub_mount_clear(s + i);
4,717✔
1638

1639
        free(s);
1,186✔
1640
}
1,186✔
1641

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

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

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

1654
        for (size_t m = 0, i = 1; i < n; i++) {
5,295✔
1655
                if (path_startswith(s[i].path, s[m].path))
3,531✔
1656
                        sub_mount_clear(s + i);
789✔
1657
                else
1658
                        m = i;
1659
        }
1660
}
1,764✔
1661

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

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

1670
        CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1,764✔
1671

1672
        assert(prefix);
1,764✔
1673
        assert(ret_mounts);
1,764✔
1674
        assert(ret_n_mounts);
1,764✔
1675

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

1680
        for (;;) {
90,708✔
1681
                _cleanup_close_ int mount_fd = -EBADF;
88,944✔
1682
                _cleanup_free_ char *p = NULL;
90,708✔
1683
                struct libmnt_fs *fs;
90,708✔
1684
                const char *path;
90,708✔
1685
                int id1, id2;
90,708✔
1686

1687
                r = sym_mnt_table_next_fs(table, iter, &fs);
90,708✔
1688
                if (r == 1)
90,708✔
1689
                        break; /* EOF */
1690
                if (r < 0)
88,944✔
UNCOV
1691
                        return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
1692

1693
                path = sym_mnt_fs_get_target(fs);
88,944✔
1694
                if (!path)
88,944✔
UNCOV
1695
                        continue;
×
1696

1697
                if (isempty(path_startswith(path, prefix)))
88,944✔
1698
                        continue;
83,443✔
1699

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

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

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

1721
                p = strdup(path);
4,717✔
1722
                if (!p)
4,717✔
UNCOV
1723
                        return log_oom_debug();
×
1724

1725
                if (!GREEDY_REALLOC(mounts, n + 1))
4,717✔
UNCOV
1726
                        return log_oom_debug();
×
1727

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

1734
        typesafe_qsort(mounts, n, sub_mount_compare);
1,764✔
1735
        sub_mount_drop(mounts, n);
1,764✔
1736

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

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

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

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

1753
        assert(source);
1,194✔
1754
        assert(target);
1,194✔
1755

1756
        CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1,194✔
1757

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

1762
        FOREACH_ARRAY(m, mounts, n) {
5,907✔
1763
                _cleanup_free_ char *t = NULL;
4,713✔
1764
                const char *suffix;
4,713✔
1765

1766
                if (isempty(m->path))
4,713✔
1767
                        continue;
789✔
1768

1769
                assert_se(suffix = path_startswith(m->path, source));
3,924✔
1770

1771
                t = path_join(target, suffix);
3,924✔
1772
                if (!t)
3,924✔
UNCOV
1773
                        return -ENOMEM;
×
1774

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

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

1790
        return ret;
1791
}
1792

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

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

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

1806
        assert(source);
864✔
1807
        assert(dest);
864✔
1808

1809
        if (stat(source, &st) < 0)
864✔
UNCOV
1810
                return -errno;
×
1811

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

1815
int trigger_automount_at(int dir_fd, const char *path) {
422✔
1816
        _cleanup_free_ char *nested = NULL;
844✔
1817

1818
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
422✔
1819

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

1824
        (void) faccessat(dir_fd, nested, F_OK, 0);
422✔
1825

1826
        return 0;
422✔
1827
}
1828

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

1834
int mount_credentials_fs(const char *path, size_t size, bool ro) {
2,025✔
1835
        _cleanup_free_ char *opts = NULL;
2,025✔
1836
        int r, noswap_supported;
2,025✔
1837

1838
        /* Mounts a file system we can place credentials in, i.e. with tight access modes right from the
1839
         * beginning, and ideally swapping turned off. In order of preference:
1840
         *
1841
         *      1. tmpfs if it supports "noswap"
1842
         *      2. ramfs
1843
         *      3. tmpfs if it doesn't support "noswap"
1844
         */
1845

1846
        noswap_supported = mount_option_supported("tmpfs", "noswap", NULL); /* Check explicitly to avoid kmsg noise */
2,025✔
1847
        if (noswap_supported > 0) {
2,025✔
1848
                _cleanup_free_ char *noswap_opts = NULL;
2,024✔
1849

1850
                if (asprintf(&noswap_opts, "mode=0700,nr_inodes=1024,size=%zu,noswap", size) < 0)
2,024✔
1851
                        return -ENOMEM;
1852

1853
                /* Best case: tmpfs with noswap (needs kernel >= 6.3) */
1854

1855
                r = mount_nofollow_verbose(
2,024✔
1856
                                LOG_DEBUG,
1857
                                "tmpfs",
1858
                                path,
1859
                                "tmpfs",
1860
                                credentials_fs_mount_flags(ro),
1861
                                noswap_opts);
1862
                if (r >= 0)
2,024✔
1863
                        return r;
1864
        }
1865

1866
        r = mount_nofollow_verbose(
1✔
1867
                        LOG_DEBUG,
1868
                        "ramfs",
1869
                        path,
1870
                        "ramfs",
1871
                        credentials_fs_mount_flags(ro),
1872
                        "mode=0700");
1873
        if (r >= 0)
1✔
1874
                return r;
1875

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

1879
        return mount_nofollow_verbose(
2,025✔
1880
                        LOG_DEBUG,
1881
                        "tmpfs",
1882
                        path,
1883
                        "tmpfs",
1884
                        credentials_fs_mount_flags(ro),
1885
                        opts);
1886
}
1887

1888
int make_fsmount(
2✔
1889
                int error_log_level,
1890
                const char *what,
1891
                const char *type,
1892
                unsigned long flags,
1893
                const char *options,
1894
                int userns_fd) {
1895

1896
        _cleanup_close_ int fs_fd = -EBADF, mnt_fd = -EBADF;
2✔
1897
        _cleanup_free_ char *o = NULL;
2✔
1898
        unsigned long f;
2✔
1899
        int r;
2✔
1900

1901
        assert(type);
2✔
1902
        assert(what);
2✔
1903

1904
        r = mount_option_mangle(options, flags, &f, &o);
2✔
1905
        if (r < 0)
2✔
1906
                return log_full_errno(
×
1907
                                error_log_level, r, "Failed to mangle mount options %s: %m",
1908
                                strempty(options));
1909

1910
        if (DEBUG_LOGGING) {
2✔
1911
                _cleanup_free_ char *fl = NULL;
2✔
1912
                (void) mount_flags_to_string(f, &fl);
2✔
1913

1914
                log_debug("Creating mount fd for %s (%s) (%s \"%s\")...",
4✔
1915
                        strna(what), strna(type), strnull(fl), strempty(o));
1916
        }
1917

1918
        fs_fd = fsopen(type, FSOPEN_CLOEXEC);
2✔
1919
        if (fs_fd < 0)
2✔
UNCOV
1920
                return log_full_errno(error_log_level, errno, "Failed to open superblock for \"%s\": %m", type);
×
1921

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

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

1929
        for (const char *p = o;;) {
2✔
UNCOV
1930
                _cleanup_free_ char *word = NULL;
×
1931
                char *eq;
2✔
1932

1933
                r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
2✔
1934
                if (r < 0)
2✔
UNCOV
1935
                        return log_full_errno(error_log_level, r, "Failed to parse mount option string \"%s\": %m", o);
×
1936
                if (r == 0)
2✔
1937
                        break;
1938

1939
                eq = strchr(word, '=');
×
UNCOV
1940
                if (eq) {
×
UNCOV
1941
                        *eq = 0;
×
UNCOV
1942
                        eq++;
×
1943

UNCOV
1944
                        if (fsconfig(fs_fd, FSCONFIG_SET_STRING, word, eq, 0) < 0)
×
UNCOV
1945
                                return log_full_errno(error_log_level, errno, "Failed to set mount option \"%s=%s\" for \"%s\": %m", word, eq, type);
×
1946
                } else {
UNCOV
1947
                        if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, word, NULL, 0) < 0)
×
UNCOV
1948
                                return log_full_errno(error_log_level, errno, "Failed to set mount flag \"%s\" for \"%s\": %m", word, type);
×
1949
                }
1950
        }
1951

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

1955
        mnt_fd = fsmount(fs_fd, FSMOUNT_CLOEXEC, 0);
2✔
1956
        if (mnt_fd < 0)
2✔
UNCOV
1957
                return log_full_errno(error_log_level, errno, "Failed to create mount fd for \"%s\" (\"%s\"): %m", what, type);
×
1958

1959
        struct mount_attr ma = {
4✔
1960
                .attr_clr = ms_flags_to_mount_attr_clr(f),
2✔
1961
                .attr_set = ms_flags_to_mount_attr(f) | (userns_fd >= 0 ? MOUNT_ATTR_IDMAP : 0),
2✔
1962
                .userns_fd = userns_fd,
1963
        };
1964
        if (ma.attr_set != 0 && mount_setattr(mnt_fd, "", AT_EMPTY_PATH|AT_RECURSIVE, &ma, MOUNT_ATTR_SIZE_VER0) < 0)
2✔
UNCOV
1965
                return log_full_errno(error_log_level,
×
1966
                                      errno,
1967
                                      "Failed to set mount flags for \"%s\" (\"%s\"): %m",
1968
                                      what,
1969
                                      type);
1970

1971
        return TAKE_FD(mnt_fd);
1972
}
1973

1974
char* umount_and_rmdir_and_free(char *p) {
158✔
1975
        if (!p)
158✔
1976
                return NULL;
158✔
1977

UNCOV
1978
        PROTECT_ERRNO;
×
1979
        (void) umount_recursive(p, 0);
158✔
1980
        (void) rmdir(p);
158✔
1981
        return mfree(p);
158✔
1982
}
1983

1984
char* umount_and_free(char *p) {
44✔
1985
        if (!p)
44✔
1986
                return NULL;
44✔
1987

1988
        PROTECT_ERRNO;
×
1989
        (void) umount_recursive(p, 0);
44✔
1990
        return mfree(p);
44✔
1991
}
1992

1993
char* umount_and_unlink_and_free(char *p) {
1✔
1994
        if (!p)
1✔
1995
                return NULL;
1✔
1996

1997
        PROTECT_ERRNO;
2✔
1998
        (void) umount2(p, 0);
1✔
1999
        (void) unlink(p);
1✔
2000
        return mfree(p);
1✔
2001
}
2002

2003
int path_get_mount_info_at(
780✔
2004
                int dir_fd,
2005
                const char *path,
2006
                char **ret_fstype,
2007
                char **ret_options,
2008
                char **ret_source) {
2009

2010
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
780✔
2011
        _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
780✔
2012
        int r, mnt_id;
780✔
2013

2014
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
780✔
2015

2016
        r = path_get_mnt_id_at(dir_fd, path, &mnt_id);
780✔
2017
        if (r < 0)
780✔
UNCOV
2018
                return log_debug_errno(r, "Failed to get mount ID: %m");
×
2019

2020
        /* When getting options is requested, we also need to parse utab, otherwise userspace options like
2021
         * "_netdev" will be lost. */
2022
        if (ret_options)
780✔
2023
                r = libmount_parse_with_utab(&table, &iter);
770✔
2024
        else
2025
                r = libmount_parse_mountinfo(/* source = */ NULL, &table, &iter);
10✔
2026
        if (r < 0)
780✔
UNCOV
2027
                return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
2028

2029
        for (;;) {
4,976✔
2030
                struct libmnt_fs *fs;
2,878✔
2031

2032
                r = sym_mnt_table_next_fs(table, iter, &fs);
2,878✔
2033
                if (r == 1)
2,878✔
2034
                        break; /* EOF */
2035
                if (r < 0)
2,878✔
2036
                        return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
780✔
2037

2038
                if (sym_mnt_fs_get_id(fs) != mnt_id)
2,878✔
2039
                        continue;
2,098✔
2040

2041
                _cleanup_free_ char *fstype = NULL, *options = NULL, *source = NULL;
780✔
2042

2043
                if (ret_fstype) {
780✔
2044
                        fstype = strdup(strempty(sym_mnt_fs_get_fstype(fs)));
770✔
2045
                        if (!fstype)
770✔
UNCOV
2046
                                return log_oom_debug();
×
2047
                }
2048

2049
                if (ret_options) {
780✔
2050
                        options = strdup(strempty(sym_mnt_fs_get_options(fs)));
770✔
2051
                        if (!options)
770✔
UNCOV
2052
                                return log_oom_debug();
×
2053
                }
2054

2055
                if (ret_source) {
780✔
2056
                        source = strdup(strempty(sym_mnt_fs_get_source(fs)));
10✔
2057
                        if (!source)
10✔
2058
                                return log_oom_debug();
×
2059
                }
2060

2061
                if (ret_fstype)
780✔
2062
                        *ret_fstype = TAKE_PTR(fstype);
770✔
2063
                if (ret_options)
780✔
2064
                        *ret_options = TAKE_PTR(options);
770✔
2065
                if (ret_source)
780✔
2066
                        *ret_source = TAKE_PTR(source);
10✔
2067

2068
                return 0;
2069
        }
2070

UNCOV
2071
        return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Cannot find mount ID %i from /proc/self/mountinfo.", mnt_id);
×
2072
}
2073

2074
int path_is_network_fs_harder_at(int dir_fd, const char *path) {
800✔
2075
        _cleanup_close_ int fd = -EBADF;
800✔
2076
        int r;
800✔
2077

2078
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
800✔
2079

2080
        fd = xopenat(dir_fd, path, O_PATH | O_CLOEXEC | O_NOFOLLOW);
800✔
2081
        if (fd < 0)
800✔
2082
                return fd;
2083

2084
        r = fd_is_network_fs(fd);
770✔
2085
        if (r != 0)
770✔
2086
                return r;
2087

2088
        _cleanup_free_ char *fstype = NULL, *options = NULL;
770✔
2089
        r = path_get_mount_info_at(fd, /* path = */ NULL, &fstype, &options, /* ret_source = */ NULL);
770✔
2090
        if (r < 0)
770✔
2091
                return r;
2092

2093
        if (fstype_is_network(fstype))
770✔
2094
                return true;
2095

2096
        if (fstab_test_option(options, "_netdev\0"))
770✔
UNCOV
2097
                return true;
×
2098

2099
        return false;
2100
}
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