]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/gpt-auto-generator/gpt-auto-generator.c
Merge pull request #9832 from yuwata/fix-9831
[thirdparty/systemd.git] / src / gpt-auto-generator / gpt-auto-generator.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <blkid.h>
4 #include <stdlib.h>
5 #include <sys/statfs.h>
6 #include <unistd.h>
7
8 #include "sd-device.h"
9 #include "sd-id128.h"
10
11 #include "alloc-util.h"
12 #include "blkid-util.h"
13 #include "blockdev-util.h"
14 #include "btrfs-util.h"
15 #include "dirent-util.h"
16 #include "dissect-image.h"
17 #include "efivars.h"
18 #include "fd-util.h"
19 #include "fileio.h"
20 #include "fstab-util.h"
21 #include "generator.h"
22 #include "gpt.h"
23 #include "missing.h"
24 #include "mkdir.h"
25 #include "mount-util.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "proc-cmdline.h"
29 #include "special.h"
30 #include "specifier.h"
31 #include "stat-util.h"
32 #include "string-util.h"
33 #include "strv.h"
34 #include "unit-name.h"
35 #include "util.h"
36 #include "virt.h"
37
38 static const char *arg_dest = "/tmp";
39 static bool arg_enabled = true;
40 static bool arg_root_enabled = true;
41 static bool arg_root_rw = false;
42
43 static int add_cryptsetup(const char *id, const char *what, bool rw, bool require, char **device) {
44 _cleanup_free_ char *e = NULL, *n = NULL, *d = NULL, *id_escaped = NULL, *what_escaped = NULL;
45 _cleanup_fclose_ FILE *f = NULL;
46 const char *p;
47 int r;
48
49 assert(id);
50 assert(what);
51
52 r = unit_name_from_path(what, ".device", &d);
53 if (r < 0)
54 return log_error_errno(r, "Failed to generate unit name: %m");
55
56 e = unit_name_escape(id);
57 if (!e)
58 return log_oom();
59
60 r = unit_name_build("systemd-cryptsetup", e, ".service", &n);
61 if (r < 0)
62 return log_error_errno(r, "Failed to generate unit name: %m");
63
64 id_escaped = specifier_escape(id);
65 if (!id_escaped)
66 return log_oom();
67
68 what_escaped = specifier_escape(what);
69 if (!what_escaped)
70 return log_oom();
71
72 p = strjoina(arg_dest, "/", n);
73 f = fopen(p, "wxe");
74 if (!f)
75 return log_error_errno(errno, "Failed to create unit file %s: %m", p);
76
77 fprintf(f,
78 "# Automatically generated by systemd-gpt-auto-generator\n\n"
79 "[Unit]\n"
80 "Description=Cryptography Setup for %%I\n"
81 "Documentation=man:systemd-gpt-auto-generator(8) man:systemd-cryptsetup@.service(8)\n"
82 "DefaultDependencies=no\n"
83 "Conflicts=umount.target\n"
84 "BindsTo=dev-mapper-%%i.device %s\n"
85 "Before=umount.target cryptsetup.target\n"
86 "After=%s\n"
87 "IgnoreOnIsolate=true\n"
88 "[Service]\n"
89 "Type=oneshot\n"
90 "RemainAfterExit=yes\n"
91 "TimeoutSec=0\n" /* the binary handles timeouts anyway */
92 "KeyringMode=shared\n" /* make sure we can share cached keys among instances */
93 "ExecStart=" SYSTEMD_CRYPTSETUP_PATH " attach '%s' '%s' '' '%s'\n"
94 "ExecStop=" SYSTEMD_CRYPTSETUP_PATH " detach '%s'\n",
95 d, d,
96 id_escaped, what_escaped, rw ? "" : "read-only",
97 id_escaped);
98
99 r = fflush_and_check(f);
100 if (r < 0)
101 return log_error_errno(r, "Failed to write file %s: %m", p);
102
103 r = generator_add_symlink(arg_dest, d, "wants", n);
104 if (r < 0)
105 return r;
106
107 if (require) {
108 const char *dmname;
109
110 r = generator_add_symlink(arg_dest, "cryptsetup.target", "requires", n);
111 if (r < 0)
112 return r;
113
114 dmname = strjoina("dev-mapper-", e, ".device");
115 r = generator_add_symlink(arg_dest, dmname, "requires", n);
116 if (r < 0)
117 return r;
118 }
119
120 p = strjoina(arg_dest, "/dev-mapper-", e, ".device.d/50-job-timeout-sec-0.conf");
121 mkdir_parents_label(p, 0755);
122 r = write_string_file(p,
123 "# Automatically generated by systemd-gpt-auto-generator\n\n"
124 "[Unit]\n"
125 "JobTimeoutSec=0\n",
126 WRITE_STRING_FILE_CREATE); /* the binary handles timeouts anyway */
127 if (r < 0)
128 return log_error_errno(r, "Failed to write device drop-in: %m");
129
130 if (device) {
131 char *ret;
132
133 ret = strappend("/dev/mapper/", id);
134 if (!ret)
135 return log_oom();
136
137 *device = ret;
138 }
139
140 return 0;
141 }
142
143 static int add_mount(
144 const char *id,
145 const char *what,
146 const char *where,
147 const char *fstype,
148 bool rw,
149 const char *options,
150 const char *description,
151 const char *post) {
152
153 _cleanup_free_ char *unit = NULL, *crypto_what = NULL, *p = NULL;
154 _cleanup_fclose_ FILE *f = NULL;
155 int r;
156
157 /* Note that we don't apply specifier escaping on the input strings here, since we know they are not configured
158 * externally, but all originate from our own sources here, and hence we know they contain no % characters that
159 * could potentially be understood as specifiers. */
160
161 assert(id);
162 assert(what);
163 assert(where);
164 assert(description);
165
166 log_debug("Adding %s: %s %s", where, what, strna(fstype));
167
168 if (streq_ptr(fstype, "crypto_LUKS")) {
169
170 r = add_cryptsetup(id, what, rw, true, &crypto_what);
171 if (r < 0)
172 return r;
173
174 what = crypto_what;
175 fstype = NULL;
176 }
177
178 r = unit_name_from_path(where, ".mount", &unit);
179 if (r < 0)
180 return log_error_errno(r, "Failed to generate unit name: %m");
181
182 p = strjoin(arg_dest, "/", unit);
183 if (!p)
184 return log_oom();
185
186 f = fopen(p, "wxe");
187 if (!f)
188 return log_error_errno(errno, "Failed to create unit file %s: %m", unit);
189
190 fprintf(f,
191 "# Automatically generated by systemd-gpt-auto-generator\n\n"
192 "[Unit]\n"
193 "Description=%s\n"
194 "Documentation=man:systemd-gpt-auto-generator(8)\n",
195 description);
196
197 if (post)
198 fprintf(f, "Before=%s\n", post);
199
200 r = generator_write_fsck_deps(f, arg_dest, what, where, fstype);
201 if (r < 0)
202 return r;
203
204 fprintf(f,
205 "\n"
206 "[Mount]\n"
207 "What=%s\n"
208 "Where=%s\n",
209 what, where);
210
211 if (fstype)
212 fprintf(f, "Type=%s\n", fstype);
213
214 if (options)
215 fprintf(f, "Options=%s,%s\n", options, rw ? "rw" : "ro");
216 else
217 fprintf(f, "Options=%s\n", rw ? "rw" : "ro");
218
219 r = fflush_and_check(f);
220 if (r < 0)
221 return log_error_errno(r, "Failed to write unit file %s: %m", p);
222
223 if (post)
224 return generator_add_symlink(arg_dest, post, "requires", unit);
225 return 0;
226 }
227
228 static int path_is_busy(const char *where) {
229 int r;
230
231 /* already a mountpoint; generators run during reload */
232 r = path_is_mount_point(where, NULL, AT_SYMLINK_FOLLOW);
233 if (r > 0)
234 return false;
235
236 /* the directory might not exist on a stateless system */
237 if (r == -ENOENT)
238 return false;
239
240 if (r < 0)
241 return log_warning_errno(r, "Cannot check if \"%s\" is a mount point: %m", where);
242
243 /* not a mountpoint but it contains files */
244 r = dir_is_empty(where);
245 if (r < 0)
246 return log_warning_errno(r, "Cannot check if \"%s\" is empty: %m", where);
247 if (r > 0)
248 return false;
249
250 log_debug("\"%s\" already populated, ignoring.", where);
251 return true;
252 }
253
254 static int add_partition_mount(
255 DissectedPartition *p,
256 const char *id,
257 const char *where,
258 const char *description) {
259
260 int r;
261 assert(p);
262
263 r = path_is_busy(where);
264 if (r != 0)
265 return r < 0 ? r : 0;
266
267 return add_mount(
268 id,
269 p->node,
270 where,
271 p->fstype,
272 p->rw,
273 NULL,
274 description,
275 SPECIAL_LOCAL_FS_TARGET);
276 }
277
278 static int add_swap(const char *path) {
279 _cleanup_free_ char *name = NULL, *unit = NULL;
280 _cleanup_fclose_ FILE *f = NULL;
281 int r;
282
283 assert(path);
284
285 /* Disable the swap auto logic if at least one swap is defined in /etc/fstab, see #6192. */
286 r = fstab_has_fstype("swap");
287 if (r < 0)
288 return log_error_errno(r, "Failed to parse fstab: %m");
289 if (r > 0) {
290 log_debug("swap specified in fstab, ignoring.");
291 return 0;
292 }
293
294 log_debug("Adding swap: %s", path);
295
296 r = unit_name_from_path(path, ".swap", &name);
297 if (r < 0)
298 return log_error_errno(r, "Failed to generate unit name: %m");
299
300 unit = strjoin(arg_dest, "/", name);
301 if (!unit)
302 return log_oom();
303
304 f = fopen(unit, "wxe");
305 if (!f)
306 return log_error_errno(errno, "Failed to create unit file %s: %m", unit);
307
308 fprintf(f,
309 "# Automatically generated by systemd-gpt-auto-generator\n\n"
310 "[Unit]\n"
311 "Description=Swap Partition\n"
312 "Documentation=man:systemd-gpt-auto-generator(8)\n\n"
313 "[Swap]\n"
314 "What=%s\n",
315 path);
316
317 r = fflush_and_check(f);
318 if (r < 0)
319 return log_error_errno(r, "Failed to write unit file %s: %m", unit);
320
321 return generator_add_symlink(arg_dest, SPECIAL_SWAP_TARGET, "wants", name);
322 }
323
324 #if ENABLE_EFI
325 static int add_automount(
326 const char *id,
327 const char *what,
328 const char *where,
329 const char *fstype,
330 bool rw,
331 const char *options,
332 const char *description,
333 usec_t timeout) {
334
335 _cleanup_free_ char *unit = NULL;
336 _cleanup_fclose_ FILE *f = NULL;
337 const char *opt = "noauto", *p;
338 int r;
339
340 assert(id);
341 assert(where);
342 assert(description);
343
344 if (options)
345 opt = strjoina(options, ",", opt);
346
347 r = add_mount(id,
348 what,
349 where,
350 fstype,
351 rw,
352 opt,
353 description,
354 NULL);
355 if (r < 0)
356 return r;
357
358 r = unit_name_from_path(where, ".automount", &unit);
359 if (r < 0)
360 return log_error_errno(r, "Failed to generate unit name: %m");
361
362 p = strjoina(arg_dest, "/", unit);
363 f = fopen(p, "wxe");
364 if (!f)
365 return log_error_errno(errno, "Failed to create unit file %s: %m", unit);
366
367 fprintf(f,
368 "# Automatically generated by systemd-gpt-auto-generator\n\n"
369 "[Unit]\n"
370 "Description=%s\n"
371 "Documentation=man:systemd-gpt-auto-generator(8)\n"
372 "[Automount]\n"
373 "Where=%s\n"
374 "TimeoutIdleSec="USEC_FMT"\n",
375 description,
376 where,
377 timeout / USEC_PER_SEC);
378
379 r = fflush_and_check(f);
380 if (r < 0)
381 return log_error_errno(r, "Failed to write unit file %s: %m", p);
382
383 return generator_add_symlink(arg_dest, SPECIAL_LOCAL_FS_TARGET, "wants", unit);
384 }
385
386 static int add_esp(DissectedPartition *p) {
387 const char *esp;
388 int r;
389
390 assert(p);
391
392 if (in_initrd()) {
393 log_debug("In initrd, ignoring the ESP.");
394 return 0;
395 }
396
397 /* If /efi exists we'll use that. Otherwise we'll use /boot, as that's usually the better choice */
398 esp = access("/efi/", F_OK) >= 0 ? "/efi" : "/boot";
399
400 /* We create an .automount which is not overridden by the .mount from the fstab generator. */
401 r = fstab_is_mount_point(esp);
402 if (r < 0)
403 return log_error_errno(r, "Failed to parse fstab: %m");
404 if (r > 0) {
405 log_debug("%s specified in fstab, ignoring.", esp);
406 return 0;
407 }
408
409 r = path_is_busy(esp);
410 if (r != 0)
411 return r < 0 ? r : 0;
412
413 if (is_efi_boot()) {
414 sd_id128_t loader_uuid;
415
416 /* If this is an EFI boot, be extra careful, and only mount the ESP if it was the ESP used for booting. */
417
418 r = efi_loader_get_device_part_uuid(&loader_uuid);
419 if (r == -ENOENT) {
420 log_debug("EFI loader partition unknown.");
421 return 0;
422 }
423 if (r < 0)
424 return log_error_errno(r, "Failed to read ESP partition UUID: %m");
425
426 if (!sd_id128_equal(p->uuid, loader_uuid)) {
427 log_debug("Partition for %s does not appear to be the partition we are booted from.", esp);
428 return 0;
429 }
430 } else
431 log_debug("Not an EFI boot, skipping ESP check.");
432
433 return add_automount("boot",
434 p->node,
435 esp,
436 p->fstype,
437 true,
438 "umask=0077",
439 "EFI System Partition Automount",
440 120 * USEC_PER_SEC);
441 }
442 #else
443 static int add_esp(DissectedPartition *p) {
444 return 0;
445 }
446 #endif
447
448 static int open_parent(dev_t devnum, int *ret) {
449 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
450 const char *name, *devtype, *node;
451 sd_device *parent;
452 dev_t pn;
453 int fd, r;
454
455 assert(ret);
456
457 r = sd_device_new_from_devnum(&d, 'b', devnum);
458 if (r < 0)
459 return log_debug_errno(r, "Failed to open device: %m");
460
461 if (sd_device_get_devname(d, &name) < 0) {
462 r = sd_device_get_syspath(d, &name);
463 if (r < 0) {
464 log_debug_errno(r, "Device %u:%u does not have a name, ignoring: %m", major(devnum), minor(devnum));
465 goto not_found;
466 }
467 }
468
469 r = sd_device_get_parent(d, &parent);
470 if (r < 0) {
471 log_debug_errno(r, "%s: not a partitioned device, ignoring: %m", name);
472 goto not_found;
473 }
474
475 /* Does it have a devtype? */
476 r = sd_device_get_devtype(parent, &devtype);
477 if (r < 0) {
478 log_debug_errno(r, "%s: parent doesn't have a device type, ignoring: %m", name);
479 goto not_found;
480 }
481
482 /* Is this a disk or a partition? We only care for disks... */
483 if (!streq(devtype, "disk")) {
484 log_debug("%s: parent isn't a raw disk, ignoring.", name);
485 goto not_found;
486 }
487
488 /* Does it have a device node? */
489 r = sd_device_get_devname(parent, &node);
490 if (r < 0) {
491 log_debug_errno(r, "%s: parent device does not have device node, ignoring: %m", name);
492 goto not_found;
493 }
494
495 log_debug("%s: root device %s.", name, node);
496
497 r = sd_device_get_devnum(parent, &pn);
498 if (r < 0) {
499 log_debug_errno(r, "%s: parent device is not a proper block device, ignoring: %m", name);
500 goto not_found;
501 }
502
503 fd = open(node, O_RDONLY|O_CLOEXEC|O_NOCTTY);
504 if (fd < 0)
505 return log_error_errno(errno, "Failed to open %s: %m", node);
506
507 *ret = fd;
508 return 1;
509
510 not_found:
511 *ret = -1;
512 return 0;
513 }
514
515 static int enumerate_partitions(dev_t devnum) {
516
517 _cleanup_close_ int fd = -1;
518 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
519 int r, k;
520
521 r = open_parent(devnum, &fd);
522 if (r <= 0)
523 return r;
524
525 r = dissect_image(fd, NULL, 0, DISSECT_IMAGE_GPT_ONLY, &m);
526 if (r == -ENOPKG) {
527 log_debug_errno(r, "No suitable partition table found, ignoring.");
528 return 0;
529 }
530 if (r < 0)
531 return log_error_errno(r, "Failed to dissect: %m");
532
533 if (m->partitions[PARTITION_SWAP].found) {
534 k = add_swap(m->partitions[PARTITION_SWAP].node);
535 if (k < 0)
536 r = k;
537 }
538
539 if (m->partitions[PARTITION_ESP].found) {
540 k = add_esp(m->partitions + PARTITION_ESP);
541 if (k < 0)
542 r = k;
543 }
544
545 if (m->partitions[PARTITION_HOME].found) {
546 k = add_partition_mount(m->partitions + PARTITION_HOME, "home", "/home", "Home Partition");
547 if (k < 0)
548 r = k;
549 }
550
551 if (m->partitions[PARTITION_SRV].found) {
552 k = add_partition_mount(m->partitions + PARTITION_SRV, "srv", "/srv", "Server Data Partition");
553 if (k < 0)
554 r = k;
555 }
556
557 return r;
558 }
559
560 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
561 int r;
562
563 assert(key);
564
565 if (STR_IN_SET(key, "systemd.gpt_auto", "rd.systemd.gpt_auto")) {
566
567 r = value ? parse_boolean(value) : 1;
568 if (r < 0)
569 log_warning("Failed to parse gpt-auto switch \"%s\". Ignoring.", value);
570 else
571 arg_enabled = r;
572
573 } else if (streq(key, "root")) {
574
575 if (proc_cmdline_value_missing(key, value))
576 return 0;
577
578 /* Disable root disk logic if there's a root= value
579 * specified (unless it happens to be "gpt-auto") */
580
581 arg_root_enabled = streq(value, "gpt-auto");
582
583 } else if (streq(key, "roothash")) {
584
585 if (proc_cmdline_value_missing(key, value))
586 return 0;
587
588 /* Disable root disk logic if there's roothash= defined (i.e. verity enabled) */
589
590 arg_root_enabled = false;
591
592 } else if (streq(key, "rw") && !value)
593 arg_root_rw = true;
594 else if (streq(key, "ro") && !value)
595 arg_root_rw = false;
596
597 return 0;
598 }
599
600 #if ENABLE_EFI
601 static int add_root_cryptsetup(void) {
602
603 /* If a device /dev/gpt-auto-root-luks appears, then make it pull in systemd-cryptsetup-root.service, which
604 * sets it up, and causes /dev/gpt-auto-root to appear which is all we are looking for. */
605
606 return add_cryptsetup("root", "/dev/gpt-auto-root-luks", true, false, NULL);
607 }
608 #endif
609
610 static int add_root_mount(void) {
611
612 #if ENABLE_EFI
613 int r;
614
615 if (!is_efi_boot()) {
616 log_debug("Not a EFI boot, not creating root mount.");
617 return 0;
618 }
619
620 r = efi_loader_get_device_part_uuid(NULL);
621 if (r == -ENOENT) {
622 log_debug("EFI loader partition unknown, exiting.");
623 return 0;
624 } else if (r < 0)
625 return log_error_errno(r, "Failed to read ESP partition UUID: %m");
626
627 /* OK, we have an ESP partition, this is fantastic, so let's
628 * wait for a root device to show up. A udev rule will create
629 * the link for us under the right name. */
630
631 if (in_initrd()) {
632 r = generator_write_initrd_root_device_deps(arg_dest, "/dev/gpt-auto-root");
633 if (r < 0)
634 return 0;
635
636 r = add_root_cryptsetup();
637 if (r < 0)
638 return r;
639 }
640
641 return add_mount(
642 "root",
643 "/dev/gpt-auto-root",
644 in_initrd() ? "/sysroot" : "/",
645 NULL,
646 arg_root_rw,
647 NULL,
648 "Root Partition",
649 in_initrd() ? SPECIAL_INITRD_ROOT_FS_TARGET : SPECIAL_LOCAL_FS_TARGET);
650 #else
651 return 0;
652 #endif
653 }
654
655 static int add_mounts(void) {
656 dev_t devno;
657 int r;
658
659 r = get_block_device_harder("/", &devno);
660 if (r < 0)
661 return log_error_errno(r, "Failed to determine block device of root file system: %m");
662 if (r == 0) {
663 r = get_block_device_harder("/usr", &devno);
664 if (r < 0)
665 return log_error_errno(r, "Failed to determine block device of /usr file system: %m");
666 if (r == 0) {
667 log_debug("Neither root nor /usr file system are on a (single) block device.");
668 return 0;
669 }
670 }
671
672 return enumerate_partitions(devno);
673 }
674
675 int main(int argc, char *argv[]) {
676 int r, k;
677
678 if (argc > 1 && argc != 4) {
679 log_error("This program takes three or no arguments.");
680 return EXIT_FAILURE;
681 }
682
683 if (argc > 1)
684 arg_dest = argv[3];
685
686 log_set_prohibit_ipc(true);
687 log_set_target(LOG_TARGET_AUTO);
688 log_parse_environment();
689 log_open();
690
691 umask(0022);
692
693 if (detect_container() > 0) {
694 log_debug("In a container, exiting.");
695 return EXIT_SUCCESS;
696 }
697
698 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
699 if (r < 0)
700 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
701
702 if (!arg_enabled) {
703 log_debug("Disabled, exiting.");
704 return EXIT_SUCCESS;
705 }
706
707 if (arg_root_enabled)
708 r = add_root_mount();
709 else
710 r = 0;
711
712 if (!in_initrd()) {
713 k = add_mounts();
714 if (k < 0)
715 r = k;
716 }
717
718 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
719 }