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

systemd / systemd / 17844524571

18 Sep 2025 08:58PM UTC coverage: 72.326% (+0.09%) from 72.24%
17844524571

push

github

DaanDeMeyer
userdb: suppress creation of empty userdb dirs

13 of 16 new or added lines in 1 file covered. (81.25%)

3248 existing lines in 52 files now uncovered.

303003 of 418940 relevant lines covered (72.33%)

1051258.58 hits per line

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

0.0
/src/mountfsd/mountwork.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <linux/loop.h>
4
#include <poll.h>
5
#include <stdlib.h>
6
#include <sys/mount.h>
7
#include <unistd.h>
8

9
#include "sd-daemon.h"
10
#include "sd-event.h"
11
#include "sd-varlink.h"
12

13
#include "argv-util.h"
14
#include "bus-polkit.h"
15
#include "chase.h"
16
#include "discover-image.h"
17
#include "dissect-image.h"
18
#include "env-util.h"
19
#include "errno-util.h"
20
#include "fd-util.h"
21
#include "fs-util.h"
22
#include "format-util.h"
23
#include "hashmap.h"
24
#include "image-policy.h"
25
#include "io-util.h"
26
#include "json-util.h"
27
#include "loop-util.h"
28
#include "main-func.h"
29
#include "memory-util.h"
30
#include "namespace-util.h"
31
#include "nsresource.h"
32
#include "nulstr-util.h"
33
#include "os-util.h"
34
#include "path-util.h"
35
#include "pidref.h"
36
#include "stat-util.h"
37
#include "string-table.h"
38
#include "string-util.h"
39
#include "strv.h"
40
#include "tmpfile-util.h"
41
#include "time-util.h"
42
#include "uid-classification.h"
43
#include "uid-range.h"
44
#include "varlink-io.systemd.MountFileSystem.h"
45
#include "varlink-util.h"
46

47
#define ITERATIONS_MAX 64U
48
#define RUNTIME_MAX_USEC (5 * USEC_PER_MINUTE)
49
#define PRESSURE_SLEEP_TIME_USEC (50 * USEC_PER_MSEC)
50
#define LISTEN_IDLE_USEC (90 * USEC_PER_SEC)
51

52
static const ImagePolicy image_policy_untrusted = {
53
        .n_policies = 2,
54
        .policies = {
55
                { PARTITION_ROOT,     PARTITION_POLICY_SIGNED|PARTITION_POLICY_ABSENT },
56
                { PARTITION_USR,      PARTITION_POLICY_SIGNED|PARTITION_POLICY_ABSENT },
57
        },
58
        .default_flags = PARTITION_POLICY_IGNORE,
59
};
60

61
static int json_dispatch_image_policy(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
×
62
        _cleanup_(image_policy_freep) ImagePolicy *q = NULL;
×
63
        ImagePolicy **p = ASSERT_PTR(userdata);
×
64
        int r;
×
65

66
        assert(p);
×
67

68
        if (sd_json_variant_is_null(variant)) {
×
69
                *p = image_policy_free(*p);
×
70
                return 0;
×
71
        }
72

73
        if (!sd_json_variant_is_string(variant))
×
74
                return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a string.", strna(name));
×
75

76
        r = image_policy_from_string(sd_json_variant_string(variant), &q);
×
77
        if (r < 0)
×
78
                return json_log(variant, flags, r, "JSON field '%s' is not a valid image policy.", strna(name));
×
79

80
        image_policy_free(*p);
×
81
        *p = TAKE_PTR(q);
×
82
        return 0;
×
83
}
84

85
typedef struct MountImageParameters {
86
        unsigned image_fd_idx;
87
        unsigned userns_fd_idx;
88
        int read_only;
89
        int growfs;
90
        char *password;
91
        ImagePolicy *image_policy;
92
} MountImageParameters;
93

94
static void mount_image_parameters_done(MountImageParameters *p) {
×
95
        assert(p);
×
96

97
        p->password = erase_and_free(p->password);
×
98
        p->image_policy = image_policy_free(p->image_policy);
×
99
}
×
100

101
static int validate_image_fd(int fd, MountImageParameters *p) {
×
102
        int r, fl;
×
103

104
        assert(fd >= 0);
×
105
        assert(p);
×
106

107
        struct stat st;
×
108
        if (fstat(fd, &st) < 0)
×
109
                return -errno;
×
110
        /* Only support regular files and block devices. Let's use stat_verify_regular() here for the nice
111
         * error numbers it generates. */
112
        if (!S_ISBLK(st.st_mode)) {
×
113
                r = stat_verify_regular(&st);
×
114
                if (r < 0)
×
115
                        return r;
116
        }
117

118
        fl = fd_verify_safe_flags(fd);
×
119
        if (fl < 0)
×
120
                return log_debug_errno(fl, "Image file descriptor has unsafe flags set: %m");
×
121

122
        switch (fl & O_ACCMODE_STRICT) {
×
123

124
        case O_RDONLY:
×
125
                p->read_only = true;
×
126
                break;
×
127

128
        case O_RDWR:
129
                break;
130

131
        default:
132
                return -EBADF;
133
        }
134

135
        return 0;
136
}
137

138
static int verify_trusted_image_fd_by_path(int fd) {
×
139
        int r;
×
140

141
        assert(fd >= 0);
×
142

143
        r = secure_getenv_bool("SYSTEMD_MOUNTFSD_TRUSTED_DIRECTORIES");
×
144
        if (r == -ENXIO)  {
×
145
                if (!DEFAULT_MOUNTFSD_TRUSTED_DIRECTORIES) {
×
146
                        log_debug("Trusted directory mechanism disabled at compile time.");
×
147
                        return false;
×
148
                }
149
        } else if (r < 0) {
×
150
                log_debug_errno(r, "Failed to parse $SYSTEMD_MOUNTFSD_TRUSTED_DIRECTORIES environment variable, not trusting any image.");
×
151
                return false;
×
152
        } else if (!r) {
×
153
                log_debug("Trusted directory mechanism disabled via $SYSTEMD_MOUNTFSD_TRUSTED_DIRECTORIES environment variable.");
×
154
                return false;
×
155
        }
156

157
        _cleanup_free_ char *p = NULL;
×
158
        r = fd_get_path(fd, &p);
×
159
        if (r < 0)
×
160
                return log_debug_errno(r, "Failed to get path of passed image file descriptor: %m");
×
161

162
        struct stat sta;
×
163
        if (fstat(fd, &sta) < 0)
×
164
                return log_debug_errno(errno, "Failed to stat() passed image file descriptor: %m");
×
165
        if (!S_ISREG(sta.st_mode)) {
×
166
                log_debug("Image '%s' is not a regular file, hence skipping trusted directory check.", p);
×
167
                return false;
×
168
        }
169

170
        log_debug("Checking if image '%s' is in trusted directories.", p);
×
171

172
        for (ImageClass c = 0; c < _IMAGE_CLASS_MAX; c++)
×
173
                NULSTR_FOREACH(s, image_search_path[c]) {
×
174
                        _cleanup_close_ int dir_fd = -EBADF, inode_fd = -EBADF;
×
175
                        _cleanup_free_ char *q = NULL;
×
176
                        struct stat stb;
×
177
                        const char *e;
×
178

179
                        r = chase(s, NULL, CHASE_SAFE|CHASE_TRIGGER_AUTOFS, &q, &dir_fd);
×
180
                        if (r == -ENOENT)
×
181
                                continue;
×
182
                        if (r < 0) {
×
183
                                log_warning_errno(r, "Failed to resolve search path '%s', ignoring: %m", s);
×
184
                                continue;
×
185
                        }
186

187
                        /* Check that the inode refers to a file immediately inside the image directory,
188
                         * i.e. not the image directory itself, and nothing further down the tree */
189
                        e = path_startswith(p, q);
×
190
                        if (isempty(e))
×
191
                                continue;
×
192

193
                        e += strspn(e, "/");
×
194
                        if (!filename_is_valid(e))
×
195
                                continue;
×
196

197
                        r = chaseat(dir_fd, e, CHASE_SAFE|CHASE_TRIGGER_AUTOFS, NULL, &inode_fd);
×
198
                        if (r < 0)
×
199
                                return log_error_errno(r, "Couldn't verify that specified image '%s' is in search path '%s': %m", p, s);
×
200

201
                        if (fstat(inode_fd, &stb) < 0)
×
202
                                return log_error_errno(errno, "Failed to stat image file '%s/%s': %m", q, e);
×
203

204
                        if (stat_inode_same(&sta, &stb)) {
×
205
                                log_debug("Image '%s' is *in* trusted directories.", p);
×
206
                                return true; /* Yay */
×
207
                        }
208
                }
209

210
        log_debug("Image '%s' is *not* in trusted directories.", p);
×
211
        return false;
212
}
213

