summaryrefslogtreecommitdiffstats
path: root/src/nspawn/nspawn-mount.c
blob: a9af889747b838e730c3b2c4f1526debf02d2c5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
/* SPDX-License-Identifier: LGPL-2.1+ */

#include <sys/mount.h>
#include <linux/magic.h>

#include "alloc-util.h"
#include "escape.h"
#include "fd-util.h"
#include "fs-util.h"
#include "label.h"
#include "mkdir.h"
#include "mount-util.h"
#include "mountpoint-util.h"
#include "nspawn-mount.h"
#include "parse-util.h"
#include "path-util.h"
#include "rm-rf.h"
#include "set.h"
#include "stat-util.h"
#include "string-util.h"
#include "strv.h"
#include "tmpfile-util.h"
#include "user-util.h"
#include "util.h"

CustomMount* custom_mount_add(CustomMount **l, size_t *n, CustomMountType t) {
        CustomMount *c, *ret;

        assert(l);
        assert(n);
        assert(t >= 0);
        assert(t < _CUSTOM_MOUNT_TYPE_MAX);

        c = reallocarray(*l, *n + 1, sizeof(CustomMount));
        if (!c)
                return NULL;

        *l = c;
        ret = *l + *n;
        (*n)++;

        *ret = (CustomMount) { .type = t };

        return ret;
}

void custom_mount_free_all(CustomMount *l, size_t n) {
        size_t i;

        for (i = 0; i < n; i++) {
                CustomMount *m = l + i;

                free(m->source);
                free(m->destination);
                free(m->options);

                if (m->work_dir) {
                        (void) rm_rf(m->work_dir, REMOVE_ROOT|REMOVE_PHYSICAL);
                        free(m->work_dir);
                }

                if (m->rm_rf_tmpdir) {
                        (void) rm_rf(m->rm_rf_tmpdir, REMOVE_ROOT|REMOVE_PHYSICAL);
                        free(m->rm_rf_tmpdir);
                }

                strv_free(m->lower);
        }

        free(l);
}

static int custom_mount_compare(const CustomMount *a, const CustomMount *b) {
        int r;

        r = path_compare(a->destination, b->destination);
        if (r != 0)
                return r;

        return CMP(a->type, b->type);
}

static bool source_path_is_valid(const char *p) {
        assert(p);

        if (*p == '+')
                p++;

        return path_is_absolute(p);
}

static char *resolve_source_path(const char *dest, const char *source) {

        if (!source)
                return NULL;

        if (source[0] == '+')
                return prefix_root(dest, source + 1);

        return strdup(source);
}

int custom_mount_prepare_all(const char *dest, CustomMount *l, size_t n) {
        size_t i;
        int r;

        /* Prepare all custom mounts. This will make source we know all temporary directories. This is called in the
         * parent process, so that we know the temporary directories to remove on exit before we fork off the
         * children. */

        assert(l || n == 0);

        /* Order the custom mounts, and make sure we have a working directory */
        typesafe_qsort(l, n, custom_mount_compare);

        for (i = 0; i < n; i++) {
                CustomMount *m = l + i;

                if (m->source) {
                        char *s;

                        s = resolve_source_path(dest, m->source);
                        if (!s)
                                return log_oom();

                        free_and_replace(m->source, s);
                } else {
                        /* No source specified? In that case, use a throw-away temporary directory in /var/tmp */

                        m->rm_rf_tmpdir = strdup("/var/tmp/nspawn-temp-XXXXXX");
                        if (!m->rm_rf_tmpdir)
                                return log_oom();

                        if (!mkdtemp(m->rm_rf_tmpdir)) {
                                m->rm_rf_tmpdir = mfree(m->rm_rf_tmpdir);
                                return log_error_errno(errno, "Failed to acquire temporary directory: %m");
                        }

                        m->source = strjoin(m->rm_rf_tmpdir, "/src");
                        if (!m->source)
                                return log_oom();

                        if (mkdir(m->source, 0755) < 0)
                                return log_error_errno(errno, "Failed to create %s: %m", m->source);
                }

                if (m->type == CUSTOM_MOUNT_OVERLAY) {
                        char **j;

                        STRV_FOREACH(j, m->lower) {
                                char *s;

                                s = resolve_source_path(dest, *j);
                                if (!s)
                                        return log_oom();

                                free_and_replace(*j, s);
                        }

                        if (m->work_dir) {
                                char *s;

                                s = resolve_source_path(dest, m->work_dir);
                                if (!s)
                                        return log_oom();

                                free_and_replace(m->work_dir, s);
                        } else {
                                assert(m->source);

                                r = tempfn_random(m->source, NULL, &m->work_dir);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to acquire working directory: %m");
                        }

                        (void) mkdir_label(m->work_dir, 0700);
                }
        }

        return 0;
}

