Debian Codegraph @

src/fstab-generator/fstab-generator.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6
7 #include "sd-bus.h"
8
9 #include "alloc-util.h"
10 #include "argv-util.h"
11 #include "bus-error.h"
12 #include "bus-locator.h"
13 #include "bus-unit-util.h"
14 #include "bus-util.h"
15 #include "chase.h"
16 #include "creds-util.h"
17 #include "efi-loader.h"
18 #include "env-util.h"
19 #include "errno-util.h"
20 #include "extract-word.h"
21 #include "fd-util.h"
22 #include "fileio.h"
23 #include "fstab-util.h"
24 #include "generator.h"
25 #include "in-addr-util.h"
26 #include "initrd-util.h"
27 #include "libmount-util.h"
28 #include "log.h"
29 #include "main-func.h"
30 #include "mount-setup.h"
31 #include "mountpoint-util.h"
32 #include "parse-util.h"
33 #include "path-util.h"
34 #include "proc-cmdline.h"
35 #include "special.h"
36 #include "specifier.h"
37 #include "stat-util.h"
38 #include "string-util.h"
39 #include "strv.h"
40 #include "unit-name.h"
41 #include "virt.h"
42 #include "volatile-util.h"
43
44 typedef enum MountPointFlags {
45 MOUNT_NOAUTO = 1 << 0,
46 MOUNT_NOFAIL = 1 << 1,
47 MOUNT_AUTOMOUNT = 1 << 2,
48 MOUNT_MAKEFS = 1 << 3,
49 MOUNT_GROWFS = 1 << 4,
50 MOUNT_RW_ONLY = 1 << 5,
51 MOUNT_PCRFS = 1 << 6,
52 MOUNT_QUOTA = 1 << 7,
53 MOUNT_VALIDATEFS = 1 << 8,
54 } MountPointFlags;
55
56 typedef struct Mount {
57 bool for_initrd;
58 char *what;
59 char *where;
60 char *fstype;
61 char *options;
62 } Mount;
63
64 static void mount_array_free(Mount *mounts, size_t n);
65
66 static bool arg_sysroot_check = false;
67 static const char *arg_dest = NULL;
68 static const char *arg_dest_late = NULL;
69 static bool arg_fstab_enabled = true;
70 static bool arg_swap_enabled = true;
71 static char *arg_root_what = NULL;
72 static char *arg_root_fstype = NULL;
73 static char *arg_root_options = NULL;
74 static char *arg_root_hash = NULL;
75 static int arg_root_rw = -1;
76 static char *arg_usr_what = NULL;
77 static char *arg_usr_fstype = NULL;
78 static char *arg_usr_options = NULL;
79 static char *arg_usr_hash = NULL;
80 static VolatileMode arg_volatile_mode = _VOLATILE_MODE_INVALID;
81 static bool arg_verity = true;
82 static Mount *arg_mounts = NULL;
83 static size_t arg_n_mounts = 0;
84
85 STATIC_DESTRUCTOR_REGISTER(arg_root_what, freep);
86 STATIC_DESTRUCTOR_REGISTER(arg_root_fstype, freep);
87 STATIC_DESTRUCTOR_REGISTER(arg_root_options, freep);
88 STATIC_DESTRUCTOR_REGISTER(arg_root_hash, freep);
89 STATIC_DESTRUCTOR_REGISTER(arg_usr_what, freep);
90 STATIC_DESTRUCTOR_REGISTER(arg_usr_fstype, freep);
91 STATIC_DESTRUCTOR_REGISTER(arg_usr_options, freep);
92 STATIC_DESTRUCTOR_REGISTER(arg_usr_hash, freep);
93 STATIC_ARRAY_DESTRUCTOR_REGISTER(arg_mounts, arg_n_mounts, mount_array_free);
94
95 static void mount_done(Mount *m) {
96 assert(m);
97
98 free(m->what);
99 free(m->where);
100 free(m->fstype);
101 free(m->options);
102 }
103
104 static void mount_array_free(Mount *mounts, size_t n) {
105 FOREACH_ARRAY(m, mounts, n)
106 mount_done(m);
107
108 free(mounts);
109 }
110
111 static int mount_array_add_internal(
112 bool for_initrd,
113 char *in_what,
114 char *in_where,
115 const char *in_fstype,
116 char *in_options) {
117
118 _cleanup_free_ char *what = NULL, *where = NULL, *fstype = NULL, *options = NULL;
119
120 /* This takes what and where. */
121
122 what = ASSERT_PTR(in_what);
123 where = in_where;
124 options = in_options;
125
126 fstype = strdup(isempty(in_fstype) ? "auto" : in_fstype);
127 if (!fstype)
128 return -ENOMEM;
129
130 if (streq(fstype, "swap"))
131 where = mfree(where);
132
133 if (!GREEDY_REALLOC(arg_mounts, arg_n_mounts + 1))
134 return -ENOMEM;
135
136 arg_mounts[arg_n_mounts++] = (Mount) {
137 .for_initrd = for_initrd,
138 .what = TAKE_PTR(what),
139 .where = TAKE_PTR(where),
140 .fstype = TAKE_PTR(fstype),
141 .options = TAKE_PTR(options),
142 };
143
144 return 0;
145 }
146
147 static int mount_array_add(bool for_initrd, const char *str) {
148 _cleanup_free_ char *what = NULL, *where = NULL, *fstype = NULL, *options = NULL;
149 int r;
150
151 assert(str);
152
153 r = extract_many_words(&str, ":", EXTRACT_CUNESCAPE | EXTRACT_DONT_COALESCE_SEPARATORS,
154 &what, &where, &fstype, &options);
155 if (r < 0)
156 return r;
157 if (r < 2)
158 return -EINVAL;
159 if (!isempty(str))
160 return -EINVAL;
161
162 return mount_array_add_internal(for_initrd, TAKE_PTR(what), TAKE_PTR(where), fstype, TAKE_PTR(options));
163 }
164
165 static int mount_array_add_swap(bool for_initrd, const char *str) {
166 _cleanup_free_ char *what = NULL, *options = NULL;
167 int r;
168
169 assert(str);
170
171 r = extract_many_words(&str, ":", EXTRACT_CUNESCAPE | EXTRACT_DONT_COALESCE_SEPARATORS,
172 &what, &options);
173 if (r < 0)
174 return r;
175 if (r < 1)
176 return -EINVAL;
177 if (!isempty(str))
178 return -EINVAL;
179
180 return mount_array_add_internal(for_initrd, TAKE_PTR(what), NULL, "swap", TAKE_PTR(options));
181 }
182
183 static int write_options(FILE *f, const char *options) {
184 _cleanup_free_ char *o = NULL;
185
186 assert(f);
187
188 if (isempty(options))
189 return 0;
190
191 if (streq(options, "defaults"))
192 return 0;
193
194 o = specifier_escape(options);
195 if (!o)
196 return log_oom();
197
198 fprintf(f, "Options=%s\n", o);
199 return 1;
200 }
201
202 static int write_what(FILE *f, const char *what) {
203 _cleanup_free_ char *w = NULL;
204
205 assert(f);
206 assert(what);
207
208 w = specifier_escape(what);
209 if (!w)
210 return log_oom();
211
212 fprintf(f, "What=%s\n", w);
213 return 1;
214 }
215
216 static int add_swap(
217 const char *source,
218 const char *what,
219 const char *options,
220 MountPointFlags flags) {
221
222 _cleanup_free_ char *name = NULL;
223 _cleanup_fclose_ FILE *f = NULL;
224 bool is_network;
225 int r;
226
227 assert(what);
228
229 if (access("/proc/swaps", F_OK) < 0) {
230 log_info("Swap not supported, ignoring swap entry for %s.", what);
231 return 0;
232 }
233
234 if (detect_container() > 0) {
235 log_info("Running in a container, ignoring swap entry for %s.", what);
236 return 0;
237 }
238
239 if (arg_sysroot_check) {
240 log_info("%s should be enabled in the initrd, will request daemon-reload.", what);
241 return true;
242 }
243
244 is_network = fstab_test_option(options, "_netdev\0");
245
246 log_debug("Found swap entry what=%s makefs=%s growfs=%s pcrfs=%s validatefs=%s noauto=%s nofail=%s netdev=%s",
247 what,
248 yes_no(flags & MOUNT_MAKEFS), yes_no(flags & MOUNT_GROWFS),
249 yes_no(flags & MOUNT_PCRFS), yes_no(flags & MOUNT_VALIDATEFS),
250 yes_no(flags & MOUNT_NOAUTO), yes_no(flags & MOUNT_NOFAIL),
251 yes_no(is_network));
252
253 r = unit_name_from_path(what, ".swap", &name);
254 if (r < 0)
255 return log_error_errno(r, "Failed to generate unit name: %m");
256
257 r = generator_open_unit_file(arg_dest, source, name, &f);
258 if (r < 0)
259 return r;
260
261 fprintf(f,
262 "[Unit]\n"
263 "Documentation=man:fstab(5) man:systemd-fstab-generator(8)\n"
264 "SourcePath=%s\n",
265 source);
266
267 r = generator_write_blockdev_dependency(f, what);
268 if (r < 0)
269 return r;
270
271 fprintf(f,
272 "\n"
273 "[Swap]\n");
274
275 r = write_what(f, what);
276 if (r < 0)
277 return r;
278
279 r = write_options(f, options);
280 if (r < 0)
281 return r;
282
283 r = fflush_and_check(f);
284 if (r < 0)
285 return log_error_errno(r, "Failed to write unit file %s: %m", name);
286
287 /* use what as where, to have a nicer error message */
288 r = generator_write_device_timeout(arg_dest, what, options, NULL);
289 if (r < 0)
290 return r;
291
292 if (is_network) {
293 r = generator_write_network_device_deps(arg_dest, what, /* where= */ NULL, options);
294 if (r < 0)
295 return r;
296 }
297
298 if (flags & MOUNT_MAKEFS) {
299 r = generator_hook_up_mkswap(arg_dest, what);
300 if (r < 0)
301 return r;
302 }
303
304 if (flags & MOUNT_GROWFS)
305 /* TODO: swap devices must be wiped and recreated */
306 log_warning("%s: growing swap devices is currently unsupported.", what);
307 if (flags & MOUNT_PCRFS)
308 log_warning("%s: measuring swap devices is currently unsupported.", what);
309 if (flags & MOUNT_VALIDATEFS)
310 log_warning("%s: validating swap devices is currently unsupported.", what);
311
312 if (!(flags & MOUNT_NOAUTO)) {
313 const char *target = is_network ? SPECIAL_REMOTE_FS_TARGET : SPECIAL_SWAP_TARGET;
314 r = generator_add_symlink(arg_dest, target,
315 (flags & MOUNT_NOFAIL) ? "wants" : "requires", name);
316 if (r < 0)
317 return r;
318 }
319
320 return true;
321 }
322
323 static bool mount_is_network(const char *fstype, const char *options) {
324 return fstab_test_option(options, "_netdev\0") ||
325 (fstype && fstype_is_network(fstype));
326 }
327
328 static bool mount_in_initrd(const char *where, const char *options, bool accept_root) {
329 return fstab_test_option(options, "x-initrd.mount\0") ||
330 (where && PATH_IN_SET(where, "/usr", accept_root ? "/" : NULL));
331 }
332
333 static int write_idle_timeout(FILE *f, const char *where, const char *opts) {
334 return generator_write_unit_timeout(f, where, opts,
335 "x-systemd.idle-timeout\0", "TimeoutIdleSec");
336 }
337
338 static int write_dependency(
339 FILE *f,
340 const char *where,
341 const char *opts,
342 const char *filter,
343 const char* const *unit_settings) {
344
345 _cleanup_strv_free_ char **unit_names = NULL;
346 _cleanup_free_ char *units = NULL;
347 int r;
348
349 assert(f);
350 assert(filter);
351 assert(unit_settings);
352
353 r = fstab_filter_options(opts, filter, NULL, NULL, &unit_names, NULL);
354 if (r < 0)
355 return log_error_errno(r, "Failed to parse options for '%s': %m", where);
356 if (r == 0)
357 return 0;
358
359 STRV_FOREACH(s, unit_names) {
360 _cleanup_free_ char *mangled = NULL;
361
362 r = unit_name_mangle_with_suffix(*s, "as dependency", 0, ".mount", &mangled);
363 if (r < 0)
364 return log_error_errno(r, "Failed to generate dependency unit name for '%s': %m", where);
365
366 if (!strextend_with_separator(&units, " ", mangled))
367 return log_oom();
368 }
369
370 STRV_FOREACH(setting, unit_settings)
371 fprintf(f, "%s=%s\n", *setting, units);
372
373 return 0;
374 }
375
376 static int write_after(FILE *f, const char *where, const char *opts) {
377 return write_dependency(f, where, opts,
378 "x-systemd.after\0", STRV_MAKE_CONST("After"));
379 }
380
381 static int write_requires_after(FILE *f, const char *where, const char *opts) {
382 return write_dependency(f, where, opts,
383 "x-systemd.requires\0", STRV_MAKE_CONST("Requires", "After"));
384 }
385
386 static int write_wants_after(FILE *f, const char *where, const char *opts) {
387 return write_dependency(f, where, opts,
388 "x-systemd.wants\0", STRV_MAKE_CONST("Wants", "After"));
389 }
390
391 static int write_before(FILE *f, const char *where, const char *opts) {
392 return write_dependency(f, where, opts,
393 "x-systemd.before\0", STRV_MAKE_CONST("Before"));
394 }
395
396 static int write_mounts_for(
397 FILE *f,
398 const char *where,
399 const char *opts,
400 const char *filter,
401 const char *unit_setting) {
402
403 _cleanup_strv_free_ char **paths = NULL, **paths_escaped = NULL;
404 int r;
405
406 assert(f);
407 assert(where);
408 assert(filter);
409 assert(unit_setting);
410
411 r = fstab_filter_options(opts, filter, NULL, NULL, &paths, NULL);
412 if (r < 0)
413 return log_error_errno(r, "Failed to parse options for '%s': %m", where);
414 if (r == 0)
415 return 0;
416
417 r = specifier_escape_strv(paths, &paths_escaped);
418 if (r < 0)
419 return log_error_errno(r, "Failed to escape paths for '%s': %m", where);
420
421 fprintf(f, "%s=", unit_setting);
422 fputstrv(f, paths_escaped, NULL, NULL);
423 fputc('\n', f);
424
425 return 0;
426 }
427
428 static int write_extra_dependencies(FILE *f, const char *where, const char *opts) {
429 int r;
430
431 assert(f);
432
433 if (isempty(opts))
434 return 0;
435
436 r = write_after(f, where, opts);
437 if (r < 0)
438 return r;
439
440 r = write_requires_after(f, where, opts);
441 if (r < 0)
442 return r;
443
444 r = write_wants_after(f, where, opts);
445 if (r < 0)
446 return r;
447
448 r = write_before(f, where, opts);
449 if (r < 0)
450 return r;
451
452 r = write_mounts_for(f, where, opts,
453 "x-systemd.requires-mounts-for\0", "RequiresMountsFor");
454 if (r < 0)
455 return r;
456
457 r = write_mounts_for(f, where, opts,
458 "x-systemd.wants-mounts-for\0", "WantsMountsFor");
459 if (r < 0)
460 return r;
461
462 return 0;
463 }
464
465 static int mandatory_mount_drop_unapplicable_options(
466 MountPointFlags *flags,
467 const char *where,
468 const char *options,
469 char **ret_options) {
470
471 int r;
472
473 assert(flags);
474 assert(where);
475 assert(ret_options);
476
477 if (!(*flags & (MOUNT_NOAUTO|MOUNT_NOFAIL|MOUNT_AUTOMOUNT)))
478 return strdup_to(ret_options, options);
479
480 log_debug("Mount '%s' is mandatory, ignoring 'noauto', 'nofail', and 'x-systemd.automount' options.",
481 where);
482
483 *flags &= ~(MOUNT_NOAUTO|MOUNT_NOFAIL|MOUNT_AUTOMOUNT);
484
485 r = fstab_filter_options(options, "noauto\0nofail\0x-systemd.automount\0", NULL, NULL, NULL, ret_options);
486 if (r < 0)
487 return r;
488
489 return 1;
490 }
491
492 static int add_mount(
493 const char *source,
494 const char *dest,
495 const char *what,
496 const char *where,
497 const char *original_where,
498 const char *fstype,
499 const char *opts,
500 int passno,
501 MountPointFlags flags,
502 const char *target_unit,
503 const char *extra_after) {
504
505 _cleanup_free_ char *name = NULL, *automount_name = NULL, *filtered = NULL, *where_escaped = NULL,
506 *opts_root_filtered = NULL;
507 _cleanup_strv_free_ char **wanted_by = NULL, **required_by = NULL;
508 _cleanup_fclose_ FILE *f = NULL;
509 int r;
510
511 assert(what);
512 assert(where);
513 assert(target_unit);
514 assert(source);
515
516 if (streq_ptr(fstype, "autofs"))
517 return 0;
518
519 if (!is_path(where)) {
520 log_warning("Mount point %s is not a valid path, ignoring.", where);
521 return 0;
522 }
523
524 if (mount_point_is_api(where) ||
525 mount_point_ignore(where))
526 return 0;
527
528 if (arg_sysroot_check) {
529 log_info("%s should be mounted in the initrd, will request daemon-reload.", where);
530 return true;
531 }
532
533 r = fstab_filter_options(opts, "x-systemd.wanted-by\0", NULL, NULL, &wanted_by, NULL);
534 if (r < 0)
535 return r;
536
537 r = fstab_filter_options(opts, "x-systemd.required-by\0", NULL, NULL, &required_by, NULL);
538 if (r < 0)
539 return r;
540
541 if (PATH_IN_SET(where, "/", "/usr")) {
542 r = mandatory_mount_drop_unapplicable_options(&flags, where, opts, &opts_root_filtered);
543 if (r < 0)
544 return r;
545 opts = opts_root_filtered;
546
547 if (!strv_isempty(wanted_by))
548 log_debug("Ignoring 'x-systemd.wanted-by=' option for root/usr device.");
549 if (!strv_isempty(required_by))
550 log_debug("Ignoring 'x-systemd.required-by=' option for root/usr device.");
551
552 required_by = strv_free(required_by);
553 wanted_by = strv_free(wanted_by);
554 }
555
556 r = unit_name_from_path(where, ".mount", &name);
557 if (r < 0)
558 return log_error_errno(r, "Failed to generate unit name: %m");
559
560 r = generator_open_unit_file(dest, source, name, &f);
561 if (r < 0)
562 return r;
563
564 fprintf(f,
565 "[Unit]\n"
566 "Documentation=man:fstab(5) man:systemd-fstab-generator(8)\n"
567 "SourcePath=%s\n",
568 source);
569
570 if (STRPTR_IN_SET(fstype, "nfs", "nfs4") && !(flags & MOUNT_AUTOMOUNT) &&
571 fstab_test_yes_no_option(opts, "bg\0" "fg\0")) {
572 /* The default retry timeout that mount.nfs uses for 'bg' mounts
573 * is 10000 minutes, where as it uses 2 minutes for 'fg' mounts.
574 * As we are making 'bg' mounts look like an 'fg' mount to
575 * mount.nfs (so systemd can manage the job-control aspects of 'bg'),
576 * we need to explicitly preserve that default, and also ensure
577 * the systemd mount-timeout doesn't interfere.
578 * By placing these options first, they can be overridden by
579 * settings in /etc/fstab. */
580 opts = strjoina("x-systemd.mount-timeout=infinity,retry=10000,nofail,", opts, ",fg");
581 SET_FLAG(flags, MOUNT_NOFAIL, true);
582 }
583
584 if (!strv_isempty(wanted_by) || !strv_isempty(required_by)) {
585 /* If x-systemd.{wanted,required}-by= is specified, target_unit is not used */
586 target_unit = NULL;
587
588 /* Don't set default ordering dependencies on local-fs.target or remote-fs.target, but we
589 * still need to conflict with umount.target. */
590 fputs("DefaultDependencies=no\n"
591 "Conflicts=umount.target\n"
592 "Before=umount.target\n",
593 f);
594 }
595
596 r = write_extra_dependencies(f, where, opts);
597 if (r < 0)
598 return r;
599
600 /* Order the mount unit we generate relative to target_unit, so that DefaultDependencies= on the
601 * target unit won't affect us. */
602 if (target_unit && !FLAGS_SET(flags, MOUNT_NOFAIL))
603 fprintf(f, "Before=%s\n", target_unit);
604
605 if (extra_after)
606 fprintf(f, "After=%s\n", extra_after);
607
608 if (passno != 0) {
609 r = generator_write_fsck_deps(f, dest, what, where, fstype, opts);
610 if (r < 0)
611 return r;
612 }
613
614 r = generator_write_blockdev_dependency(f, what);
615 if (r < 0)
616 return r;
617
618 fprintf(f,
619 "\n"
620 "[Mount]\n");
621
622 r = write_what(f, what);
623 if (r < 0)
624 return r;
625
626 if (original_where)
627 fprintf(f, "# Canonicalized from %s\n", original_where);
628
629 where_escaped = specifier_escape(where);
630 if (!where_escaped)
631 return log_oom();
632 fprintf(f, "Where=%s\n", where_escaped);
633
634 if (!isempty(fstype) && !streq(fstype, "auto")) {
635 _cleanup_free_ char *t = NULL;
636
637 t = specifier_escape(fstype);
638 if (!t)
639 return -ENOMEM;
640
641 fprintf(f, "Type=%s\n", t);
642 }
643
644 r = generator_write_device_timeout(dest, what, opts, &filtered);
645 if (r < 0)
646 return r;
647
648 r = generator_write_network_device_deps(dest, what, where, opts);
649 if (r < 0)
650 return r;
651
652 if (in_initrd() && path_equal(where, "/sysroot") && is_device_path(what)) {
653 r = generator_write_initrd_root_device_deps(dest, what);
654 if (r < 0)
655 return r;
656 }
657
658 r = generator_write_mount_timeout(f, where, opts);
659 if (r < 0)
660 return r;
661
662 r = write_options(f, filtered);
663 if (r < 0)
664 return r;
665
666 if (flags & MOUNT_RW_ONLY)
667 fprintf(f, "ReadWriteOnly=yes\n");
668
669 r = fflush_and_check(f);
670 if (r < 0)
671 return log_error_errno(r, "Failed to write unit file %s: %m", name);
672
673 if (flags & MOUNT_MAKEFS) {
674 r = generator_hook_up_mkfs(dest, what, where, fstype);
675 if (r < 0)
676 return r;
677 }
678
679 if (flags & MOUNT_GROWFS) {
680 r = generator_hook_up_growfs(dest, where, target_unit);
681 if (r < 0)
682 return r;
683 }
684
685 if (flags & MOUNT_PCRFS) {
686 r = efi_measured_os(LOG_WARNING);
687 if (r == 0)
688 log_debug("OS measurements not explicitly requested and kernel stub did not measure kernel image into PCR, skipping userspace measurement, too.");
689 else if (r > 0) {
690 r = generator_hook_up_pcrfs(dest, where, target_unit);
691 if (r < 0)
692 return r;
693 }
694 }
695
696 if (flags & MOUNT_VALIDATEFS) {
697 r = generator_hook_up_validatefs(dest, where, target_unit);
698 if (r < 0)
699 return r;
700 }
701
702 if (flags & MOUNT_QUOTA) {
703 r = generator_hook_up_quotacheck(dest, what, where, target_unit, fstype);
704 if (r < 0) {
705 if (r != -EOPNOTSUPP)
706 return r;
707 } else if (r > 0) {
708 r = generator_hook_up_quotaon(dest, where, target_unit);
709 if (r < 0)
710 return r;
711 }
712 }
713
714 if (FLAGS_SET(flags, MOUNT_AUTOMOUNT)) {
715 r = unit_name_from_path(where, ".automount", &automount_name);
716 if (r < 0)
717 return log_error_errno(r, "Failed to generate unit name: %m");
718
719 f = safe_fclose(f);
720
721 r = generator_open_unit_file(dest, source, automount_name, &f);
722 if (r < 0)
723 return r;
724
725 fprintf(f,
726 "[Unit]\n"
727 "SourcePath=%s\n"
728 "Documentation=man:fstab(5) man:systemd-fstab-generator(8)\n",
729 source);
730
731 fprintf(f,
732 "\n"
733 "[Automount]\n"
734 "Where=%s\n",
735 where_escaped);
736
737 r = write_idle_timeout(f, where, opts);
738 if (r < 0)
739 return r;
740
741 r = fflush_and_check(f);
742 if (r < 0)
743 return log_error_errno(r, "Failed to write unit file %s: %m", automount_name);
744 }
745
746 if (target_unit) {
747 assert(strv_isempty(wanted_by));
748 assert(strv_isempty(required_by));
749
750 /* noauto has no effect if x-systemd.automount is used */
751 if (!FLAGS_SET(flags, MOUNT_NOAUTO) || automount_name) {
752 r = generator_add_symlink(dest, target_unit,
753 FLAGS_SET(flags, MOUNT_NOFAIL) ? "wants" : "requires",
754 automount_name ?: name);
755 if (r < 0)
756 return r;
757 }
758 } else {
759 const char *unit_name = automount_name ?: name;
760
761 STRV_FOREACH(s, wanted_by) {
762 r = generator_add_symlink(dest, *s, "wants", unit_name);
763 if (r < 0)
764 return r;
765 }
766
767 STRV_FOREACH(s, required_by) {
768 r = generator_add_symlink(dest, *s, "requires", unit_name);
769 if (r < 0)
770 return r;
771 }
772
773 if ((flags & (MOUNT_NOAUTO|MOUNT_NOFAIL)) != 0)
774 log_warning("x-systemd.wanted-by= and/or x-systemd.required-by= specified, 'noauto' and 'nofail' have no effect.");
775 }
776
777 return true;
778 }
779
780 static int do_daemon_reload(void) {
781 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
782 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
783 int r, k;
784
785 log_debug("Calling org.freedesktop.systemd1.Manager.Reload()...");
786
787 r = bus_connect_system_systemd(&bus);
788 if (r < 0)
789 return log_error_errno(r, "Failed to get D-Bus connection: %m");
790
791 r = bus_service_manager_reload(bus);
792 if (r < 0)
793 return r;
794
795 /* We need to requeue the two targets so that any new units which previously were not part of the
796 * targets, and which we now added, will be started. */
797
798 r = 0;
799 FOREACH_STRING(unit, SPECIAL_INITRD_FS_TARGET, SPECIAL_SWAP_TARGET) {
800 log_info("Requesting %s/start/replace...", unit);
801
802 k = bus_call_method(bus, bus_systemd_mgr, "StartUnit", &error, NULL, "ss", unit, "replace");
803 if (k < 0) {
804 log_error_errno(k, "Failed to (re)start %s: %s", unit, bus_error_message(&error, k));
805 RET_GATHER(r, k);
806 }
807 }
808
809 return r;
810 }
811
812 static const char* sysroot_fstab_path(void) {
813 return getenv("SYSTEMD_SYSROOT_FSTAB") ?: "/sysroot/etc/fstab";
814 }
815
816 static bool sysfs_check(void) {
817 static int cached = -1;
818 int r;
819
820 if (cached < 0) {
821 r = secure_getenv_bool("SYSTEMD_SYSFS_CHECK");
822 if (r < 0 && r != -ENXIO)
823 log_debug_errno(r, "Failed to parse $SYSTEMD_SYSFS_CHECK, ignoring: %m");
824 cached = r != 0;
825 }
826
827 return cached;
828 }
829
830 static int add_sysusr_sysroot_usr_bind_mount(const char *source, bool validatefs) {
831 log_debug("Synthesizing entry what=/sysusr/usr where=/sysroot/usr opts=bind validatefs=%s", yes_no(validatefs));
832
833 return add_mount(source,
834 arg_dest,
835 "/sysusr/usr",
836 "/sysroot/usr",
837 /* original_where= */ NULL,
838 /* fstype= */ NULL,
839 "bind",
840 /* passno= */ 0,
841 validatefs ? MOUNT_VALIDATEFS : 0,
842 SPECIAL_INITRD_FS_TARGET,
843 /* extra_after= */ NULL);
844 }
845
846 static MountPointFlags fstab_options_to_flags(const char *options, bool is_swap) {
847 MountPointFlags flags = 0;
848
849 if (isempty(options))
850 return 0;
851
852 if (fstab_test_option(options, "x-systemd.makefs\0"))
853 flags |= MOUNT_MAKEFS;
854 if (fstab_test_option(options, "x-systemd.growfs\0"))
855 flags |= MOUNT_GROWFS;
856 if (fstab_test_option(options, "x-systemd.pcrfs\0"))
857 flags |= MOUNT_PCRFS;
858 if (fstab_test_option(options, "x-systemd.validatefs\0"))
859 flags |= MOUNT_VALIDATEFS;
860 if (fstab_test_option(options, "usrquota\0" "grpquota\0" "quota\0" "usrjquota\0" "grpjquota\0" "prjquota\0"))
861 flags |= MOUNT_QUOTA;
862 if (fstab_test_yes_no_option(options, "noauto\0" "auto\0"))
863 flags |= MOUNT_NOAUTO;
864 if (fstab_test_yes_no_option(options, "nofail\0" "fail\0"))
865 flags |= MOUNT_NOFAIL;
866
867 if (!is_swap) {
868 if (fstab_test_option(options, "x-systemd.rw-only\0"))
869 flags |= MOUNT_RW_ONLY;
870 if (fstab_test_option(options,
871 "comment=systemd.automount\0"
872 "x-systemd.automount\0"))
873 flags |= MOUNT_AUTOMOUNT;
874 }
875
876 return flags;
877 }
878
879 static int canonicalize_mount_path(const char *path, const char *type, bool prefix_sysroot, char **ret) {
880 _cleanup_free_ char *p = NULL;
881 bool changed;
882 int r;
883
884 assert(path);
885 assert(type);
886 assert(STR_IN_SET(type, "where", "what"));
887 assert(ret);
888
889 // FIXME: when chase() learns to chase non-existent paths, use this here and drop the prefixing with
890 // /sysroot on error below.
891 r = chase(path, prefix_sysroot ? "/sysroot" : NULL, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &p, NULL);
892 if (r < 0) {
893 log_debug_errno(r, "Failed to chase '%s', using as-is: %m", path);
894
895 if (prefix_sysroot)
896 p = path_join("/sysroot", path);
897 else
898 p = strdup(path);
899 if (!p)
900 return log_oom();
901
902 path_simplify(p);
903 }
904
905 changed = !streq(path, p);
906 if (changed)
907 log_debug("Canonicalized %s=%s to %s", type, path, p);
908
909 *ret = TAKE_PTR(p);
910 return changed;
911 }
912
913 static int parse_fstab_one(
914 const char *source,
915 const char *what_original,
916 const char *where_original,
917 const char *fstype,
918 const char *options,
919 int passno,
920 bool prefix_sysroot,
921 bool accept_root, /* This takes an effect only when prefix_sysroot is true. */
922 bool use_swap_enabled) {
923
924 _cleanup_free_ char *what = NULL, *where = NULL, *opts = NULL;
925 MountPointFlags flags;
926 bool is_swap, where_changed;
927 int r;
928
929 assert(what_original);
930 assert(fstype);
931
932 if (prefix_sysroot && !mount_in_initrd(where_original, options, accept_root))
933 return 0;
934
935 is_swap = streq_ptr(fstype, "swap");
936 if (is_swap && use_swap_enabled && !arg_swap_enabled) {
937 log_info("Swap unit generation disabled on kernel command line, ignoring swap entry for %s.", what_original);
938 return 0;
939 }
940
941 what = fstab_node_to_udev_node(what_original);
942 if (!what)
943 return log_oom();
944
945 if (path_is_read_only_fs("/sys") > 0 &&
946 (streq(what, "sysfs") ||
947 (sysfs_check() && is_device_path(what)))) {
948 log_info("/sys/ is read-only (running in a container?), ignoring mount for %s.", what);
949 return 0;
950 }
951
952 flags = fstab_options_to_flags(options, is_swap);
953
954 if (is_swap)
955 return add_swap(source, what, options, flags);
956
957 if (passno < 0)
958 passno = is_device_path(what);
959
960 assert(where_original); /* 'where' is not necessary for swap entry. */
961
962 if (!is_path(where_original)) {
963 log_warning("Mount point %s is not a valid path, ignoring.", where_original);
964 return 0;
965 }
966
967 /* Follow symlinks here; see 5261ba901845c084de5a8fd06500ed09bfb0bd80 which makes sense for
968 * mount units, but causes problems since it historically worked to have symlinks in e.g.
969 * /etc/fstab. So we canonicalize here. Note that we use CHASE_NONEXISTENT to handle the case
970 * where a symlink refers to another mount target; this works assuming the sub-mountpoint
971 * target is the final directory. */
972 r = canonicalize_mount_path(where_original, "where", prefix_sysroot, &where);
973 if (r < 0)
974 return r;
975 where_changed = r > 0;
976
977 if (prefix_sysroot && fstab_is_bind(options, fstype)) {
978 /* When in initrd, the source of bind mount needs to be prepended with /sysroot as well. */
979 _cleanup_free_ char *p = NULL;
980
981 r = canonicalize_mount_path(what, "what", prefix_sysroot, &p);
982 if (r < 0)
983 return r;
984
985 free_and_replace(what, p);
986 }
987
988 log_debug("Found entry what=%s where=%s type=%s makefs=%s growfs=%s pcrfs=%s validatefs=%s noauto=%s nofail=%s",
989 what, where, strna(fstype),
990 yes_no(flags & MOUNT_MAKEFS), yes_no(flags & MOUNT_GROWFS),
991 yes_no(flags & MOUNT_PCRFS), yes_no(flags & MOUNT_VALIDATEFS),
992 yes_no(flags & MOUNT_NOAUTO), yes_no(flags & MOUNT_NOFAIL));
993
994 bool is_sysroot = in_initrd() && path_equal(where, "/sysroot");
995 /* See comment from add_sysroot_usr_mount() about the need for extra indirection in case /usr needs
996 * to be mounted in order for the root fs to be synthesized based on configuration included in /usr/,
997 * e.g. systemd-repart. */
998 bool is_sysroot_usr = in_initrd() && path_equal(where, "/sysroot/usr");
999
1000 const char *target_unit =
1001 is_sysroot ? SPECIAL_INITRD_ROOT_FS_TARGET :
1002 is_sysroot_usr ? SPECIAL_INITRD_USR_FS_TARGET :
1003 prefix_sysroot ? SPECIAL_INITRD_FS_TARGET :
1004 mount_is_network(fstype, options) ? SPECIAL_REMOTE_FS_TARGET :
1005 SPECIAL_LOCAL_FS_TARGET;
1006
1007 /* nofail, noauto and x-systemd.automount don't make sense for critical filesystems we must mount in initrd. */
1008 if (is_sysroot || is_sysroot_usr) {
1009 r = mandatory_mount_drop_unapplicable_options(&flags, where, options, &opts);
1010 if (r < 0)
1011 return r;
1012 options = opts;
1013 }
1014
1015 r = add_mount(source,
1016 arg_dest,
1017 what,
1018 is_sysroot_usr ? "/sysusr/usr" : where,
1019 !is_sysroot_usr && where_changed ? where_original : NULL,
1020 fstype,
1021 options,
1022 passno,
1023 flags & ~(is_sysroot_usr ? MOUNT_VALIDATEFS : 0),
1024 target_unit,
1025 /* extra_after= */ NULL);
1026 if (r <= 0)
1027 return r;
1028
1029 if (is_sysroot_usr) {
1030 r = add_sysusr_sysroot_usr_bind_mount(source, flags & MOUNT_VALIDATEFS);
1031 if (r < 0)
1032 return r;
1033 }
1034
1035 return true;
1036 }
1037
1038 static int parse_fstab(bool prefix_sysroot) {
1039 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
1040 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
1041 const char *fstab;
1042 int r, ret = 0;
1043
1044 if (prefix_sysroot)
1045 fstab = sysroot_fstab_path();
1046 else {
1047 fstab = fstab_path();
1048 assert(!arg_sysroot_check);
1049 }
1050
1051 log_debug("Parsing %s...", fstab);
1052
1053 r = libmount_parse_full(fstab, /* source= */ NULL, MNT_ITER_FORWARD, &table, &iter);
1054 if (r == -ENOENT)
1055 return 0;
1056 if (r < 0)
1057 return log_error_errno(r, "Failed to parse '%s': %m", fstab);
1058
1059 for (;;) {
1060 struct libmnt_fs *fs;
1061
1062 r = sym_mnt_table_next_fs(table, iter, &fs);
1063 if (r < 0)
1064 return log_error_errno(r, "Failed to get next entry from '%s': %m", fstab);
1065 if (r > 0) /* EOF */
1066 return ret;
1067
1068 r = parse_fstab_one(
1069 fstab,
1070 sym_mnt_fs_get_source(fs),
1071 sym_mnt_fs_get_target(fs),
1072 sym_mnt_fs_get_fstype(fs),
1073 sym_mnt_fs_get_options(fs),
1074 sym_mnt_fs_get_passno(fs),
1075 prefix_sysroot,
1076 /* accept_root= */ false,
1077 /* use_swap_enabled= */ true);
1078 if (arg_sysroot_check && r > 0)
1079 return true; /* We found a mount or swap that would be started… */
1080 RET_GATHER(ret, r);
1081 }
1082 }
1083
1084 static int mount_source_is_nfsroot(const char *what) {
1085 union in_addr_union u;
1086 const char *sep, *a;
1087 int r;
1088
1089 assert(what);
1090
1091 /* From dracut.cmdline(7).
1092 *
1093 * root=[<server-ip>:]<root-dir>[:<nfs-options>]
1094 * root=nfs:[<server-ip>:]<root-dir>[:<nfs-options>],
1095 * root=nfs4:[<server-ip>:]<root-dir>[:<nfs-options>],
1096 * root={dhcp|dhcp6}
1097 *
1098 * mount nfs share from <server-ip>:/<root-dir>, if no server-ip is given, use dhcp next_server.
1099 * If server-ip is an IPv6 address it has to be put in brackets, e.g. [2001:DB8::1]. NFS options
1100 * can be appended with the prefix ":" or "," and are separated by ",". */
1101
1102 if (path_equal(what, "/dev/nfs") ||
1103 STR_IN_SET(what, "dhcp", "dhcp6") ||
1104 STARTSWITH_SET(what, "nfs:", "nfs4:"))
1105 return true;
1106
1107 /* IPv6 address */
1108 if (what[0] == '[') {
1109 sep = strchr(what + 1, ']');
1110 if (!sep)
1111 return -EINVAL;
1112
1113 a = strndupa_safe(what + 1, sep - what - 1);
1114
1115 r = in_addr_from_string(AF_INET6, a, &u);
1116 if (r < 0)
1117 return r;
1118
1119 return true;
1120 }
1121
1122 /* IPv4 address */
1123 sep = strchr(what, ':');
1124 if (sep) {
1125 a = strndupa_safe(what, sep - what);
1126
1127 if (in_addr_from_string(AF_INET, a, &u) >= 0)
1128 return true;
1129 }
1130
1131 /* root directory without address */
1132 return path_is_absolute(what) && !path_startswith(what, "/dev");
1133 }
1134
1135 static bool validate_root_or_usr_mount_source(const char *what, const char *switch_name) {
1136 int r;
1137
1138 assert(switch_name);
1139
1140 if (isempty(what)) {
1141 log_debug("No %s switch specified on the kernel command line.", switch_name);
1142 return false;
1143 }
1144
1145 if (streq(what, "off")) {
1146 log_debug("Skipping %s directory handling, as this was explicitly turned off.", switch_name);
1147 return false;
1148 }
1149
1150 if (parse_gpt_auto_root(switch_name, what) > 0) {
1151 /* This is handled by gpt-auto-generator */
1152 log_debug("Skipping %s directory handling, as gpt-auto was requested.", switch_name);
1153 return false;
1154 }
1155
1156 if (streq(what, "fstab")) {
1157 /* This is handled by parse_fstab() */
1158 log_debug("Using initrd's fstab for %s configuration.", switch_name);
1159 return false;
1160 }
1161
1162 r = mount_source_is_nfsroot(what);
1163 if (r < 0)
1164 log_debug_errno(r, "Failed to determine if the %s directory is on NFS, assuming not: %m", switch_name);
1165 else if (r > 0) {
1166 /* This is handled by the kernel or the initrd */
1167 log_debug("Skipping %s directory handling, as root on NFS was requested.", switch_name);
1168 return false;
1169 }
1170
1171 if (startswith(what, "cifs://")) {
1172 log_debug("Skipping %s directory handling, as root on CIFS was requested.", switch_name);
1173 return false;
1174 }
1175
1176 if (startswith(what, "iscsi:")) {
1177 log_debug("Skipping %s directory handling, as root on iSCSI was requested.", switch_name);
1178 return false;
1179 }
1180
1181 if (startswith(what, "live:")) {
1182 log_debug("Skipping %s directory handling, as root on live image was requested.", switch_name);
1183 return false;
1184 }
1185
1186 return true;
1187 }
1188
1189 static int add_sysroot_mount(void) {
1190 _cleanup_free_ char *what = NULL;
1191 const char *extra_opts = NULL, *fstype = NULL;
1192 bool default_rw = true;
1193 MountPointFlags flags;
1194
1195 if (!validate_root_or_usr_mount_source(arg_root_what, "root="))
1196 return 0;
1197
1198 const char *bind = startswith(arg_root_what, "bind:");
1199 if (bind) {
1200 if (!path_is_valid(bind) || !path_is_absolute(bind)) {
1201 log_debug("Invalid root=bind: source path, ignoring: %s", bind);
1202 return 0;
1203 }
1204
1205 what = strdup(bind);
1206 if (!what)
1207 return log_oom();
1208
1209 extra_opts = "bind";
1210
1211 } else if (streq(arg_root_what, "tmpfs")) {
1212 /* If root=tmpfs is specified, then take this as shortcut for a writable tmpfs mount as root */
1213
1214 what = strdup("rootfs"); /* just a pretty name, to show up in /proc/self/mountinfo */
1215 if (!what)
1216 return log_oom();
1217
1218 fstype = arg_root_fstype ?: "tmpfs"; /* tmpfs, unless overridden */
1219 if (streq(fstype, "tmpfs") && !fstab_test_option(arg_root_options, "mode\0"))
1220 extra_opts = "mode=0755"; /* root directory should not be world/group writable, unless overridden */
1221 } else {
1222
1223 what = fstab_node_to_udev_node(arg_root_what);
1224 if (!what)
1225 return log_oom();
1226
1227 fstype = arg_root_fstype; /* if not specified explicitly, don't default to anything here */
1228 default_rw = false; /* read-only, unless overridden */
1229 }
1230
1231 _cleanup_free_ char *combined_options = NULL;
1232 if (strdup_to(&combined_options, arg_root_options) < 0)
1233 return log_oom();
1234
1235 if (arg_root_rw >= 0 || !fstab_test_option(combined_options, "ro\0" "rw\0"))
1236 if (!strextend_with_separator(&combined_options, ",", arg_root_rw > 0 || (arg_root_rw < 0 && default_rw) ? "rw" : "ro"))
1237 return log_oom();
1238
1239 if (extra_opts)
1240 if (!strextend_with_separator(&combined_options, ",", extra_opts))
1241 return log_oom();
1242
1243 /* A bind mount inherits the mount flags (nosuid, nodev, noexec, …) of the file system the source
1244 * directory is located on. The source typically lives below /run/ (e.g. a freshly unpacked tar image
1245 * in /run/machines/), which is mounted nosuid,nodev, and these flags would then propagate to our root
1246 * file system, breaking suid binaries (e.g. sudo) and device nodes. Since this is supposed to become a
1247 * regular OS root file system, default to dev,suid,exec instead, unless the user explicitly requested
1248 * otherwise. */
1249 if (bind) {
1250 static const char* const defaults[] = {
1251 "suid", "suid\0" "nosuid\0",
1252 "dev", "dev\0" "nodev\0",
1253 "exec", "exec\0" "noexec\0",
1254 NULL,
1255 };
1256
1257 STRV_FOREACH_PAIR(add, test, defaults)
1258 if (!fstab_test_option(combined_options, *test))
1259 if (!strextend_with_separator(&combined_options, ",", *add))
1260 return log_oom();
1261 }
1262
1263 log_debug("Found entry what=%s where=/sysroot type=%s opts=%s", what, strna(fstype), strempty(combined_options));
1264
1265 /* Only honor x-systemd.makefs and .validatefs here, others are not relevant in initrd/not used
1266 * at all (also see mandatory_mount_drop_unapplicable_options()) */
1267 flags = fstab_options_to_flags(combined_options, /* is_swap= */ false) & (MOUNT_MAKEFS|MOUNT_VALIDATEFS);
1268
1269 return add_mount("/proc/cmdline",
1270 arg_dest,
1271 what,
1272 "/sysroot",
1273 /* original_where= */ NULL,
1274 fstype,
1275 combined_options,
1276 /* passno= */ is_device_path(what) ? 1 : 0,
1277 flags,
1278 SPECIAL_INITRD_ROOT_FS_TARGET,
1279 "imports.target");
1280 }
1281
1282 static int add_sysroot_usr_mount(void) {
1283 _cleanup_free_ char *what = NULL;
1284 const char *extra_opts = NULL;
1285 bool makefs, validatefs;
1286 int r;
1287
1288 /* Returns 0 if we didn't do anything, > 0 if we either generated a unit for the /usr/ mount, or we
1289 * know for sure something else did */
1290
1291 if (!arg_usr_what && !arg_usr_fstype && !arg_usr_options)
1292 return 0;
1293
1294 if (arg_root_what && !arg_usr_what) {
1295 /* Copy over the root device, in case the /usr mount just differs in a mount option (consider btrfs subvolumes) */
1296 arg_usr_what = strdup(arg_root_what);
1297 if (!arg_usr_what)
1298 return log_oom();
1299 }
1300
1301 if (arg_root_fstype && !arg_usr_fstype) {
1302 arg_usr_fstype = strdup(arg_root_fstype);
1303 if (!arg_usr_fstype)
1304 return log_oom();
1305 }
1306
1307 if (arg_root_options && !arg_usr_options) {
1308 arg_usr_options = strdup(arg_root_options);
1309 if (!arg_usr_options)
1310 return log_oom();
1311 }
1312
1313 if (!validate_root_or_usr_mount_source(arg_usr_what, "mount.usr="))
1314 return 0;
1315
1316 const char *bind = startswith(arg_usr_what, "bind:");
1317 if (bind) {
1318 if (!path_is_valid(bind) || !path_is_absolute(bind)) {
1319 log_debug("Invalid mount.usr=bind: source path, ignoring: %s", bind);
1320 return 0;
1321 }
1322
1323 what = strdup(bind);
1324 if (!what)
1325 return log_oom();
1326
1327 extra_opts = "bind";
1328 } else {
1329 what = fstab_node_to_udev_node(arg_usr_what);
1330 if (!what)
1331 return log_oom();
1332 }
1333
1334 _cleanup_free_ char *combined_options = NULL;
1335 if (strdup_to(&combined_options, arg_usr_options) < 0)
1336 return log_oom();
1337
1338 if (!fstab_test_option(combined_options, "ro\0" "rw\0"))
1339 if (!strextend_with_separator(&combined_options, ",", arg_root_rw > 0 ? "rw" : "ro"))
1340 return log_oom();
1341
1342 if (extra_opts)
1343 if (!strextend_with_separator(&combined_options, ",", extra_opts))
1344 return log_oom();
1345
1346 /* When mounting /usr from the initrd, we add an extra level of indirection: we first mount the /usr/
1347 * partition to /sysusr/usr/, and then afterwards bind mount that to /sysroot/usr/. We do this so
1348 * that we can cover for systems that initially only have a /usr/ around and where the root fs needs
1349 * to be synthesized, based on configuration included in /usr/, e.g. systemd-repart. Software like
1350 * this should order itself after initrd-usr-fs.target and before initrd-fs.target; and it should
1351 * look into both /sysusr/ and /sysroot/ for the configuration data to apply. */
1352
1353 log_debug("Found entry what=%s where=/sysusr/usr type=%s opts=%s", what, strna(arg_usr_fstype), strempty(combined_options));
1354
1355 /* Only honor x-systemd.makefs and .validatefs here, others are not relevant in initrd/not used
1356 * at all (also see mandatory_mount_drop_unapplicable_options()) */
1357 makefs = fstab_test_option(combined_options, "x-systemd.makefs\0");
1358 validatefs = fstab_test_option(combined_options, "x-systemd.validatefs\0");
1359
1360 r = add_mount("/proc/cmdline",
1361 arg_dest,
1362 what,
1363 "/sysusr/usr",
1364 /* original_where= */ NULL,
1365 arg_usr_fstype,
1366 combined_options,
1367 /* passno= */ is_device_path(what) ? 1 : 0,
1368 makefs ? MOUNT_MAKEFS : 0,
1369 SPECIAL_INITRD_USR_FS_TARGET,
1370 "imports.target");
1371 if (r < 0)
1372 return r;
1373
1374 r = add_sysusr_sysroot_usr_bind_mount("/proc/cmdline", validatefs);
1375 if (r < 0)
1376 return r;
1377
1378 return 1;
1379 }
1380
1381 static int add_sysroot_usr_mount_or_fallback(void) {
1382 int r;
1383
1384 r = add_sysroot_usr_mount();
1385 if (r != 0)
1386 return r;
1387
1388 /* OK, so we didn't write anything out for /sysusr/usr/ nor /sysroot/usr/. In this case, let's make
1389 * sure that initrd-usr-fs.target is at least ordered after sysroot.mount so that services that order
1390 * themselves after it get the guarantee that /usr/ is definitely mounted somewhere. */
1391
1392 return generator_add_symlink(
1393 arg_dest,
1394 SPECIAL_INITRD_USR_FS_TARGET,
1395 "requires",
1396 "sysroot.mount");
1397 }
1398
1399 static int add_volatile_root(void) {
1400
1401 /* Let's add in systemd-remount-volatile.service which will remount the root device to tmpfs if this is
1402 * requested (or as an overlayfs), leaving only /usr from the root mount inside. */
1403
1404 if (!IN_SET(arg_volatile_mode, VOLATILE_YES, VOLATILE_OVERLAY))
1405 return 0;
1406
1407 return generator_add_symlink(arg_dest, SPECIAL_INITRD_ROOT_FS_TARGET, "requires",
1408 SYSTEM_DATA_UNIT_DIR "/" SPECIAL_VOLATILE_ROOT_SERVICE);
1409 }
1410
1411 static int add_volatile_var(void) {
1412
1413 if (arg_volatile_mode != VOLATILE_STATE)
1414 return 0;
1415
1416 /* If requested, mount /var as tmpfs, but do so only if there's nothing else defined for this. */
1417
1418 return add_mount("/proc/cmdline",
1419 arg_dest_late,
1420 "tmpfs",
1421 "/var",
1422 /* original_where= */ NULL,
1423 "tmpfs",
1424 "mode=0755" TMPFS_LIMITS_VAR,
1425 /* passno= */ 0,
1426 /* flags= */ 0,
1427 SPECIAL_LOCAL_FS_TARGET,
1428 /* extra_after= */ NULL);
1429 }
1430
1431 static int add_mounts_from_cmdline(void) {
1432 int r = 0;
1433
1434 /* Handle each entries found in cmdline as a fstab entry. */
1435
1436 FOREACH_ARRAY(m, arg_mounts, arg_n_mounts) {
1437 if (m->for_initrd && !in_initrd())
1438 continue;
1439
1440 RET_GATHER(r, parse_fstab_one("/proc/cmdline",
1441 m->what,
1442 m->where,
1443 m->fstype,
1444 m->options,
1445 /* passno= */ -1,
1446 /* prefix_sysroot= */ !m->for_initrd && in_initrd(),
1447 /* accept_root= */ true,
1448 /* use_swap_enabled= */ false));
1449 }
1450
1451 return r;
1452 }
1453
1454 static int add_mounts_from_creds(bool prefix_sysroot) {
1455 _cleanup_free_ void *b = NULL;
1456 size_t bs;
1457 const char *cred;
1458 int r, ret = 0;
1459
1460 assert(in_initrd() || !prefix_sysroot);
1461
1462 cred = in_initrd() && !prefix_sysroot ? "fstab.extra.initrd" : "fstab.extra";
1463
1464 r = read_credential_with_decryption(cred, &b, &bs);
1465 if (r <= 0)
1466 return r;
1467
1468 _cleanup_fclose_ FILE *f = NULL;
1469 f = fmemopen_unlocked(b, bs, "r");
1470 if (!f)
1471 return log_oom();
1472
1473 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
1474 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
1475
1476 r = libmount_parse_full(cred, f, MNT_ITER_FORWARD, &table, &iter);
1477 if (r < 0)
1478 return log_error_errno(r, "Failed to parse credential '%s' (as fstab): %m", cred);
1479
1480 for (;;) {
1481 struct libmnt_fs *fs;
1482
1483 r = sym_mnt_table_next_fs(table, iter, &fs);
1484 if (r < 0)
1485 return log_error_errno(r, "Failed to get next fstab entry from credential '%s': %m", cred);
1486 if (r > 0) /* EOF */
1487 return ret;
1488
1489 RET_GATHER(ret, parse_fstab_one(
1490 "/run/credentials",
1491 sym_mnt_fs_get_source(fs),
1492 sym_mnt_fs_get_target(fs),
1493 sym_mnt_fs_get_fstype(fs),
1494 sym_mnt_fs_get_options(fs),
1495 sym_mnt_fs_get_passno(fs),
1496 prefix_sysroot,
1497 /* accept_root= */ true,
1498 /* use_swap_enabled= */ true));
1499 }
1500 }
1501
1502 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
1503 int r;
1504
1505 assert(key);
1506
1507 /* root=, usr=, usrfstype= and roofstype= may occur more than once, the last
1508 * instance should take precedence. In the case of multiple rootflags=
1509 * or usrflags= the arguments should be concatenated */
1510
1511 if (STR_IN_SET(key, "fstab", "rd.fstab")) {
1512
1513 r = value ? parse_boolean(value) : 1;
1514 if (r < 0)
1515 log_warning("Failed to parse fstab switch %s. Ignoring.", value);
1516 else
1517 arg_fstab_enabled = fstab_set_enabled(r);
1518
1519 } else if (streq(key, "root")) {
1520
1521 if (proc_cmdline_value_missing(key, value))
1522 return 0;
1523
1524 return free_and_strdup_warn(&arg_root_what, empty_to_null(value));
1525
1526 } else if (streq(key, "rootfstype")) {
1527
1528 if (proc_cmdline_value_missing(key, value))
1529 return 0;
1530
1531 return free_and_strdup_warn(&arg_root_fstype, empty_to_null(value));
1532
1533 } else if (streq(key, "rootflags")) {
1534
1535 if (proc_cmdline_value_missing(key, value))
1536 return 0;
1537
1538 if (!strextend_with_separator(&arg_root_options, ",", value))
1539 return log_oom();
1540
1541 } else if (streq(key, "roothash")) {
1542
1543 if (proc_cmdline_value_missing(key, value))
1544 return 0;
1545
1546 return free_and_strdup_warn(&arg_root_hash, empty_to_null(value));
1547
1548 } else if (streq(key, "mount.usr")) {
1549
1550 if (proc_cmdline_value_missing(key, value))
1551 return 0;
1552
1553 return free_and_strdup_warn(&arg_usr_what, empty_to_null(value));
1554
1555 } else if (streq(key, "mount.usrfstype")) {
1556
1557 if (proc_cmdline_value_missing(key, value))
1558 return 0;
1559
1560 return free_and_strdup_warn(&arg_usr_fstype, empty_to_null(value));
1561
1562 } else if (streq(key, "mount.usrflags")) {
1563
1564 if (proc_cmdline_value_missing(key, value))
1565 return 0;
1566
1567 if (!strextend_with_separator(&arg_usr_options, ",", value))
1568 return log_oom();
1569
1570 } else if (streq(key, "usrhash")) {
1571
1572 if (proc_cmdline_value_missing(key, value))
1573 return 0;
1574
1575 return free_and_strdup_warn(&arg_usr_hash, empty_to_null(value));
1576
1577 } else if (streq(key, "rw") && !value)
1578 arg_root_rw = true;
1579 else if (streq(key, "ro") && !value)
1580 arg_root_rw = false;
1581 else if (streq(key, "systemd.volatile")) {
1582 VolatileMode m;
1583
1584 if (value) {
1585 m = volatile_mode_from_string(value);
1586 if (m < 0)
1587 log_warning_errno(m, "Failed to parse systemd.volatile= argument: %s", value);
1588 else
1589 arg_volatile_mode = m;
1590 } else
1591 arg_volatile_mode = VOLATILE_YES;
1592
1593 } else if (streq(key, "systemd.swap")) {
1594
1595 r = value ? parse_boolean(value) : 1;
1596 if (r < 0)
1597 log_warning("Failed to parse systemd.swap switch %s. Ignoring.", value);
1598 else
1599 arg_swap_enabled = r;
1600
1601 } else if (streq(key, "systemd.verity")) {
1602
1603 r = value ? parse_boolean(value) : 1;
1604 if (r < 0)
1605 log_warning("Failed to parse systemd.verity= kernel command line switch %s. Ignoring.", value);
1606 else
1607 arg_verity = r;
1608
1609 } else if (STR_IN_SET(key, "systemd.mount-extra", "rd.systemd.mount-extra")) {
1610
1611 if (proc_cmdline_value_missing(key, value))
1612 return 0;
1613
1614 r = mount_array_add(startswith(key, "rd."), value);
1615 if (r < 0)
1616 log_warning("Failed to parse systemd.mount-extra= option, ignoring: %s", value);
1617
1618 } else if (STR_IN_SET(key, "systemd.swap-extra", "rd.systemd.swap-extra")) {
1619
1620 if (proc_cmdline_value_missing(key, value))
1621 return 0;
1622
1623 r = mount_array_add_swap(startswith(key, "rd."), value);
1624 if (r < 0)
1625 log_warning("Failed to parse systemd.swap-extra= option, ignoring: %s", value);
1626 }
1627
1628 return 0;
1629 }
1630
1631 static int determine_device(
1632 char **what,
1633 int *rw,
1634 char **options,
1635 const char *hash,
1636 const char *name) {
1637
1638 assert(what);
1639 assert(name);
1640
1641 /* If we have a hash but no device then Verity is used, and we use the DM device. */
1642 if (*what)
1643 return 0;
1644
1645 if (!hash)
1646 return 0;
1647
1648 if (!arg_verity)
1649 return 0;
1650
1651 *what = path_join("/dev/mapper/", name);
1652 if (!*what)
1653 return log_oom();
1654
1655 /* Verity is always read-only */
1656 if (rw)
1657 *rw = false;
1658 if (options && !strextend_with_separator(options, ",", "ro"))
1659 return log_oom();
1660
1661 log_info("Using verity %s device %s.", name, *what);
1662 return 1;
1663 }
1664
1665 static int determine_root(void) {
1666 return determine_device(&arg_root_what, &arg_root_rw, NULL, arg_root_hash, "root");
1667 }
1668
1669 static int determine_usr(void) {
1670 return determine_device(&arg_usr_what, NULL, &arg_usr_options, arg_usr_hash, "usr");
1671 }
1672
1673 /* If arg_sysroot_check is false, run as generator in the usual fashion.
1674 * If it is true, check /sysroot/etc/fstab for any units that we'd want to mount
1675 * in the initrd, and call daemon-reload. We will get reinvoked as a generator,
1676 * with /sysroot/etc/fstab available, and then we can write additional units based
1677 * on that file. */
1678 static int run_generator(void) {
1679 int r;
1680
1681 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
1682 if (r < 0)
1683 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
1684
1685 (void) determine_root();
1686 (void) determine_usr();
1687
1688 if (arg_sysroot_check) {
1689 r = parse_fstab(/* prefix_sysroot= */ true);
1690 if (r == 0)
1691 log_debug("Nothing interesting found, not doing daemon-reload.");
1692 if (r > 0)
1693 r = do_daemon_reload();
1694 return r;
1695 }
1696
1697 r = 0;
1698
1699 /* Always honour root= and usr= in the kernel command line if we are in an initrd */
1700 if (in_initrd()) {
1701 RET_GATHER(r, add_sysroot_mount());
1702
1703 RET_GATHER(r, add_sysroot_usr_mount_or_fallback());
1704
1705 RET_GATHER(r, add_volatile_root());
1706 } else
1707 RET_GATHER(r, add_volatile_var());
1708
1709 /* Honour /etc/fstab only when that's enabled */
1710 if (arg_fstab_enabled) {
1711 /* Parse the local /etc/fstab, possibly from the initrd */
1712 RET_GATHER(r, parse_fstab(/* prefix_sysroot= */ false));
1713
1714 /* If running in the initrd also parse the /etc/fstab from the host */
1715 if (in_initrd())
1716 RET_GATHER(r, parse_fstab(/* prefix_sysroot= */ true));
1717 else
1718 RET_GATHER(r, generator_enable_remount_fs_service(arg_dest));
1719 }
1720
1721 RET_GATHER(r, add_mounts_from_cmdline());
1722
1723 RET_GATHER(r, add_mounts_from_creds(/* prefix_sysroot= */ false));
1724
1725 if (in_initrd())
1726 RET_GATHER(r, add_mounts_from_creds(/* prefix_sysroot= */ true));
1727
1728 return r;
1729 }
1730
1731 static int run(int argc, char **argv) {
1732 arg_sysroot_check = invoked_as(argv, "systemd-sysroot-fstab-check");
1733
1734 if (arg_sysroot_check) {
1735 /* Run as in systemd-sysroot-fstab-check mode */
1736 log_setup();
1737
1738 if (strv_length(argv) > 1)
1739 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1740 "This program takes no arguments.");
1741 if (!in_initrd())
1742 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1743 "This program is only useful in the initrd.");
1744 } else {
1745 /* Run in generator mode */
1746 log_setup_generator();
1747
1748 if (!IN_SET(strv_length(argv), 2, 4))
1749 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1750 "This program takes one or three arguments.");
1751
1752 arg_dest = ASSERT_PTR(argv[1]);
1753 arg_dest_late = ASSERT_PTR(argv[argc > 3 ? 3 : 1]);
1754 }
1755
1756 return run_generator();
1757 }
1758
1759 DEFINE_MAIN_FUNCTION(run);