214
static int determine_image_policy(
×
215
                int image_fd,
216
                bool trusted,
217
                ImagePolicy *client_policy,
218
                ImagePolicy **ret) {
219

220
        _cleanup_(image_policy_freep) ImagePolicy *envvar_policy = NULL;
×
221
        const ImagePolicy *default_policy;
×
222
        const char *envvar, *e;
×
223
        int r;
×
224

225
        assert(image_fd >= 0);
×
226
        assert(ret);
×
227

228
        if (trusted) {
×
229
                envvar = "SYSTEMD_MOUNTFSD_IMAGE_POLICY_TRUSTED";
230
                default_policy = &image_policy_allow;
231
        } else {
232
                envvar = "SYSTEMD_MOUNTFSD_IMAGE_POLICY_UNTRUSTED";
×
233
                default_policy = &image_policy_untrusted;
×
234
        }
235

236
        e = secure_getenv(envvar);
×
237
        if (e) {
×
238
                r = image_policy_from_string(e, &envvar_policy);
×
239
                if (r < 0)
×
240
                        return log_error_errno(r, "Failed to parse image policy supplied via $%s: %m", envvar);
×
241

242
                default_policy = envvar_policy;
×
243
        }
244

245
        return image_policy_intersect(default_policy, client_policy, ret);
×
246
}
247

248
static int validate_userns(sd_varlink *link, int *userns_fd) {
×
249
        int r;
×
250

251
        assert(link);
×
252
        assert(userns_fd);
×
253

254
        if (*userns_fd < 0)
×
255
                return 0;
256

257
        r = fd_verify_safe_flags(*userns_fd);
×
258
        if (r < 0)
×
259
                return log_debug_errno(r, "User namespace file descriptor has unsafe flags set: %m");
×
260

261
        r = fd_is_namespace(*userns_fd, NAMESPACE_USER);
×
262
        if (r < 0)
×
263
                return r;
264
        if (r == 0)
×
265
                return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
×
266

267
        /* Our own host user namespace? Then close the fd, and handle it as if none was specified. */
268
        r = is_our_namespace(*userns_fd, NAMESPACE_USER);
×
269
        if (r < 0)
×
270
                return log_debug_errno(r, "Failed to determine if user namespace provided by client is our own.");
×
271
        if (r > 0) {
×
272
                log_debug("User namespace provided by client is our own.");
×
273
                *userns_fd = safe_close(*userns_fd);
×
274
        }
275

276
        return 0;
277
}
278