int bind_mount_parse(CustomMount **l, size_t *n, const char *s, bool read_only) {
        _cleanup_free_ char *source = NULL, *destination = NULL, *opts = NULL;
        const char *p = s;
        CustomMount *m;
        int r;

        assert(l);
        assert(n);

        r = extract_many_words(&p, ":", EXTRACT_DONT_COALESCE_SEPARATORS, &source, &destination, NULL);
        if (r < 0)
                return r;
        if (r == 0)
                return -EINVAL;
        if (r == 1) {
                destination = strdup(source[0] == '+' ? source+1 : source);
                if (!destination)
                        return -ENOMEM;
        }
        if (r == 2 && !isempty(p)) {
                opts = strdup(p);
                if (!opts)
                        return -ENOMEM;
        }

        if (isempty(source))
                source = NULL;
        else if (!source_path_is_valid(source))
                return -EINVAL;

        if (!path_is_absolute(destination))
                return -EINVAL;

        m = custom_mount_add(l, n, CUSTOM_MOUNT_BIND);
        if (!m)
                return -ENOMEM;

        m->source = source;
        m->destination = destination;
        m->read_only = read_only;
        m->options = opts;

        source = destination = opts = NULL;
        return 0;
}

int tmpfs_mount_parse(CustomMount **l, size_t *n, const char *s) {
        _cleanup_free_ char *path = NULL, *opts = NULL;
        const char *p = s;
        CustomMount *m;
        int r;

        assert(l);
        assert(n);
        assert(s);

        r = extract_first_word(&p, &path, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
        if (r < 0)
                return r;
        if (r == 0)
                return -EINVAL;

        if (isempty(p))
                opts = strdup("mode=0755");
        else
                opts = strdup(p);
        if (!opts)
                return -ENOMEM;

        if (!path_is_absolute(path))
                return -EINVAL;

        m = custom_mount_add(l, n, CUSTOM_MOUNT_TMPFS);
        if (!m)
                return -ENOMEM;

        m->destination = TAKE_PTR(path);
        m->options = TAKE_PTR(opts);

        return 0;
}

int overlay_mount_parse(CustomMount **l, size_t *n, const char *s, bool read_only) {
        _cleanup_free_ char *upper = NULL, *destination = NULL;
        _cleanup_strv_free_ char **lower = NULL;
        CustomMount *m;
        int k;

        k = strv_split_extract(&lower, s, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
        if (k < 0)
                return k;
        if (k < 2)
                return -EADDRNOTAVAIL;
        if (k == 2) {
                /* If two parameters are specified, the first one is the lower, the second one the upper directory. And
                 * we'll also define the destination mount point the same as the upper. */

                if (!source_path_is_valid(lower[0]) ||
                    !source_path_is_valid(lower[1]))
                        return -EINVAL;

                upper = TAKE_PTR(lower[1]);

                destination = strdup(upper[0] == '+' ? upper+1 : upper); /* take the destination without "+" prefix */
                if (!destination)
                        return -ENOMEM;
        } else {
                char **i;

                /* If more than two parameters are specified, the last one is the destination, the second to last one
                 * the "upper", and all before that the "lower" directories. */

                destination = lower[k - 1];
                upper = TAKE_PTR(lower[k - 2]);

                STRV_FOREACH(i, lower)
                        if (!source_path_is_valid(*i))
                                return -EINVAL;

                /* If the upper directory is unspecified, then let's create it automatically as a throw-away directory
                 * in /var/tmp */
                if (isempty(upper))
                        upper = NULL;
                else if (!source_path_is_valid(upper))
                        return -EINVAL;

                if (!path_is_absolute(destination))
                        return -EINVAL;
        }

        m = custom_mount_add(l, n, CUSTOM_MOUNT_OVERLAY);
        if (!m)
                return -ENOMEM;

        m->destination = TAKE_PTR(destination);
        m->source = TAKE_PTR(upper);
        m->lower = TAKE_PTR(lower);
        m->read_only = read_only;

        return 0;
}

int tmpfs_patch_options(
                const char *options,
                uid_t uid_shift,
                const char *selinux_apifs_context,
                char **ret) {

        char *buf = NULL;

        if (uid_shift != UID_INVALID) {
                if (asprintf(&buf, "%s%suid=" UID_FMT ",gid=" UID_FMT,
                             strempty(options), options ? "," : "",
                             uid_shift, uid_shift) < 0)
                        return -ENOMEM;

                options = buf;
        }

#if HAVE_SELINUX
        if (selinux_apifs_context) {
                char *t;

                t = strjoin(strempty(options), options ? "," : "",
                            "context=\"", selinux_apifs_context, "\"");
                free(buf);
                if (!t)
                        return -ENOMEM;

                buf = t;
        }
#endif

        if (!buf && options) {
                buf = strdup(options);
                if (!buf)
                        return -ENOMEM;
        }
        *ret = buf;

        return !!buf;
}

int mount_sysfs(const char *dest, MountSettingsMask mount_settings) {
        const char *full, *top, *x;
        int r;
        unsigned long extra_flags = 0;

        top = prefix_roota(dest, "/sys");
        r = path_is_fs_type(top, SYSFS_MAGIC);
        if (r < 0)
                return log_error_errno(r, "Failed to determine filesystem type of %s: %m", top);
        /* /sys might already be mounted as sysfs by the outer child in the
         * !netns case. In this case, it's all good. Don't touch it because we
         * don't have the right to do so, see https://github.com/systemd/systemd/issues/1555.
         */
        if (r > 0)
                return 0;

        full = prefix_roota(top, "/full");

        (void) mkdir(full, 0755);

        if (mount_settings & MOUNT_APPLY_APIVFS_RO)
                extra_flags |= MS_RDONLY;

        r = mount_verbose(LOG_ERR, "sysfs", full, "sysfs",
                          MS_NOSUID|MS_NOEXEC|MS_NODEV|extra_flags, NULL);
        if (r < 0)
                return r;

        FOREACH_STRING(x, "block", "bus", "class", "dev", "devices", "kernel") {
                _cleanup_free_ char *from = NULL, *to = NULL;

                from = prefix_root(full, x);
                if (!from)
                        return log_oom();

                to = prefix_root(top, x);
                if (!to)
                        return log_oom();

                (void) mkdir(to, 0755);

                r = mount_verbose(LOG_ERR, from, to, NULL, MS_BIND, NULL);
                if (r < 0)
                        return r;

                r = mount_verbose(LOG_ERR, NULL, to, NULL,
                                  MS_BIND|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT|extra_flags, NULL);
                if (r < 0)
                        return r;
        }

        r = umount_verbose(full);
        if (r < 0)
                return r;

        if (rmdir(full) < 0)
                return log_error_errno(errno, "Failed to remove %s: %m", full);

        /* Create mountpoint for cgroups. Otherwise we are not allowed since we
         * remount /sys read-only.
         */
        x = prefix_roota(top, "/fs/cgroup");
        (void) mkdir_p(x, 0755);

        return mount_verbose(LOG_ERR, NULL, top, NULL,
                             MS_BIND|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT|extra_flags, NULL);
}

static int mkdir_userns(const char *path, mode_t mode, uid_t uid_shift) {
        int r;

        assert(path);

        r = mkdir_errno_wrapper(path, mode);
        if (r < 0 && r != -EEXIST)
                return r;

        if (uid_shift == UID_INVALID)
                return 0;

        if (lchown(path, uid_shift, uid_shift) < 0)
                return -errno;

        return 0;
}

static int mkdir_userns_p(const char *prefix, const char *path, mode_t mode, uid_t uid_shift) {
        const char *p, *e;
        int r;

        assert(path);

        if (prefix && !path_startswith(path, prefix))
                return -ENOTDIR;

        /* create every parent directory in the path, except the last component */
        p = path + strspn(path, "/");
        for (;;) {
                char t[strlen(path) + 1];

                e = p + strcspn(p, "/");
                p = e + strspn(e, "/");

                /* Is this the last component? If so, then we're done */
                if (*p == 0)
                        break;

                memcpy(t, path, e - path);
                t[e-path] = 0;

                if (prefix && path_startswith(prefix, t))
                        continue;

                r = mkdir_userns(t, mode, uid_shift);
                if (r < 0)
                        return r;
        }

        return mkdir_userns(path, mode, uid_shift);
}

int mount_all(const char *dest,
              MountSettingsMask mount_settings,
              uid_t uid_shift,
              const char *selinux_apifs_context) {

#define PROC_INACCESSIBLE(path)                                         \
        { NULL, (path), NULL, NULL, MS_BIND,                            \
          MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO|MOUNT_INACCESSIBLE_REG }, /* Bind mount first ... */ \
        { NULL, (path), NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, \
          MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO } /* Then, make it r/o */

#define PROC_READ_ONLY(path)                                            \
        { (path), (path), NULL, NULL, MS_BIND,                          \
          MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* Bind mount first ... */ \
        { NULL,   (path), NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, \
          MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO } /* Then, make it r/o */

        typedef struct MountPoint {
                const char *what;
                const char *where;
                const char *type;
                const char *options;
                unsigned long flags;
                MountSettingsMask mount_settings;
        } MountPoint;

        static const MountPoint mount_table[] = {
                /* First we list inner child mounts (i.e. mounts applied *after* entering user namespacing) */
                { "proc",            "/proc",           "proc",  NULL,        MS_NOSUID|MS_NOEXEC|MS_NODEV,
                  MOUNT_FATAL|MOUNT_IN_USERNS },

                { "/proc/sys",       "/proc/sys",       NULL,    NULL,        MS_BIND,
                  MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO },                          /* Bind mount first ... */

                { "/proc/sys/net",   "/proc/sys/net",   NULL,    NULL,        MS_BIND,
                  MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO|MOUNT_APPLY_APIVFS_NETNS }, /* (except for this) */

                { NULL,              "/proc/sys",       NULL,    NULL,        MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT,
                  MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO },                          /* ... then, make it r/o */

                /* Make these files inaccessible to container payloads: they potentially leak information about kernel
                 * internals or the host's execution environment to the container */
                PROC_INACCESSIBLE("/proc/kallsyms"),
                PROC_INACCESSIBLE("/proc/kcore"),
                PROC_INACCESSIBLE("/proc/keys"),
                PROC_INACCESSIBLE("/proc/sysrq-trigger"),
                PROC_INACCESSIBLE("/proc/timer_list"),

                /* Make these directories read-only to container payloads: they show hardware information, and in some
                 * cases contain tunables the container really shouldn't have access to. */
                PROC_READ_ONLY("/proc/acpi"),
                PROC_READ_ONLY("/proc/apm"),
                PROC_READ_ONLY("/proc/asound"),
                PROC_READ_ONLY("/proc/bus"),
                PROC_READ_ONLY("/proc/fs"),
                PROC_READ_ONLY("/proc/irq"),
                PROC_READ_ONLY("/proc/scsi"),

                /* Then we list outer child mounts (i.e. mounts applied *before* entering user namespacing) */
                { "tmpfs",           "/tmp",            "tmpfs", "mode=1777", MS_NOSUID|MS_NODEV|MS_STRICTATIME,
                  MOUNT_FATAL|MOUNT_APPLY_TMPFS_TMP },
                { "tmpfs",           "/sys",            "tmpfs", "mode=555",  MS_NOSUID|MS_NOEXEC|MS_NODEV,
                  MOUNT_FATAL|MOUNT_APPLY_APIVFS_NETNS },
                { "sysfs",           "/sys",            "sysfs", NULL,        MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV,
                  MOUNT_FATAL|MOUNT_APPLY_APIVFS_RO },    /* skipped if above was mounted */
                { "sysfs",           "/sys",            "sysfs", NULL,        MS_NOSUID|MS_NOEXEC|MS_NODEV,
                  MOUNT_FATAL },                          /* skipped if above was mounted */
                { "tmpfs",           "/dev",            "tmpfs", "mode=755",  MS_NOSUID|MS_STRICTATIME,
                  MOUNT_FATAL },
                { "tmpfs",           "/dev/shm",        "tmpfs", "mode=1777", MS_NOSUID|MS_NODEV|MS_STRICTATIME,
                  MOUNT_FATAL },
                { "tmpfs",           "/run",            "tmpfs", "mode=755",  MS_NOSUID|MS_NODEV|MS_STRICTATIME,
                  MOUNT_FATAL },
                { "mqueue",          "/dev/mqueue",     "mqueue", NULL,       0,
                  MOUNT_FATAL },

#if HAVE_SELINUX
                { "/sys/fs/selinux", "/sys/fs/selinux", NULL,    NULL,        MS_BIND,
                  0 },  /* Bind mount first */
                { NULL,              "/sys/fs/selinux", NULL,    NULL,        MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT,
                  0 },  /* Then, make it r/o */
#endif
        };

        _cleanup_(unlink_and_freep) char *inaccessible = NULL;
        bool use_userns = (mount_settings & MOUNT_USE_USERNS);
        bool netns = (mount_settings & MOUNT_APPLY_APIVFS_NETNS);
        bool ro = (mount_settings & MOUNT_APPLY_APIVFS_RO);
        bool in_userns = (mount_settings & MOUNT_IN_USERNS);
        bool tmpfs_tmp = (mount_settings & MOUNT_APPLY_TMPFS_TMP);
        size_t k;
        int r;

        for (k = 0; k < ELEMENTSOF(mount_table); k++) {
                _cleanup_free_ char *where = NULL, *options = NULL;
                const char *o, *what;
                bool fatal = (mount_table[k].mount_settings & MOUNT_FATAL);

                if (in_userns != (bool)(mount_table[k].mount_settings & MOUNT_IN_USERNS))
                        continue;

                if (!netns && (bool)(mount_table[k].mount_settings & MOUNT_APPLY_APIVFS_NETNS))
                        continue;

                if (!ro && (bool)(mount_table[k].mount_settings & MOUNT_APPLY_APIVFS_RO))
                        continue;

                if (!tmpfs_tmp && (bool)(mount_table[k].mount_settings & MOUNT_APPLY_TMPFS_TMP))
                        continue;

                r = chase_symlinks(mount_table[k].where, dest, CHASE_NONEXISTENT|CHASE_PREFIX_ROOT, &where);
                if (r < 0)
                        return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, mount_table[k].where);

                if (mount_table[k].mount_settings & MOUNT_INACCESSIBLE_REG) {

                        if (!inaccessible) {
                                _cleanup_free_ char *np = NULL;

                                r = tempfn_random_child(NULL, "inaccessible", &np);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to generate inaccessible file node path: %m");

                                r = touch_file(np, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0000);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to create inaccessible file node '%s': %m", np);

                                inaccessible = TAKE_PTR(np);
                        }

                        what = inaccessible;
                } else
                        what = mount_table[k].what;

                r = path_is_mount_point(where, NULL, 0);
                if (r < 0 && r != -ENOENT)
                        return log_error_errno(r, "Failed to detect whether %s is a mount point: %m", where);

                /* Skip this entry if it is not a remount. */
                if (what && r > 0)
                        continue;

                r = mkdir_userns_p(dest, where, 0755, (use_userns && !in_userns) ? uid_shift : UID_INVALID);
                if (r < 0 && r != -EEXIST) {
                        if (fatal && r != -EROFS)
                                return log_error_errno(r, "Failed to create directory %s: %m", where);

                        log_debug_errno(r, "Failed to create directory %s: %m", where);
                        /* If we failed mkdir() or chown() due to the root
                         * directory being read only, attempt to mount this fs
                         * anyway and let mount_verbose log any errors */
                        if (r != -EROFS)
                                continue;
                }

                o = mount_table[k].options;
                if (streq_ptr(mount_table[k].type, "tmpfs")) {
                        r = tmpfs_patch_options(o, in_userns ? 0 : uid_shift, selinux_apifs_context, &options);
                        if (r < 0)
                                return log_oom();
                        if (r > 0)
                                o = options;
                }

                r = mount_verbose(fatal ? LOG_ERR : LOG_DEBUG,
                                  what,
                                  where,
                                  mount_table[k].type,
                                  mount_table[k].flags,
                                  o);
                if (r < 0 && fatal)
                        return r;
        }

        return 0;
}

static int mount_bind(const char *dest, CustomMount *m) {

        _cleanup_free_ char *where = NULL;
        struct stat source_st, dest_st;
        int r;

        assert(dest);
        assert(m);

        if (stat(m->source, &source_st) < 0)
                return log_error_errno(errno, "Failed to stat %s: %m", m->source);

        r = chase_symlinks(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where);
        if (r < 0)
                return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
        if (r > 0) { /* Path exists already? */

                if (stat(where, &dest_st) < 0)
                        return log_error_errno(errno, "Failed to stat %s: %m", where);

                if (S_ISDIR(source_st.st_mode) && !S_ISDIR(dest_st.st_mode))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Cannot bind mount directory %s on file %s.",
                                               m->source, where);

                if (!S_ISDIR(source_st.st_mode) && S_ISDIR(dest_st.st_mode))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Cannot bind mount file %s on directory %s.",
                                               m->source, where);

        } else { /* Path doesn't exist yet? */
                r = mkdir_parents_label(where, 0755);
                if (r < 0)
                        return log_error_errno(r, "Failed to make parents of %s: %m", where);

                /* Create the mount point. Any non-directory file can be
                * mounted on any non-directory file (regular, fifo, socket,
                * char, block).
                */
                if (S_ISDIR(source_st.st_mode))
                        r = mkdir_label(where, 0755);
                else
                        r = touch(where);
                if (r < 0)
                        return log_error_errno(r, "Failed to create mount point %s: %m", where);

        }

        r = mount_verbose(LOG_ERR, m->source, where, NULL, MS_BIND | MS_REC, m->options);
        if (r < 0)
                return r;

        if (m->read_only) {
                r = bind_remount_recursive(where, true, NULL);
                if (r < 0)
                        return log_error_errno(r, "Read-only bind mount failed: %m");
        }

        return 0;
}