279
static int vl_method_mount_image(
×
280
                sd_varlink *link,
281
                sd_json_variant *parameters,
282
                sd_varlink_method_flags_t flags,
283
                void *userdata) {
284

285
        static const sd_json_dispatch_field dispatch_table[] = {
×
286
                { "imageFileDescriptor",         SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint,      offsetof(MountImageParameters, image_fd_idx),  SD_JSON_MANDATORY },
287
                { "userNamespaceFileDescriptor", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint,      offsetof(MountImageParameters, userns_fd_idx), 0 },
288
                { "readOnly",                    SD_JSON_VARIANT_BOOLEAN,  sd_json_dispatch_tristate,  offsetof(MountImageParameters, read_only),     0 },
289
                { "growFileSystems",             SD_JSON_VARIANT_BOOLEAN,  sd_json_dispatch_tristate,  offsetof(MountImageParameters, growfs),        0 },
290
                { "password",                    SD_JSON_VARIANT_STRING,   sd_json_dispatch_string,    offsetof(MountImageParameters, password),      0 },
291
                { "imagePolicy",                 SD_JSON_VARIANT_STRING,   json_dispatch_image_policy, offsetof(MountImageParameters, image_policy),  0 },
292
                VARLINK_DISPATCH_POLKIT_FIELD,
293
                {}
294
        };
295

296
        _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
×
297
        _cleanup_(mount_image_parameters_done) MountImageParameters p = {
×
298
                .image_fd_idx = UINT_MAX,
299
                .userns_fd_idx = UINT_MAX,
300
                .read_only = -1,
301
                .growfs = -1,
302
        };
303
        _cleanup_(dissected_image_unrefp) DissectedImage *di = NULL;
×
304
        _cleanup_(loop_device_unrefp) LoopDevice *loop = NULL;
×
305
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *aj = NULL;
×
306
        _cleanup_close_ int image_fd = -EBADF, userns_fd = -EBADF;
×
307
        _cleanup_(image_policy_freep) ImagePolicy *use_policy = NULL;
×
308
        Hashmap **polkit_registry = ASSERT_PTR(userdata);
×
309
        _cleanup_free_ char *ps = NULL;
×
310
        bool image_is_trusted = false;
×
311
        int r;
×
312

313
        assert(link);
×
314
        assert(parameters);
×
315

316
        sd_json_variant_sensitive(parameters); /* might contain passwords */
×
317

318
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
×
319
        if (r != 0)
×
320
                return r;
321

322
        if (p.image_fd_idx != UINT_MAX) {
×
323
                image_fd = sd_varlink_peek_dup_fd(link, p.image_fd_idx);
×
324
                if (image_fd < 0)
×
325
                        return log_debug_errno(image_fd, "Failed to peek image fd from client: %m");
×
326
        }
327

328
        if (p.userns_fd_idx != UINT_MAX) {
×
329
                userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
×
330
                if (userns_fd < 0)
×
331
                        return log_debug_errno(userns_fd, "Failed to peek user namespace fd from client: %m");
×
332
        }
333

334
        r = validate_image_fd(image_fd, &p);
×
335
        if (r < 0)
×
336
                return r;
337

338
        r = validate_userns(link, &userns_fd);
×
339
        if (r != 0)
×
340
                return r;
341

342
        r = verify_trusted_image_fd_by_path(image_fd);
×
343
        if (r < 0)
×
344
                return r;
345
        image_is_trusted = r;
×
346

347
        const char *polkit_details[] = {
×
348
                "read_only", one_zero(p.read_only > 0),
×
349
                NULL,
350
        };
351

352
        const char *polkit_action, *polkit_untrusted_action;
×
353
        PolkitFlags polkit_flags;
×
354
        if (userns_fd < 0) {
×
355
                /* Mount into the host user namespace */
356
                polkit_action = "io.systemd.mount-file-system.mount-image";
357
                polkit_untrusted_action = "io.systemd.mount-file-system.mount-untrusted-image";
358
                polkit_flags = 0;
359
        } else {
360
                /* Mount into a private user namespace */
361
                polkit_action = "io.systemd.mount-file-system.mount-image-privately";
×
362
                polkit_untrusted_action = "io.systemd.mount-file-system.mount-untrusted-image-privately";
×
363

364
                /* If polkit is not around, let's allow mounting authenticated images by default */
365
                polkit_flags = POLKIT_DEFAULT_ALLOW;
×
366
        }
367

368
        /* Let's definitely acquire the regular action privilege, for mounting properly signed images */
369
        r = varlink_verify_polkit_async_full(
×
370
                        link,
371
                        /* bus= */ NULL,
372
                        polkit_action,
373
                        polkit_details,
374
                        /* good_user= */ UID_INVALID,
375
                        polkit_flags,
376
                        polkit_registry);
377
        if (r <= 0)
×
378
                return r;
379

380
        /* Generate the common dissection directory here. We are not going to use it, but the clients might,
381
         * and they likely are unprivileged, hence cannot create it themselves. Hence let's just create it
382
         * here, if it is missing. */
383
        r = get_common_dissect_directory(NULL);
×
384
        if (r < 0)
×
385
                return r;
386

387
        r = loop_device_make(
×
388
                        image_fd,
389
                        p.read_only == 0 ? O_RDONLY : O_RDWR,
×
390
                        0,
391
                        UINT64_MAX,
392
                        UINT32_MAX,
393
                        LO_FLAGS_PARTSCAN,
394
                        LOCK_EX,
395
                        &loop);
396
        if (r < 0)
×
397
                return r;
398

399
        DissectImageFlags dissect_flags =
×
400
                (p.read_only == 0 ? DISSECT_IMAGE_READ_ONLY : 0) |
×
401
                (p.growfs != 0 ? DISSECT_IMAGE_GROWFS : 0) |
×
402
                DISSECT_IMAGE_DISCARD_ANY |
403
                DISSECT_IMAGE_FSCK |
404
                DISSECT_IMAGE_ADD_PARTITION_DEVICES |
405
                DISSECT_IMAGE_PIN_PARTITION_DEVICES |
×
406
                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
407

408
        /* Let's see if we have acquired the privilege to mount untrusted images already */
409
        bool polkit_have_untrusted_action =
×
410
                varlink_has_polkit_action(link, polkit_untrusted_action, polkit_details, polkit_registry);
×
411

412
        for (;;) {
×
413
                use_policy = image_policy_free(use_policy);
×
414
                ps = mfree(ps);
×
415

416
                /* We use the image policy for trusted images if either the path is below a trusted
417
                 * directory, or if we have already acquired a PK authentication that tells us that untrusted
418
                 * images are OK */
419
                bool use_trusted_policy =
×
420
                        image_is_trusted ||
421
                        polkit_have_untrusted_action;
422

423
                r = determine_image_policy(
×
424
                                image_fd,
425
                                use_trusted_policy,
426
                                p.image_policy,
427
                                &use_policy);
428
                if (r < 0)
×
429
                        return r;
430

431
                r = image_policy_to_string(use_policy, /* simplify= */ true, &ps);
×
432
                if (r < 0)
×
433
                        return r;
434

435
                log_debug("Using image policy: %s", ps);
×
436

437
                r = dissect_loop_device(
×
438
                                loop,
439
                                &verity,
440
                                /* mount_options= */ NULL,
441
                                use_policy,
442
                                /* image_filter= */ NULL,
443
                                dissect_flags,
444
                                &di);
445
                if (r == -ENOPKG)
×
446
                        return sd_varlink_error(link, "io.systemd.MountFileSystem.IncompatibleImage", NULL);
×
447
                if (r == -ENOTUNIQ)
×
448
                        return sd_varlink_error(link, "io.systemd.MountFileSystem.MultipleRootPartitionsFound", NULL);
×
449
                if (r == -ENXIO)
×
450
                        return sd_varlink_error(link, "io.systemd.MountFileSystem.RootPartitionNotFound", NULL);
×
451
                if (r == -ERFKILL) {
×
452
                        /* The image policy refused this, let's retry after trying to get PolicyKit */
453

454
                        if (!polkit_have_untrusted_action) {
×
455
                                log_debug("Denied by image policy. Trying a stronger polkit authentication before continuing.");
×
456
                                r = varlink_verify_polkit_async_full(
×
457
                                                link,
458
                                                /* bus= */ NULL,
459
                                                polkit_untrusted_action,
460
                                                polkit_details,
461
                                                /* good_user= */ UID_INVALID,
462
                                                /* flags= */ 0,                   /* NB: the image cannot be authenticated, hence unless PK is around to allow this anyway, fail! */
463
                                                polkit_registry);
464
                                if (r <= 0 && !ERRNO_IS_NEG_PRIVILEGE(r))
×
465
                                        return r;
466
                                if (r > 0) {
×
467
                                        /* Try again, now that we know the client has enough privileges. */
468
                                        log_debug("Denied by image policy, retrying after polkit authentication.");
×
469
                                        polkit_have_untrusted_action = true;
×
470
                                        continue;
×
471
                                }
472
                        }
473

474
                        return sd_varlink_error(link, "io.systemd.MountFileSystem.DeniedByImagePolicy", NULL);
×
475
                }
476
                if (r < 0)
×
477
                        return r;
478

479
                /* Success */
480
                break;
×
481
        }
482

483
        r = dissected_image_load_verity_sig_partition(
×
484
                        di,
485
                        loop->fd,
×
486
                        &verity);
487
        if (r < 0)
×
488
                return r;
489

490
        r = dissected_image_guess_verity_roothash(
×
491
                        di,
492
                        &verity);
493
        if (r < 0)
×
494
                return r;
495

496
        r = dissected_image_decrypt(
×
497
                        di,
498
                        p.password,
×
499
                        &verity,
500
                        dissect_flags);
501
        if (r == -ENOKEY) /* new dm-verity userspace returns ENOKEY if the dm-verity signature key is not in
×
502
                           * key chain. That's great. */
503
                return sd_varlink_error(link, "io.systemd.MountFileSystem.KeyNotFound", NULL);
×
504
        if (r == -EBUSY) /* DM kernel subsystem is shit with returning useful errors hence we keep retrying
×
505
                          * under the assumption that some errors are transitional. Which the errors might
506
                          * not actually be. After all retries failed we return EBUSY. Let's turn that into a
507
                          * generic Verity error. It's not very helpful, could mean anything, but at least it
508
                          * gives client a clear idea that this has to do with Verity. */
509
                return sd_varlink_error(link, "io.systemd.MountFileSystem.VerityFailure", NULL);
×
510
        if (r < 0)
×
511
                return r;
512

513
        r = dissected_image_mount(
×
514
                        di,
515
                        /* where= */ NULL,
516
                        /* uid_shift= */ UID_INVALID,
517
                        /* uid_range= */ UID_INVALID,
518
                        userns_fd,
519
                        dissect_flags);
520
        if (r < 0)
×
521
                return r;
522

523
        for (PartitionDesignator d = 0; d < _PARTITION_DESIGNATOR_MAX; d++) {
×
524
                DissectedPartition *pp = di->partitions + d;
×
525
                int fd_idx;
×
526

527
                if (!pp->found)
×
528
                        continue;
×
529

530
                if (pp->fsmount_fd < 0)
×
531
                        continue;
×
532

533
                if (userns_fd >= 0) {
×
534
                        r = nsresource_add_mount(userns_fd, pp->fsmount_fd);
×
535
                        if (r < 0)
×
536
                                return r;
×
537
                }
538

539
                fd_idx = sd_varlink_push_fd(link, pp->fsmount_fd);
×
540
                if (fd_idx < 0)
×
541
                        return fd_idx;
542

543
                TAKE_FD(pp->fsmount_fd);
×
544

545
                const char *m = partition_mountpoint_to_string(d);
×
546
                _cleanup_strv_free_ char **l = NULL;
×
547
                if (!isempty(m)) {
×
548
                        l = strv_split_nulstr(m);
×
549
                        if (!l)
×
550
                                return log_oom_debug();
×
551
                }
552

553
                r = sd_json_variant_append_arraybo(
×
554
                                &aj,
555
                                SD_JSON_BUILD_PAIR("designator", SD_JSON_BUILD_STRING(partition_designator_to_string(d))),
556
                                SD_JSON_BUILD_PAIR("writable", SD_JSON_BUILD_BOOLEAN(pp->rw)),
557
                                SD_JSON_BUILD_PAIR("growFileSystem", SD_JSON_BUILD_BOOLEAN(pp->growfs)),
558
                                SD_JSON_BUILD_PAIR_CONDITION(pp->partno > 0, "partitionNumber", SD_JSON_BUILD_INTEGER(pp->partno)),
559
                                SD_JSON_BUILD_PAIR_CONDITION(pp->architecture > 0, "architecture", SD_JSON_BUILD_STRING(architecture_to_string(pp->architecture))),
560
                                SD_JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(pp->uuid), "partitionUuid", SD_JSON_BUILD_UUID(pp->uuid)),
561
                                SD_JSON_BUILD_PAIR("fileSystemType", SD_JSON_BUILD_STRING(dissected_partition_fstype(pp))),
562
                                SD_JSON_BUILD_PAIR_CONDITION(!!pp->label, "partitionLabel", SD_JSON_BUILD_STRING(pp->label)),
563
                                SD_JSON_BUILD_PAIR("size", SD_JSON_BUILD_INTEGER(pp->size)),
564
                                SD_JSON_BUILD_PAIR("offset", SD_JSON_BUILD_INTEGER(pp->offset)),
565
                                SD_JSON_BUILD_PAIR("mountFileDescriptor", SD_JSON_BUILD_INTEGER(fd_idx)),
566
                                JSON_BUILD_PAIR_STRV_NON_EMPTY("mountPoint", l));
567
                if (r < 0)
×
568
                        return r;
569
        }
570

571
        loop_device_relinquish(loop);
×
572

573
        return sd_varlink_replybo(
×
574
                        link,
575
                        SD_JSON_BUILD_PAIR("partitions", SD_JSON_BUILD_VARIANT(aj)),
576
                        SD_JSON_BUILD_PAIR("imagePolicy", SD_JSON_BUILD_STRING(ps)),
577
                        SD_JSON_BUILD_PAIR("imageSize", SD_JSON_BUILD_INTEGER(di->image_size)),
578
                        SD_JSON_BUILD_PAIR("sectorSize", SD_JSON_BUILD_INTEGER(di->sector_size)),
579
                        SD_JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(di->image_uuid), "imageUuid", SD_JSON_BUILD_UUID(di->image_uuid)));
580
}
581

582
typedef enum MountMapMode {
583
        MOUNT_MAP_AUTO = 0,     /* determine automatically from image and caller */
584
        MOUNT_MAP_ROOT,         /* map caller's UID to root in namespace (map 1 UID only) */
585
        MOUNT_MAP_FOREIGN,      /* map foreign UID range to base in namespace (map 64K) */
586
        MOUNT_MAP_IDENTITY,     /* apply identity mapping (map 64K) */
587
        _MOUNT_MAP_MODE_MAX,
588
        _MOUNT_MAP_MODE_INVALID = -EINVAL,
589
} MountMapMode;
590

591
static const char *const mount_map_mode_table[_MOUNT_MAP_MODE_MAX] = {
592
        [MOUNT_MAP_AUTO]     = "auto",
593
        [MOUNT_MAP_ROOT]     = "root",
594
        [MOUNT_MAP_FOREIGN]  = "foreign",
595
        [MOUNT_MAP_IDENTITY] = "identity",
596
};
597

598
DEFINE_PRIVATE_STRING_TABLE_LOOKUP(mount_map_mode, MountMapMode);
×
599

600
typedef struct MountDirectoryParameters {
601
        MountMapMode mode;
602
        unsigned directory_fd_idx;
603
        unsigned userns_fd_idx;
604
        int read_only;
605
} MountDirectoryParameters;
606

607
typedef enum DirectoryOwnership {
608
        DIRECTORY_IS_ROOT_PEER_OWNED,  /* This is returned if the directory is owned by the root user and the peer is root */
609
        DIRECTORY_IS_ROOT_OWNED,       /* This is returned if the directory is owned by the root user (and the peer user is not root) */
610
        DIRECTORY_IS_PEER_OWNED,       /* This is returned if the directory is owned by the peer user (who is not root) */
611
        DIRECTORY_IS_FOREIGN_OWNED,    /* This is returned if the directory is owned by the foreign UID range */
612
        DIRECTORY_IS_OTHERWISE_OWNED,  /* This is returned if the directory is owned by something else */
613
        _DIRECTORY_OWNERSHIP_MAX,
614
        _DIRECTORY_OWNERSHIP_ERRNO_MAX = -ERRNO_MAX, /* Guarantee the whole negative errno range fits */
615
} DirectoryOwnership;
616

617
static MountMapMode default_mount_map_mode(DirectoryOwnership ownership) {
×
618
        /* Derives a suitable mapping mode from the ownership of the base tree */
619

620
        switch (ownership) {
×
621
        case DIRECTORY_IS_PEER_OWNED:
622
                return MOUNT_MAP_ROOT;     /* Map the peer's UID to root in the container */
623

624
        case DIRECTORY_IS_FOREIGN_OWNED:
×
625
                return MOUNT_MAP_FOREIGN;  /* Map the foreign UID range to the container's UID range */
×
626

627
        case DIRECTORY_IS_ROOT_PEER_OWNED:
×
628
        case DIRECTORY_IS_ROOT_OWNED:
629
        case DIRECTORY_IS_OTHERWISE_OWNED:
630
                return MOUNT_MAP_IDENTITY; /* Don't map */
×
631

632
        default:
×
633
                return _MOUNT_MAP_MODE_INVALID;
×
634
        }
635
}
636

637
static JSON_DISPATCH_ENUM_DEFINE(dispatch_mount_directory_mode, MountMapMode, mount_map_mode_from_string);
×
638