static int mount_tmpfs(
                const char *dest,
                CustomMount *m,
                bool userns, uid_t uid_shift, uid_t uid_range,
                const char *selinux_apifs_context) {

        const char *options;
        _cleanup_free_ char *buf = NULL, *where = NULL;
        int r;

        assert(dest);
        assert(m);

        r = chase_symlinks(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where);
        if (r < 0)
                return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
        if (r == 0) { /* Doesn't exist yet? */
                r = mkdir_p_label(where, 0755);
                if (r < 0)
                        return log_error_errno(r, "Creating mount point for tmpfs %s failed: %m", where);
        }

        r = tmpfs_patch_options(m->options, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &buf);
        if (r < 0)
                return log_oom();
        options = r > 0 ? buf : m->options;

        return mount_verbose(LOG_ERR, "tmpfs", where, "tmpfs", MS_NODEV|MS_STRICTATIME, options);
}

static char *joined_and_escaped_lower_dirs(char **lower) {
        _cleanup_strv_free_ char **sv = NULL;

        sv = strv_copy(lower);
        if (!sv)
                return NULL;

        strv_reverse(sv);

        if (!strv_shell_escape(sv, ",:"))
                return NULL;

        return strv_join(sv, ":");
}

static int mount_overlay(const char *dest, CustomMount *m) {

        _cleanup_free_ char *lower = NULL, *where = NULL, *escaped_source = NULL;
        const char *options;
        int r;

        assert(dest);
        assert(m);

        r = chase_symlinks(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where);
        if (r < 0)
                return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
        if (r == 0) { /* Doesn't exist yet? */
                r = mkdir_label(where, 0755);
                if (r < 0)
                        return log_error_errno(r, "Creating mount point for overlay %s failed: %m", where);
        }

        (void) mkdir_p_label(m->source, 0755);

        lower = joined_and_escaped_lower_dirs(m->lower);
        if (!lower)
                return log_oom();

        escaped_source = shell_escape(m->source, ",:");
        if (!escaped_source)
                return log_oom();

        if (m->read_only)
                options = strjoina("lowerdir=", escaped_source, ":", lower);
        else {
                _cleanup_free_ char *escaped_work_dir = NULL;

                escaped_work_dir = shell_escape(m->work_dir, ",:");
                if (!escaped_work_dir)
                        return log_oom();

                options = strjoina("lowerdir=", lower, ",upperdir=", escaped_source, ",workdir=", escaped_work_dir);
        }

        return mount_verbose(LOG_ERR, "overlay", where, "overlay", m->read_only ? MS_RDONLY : 0, options);
}