639
static DirectoryOwnership validate_directory_fd(int fd, uid_t peer_uid) {
×
640
        int r, fl;
×
641

642
        assert(fd >= 0);
×
643

644
        /* Checks if the specified directory fd looks sane. Returns a DirectoryOwnership that categorizes the
645
         * ownership situation in comparison to the peer's UID.
646
         *
647
         * Note one key difference to image validation (as implemented above): for regular files if the
648
         * client provided us with an open fd it implies the client has access, as well as what kind of
649
         * access (i.e. ro or rw). But for directories this doesn't work the same way, as directories are
650
         * always opened read-only only. Hence we use a different mechanism to validate access to them: we
651
         * check if the directory is owned by the peer UID or by the foreign UID range (in the latter case
652
         * one of the parent directories must be owned by the peer though). */
653

654
        struct stat st;
×
655
        if (fstat(fd, &st) < 0)
×
656
                return log_debug_errno(errno, "Failed to stat() directory fd: %m");
×
657

658
        r = stat_verify_directory(&st);
×
659
        if (r < 0)
×
660
                return r;
661

662
        fl = fd_verify_safe_flags_full(fd, O_DIRECTORY);
×
663
        if (fl < 0)
×
664
                return log_debug_errno(fl, "Directory file descriptor has unsafe flags set: %m");
×
665

666
        if (st.st_uid == 0) {
×
667
                if (peer_uid == 0) {
×
668
                        log_debug("Directory file descriptor points to root owned directory, who is also the peer.");
×
669
                        return DIRECTORY_IS_ROOT_PEER_OWNED;
×
670
                }
671
                log_debug("Directory file descriptor points to root owned directory.");
×
672
                return DIRECTORY_IS_ROOT_OWNED;
×
673
        }
674
        if (st.st_uid == peer_uid) {
×
675
                log_debug("Directory file descriptor points to peer owned directory.");
×
676
                return DIRECTORY_IS_PEER_OWNED;
×
677
        }
678

679
        /* For bind mounted directories we check if they are either owned by the client's UID, or by the
680
         * foreign UID set, but in that case the parent directory must be owned by the client's UID, or some
681
         * directory iteratively up the chain */
682

683
        _cleanup_close_ int parent_fd = -EBADF;
×
684
        unsigned n_level;
685
        for (n_level = 0; n_level < 16; n_level++) {
×
686
                /* Stop iteration if we find a directory up the tree that is neither owned by the user, nor is from the foreign UID range */
687
                if (!uid_is_foreign(st.st_uid) || !gid_is_foreign(st.st_gid)) {
×
688
                        log_debug("Directory file descriptor points to directory which itself or its parents is neither owned by foreign UID range nor by the user.");
×
689
                        return DIRECTORY_IS_OTHERWISE_OWNED;
×
690
                }
691

692
                /* If the peer is root, then it doesn't matter if we find a parent owned by root, let's shortcut things. */
693
                if (peer_uid == 0) {
×
694
                        log_debug("Directory file descriptor is owned by foreign UID range, and peer is root.");
×
695
                        return DIRECTORY_IS_FOREIGN_OWNED;
×
696
                }
697

698
                /* Go one level up */
699
                _cleanup_close_ int new_parent_fd = openat(fd, "..", O_DIRECTORY|O_PATH|O_CLOEXEC);
×
700
                if (new_parent_fd < 0)
×
701
                        return log_debug_errno(errno, "Failed to open parent directory of directory file descriptor: %m");
×
702

703
                struct stat new_st;
×
704
                if (fstat(new_parent_fd, &new_st) < 0)
×
705
                        return log_debug_errno(errno, "Failed to stat parent directory of directory file descriptor: %m");
×
706

707
                /* Safety check to see if we hit the root dir */
708
                if (stat_inode_same(&st, &new_st)) {
×
709
                        log_debug("Directory file descriptor is owned by foreign UID range, but didn't find parent directory that is owned by peer among ancestors.");
×
710
                        return DIRECTORY_IS_OTHERWISE_OWNED;
×
711
                }
712

713
                if (new_st.st_uid == peer_uid) { /* Parent inode is owned by the peer. That's good! Everything's fine. */
×
714
                        log_debug("Directory file descriptor is owned by foreign UID range, and ancestor is owned by peer.");
×
715
                        return DIRECTORY_IS_FOREIGN_OWNED;
×
716
                }
717

718
                close_and_replace(parent_fd, new_parent_fd);
×
719
                st = new_st;
×
720
        }
721

722
        log_debug("Failed to find peer owned parent directory after %u levels, refusing.", n_level);
×
723
        return DIRECTORY_IS_OTHERWISE_OWNED;
724
}
725

726
static int vl_method_mount_directory(
×
727
                sd_varlink *link,
728
                sd_json_variant *parameters,
729
                sd_varlink_method_flags_t flags,
730
                void *userdata) {
731

732
        static const sd_json_dispatch_field dispatch_table[] = {
×
733
                { "mode",                        SD_JSON_VARIANT_STRING,   dispatch_mount_directory_mode, offsetof(MountDirectoryParameters, mode),             0                 },
734
                { "directoryFileDescriptor",     SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint,         offsetof(MountDirectoryParameters, directory_fd_idx), SD_JSON_MANDATORY },
735
                { "userNamespaceFileDescriptor", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint,         offsetof(MountDirectoryParameters, userns_fd_idx),    0                 },
736
                { "readOnly",                    SD_JSON_VARIANT_BOOLEAN,  sd_json_dispatch_tristate,     offsetof(MountDirectoryParameters, read_only),        0                 },
737
                VARLINK_DISPATCH_POLKIT_FIELD,
738
                {}
739
        };
740

741
        MountDirectoryParameters p = {
×
742
                .mode = MOUNT_MAP_AUTO,
743
                .directory_fd_idx = UINT_MAX,
744
                .userns_fd_idx = UINT_MAX,
745
                .read_only = -1,
746
        };
747
        _cleanup_close_ int directory_fd = -EBADF, userns_fd = -EBADF;
×
748
        Hashmap **polkit_registry = ASSERT_PTR(userdata);
×
749
        int r;
×
750

751
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
×
752
        if (r != 0)
×
753
                return r;
754

755
        if (p.directory_fd_idx == UINT_MAX)
×
756
                return sd_varlink_error_invalid_parameter_name(link, "directoryFileDescriptor");
×
757

758
        directory_fd = sd_varlink_peek_dup_fd(link, p.directory_fd_idx);
×
759
        if (directory_fd < 0)
×
760
                return log_debug_errno(directory_fd, "Failed to peek directory fd from client: %m");
×
761

762
        if (p.userns_fd_idx != UINT_MAX) {
×
763
                userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
×
764
                if (userns_fd < 0)
×
765
                        return log_debug_errno(userns_fd, "Failed to peek user namespace fd from client: %m");
×
766
        }
767

768
        uid_t peer_uid;
×
769
        r = sd_varlink_get_peer_uid(link, &peer_uid);
×
770
        if (r < 0)
×
771
                return log_debug_errno(r, "Failed to get client UID: %m");
×
772

773
        DirectoryOwnership owned_by = validate_directory_fd(directory_fd, peer_uid);
×
774
        if (owned_by == -EREMOTEIO)
×
UNCOV
775
                return sd_varlink_errorbo(link, "io.systemd.MountFileSystem.BadFileDescriptorFlags", SD_JSON_BUILD_PAIR_STRING("parameter", "directoryFileDescriptor"));
×
UNCOV
776
        if (owned_by < 0)
×
777
                return owned_by;
778

UNCOV
779
        r = validate_userns(link, &userns_fd);
×
UNCOV
780
        if (r != 0)
×
781
                return r;
782

783
        /* If no mode is specified, pick sensible default */
784
        if (p.mode <= 0) {
×
UNCOV
785
                p.mode = default_mount_map_mode(owned_by);
×
UNCOV
786
                assert(p.mode > 0);
×
787
        }
788

UNCOV
789
        _cleanup_free_ char *directory_path = NULL;
×
790
        (void) fd_get_path(directory_fd, &directory_path);
×
791

792
        log_debug("Mounting '%s' with mapping mode: %s", strna(directory_path), mount_map_mode_to_string(p.mode));
×
793

794
        const char *polkit_details[] = {
×
UNCOV
795
                "read_only", one_zero(p.read_only > 0),
×
UNCOV
796
                "directory", strna(directory_path),
×
797
                NULL,
798
        };
799

800
        const char *polkit_action, *polkit_untrusted_action;
×
UNCOV
801
        PolkitFlags polkit_flags;
×
UNCOV
802
        if (userns_fd < 0) {
×
803
                /* Mount into the host user namespace */
804
                polkit_action = "io.systemd.mount-file-system.mount-directory";
805
                polkit_untrusted_action = "io.systemd.mount-file-system.mount-untrusted-directory";
806
                polkit_flags = 0;
807
        } else {
808
                /* Mount into a private user namespace */
UNCOV
809
                polkit_action = "io.systemd.mount-file-system.mount-directory-privately";
×
UNCOV
810
                polkit_untrusted_action = "io.systemd.mount-file-system.mount-untrusted-directory-privately";
×
811

812
                /* If polkit is not around, let's allow mounting authenticated images by default */
UNCOV
813
                polkit_flags = POLKIT_DEFAULT_ALLOW;
×
814
        }
815

816
        /* We consider a directory "trusted" if it is owned by the peer or the foreign UID range */
UNCOV
817
        bool trusted_directory = IN_SET(owned_by, DIRECTORY_IS_ROOT_PEER_OWNED, DIRECTORY_IS_PEER_OWNED, DIRECTORY_IS_FOREIGN_OWNED);
×
818

819
        /* Let's definitely acquire the regular action privilege, for mounting properly signed images */
UNCOV
820
        r = varlink_verify_polkit_async_full(
×
821
                        link,
822
                        /* bus= */ NULL,
823
                        trusted_directory ? polkit_action : polkit_untrusted_action,
824
                        polkit_details,
825
                        /* good_user= */ UID_INVALID,
826
                        trusted_directory ? polkit_flags : 0,
827
                        polkit_registry);
UNCOV
828
        if (r <= 0)
×
829
                return r;
830

831
        /* Generate the common dissection directory here. We are not going to use it, but the clients might,
832
         * and they likely are unprivileged, hence cannot create it themselves. Hence let's just create it
833
         * here, if it is missing. */
UNCOV
834
        r = get_common_dissect_directory(NULL);
×
UNCOV
835
        if (r < 0)
×
836
                return r;
837

838
        _cleanup_close_ int mount_fd = open_tree(directory_fd, "", OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH);
×
UNCOV
839
        if (mount_fd < 0)
×
840
                return log_debug_errno(errno, "Failed to issue open_tree() of provided directory '%s': %m", strna(directory_path));
×
841

842
        if (p.read_only > 0 && mount_setattr(
×
843
                            mount_fd, "", AT_EMPTY_PATH,
UNCOV
844
                            &(struct mount_attr) {
×
845
                                    .attr_set = MOUNT_ATTR_RDONLY,
846
                            }, MOUNT_ATTR_SIZE_VER0) < 0)
847
                return log_debug_errno(errno, "Failed to enable read-only mode: %m");
×
848

UNCOV
849
        if (p.mode != MOUNT_MAP_IDENTITY) {
×
850
                uid_t start;
×
851

852
                if (userns_fd >= 0) {
×
853
                        _cleanup_(uid_range_freep) UIDRange *uid_range_outside = NULL, *uid_range_inside = NULL, *gid_range_outside = NULL, *gid_range_inside = NULL;
×
854
                        r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_OUTSIDE, &uid_range_outside);
×
855
                        if (r < 0)
×
856
                                return log_debug_errno(r, "Failed to load outside UID range of provided userns: %m");
×
857
                        r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_INSIDE, &uid_range_inside);
×
858
                        if (r < 0)
×
859
                                return log_debug_errno(r, "Failed to load inside UID range of provided userns: %m");
×
860
                        r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_OUTSIDE, &gid_range_outside);
×
861
                        if (r < 0)
×
862
                                return log_debug_errno(r, "Failed to load outside GID range of provided userns: %m");
×
863
                        r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_INSIDE, &gid_range_inside);
×
UNCOV
864
                        if (r < 0)
×
UNCOV
865
                                return log_debug_errno(r, "Failed to load inside GID range of provided userns: %m");
×
866

867
                        /* Be very strict for now */
868
                        if (!uid_range_equal(uid_range_outside, gid_range_outside) ||
×
869
                            !uid_range_equal(uid_range_inside, gid_range_inside) ||
×
870
                            uid_range_outside->n_entries != 1 ||
×
871
                            uid_range_outside->entries[0].nr != 0x10000 ||
×
872
                            uid_range_inside->n_entries != 1 ||
×
873
                            uid_range_inside->entries[0].start != 0 ||
×
UNCOV
874
                            uid_range_inside->entries[0].nr != 0x10000)
×
875
                                return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
×
876

UNCOV
877
                        start = uid_range_outside->entries[0].start;
×
878
                } else
879
                        start = 0;
880

881
                _cleanup_free_ char *new_uid_map = NULL;
×
882
                switch (p.mode) {
×
UNCOV
883
                case MOUNT_MAP_ROOT:
×
UNCOV
884
                        r = strextendf(&new_uid_map, UID_FMT " " UID_FMT " " UID_FMT,
×
885
                                       peer_uid, start, (uid_t) 1);
886
                        break;
UNCOV
887
                case MOUNT_MAP_FOREIGN:
×
UNCOV
888
                        r = strextendf(&new_uid_map, UID_FMT " " UID_FMT " " UID_FMT,
×
889
                                       (uid_t) FOREIGN_UID_MIN, start, (uid_t) 0x10000);
890
                        break;
UNCOV
891
                default:
×
892
                        assert_not_reached();
×
893
                }
UNCOV
894
                if (r < 0)
×
895
                        return r;
896

897
                _cleanup_close_ int idmap_userns_fd = userns_acquire(new_uid_map, new_uid_map, /* setgroups_deny= */ true);
×
UNCOV
898
                if (idmap_userns_fd < 0)
×
899
                        return log_debug_errno(idmap_userns_fd, "Failed to acquire user namespace for id mapping: %m");
×
900

UNCOV
901
                if (mount_setattr(mount_fd, "", AT_EMPTY_PATH,
×
UNCOV
902
                                  &(struct mount_attr) {
×
903
                                          .attr_set = MOUNT_ATTR_IDMAP,
904
                                          .userns_fd = idmap_userns_fd,
905
                                          .propagation = MS_PRIVATE,
906
                                  }, MOUNT_ATTR_SIZE_VER0) < 0)
UNCOV
907
                        return log_debug_errno(errno, "Failed to enable id mapping: %m");
×
908
        }
909

910
        if (userns_fd >= 0) {
×
UNCOV
911
                r = nsresource_add_mount(userns_fd, mount_fd);
×
UNCOV
912
                if (r < 0)
×
913
                        return r;
914
        }