int mount_custom(
                const char *dest,
                CustomMount *mounts, size_t n,
                bool userns, uid_t uid_shift, uid_t uid_range,
                const char *selinux_apifs_context) {

        size_t i;
        int r;

        assert(dest);

        for (i = 0; i < n; i++) {
                CustomMount *m = mounts + i;

                switch (m->type) {

                case CUSTOM_MOUNT_BIND:
                        r = mount_bind(dest, m);
                        break;

                case CUSTOM_MOUNT_TMPFS:
                        r = mount_tmpfs(dest, m, userns, uid_shift, uid_range, selinux_apifs_context);
                        break;

                case CUSTOM_MOUNT_OVERLAY:
                        r = mount_overlay(dest, m);
                        break;

                default:
                        assert_not_reached("Unknown custom mount type");
                }

                if (r < 0)
                        return r;
        }

        return 0;
}

int setup_volatile_state(
                const char *directory,
                VolatileMode mode,
                bool userns, uid_t uid_shift, uid_t uid_range,
                const char *selinux_apifs_context) {

        _cleanup_free_ char *buf = NULL;
        const char *p, *options;
        int r;

        assert(directory);

        if (mode != VOLATILE_STATE)
                return 0;

        /* --volatile=state means we simply overmount /var
           with a tmpfs, and the rest read-only. */

        r = bind_remount_recursive(directory, true, NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to remount %s read-only: %m", directory);

        p = prefix_roota(directory, "/var");
        r = mkdir(p, 0755);
        if (r < 0 && errno != EEXIST)
                return log_error_errno(errno, "Failed to create %s: %m", directory);

        options = "mode=755";
        r = tmpfs_patch_options(options, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &buf);
        if (r < 0)
                return log_oom();
        if (r > 0)
                options = buf;

        return mount_verbose(LOG_ERR, "tmpfs", p, "tmpfs", MS_STRICTATIME, options);
}

int setup_volatile(
                const char *directory,
                VolatileMode mode,
                bool userns, uid_t uid_shift, uid_t uid_range,
                const char *selinux_apifs_context) {

        bool tmpfs_mounted = false, bind_mounted = false;
        char template[] = "/tmp/nspawn-volatile-XXXXXX";
        _cleanup_free_ char *buf = NULL;
        const char *f, *t, *options;
        int r;

        assert(directory);

        if (mode != VOLATILE_YES)
                return 0;

        /* --volatile=yes means we mount a tmpfs to the root dir, and
           the original /usr to use inside it, and that read-only. */

        if (!mkdtemp(template))
                return log_error_errno(errno, "Failed to create temporary directory: %m");

        options = "mode=755";
        r = tmpfs_patch_options(options, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &buf);
        if (r < 0)
                return log_oom();
        if (r > 0)
                options = buf;

        r = mount_verbose(LOG_ERR, "tmpfs", template, "tmpfs", MS_STRICTATIME, options);
        if (r < 0)
                goto fail;

        tmpfs_mounted = true;

        f = prefix_roota(directory, "/usr");
        t = prefix_roota(template, "/usr");

        r = mkdir(t, 0755);
        if (r < 0 && errno != EEXIST) {
                r = log_error_errno(errno, "Failed to create %s: %m", t);
                goto fail;
        }

        r = mount_verbose(LOG_ERR, f, t, NULL, MS_BIND|MS_REC, NULL);
        if (r < 0)
                goto fail;

        bind_mounted = true;

        r = bind_remount_recursive(t, true, NULL);
        if (r < 0) {
                log_error_errno(r, "Failed to remount %s read-only: %m", t);
                goto fail;
        }

        r = mount_verbose(LOG_ERR, template, directory, NULL, MS_MOVE, NULL);
        if (r < 0)
                goto fail;

        (void) rmdir(template);

        return 0;

fail:
        if (bind_mounted)
                (void) umount_verbose(t);

        if (tmpfs_mounted)
                (void) umount_verbose(template);
        (void) rmdir(template);
        return r;
}

/* Expects *pivot_root_new and *pivot_root_old to be initialised to allocated memory or NULL. */
int pivot_root_parse(char **pivot_root_new, char **pivot_root_old, const char *s) {
        _cleanup_free_ char *root_new = NULL, *root_old = NULL;
        const char *p = s;
        int r;

        assert(pivot_root_new);
        assert(pivot_root_old);

        r = extract_first_word(&p, &root_new, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
        if (r < 0)
                return r;
        if (r == 0)
                return -EINVAL;

        if (isempty(p))
                root_old = NULL;
        else {
                root_old = strdup(p);
                if (!root_old)
                        return -ENOMEM;
        }

        if (!path_is_absolute(root_new))
                return -EINVAL;
        if (root_old && !path_is_absolute(root_old))
                return -EINVAL;

        free_and_replace(*pivot_root_new, root_new);
        free_and_replace(*pivot_root_old, root_old);

        return 0;
}

int setup_pivot_root(const char *directory, const char *pivot_root_new, const char *pivot_root_old) {
        _cleanup_free_ char *directory_pivot_root_new = NULL;
        _cleanup_free_ char *pivot_tmp_pivot_root_old = NULL;
        char pivot_tmp[] = "/tmp/nspawn-pivot-XXXXXX";
        bool remove_pivot_tmp = false;
        int r;

        assert(directory);

        if (!pivot_root_new)
                return 0;

        /* Pivot pivot_root_new to / and the existing / to pivot_root_old.
         * If pivot_root_old is NULL, the existing / disappears.
         * This requires a temporary directory, pivot_tmp, which is
         * not a child of either.
         *
         * This is typically used for OSTree-style containers, where
         * the root partition contains several sysroots which could be
         * run. Normally, one would be chosen by the bootloader and
         * pivoted to / by initramfs.
         *
         * For example, for an OSTree deployment, pivot_root_new
         * would be: /ostree/deploy/$os/deploy/$checksum. Note that this
         * code doesn’t do the /var mount which OSTree expects: use
         * --bind +/sysroot/ostree/deploy/$os/var:/var for that.
         *
         * So in the OSTree case, we’ll end up with something like:
         *  - directory = /tmp/nspawn-root-123456
         *  - pivot_root_new = /ostree/deploy/os/deploy/123abc
         *  - pivot_root_old = /sysroot
         *  - directory_pivot_root_new =
         *       /tmp/nspawn-root-123456/ostree/deploy/os/deploy/123abc
         *  - pivot_tmp = /tmp/nspawn-pivot-123456
         *  - pivot_tmp_pivot_root_old = /tmp/nspawn-pivot-123456/sysroot
         *
         * Requires all file systems at directory and below to be mounted
         * MS_PRIVATE or MS_SLAVE so they can be moved.
         */
        directory_pivot_root_new = prefix_root(directory, pivot_root_new);

        /* Remount directory_pivot_root_new to make it movable. */
        r = mount_verbose(LOG_ERR, directory_pivot_root_new, directory_pivot_root_new, NULL, MS_BIND, NULL);
        if (r < 0)
                goto done;

        if (pivot_root_old) {
                if (!mkdtemp(pivot_tmp)) {
                        r = log_error_errno(errno, "Failed to create temporary directory: %m");
                        goto done;
                }

                remove_pivot_tmp = true;
                pivot_tmp_pivot_root_old = prefix_root(pivot_tmp, pivot_root_old);

                r = mount_verbose(LOG_ERR, directory_pivot_root_new, pivot_tmp, NULL, MS_MOVE, NULL);
                if (r < 0)
                        goto done;

                r = mount_verbose(LOG_ERR, directory, pivot_tmp_pivot_root_old, NULL, MS_MOVE, NULL);
                if (r < 0)
                        goto done;

                r = mount_verbose(LOG_ERR, pivot_tmp, directory, NULL, MS_MOVE, NULL);
                if (r < 0)
                        goto done;
        } else {
                r = mount_verbose(LOG_ERR, directory_pivot_root_new, directory, NULL, MS_MOVE, NULL);
                if (r < 0)
                        goto done;
        }

done:
        if (remove_pivot_tmp)
                (void) rmdir(pivot_tmp);

        return r;
}