915

UNCOV
916
        int fd_idx = sd_varlink_push_fd(link, mount_fd);
×
UNCOV
917
        if (fd_idx < 0)
×
918
                return fd_idx;
919

920
        TAKE_FD(mount_fd);
×
921

UNCOV
922
        return sd_varlink_replybo(
×
923
                        link,
924
                        SD_JSON_BUILD_PAIR("mountFileDescriptor", SD_JSON_BUILD_INTEGER(fd_idx)));
925
}
926

927
typedef struct MakeDirectoryParameters {
928
        unsigned parent_fd_idx;
929
        const char *name;
930
} MakeDirectoryParameters;
931

UNCOV
932
static int vl_method_make_directory(
×
933
                sd_varlink *link,
934
                sd_json_variant *parameters,
935
                sd_varlink_method_flags_t flags,
936
                void *userdata) {
937

UNCOV
938
        static const sd_json_dispatch_field dispatch_table[] = {
×
939
                { "parentFileDescriptor", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint,        offsetof(MakeDirectoryParameters, parent_fd_idx), SD_JSON_MANDATORY },
940
                { "name",                 SD_JSON_VARIANT_STRING,   json_dispatch_const_filename, offsetof(MakeDirectoryParameters, name),          SD_JSON_MANDATORY },
941
                VARLINK_DISPATCH_POLKIT_FIELD,
942
                {}
943
        };
944

UNCOV
945
        MakeDirectoryParameters p = {
×
946
                .parent_fd_idx = UINT_MAX,
947
        };
UNCOV
948
        Hashmap **polkit_registry = ASSERT_PTR(userdata);
×
949
        int r;
×
950

951
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
×
UNCOV
952
        if (r != 0)
×
953
                return r;
×
954

UNCOV
955
        if (p.parent_fd_idx == UINT_MAX)
×
956
                return sd_varlink_error_invalid_parameter_name(link, "parentFileDescriptor");
×
957

958
        _cleanup_close_ int parent_fd = sd_varlink_peek_dup_fd(link, p.parent_fd_idx);
×
UNCOV
959
        if (parent_fd < 0)
×
960
                return log_debug_errno(parent_fd, "Failed to peek parent directory fd from client: %m");
×
961

962
        uid_t peer_uid;
×
963
        r = sd_varlink_get_peer_uid(link, &peer_uid);
×
UNCOV
964
        if (r < 0)
×
965
                return log_debug_errno(r, "Failed to get client UID: %m");
×
966

UNCOV
967
        struct stat parent_stat;
×
UNCOV
968
        if (fstat(parent_fd, &parent_stat) < 0)
×
969
                return r;
970

UNCOV
971
        r = stat_verify_directory(&parent_stat);
×
UNCOV
972
        if (r < 0)
×
973
                return r;
974

975
        int fl = fd_verify_safe_flags_full(parent_fd, O_DIRECTORY);
×
UNCOV
976
        if (fl < 0)
×
977
                return log_debug_errno(fl, "Directory file descriptor has unsafe flags set: %m");
×
978

UNCOV
979
        _cleanup_free_ char *parent_path = NULL;
×
980
        (void) fd_get_path(parent_fd, &parent_path);
×
981

UNCOV
982
        _cleanup_free_ char *new_path = parent_path ? path_join(parent_path, p.name) : NULL;
×
983
        log_debug("Asked to make directory: %s", strna(new_path));
×
984

UNCOV
985
        const char *polkit_details[] = {
×
UNCOV
986
                "directory", strna(new_path),
×
987
                NULL,
988
        };
989

990
        const char *polkit_action;
×
UNCOV
991
        PolkitFlags polkit_flags;
×
UNCOV
992
        if (parent_stat.st_uid != peer_uid) {
×
993
                polkit_action = "io.systemd.mount-file-system.make-directory-untrusted";
994
                polkit_flags = 0;
995
        } else {
UNCOV
996
                polkit_action = "io.systemd.mount-file-system.make-directory";
×
UNCOV
997
                polkit_flags = POLKIT_DEFAULT_ALLOW;
×
998
        }
999

UNCOV
1000
        r = varlink_verify_polkit_async_full(
×
1001
                        link,
1002
                        /* bus= */ NULL,
1003
                        polkit_action,
1004
                        polkit_details,
1005
                        /* good_user= */ UID_INVALID,
1006
                        polkit_flags,
1007
                        polkit_registry);
UNCOV
1008
        if (r <= 0)
×
1009
                return r;
1010

1011
        _cleanup_free_ char *t = NULL;
×
UNCOV
1012
        r = tempfn_random(p.name, "mountfsd", &t);
×
UNCOV
1013
        if (r < 0)
×
1014
                return r;
1015

UNCOV
1016
        _cleanup_close_ int fd = open_mkdir_at(parent_fd, t, O_CLOEXEC, 0700);
×
UNCOV
1017
        if (fd < 0)
×
1018
                return fd;
1019

1020
        r = RET_NERRNO(fchmod(fd, 0700)); /* Set mode explicitly, as paranoia regarding umask games */
×
UNCOV
1021
        if (r < 0)
×
1022
                goto fail;
×
1023

1024
        r = RET_NERRNO(fchown(fd, FOREIGN_UID_BASE, FOREIGN_UID_BASE));
×
UNCOV
1025
        if (r < 0)
×
1026
                goto fail;
×
1027

1028
        r = rename_noreplace(parent_fd, t, parent_fd, p.name);
×
UNCOV
1029
        if (r < 0)
×
1030
                goto fail;
×
1031

1032
        t = mfree(t); /* temporary filename no longer exists */
×
1033

1034
        int fd_idx = sd_varlink_push_fd(link, fd);
×
1035
        if (fd_idx < 0) {
×
UNCOV
1036
                r = fd_idx;
×
UNCOV
1037
                goto fail;
×
1038
        }
1039

1040
        TAKE_FD(fd);
×
1041

UNCOV
1042
        return sd_varlink_replybo(
×
1043
                        link,
1044
                        SD_JSON_BUILD_PAIR("directoryFileDescriptor", SD_JSON_BUILD_INTEGER(fd_idx)));
1045

1046
fail:
×
UNCOV
1047
        (void) unlinkat(parent_fd, t ?: p.name, AT_REMOVEDIR);
×
UNCOV
1048
        return r;
×
1049
}
1050

1051
static int process_connection(sd_varlink_server *server, int _fd) {
×
1052
        _cleanup_close_ int fd = TAKE_FD(_fd); /* always take possession */
×
1053
        _cleanup_(sd_varlink_close_unrefp) sd_varlink *vl = NULL;
×
UNCOV
1054
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1055
        int r;
×
1056

UNCOV
1057
        r = sd_event_new(&event);
×
UNCOV
1058
        if (r < 0)
×
1059
                return r;
1060

1061
        r = sd_varlink_server_attach_event(server, event, 0);
×
UNCOV
1062
        if (r < 0)
×
1063
                return log_error_errno(r, "Failed to attach Varlink server to event loop: %m");
×
1064

1065
        r = sd_varlink_server_add_connection(server, fd, &vl);
×
UNCOV
1066
        if (r < 0)
×
1067
                return log_error_errno(r, "Failed to add connection: %m");
×
1068

UNCOV
1069
        TAKE_FD(fd);
×
1070
        vl = sd_varlink_ref(vl);
×
1071

1072
        r = sd_event_loop(event);
×
UNCOV
1073
        if (r < 0)
×
1074
                return log_error_errno(r, "Failed to run event loop: %m");
×
1075

1076
        r = sd_varlink_server_detach_event(server);
×
UNCOV
1077
        if (r < 0)
×
UNCOV
1078
                return log_error_errno(r, "Failed to detach Varlink server from event loop: %m");
×
1079

1080
        return 0;
1081
}
1082

1083
static int run(int argc, char *argv[]) {
×
1084
        usec_t start_time, listen_idle_usec, last_busy_usec = USEC_INFINITY;
×
1085
        _cleanup_(sd_varlink_server_unrefp) sd_varlink_server *server = NULL;
×
1086
        _cleanup_hashmap_free_ Hashmap *polkit_registry = NULL;
×
1087
        _cleanup_(pidref_done) PidRef parent = PIDREF_NULL;
×
UNCOV
1088
        unsigned n_iterations = 0;
×
1089
        int m, listen_fd, r;
×
1090

1091
        log_setup();
×
1092

1093
        m = sd_listen_fds(false);
×
1094
        if (m < 0)
×
1095
                return log_error_errno(m, "Failed to determine number of listening fds: %m");
×
1096
        if (m == 0)
×
1097
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No socket to listen on received.");
×
UNCOV
1098
        if (m > 1)
×
1099
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Worker can only listen on a single socket at a time.");
×
1100

1101
        listen_fd = SD_LISTEN_FDS_START;
×
1102

1103
        r = fd_nonblock(listen_fd, false);
×
UNCOV
1104
        if (r < 0)
×
1105
                return log_error_errno(r, "Failed to turn off non-blocking mode for listening socket: %m");
×
1106

UNCOV
1107
        r = varlink_server_new(&server,
×
1108
                               SD_VARLINK_SERVER_INHERIT_USERDATA|
1109
                               SD_VARLINK_SERVER_ALLOW_FD_PASSING_INPUT|SD_VARLINK_SERVER_ALLOW_FD_PASSING_OUTPUT,
1110
                               &polkit_registry);
UNCOV
1111
        if (r < 0)
×
1112
                return log_error_errno(r, "Failed to allocate server: %m");
×
1113

1114
        r = sd_varlink_server_add_interface(server, &vl_interface_io_systemd_MountFileSystem);
×
UNCOV
1115
        if (r < 0)
×
1116
                return log_error_errno(r, "Failed to add MountFileSystem interface to varlink server: %m");
×
1117

UNCOV
1118
        r = sd_varlink_server_bind_method_many(
×
1119
                        server,
1120
                        "io.systemd.MountFileSystem.MountImage",     vl_method_mount_image,
1121
                        "io.systemd.MountFileSystem.MountDirectory", vl_method_mount_directory,
1122
                        "io.systemd.MountFileSystem.MakeDirectory",  vl_method_make_directory);
UNCOV
1123
        if (r < 0)
×
1124
                return log_error_errno(r, "Failed to bind methods: %m");
×
1125

1126
        r = sd_varlink_server_set_exit_on_idle(server, true);
×
UNCOV
1127
        if (r < 0)
×
1128
                return log_error_errno(r, "Failed to enable exit-on-idle mode: %m");
×
1129

1130
        r = getenv_bool("MOUNTFS_FIXED_WORKER");
×
1131
        if (r < 0)
×
UNCOV
1132
                return log_error_errno(r, "Failed to parse MOUNTFSD_FIXED_WORKER: %m");
×
1133
        listen_idle_usec = r ? USEC_INFINITY : LISTEN_IDLE_USEC;
×
1134

1135
        r = pidref_set_parent(&parent);
×
UNCOV
1136
        if (r < 0)
×
1137
                return log_error_errno(r, "Failed to acquire pidfd of parent process: %m");
×
1138

1139
        start_time = now(CLOCK_MONOTONIC);
×
1140

1141
        for (;;) {
×
UNCOV
1142
                _cleanup_close_ int fd = -EBADF;
×
UNCOV
1143
                usec_t n;
×
1144

1145
                /* Exit the worker in regular intervals, to flush out all memory use */
UNCOV
1146
                if (n_iterations++ > ITERATIONS_MAX) {
×
UNCOV
1147
                        log_debug("Exiting worker, processed %u iterations, that's enough.", n_iterations);
×
1148
                        break;
1149
                }
1150

1151
                n = now(CLOCK_MONOTONIC);
×
UNCOV
1152
                if (n >= usec_add(start_time, RUNTIME_MAX_USEC)) {
×
1153
                        log_debug("Exiting worker, ran for %s, that's enough.",
×
1154
                                  FORMAT_TIMESPAN(usec_sub_unsigned(n, start_time), 0));
UNCOV
1155
                        break;
×
1156
                }
1157

1158
                if (last_busy_usec == USEC_INFINITY)
×
1159
                        last_busy_usec = n;
UNCOV
1160
                else if (listen_idle_usec != USEC_INFINITY && n >= usec_add(last_busy_usec, listen_idle_usec)) {
×
1161
                        log_debug("Exiting worker, been idle for %s.",
×
1162
                                  FORMAT_TIMESPAN(usec_sub_unsigned(n, last_busy_usec), 0));
UNCOV
1163
                        break;
×
1164
                }
1165

1166
                (void) rename_process("systemd-mountwork: waiting...");
×
UNCOV
1167
                fd = RET_NERRNO(accept4(listen_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC));
×
1168
                (void) rename_process("systemd-mountwork: processing...");
×
1169

UNCOV
1170
                if (fd == -EAGAIN)
×
1171
                        continue; /* The listening socket has SO_RECVTIMEO set, hence a timeout is expected
×
1172
                                   * after a while, let's check if it's time to exit though. */
UNCOV
1173
                if (fd == -EINTR)
×
1174
                        continue; /* Might be that somebody attached via strace, let's just continue in that
×
1175
                                   * case */
UNCOV
1176
                if (fd < 0)
×
1177
                        return log_error_errno(fd, "Failed to accept() from listening socket: %m");
×
1178

UNCOV
1179
                if (now(CLOCK_MONOTONIC) <= usec_add(n, PRESSURE_SLEEP_TIME_USEC)) {
×
1180
                        /* We only slept a very short time? If so, let's see if there are more sockets
1181
                         * pending, and if so, let's ask our parent for more workers */
1182

1183
                        r = fd_wait_for_event(listen_fd, POLLIN, 0);
×
UNCOV
1184
                        if (r < 0)
×
1185
                                return log_error_errno(r, "Failed to test for POLLIN on listening socket: %m");
×
1186

1187
                        if (FLAGS_SET(r, POLLIN)) {
×
1188
                                r = pidref_kill(&parent, SIGUSR2);
×
1189
                                if (r == -ESRCH)
×
1190
                                        return log_error_errno(r, "Parent already died?");
×
UNCOV
1191
                                if (r < 0)
×
UNCOV
1192
                                        return log_error_errno(r, "Failed to send SIGUSR2 signal to parent: %m");
×
1193
                        }
1194
                }
1195

UNCOV
1196
                (void) process_connection(server, TAKE_FD(fd));
×
UNCOV
1197
                last_busy_usec = USEC_INFINITY;
×
1198
        }
1199

1200
        return 0;
1201
}
1202

UNCOV
1203
DEFINE_MAIN_FUNCTION(run);
×
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