]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/dissect-image.c
gpt: add definition for boot loader spec partition
[thirdparty/systemd.git] / src / shared / dissect-image.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
8c1be37e
LP
2
3#include <sys/mount.h>
3b925504
LP
4#include <sys/prctl.h>
5#include <sys/wait.h>
8c1be37e 6
3c1f2cee 7#include "sd-device.h"
dccca82b
LP
8#include "sd-id128.h"
9
8c1be37e 10#include "architecture.h"
18b5886e 11#include "ask-password-api.h"
8c1be37e 12#include "blkid-util.h"
18c528e9 13#include "blockdev-util.h"
3b925504 14#include "copy.h"
294bd454 15#include "crypt-util.h"
3b925504 16#include "def.h"
553e15f2 17#include "device-nodes.h"
8437c059 18#include "device-util.h"
8c1be37e 19#include "dissect-image.h"
686d13b9 20#include "env-file.h"
18b5886e 21#include "fd-util.h"
78ebe980 22#include "fileio.h"
2eedfd2d 23#include "fs-util.h"
8c1be37e 24#include "gpt.h"
78ebe980 25#include "hexdecoct.h"
3b925504
LP
26#include "hostname-util.h"
27#include "id128-util.h"
dcce98a4 28#include "linux-3.13/dm-ioctl.h"
ffc01f06 29#include "missing.h"
8c1be37e 30#include "mount-util.h"
e4de7287 31#include "mountpoint-util.h"
d58ad743 32#include "os-util.h"
8c1be37e 33#include "path-util.h"
3b925504
LP
34#include "process-util.h"
35#include "raw-clone.h"
36#include "signal-util.h"
8c1be37e 37#include "stat-util.h"
18b5886e 38#include "stdio-util.h"
8c1be37e
LP
39#include "string-table.h"
40#include "string-util.h"
2eedfd2d 41#include "strv.h"
e4de7287 42#include "tmpfile-util.h"
a8040b6d 43#include "udev-util.h"
2d3a5a73 44#include "user-util.h"
41488e1f 45#include "xattr-util.h"
8c1be37e 46
c34b75a1 47int probe_filesystem(const char *node, char **ret_fstype) {
7cc84b2c
ZJS
48 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
49 * 0/NULL will be returned. -EUCLEAN will be returned for ambigous results, and an
50 * different error otherwise. */
51
349cc4a5 52#if HAVE_BLKID
8e766630 53 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
18b5886e
LP
54 const char *fstype;
55 int r;
56
995fa2e5 57 errno = 0;
18b5886e
LP
58 b = blkid_new_probe_from_filename(node);
59 if (!b)
995fa2e5 60 return -errno ?: -ENOMEM;
18b5886e
LP
61
62 blkid_probe_enable_superblocks(b, 1);
63 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
64
65 errno = 0;
66 r = blkid_do_safeprobe(b);
7cc84b2c
ZJS
67 if (r == 1) {
68 log_debug("No type detected on partition %s", node);
18b5886e
LP
69 goto not_found;
70 }
7cc84b2c
ZJS
71 if (r == -2) {
72 log_debug("Results ambiguous for partition %s", node);
73 return -EUCLEAN;
74 }
b382db9f
ZJS
75 if (r != 0)
76 return -errno ?: -EIO;
18b5886e
LP
77
78 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
79
80 if (fstype) {
81 char *t;
82
83 t = strdup(fstype);
84 if (!t)
85 return -ENOMEM;
86
87 *ret_fstype = t;
88 return 1;
89 }
90
91not_found:
92 *ret_fstype = NULL;
93 return 0;
d1c536f5
ZJS
94#else
95 return -EOPNOTSUPP;
a75e27eb 96#endif
d1c536f5 97}
18b5886e 98
40c10d3f 99#if HAVE_BLKID
cde942f6
JPRV
100/* Detect RPMB and Boot partitions, which are not listed by blkid.
101 * See https://github.com/systemd/systemd/issues/5806. */
3c1f2cee 102static bool device_is_mmc_special_partition(sd_device *d) {
aae22eb3
LP
103 const char *sysname;
104
f70e7f70
LP
105 assert(d);
106
3c1f2cee
YW
107 if (sd_device_get_sysname(d, &sysname) < 0)
108 return false;
109
110 return startswith(sysname, "mmcblk") &&
0cfa78dd 111 (endswith(sysname, "rpmb") || endswith(sysname, "boot0") || endswith(sysname, "boot1"));
cde942f6
JPRV
112}
113
3c1f2cee 114static bool device_is_block(sd_device *d) {
aae22eb3
LP
115 const char *ss;
116
f70e7f70
LP
117 assert(d);
118
3c1f2cee 119 if (sd_device_get_subsystem(d, &ss) < 0)
aae22eb3
LP
120 return false;
121
122 return streq(ss, "block");
123}
ea887be0
ZJS
124
125static int enumerator_for_parent(sd_device *d, sd_device_enumerator **ret) {
126 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
127 int r;
128
f70e7f70
LP
129 assert(d);
130 assert(ret);
131
ea887be0
ZJS
132 r = sd_device_enumerator_new(&e);
133 if (r < 0)
134 return r;
135
136 r = sd_device_enumerator_allow_uninitialized(e);
137 if (r < 0)
138 return r;
139
140 r = sd_device_enumerator_add_match_parent(e, d);
141 if (r < 0)
142 return r;
143
144 *ret = TAKE_PTR(e);
145 return 0;
146}
147
148/* how many times to wait for the device nodes to appear */
149#define N_DEVICE_NODE_LIST_ATTEMPTS 10
150
151static int wait_for_partitions_to_appear(
152 int fd,
153 sd_device *d,
154 unsigned num_partitions,
052eaf5c 155 DissectImageFlags flags,
ea887be0
ZJS
156 sd_device_enumerator **ret_enumerator) {
157
158 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
159 sd_device *q;
160 unsigned n;
161 int r;
162
f70e7f70
LP
163 assert(fd >= 0);
164 assert(d);
165 assert(ret_enumerator);
166
ea887be0
ZJS
167 r = enumerator_for_parent(d, &e);
168 if (r < 0)
169 return r;
170
171 /* Count the partitions enumerated by the kernel */
172 n = 0;
173 FOREACH_DEVICE(e, q) {
174 if (sd_device_get_devnum(q, NULL) < 0)
175 continue;
176 if (!device_is_block(q))
177 continue;
178 if (device_is_mmc_special_partition(q))
179 continue;
180
052eaf5c
LP
181 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
182 r = device_wait_for_initialization(q, "block", NULL);
183 if (r < 0)
184 return r;
185 }
a8040b6d 186
ea887be0
ZJS
187 n++;
188 }
189
190 if (n == num_partitions + 1) {
191 *ret_enumerator = TAKE_PTR(e);
192 return 0; /* success! */
193 }
194 if (n > num_partitions + 1)
195 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
196 "blkid and kernel partition lists do not match.");
197
198 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running or it
199 * got EBUSY because udev already opened the device. Let's reprobe the device, which is a synchronous
200 * call that waits until probing is complete. */
201
202 for (unsigned j = 0; ; j++) {
203 if (j++ > 20)
204 return -EBUSY;
205
206 if (ioctl(fd, BLKRRPART, 0) >= 0)
207 break;
208 r = -errno;
209 if (r == -EINVAL) {
210 struct loop_info64 info;
211
212 /* If we are running on a loop device that has partition scanning off, return
213 * an explicit recognizable error about this, so that callers can generate a
214 * proper message explaining the situation. */
215
216 if (ioctl(fd, LOOP_GET_STATUS64, &info) >= 0 && (info.lo_flags & LO_FLAGS_PARTSCAN) == 0) {
217 log_debug("Device is a loop device and partition scanning is off!");
218 return -EPROTONOSUPPORT;
219 }
220 }
221 if (r != -EBUSY)
222 return r;
223
224 /* If something else has the device open, such as an udev rule, the ioctl will return
225 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a bit,
226 * and try again.
227 *
228 * This is really something they should fix in the kernel! */
229 (void) usleep(50 * USEC_PER_MSEC);
230
231 }
232
233 return -EAGAIN; /* no success yet, try again */
234}
235
236static int loop_wait_for_partitions_to_appear(
237 int fd,
238 sd_device *d,
239 unsigned num_partitions,
052eaf5c 240 DissectImageFlags flags,
ea887be0 241 sd_device_enumerator **ret_enumerator) {
a8040b6d 242 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
ea887be0
ZJS
243 int r;
244
f70e7f70
LP
245 assert(fd >= 0);
246 assert(d);
247 assert(ret_enumerator);
248
b887c8b8
ZJS
249 log_debug("Waiting for device (parent + %d partitions) to appear...", num_partitions);
250
052eaf5c
LP
251 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
252 r = device_wait_for_initialization(d, "block", &device);
253 if (r < 0)
254 return r;
255 } else
256 device = sd_device_ref(d);
a8040b6d 257
ea887be0 258 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
052eaf5c 259 r = wait_for_partitions_to_appear(fd, device, num_partitions, flags, ret_enumerator);
ea887be0
ZJS
260 if (r != -EAGAIN)
261 return r;
262 }
263
264 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO),
265 "Kernel partitions dit not appear within %d attempts",
266 N_DEVICE_NODE_LIST_ATTEMPTS);
267}
268
40c10d3f 269#endif
aae22eb3 270
4526113f
LP
271int dissect_image(
272 int fd,
273 const void *root_hash,
274 size_t root_hash_size,
275 DissectImageFlags flags,
276 DissectedImage **ret) {
8c1be37e 277
349cc4a5 278#if HAVE_BLKID
4623e8e6 279 sd_id128_t root_uuid = SD_ID128_NULL, verity_uuid = SD_ID128_NULL;
3c1f2cee 280 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
8c1be37e 281 bool is_gpt, is_mbr, generic_rw, multiple_generic = false;
3c1f2cee 282 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
8c1be37e 283 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
8e766630 284 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
8c1be37e 285 _cleanup_free_ char *generic_node = NULL;
be30ad41 286 sd_id128_t generic_uuid = SD_ID128_NULL;
9b6deb03 287 const char *pttype = NULL;
8c1be37e
LP
288 blkid_partlist pl;
289 int r, generic_nr;
290 struct stat st;
3c1f2cee 291 sd_device *q;
8c1be37e
LP
292 unsigned i;
293
294 assert(fd >= 0);
295 assert(ret);
4623e8e6 296 assert(root_hash || root_hash_size == 0);
8c1be37e
LP
297
298 /* Probes a disk image, and returns information about what it found in *ret.
299 *
4623e8e6
LP
300 * Returns -ENOPKG if no suitable partition table or file system could be found.
301 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
302
303 if (root_hash) {
304 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
305 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
306 * 128bit. */
307
308 if (root_hash_size < sizeof(sd_id128_t))
309 return -EINVAL;
310
311 memcpy(&root_uuid, root_hash, sizeof(sd_id128_t));
312 memcpy(&verity_uuid, (const uint8_t*) root_hash + root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
313
314 if (sd_id128_is_null(root_uuid))
315 return -EINVAL;
316 if (sd_id128_is_null(verity_uuid))
317 return -EINVAL;
318 }
8c1be37e
LP
319
320 if (fstat(fd, &st) < 0)
321 return -errno;
322
323 if (!S_ISBLK(st.st_mode))
324 return -ENOTBLK;
325
326 b = blkid_new_probe();
327 if (!b)
328 return -ENOMEM;
329
330 errno = 0;
331 r = blkid_probe_set_device(b, fd, 0, 0);
b382db9f
ZJS
332 if (r != 0)
333 return -errno ?: -ENOMEM;
8c1be37e 334
9b6deb03
LP
335 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
336 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
337 blkid_probe_enable_superblocks(b, 1);
338 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
339 }
340
8c1be37e
LP
341 blkid_probe_enable_partitions(b, 1);
342 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
343
344 errno = 0;
345 r = blkid_do_safeprobe(b);
59ba6d0c
LP
346 if (IN_SET(r, -2, 1))
347 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
b382db9f
ZJS
348 if (r != 0)
349 return -errno ?: -EIO;
8c1be37e
LP
350
351 m = new0(DissectedImage, 1);
352 if (!m)
353 return -ENOMEM;
354
b887c8b8
ZJS
355 r = sd_device_new_from_devnum(&d, 'b', st.st_rdev);
356 if (r < 0)
357 return r;
358
e0f9e7bd
LP
359 if (!(flags & DISSECT_IMAGE_GPT_ONLY) &&
360 (flags & DISSECT_IMAGE_REQUIRE_ROOT)) {
9b6deb03 361 const char *usage = NULL;
8c1be37e 362
9b6deb03
LP
363 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
364 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
365 _cleanup_free_ char *t = NULL, *n = NULL;
366 const char *fstype = NULL;
8c1be37e 367
9b6deb03
LP
368 /* OK, we have found a file system, that's our root partition then. */
369 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
8c1be37e 370
9b6deb03
LP
371 if (fstype) {
372 t = strdup(fstype);
373 if (!t)
374 return -ENOMEM;
375 }
376
54b22b26
LP
377 r = device_path_make_major_minor(st.st_mode, st.st_rdev, &n);
378 if (r < 0)
379 return r;
8c1be37e 380
9b6deb03
LP
381 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
382 .found = true,
383 .rw = true,
384 .partno = -1,
385 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a
YW
386 .fstype = TAKE_PTR(t),
387 .node = TAKE_PTR(n),
9b6deb03 388 };
8c1be37e 389
4db1879a 390 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
18b5886e 391
052eaf5c 392 r = loop_wait_for_partitions_to_appear(fd, d, 0, flags, &e);
b887c8b8
ZJS
393 if (r < 0)
394 return r;
395
1cc6c93a 396 *ret = TAKE_PTR(m);
8c1be37e 397
9b6deb03
LP
398 return 0;
399 }
8c1be37e
LP
400 }
401
402 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
403 if (!pttype)
404 return -ENOPKG;
405
406 is_gpt = streq_ptr(pttype, "gpt");
407 is_mbr = streq_ptr(pttype, "dos");
408
9b6deb03 409 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
8c1be37e
LP
410 return -ENOPKG;
411
412 errno = 0;
413 pl = blkid_probe_get_partitions(b);
b382db9f
ZJS
414 if (!pl)
415 return -errno ?: -ENOMEM;
8c1be37e 416
052eaf5c 417 r = loop_wait_for_partitions_to_appear(fd, d, blkid_partlist_numof_partitions(pl), flags, &e);
ea887be0
ZJS
418 if (r < 0)
419 return r;
8c1be37e 420
8437c059 421 FOREACH_DEVICE(e, q) {
9b6deb03 422 unsigned long long pflags;
8c1be37e 423 blkid_partition pp;
cde942f6 424 const char *node;
8c1be37e
LP
425 dev_t qn;
426 int nr;
427
3c1f2cee
YW
428 r = sd_device_get_devnum(q, &qn);
429 if (r < 0)
8c1be37e
LP
430 continue;
431
432 if (st.st_rdev == qn)
433 continue;
434
aae22eb3
LP
435 if (!device_is_block(q))
436 continue;
437
cde942f6 438 if (device_is_mmc_special_partition(q))
7be1420f
LP
439 continue;
440
3c1f2cee
YW
441 r = sd_device_get_devname(q, &node);
442 if (r < 0)
8c1be37e
LP
443 continue;
444
445 pp = blkid_partlist_devno_to_partition(pl, qn);
446 if (!pp)
447 continue;
448
9b6deb03 449 pflags = blkid_partition_get_flags(pp);
8c1be37e
LP
450
451 nr = blkid_partition_get_partno(pp);
452 if (nr < 0)
453 continue;
454
455 if (is_gpt) {
456 int designator = _PARTITION_DESIGNATOR_INVALID, architecture = _ARCHITECTURE_INVALID;
4623e8e6
LP
457 const char *stype, *sid, *fstype = NULL;
458 sd_id128_t type_id, id;
8c1be37e
LP
459 bool rw = true;
460
4623e8e6
LP
461 sid = blkid_partition_get_uuid(pp);
462 if (!sid)
463 continue;
464 if (sd_id128_from_string(sid, &id) < 0)
465 continue;
466
8c1be37e
LP
467 stype = blkid_partition_get_type_string(pp);
468 if (!stype)
469 continue;
8c1be37e
LP
470 if (sd_id128_from_string(stype, &type_id) < 0)
471 continue;
472
473 if (sd_id128_equal(type_id, GPT_HOME)) {
a48dd347
LP
474
475 if (pflags & GPT_FLAG_NO_AUTO)
476 continue;
477
8c1be37e 478 designator = PARTITION_HOME;
9b6deb03 479 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e 480 } else if (sd_id128_equal(type_id, GPT_SRV)) {
a48dd347
LP
481
482 if (pflags & GPT_FLAG_NO_AUTO)
483 continue;
484
8c1be37e 485 designator = PARTITION_SRV;
9b6deb03 486 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e 487 } else if (sd_id128_equal(type_id, GPT_ESP)) {
a48dd347
LP
488
489 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
490 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
491 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
492
493 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
494 continue;
495
8c1be37e
LP
496 designator = PARTITION_ESP;
497 fstype = "vfat";
498 }
499#ifdef GPT_ROOT_NATIVE
500 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
4623e8e6 501
a48dd347
LP
502 if (pflags & GPT_FLAG_NO_AUTO)
503 continue;
504
4623e8e6
LP
505 /* If a root ID is specified, ignore everything but the root id */
506 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
507 continue;
508
8c1be37e
LP
509 designator = PARTITION_ROOT;
510 architecture = native_architecture();
9b6deb03 511 rw = !(pflags & GPT_FLAG_READ_ONLY);
4f8b86e3 512 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
4623e8e6 513
a48dd347
LP
514 if (pflags & GPT_FLAG_NO_AUTO)
515 continue;
516
4623e8e6
LP
517 m->can_verity = true;
518
519 /* Ignore verity unless a root hash is specified */
520 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
521 continue;
522
523 designator = PARTITION_ROOT_VERITY;
524 fstype = "DM_verity_hash";
525 architecture = native_architecture();
526 rw = false;
527 }
528#endif
8c1be37e
LP
529#ifdef GPT_ROOT_SECONDARY
530 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
4623e8e6 531
a48dd347
LP
532 if (pflags & GPT_FLAG_NO_AUTO)
533 continue;
534
4623e8e6
LP
535 /* If a root ID is specified, ignore everything but the root id */
536 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
537 continue;
538
8c1be37e
LP
539 designator = PARTITION_ROOT_SECONDARY;
540 architecture = SECONDARY_ARCHITECTURE;
9b6deb03 541 rw = !(pflags & GPT_FLAG_READ_ONLY);
4f8b86e3 542 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
a48dd347
LP
543
544 if (pflags & GPT_FLAG_NO_AUTO)
545 continue;
546
4623e8e6
LP
547 m->can_verity = true;
548
549 /* Ignore verity unless root has is specified */
550 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
551 continue;
552
553 designator = PARTITION_ROOT_SECONDARY_VERITY;
554 fstype = "DM_verity_hash";
555 architecture = SECONDARY_ARCHITECTURE;
556 rw = false;
557 }
8c1be37e
LP
558#endif
559 else if (sd_id128_equal(type_id, GPT_SWAP)) {
a48dd347
LP
560
561 if (pflags & GPT_FLAG_NO_AUTO)
562 continue;
563
8c1be37e
LP
564 designator = PARTITION_SWAP;
565 fstype = "swap";
566 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
567
a48dd347
LP
568 if (pflags & GPT_FLAG_NO_AUTO)
569 continue;
570
8c1be37e
LP
571 if (generic_node)
572 multiple_generic = true;
573 else {
574 generic_nr = nr;
9b6deb03 575 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
be30ad41 576 generic_uuid = id;
8c1be37e
LP
577 generic_node = strdup(node);
578 if (!generic_node)
579 return -ENOMEM;
580 }
581 }
582
583 if (designator != _PARTITION_DESIGNATOR_INVALID) {
584 _cleanup_free_ char *t = NULL, *n = NULL;
585
586 /* First one wins */
587 if (m->partitions[designator].found)
588 continue;
589
590 if (fstype) {
591 t = strdup(fstype);
592 if (!t)
593 return -ENOMEM;
594 }
595
596 n = strdup(node);
597 if (!n)
598 return -ENOMEM;
599
600 m->partitions[designator] = (DissectedPartition) {
601 .found = true,
602 .partno = nr,
603 .rw = rw,
604 .architecture = architecture,
1cc6c93a
YW
605 .node = TAKE_PTR(n),
606 .fstype = TAKE_PTR(t),
be30ad41 607 .uuid = id,
8c1be37e 608 };
8c1be37e
LP
609 }
610
611 } else if (is_mbr) {
612
9b6deb03 613 if (pflags != 0x80) /* Bootable flag */
8c1be37e
LP
614 continue;
615
616 if (blkid_partition_get_type(pp) != 0x83) /* Linux partition */
617 continue;
618
619 if (generic_node)
620 multiple_generic = true;
621 else {
622 generic_nr = nr;
623 generic_rw = true;
624 generic_node = strdup(node);
625 if (!generic_node)
626 return -ENOMEM;
627 }
628 }
629 }
630
631 if (!m->partitions[PARTITION_ROOT].found) {
632 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
633 * either, then check if there's a single generic one, and use that. */
634
4623e8e6 635 if (m->partitions[PARTITION_ROOT_VERITY].found)
e0f9e7bd 636 return -EADDRNOTAVAIL;
4623e8e6 637
8c1be37e
LP
638 if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
639 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
640 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
4623e8e6
LP
641
642 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
643 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
644
e0f9e7bd
LP
645 } else if (flags & DISSECT_IMAGE_REQUIRE_ROOT) {
646
647 /* If the root has was set, then we won't fallback to a generic node, because the root hash
648 * decides */
649 if (root_hash)
650 return -EADDRNOTAVAIL;
8c1be37e 651
e0f9e7bd
LP
652 /* If we didn't find a generic node, then we can't fix this up either */
653 if (!generic_node)
654 return -ENXIO;
655
656 /* If we didn't find a properly marked root partition, but we did find a single suitable
657 * generic Linux partition, then use this as root partition, if the caller asked for it. */
8c1be37e
LP
658 if (multiple_generic)
659 return -ENOTUNIQ;
660
661 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
662 .found = true,
663 .rw = generic_rw,
664 .partno = generic_nr,
665 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a 666 .node = TAKE_PTR(generic_node),
be30ad41 667 .uuid = generic_uuid,
8c1be37e 668 };
e0f9e7bd 669 }
8c1be37e
LP
670 }
671
4623e8e6 672 if (root_hash) {
e0f9e7bd 673 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
4623e8e6
LP
674 return -EADDRNOTAVAIL;
675
676 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
677 * (which would be weird, after all the root hash should only be assigned to one pair of
678 * partitions... */
679 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
680 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
681
682 /* If we found a verity setup, then the root partition is necessarily read-only. */
683 m->partitions[PARTITION_ROOT].rw = false;
684
685 m->verity = true;
686 }
687
18b5886e
LP
688 blkid_free_probe(b);
689 b = NULL;
690
8c1be37e
LP
691 /* Fill in file system types if we don't know them yet. */
692 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 693 DissectedPartition *p = m->partitions + i;
8c1be37e 694
18b5886e 695 if (!p->found)
8c1be37e
LP
696 continue;
697
18b5886e
LP
698 if (!p->fstype && p->node) {
699 r = probe_filesystem(p->node, &p->fstype);
7cc84b2c 700 if (r < 0 && r != -EUCLEAN)
18b5886e 701 return r;
8c1be37e
LP
702 }
703
18b5886e
LP
704 if (streq_ptr(p->fstype, "crypto_LUKS"))
705 m->encrypted = true;
896f937f
LP
706
707 if (p->fstype && fstype_is_ro(p->fstype))
708 p->rw = false;
8c1be37e
LP
709 }
710
1cc6c93a 711 *ret = TAKE_PTR(m);
8c1be37e
LP
712
713 return 0;
714#else
715 return -EOPNOTSUPP;
716#endif
717}
718
719DissectedImage* dissected_image_unref(DissectedImage *m) {
720 unsigned i;
721
722 if (!m)
723 return NULL;
724
725 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
726 free(m->partitions[i].fstype);
727 free(m->partitions[i].node);
18b5886e
LP
728 free(m->partitions[i].decrypted_fstype);
729 free(m->partitions[i].decrypted_node);
8c1be37e
LP
730 }
731
3b925504
LP
732 free(m->hostname);
733 strv_free(m->machine_info);
734 strv_free(m->os_release);
735
5fecf46d 736 return mfree(m);
8c1be37e
LP
737}
738
18b5886e 739static int is_loop_device(const char *path) {
553e15f2 740 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
18b5886e
LP
741 struct stat st;
742
743 assert(path);
744
745 if (stat(path, &st) < 0)
746 return -errno;
747
748 if (!S_ISBLK(st.st_mode))
749 return -ENOTBLK;
750
553e15f2 751 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
18b5886e
LP
752 if (access(s, F_OK) < 0) {
753 if (errno != ENOENT)
754 return -errno;
755
756 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
553e15f2 757 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
18b5886e
LP
758 if (access(s, F_OK) < 0)
759 return errno == ENOENT ? false : -errno;
760 }
761
762 return true;
763}
764
765static int mount_partition(
766 DissectedPartition *m,
767 const char *where,
768 const char *directory,
2d3a5a73 769 uid_t uid_shift,
18b5886e
LP
770 DissectImageFlags flags) {
771
2d3a5a73
LP
772 _cleanup_free_ char *chased = NULL, *options = NULL;
773 const char *p, *node, *fstype;
8c1be37e 774 bool rw;
2eedfd2d 775 int r;
8c1be37e
LP
776
777 assert(m);
778 assert(where);
779
18b5886e
LP
780 node = m->decrypted_node ?: m->node;
781 fstype = m->decrypted_fstype ?: m->fstype;
782
783 if (!m->found || !node || !fstype)
8c1be37e
LP
784 return 0;
785
18b5886e
LP
786 /* Stacked encryption? Yuck */
787 if (streq_ptr(fstype, "crypto_LUKS"))
788 return -ELOOP;
789
790 rw = m->rw && !(flags & DISSECT_IMAGE_READ_ONLY);
8c1be37e 791
2eedfd2d
LP
792 if (directory) {
793 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased);
794 if (r < 0)
795 return r;
796
797 p = chased;
798 } else
8c1be37e
LP
799 p = where;
800
18b5886e 801 /* If requested, turn on discard support. */
154d2269 802 if (fstype_can_discard(fstype) &&
18b5886e 803 ((flags & DISSECT_IMAGE_DISCARD) ||
2d3a5a73
LP
804 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node)))) {
805 options = strdup("discard");
806 if (!options)
807 return -ENOMEM;
808 }
809
810 if (uid_is_valid(uid_shift) && uid_shift != 0 && fstype_can_uid_gid(fstype)) {
811 _cleanup_free_ char *uid_option = NULL;
812
813 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
814 return -ENOMEM;
815
816 if (!strextend_with_separator(&options, ",", uid_option, NULL))
817 return -ENOMEM;
818 }
8c1be37e 819
18b5886e 820 return mount_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
8c1be37e
LP
821}
822
2d3a5a73 823int dissected_image_mount(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
8c1be37e
LP
824 int r;
825
826 assert(m);
827 assert(where);
828
829 if (!m->partitions[PARTITION_ROOT].found)
830 return -ENXIO;
831
2d3a5a73
LP
832 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
833 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, flags);
834 if (r < 0)
835 return r;
03bcb6d4
LP
836
837 if (flags & DISSECT_IMAGE_VALIDATE_OS) {
838 r = path_is_os_tree(where);
839 if (r < 0)
840 return r;
841 if (r == 0)
842 return -EMEDIUMTYPE;
843 }
2d3a5a73
LP
844 }
845
705727fd 846 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2d3a5a73 847 return 0;
8c1be37e 848
2d3a5a73 849 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, flags);
8c1be37e
LP
850 if (r < 0)
851 return r;
852
2d3a5a73 853 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, flags);
8c1be37e
LP
854 if (r < 0)
855 return r;
856
857 if (m->partitions[PARTITION_ESP].found) {
2eedfd2d 858 const char *mp;
8c1be37e
LP
859
860 /* Mount the ESP to /efi if it exists and is empty. If it doesn't exist, use /boot instead. */
861
2eedfd2d
LP
862 FOREACH_STRING(mp, "/efi", "/boot") {
863 _cleanup_free_ char *p = NULL;
864
865 r = chase_symlinks(mp, where, CHASE_PREFIX_ROOT, &p);
8c1be37e 866 if (r < 0)
2eedfd2d
LP
867 continue;
868
869 r = dir_is_empty(p);
870 if (r > 0) {
2d3a5a73 871 r = mount_partition(m->partitions + PARTITION_ESP, where, mp, uid_shift, flags);
2eedfd2d
LP
872 if (r < 0)
873 return r;
874 }
8c1be37e
LP
875 }
876 }
877
878 return 0;
879}
880
349cc4a5 881#if HAVE_LIBCRYPTSETUP
18b5886e
LP
882typedef struct DecryptedPartition {
883 struct crypt_device *device;
884 char *name;
885 bool relinquished;
886} DecryptedPartition;
887
888struct DecryptedImage {
889 DecryptedPartition *decrypted;
890 size_t n_decrypted;
891 size_t n_allocated;
892};
893#endif
894
895DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
349cc4a5 896#if HAVE_LIBCRYPTSETUP
18b5886e
LP
897 size_t i;
898 int r;
899
900 if (!d)
901 return NULL;
902
903 for (i = 0; i < d->n_decrypted; i++) {
904 DecryptedPartition *p = d->decrypted + i;
905
906 if (p->device && p->name && !p->relinquished) {
907 r = crypt_deactivate(p->device, p->name);
908 if (r < 0)
909 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
910 }
911
912 if (p->device)
913 crypt_free(p->device);
914 free(p->name);
915 }
916
917 free(d);
918#endif
919 return NULL;
920}
921
349cc4a5 922#if HAVE_LIBCRYPTSETUP
4623e8e6
LP
923
924static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
925 _cleanup_free_ char *name = NULL, *node = NULL;
926 const char *base;
927
928 assert(original_node);
929 assert(suffix);
930 assert(ret_name);
931 assert(ret_node);
932
933 base = strrchr(original_node, '/');
934 if (!base)
935 return -EINVAL;
936 base++;
937 if (isempty(base))
938 return -EINVAL;
939
940 name = strjoin(base, suffix);
941 if (!name)
942 return -ENOMEM;
943 if (!filename_is_valid(name))
944 return -EINVAL;
945
946 node = strjoin(crypt_get_dir(), "/", name);
947 if (!node)
948 return -ENOMEM;
949
1cc6c93a
YW
950 *ret_name = TAKE_PTR(name);
951 *ret_node = TAKE_PTR(node);
4623e8e6 952
4623e8e6
LP
953 return 0;
954}
955
18b5886e
LP
956static int decrypt_partition(
957 DissectedPartition *m,
958 const char *passphrase,
959 DissectImageFlags flags,
960 DecryptedImage *d) {
961
962 _cleanup_free_ char *node = NULL, *name = NULL;
294bd454 963 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
18b5886e
LP
964 int r;
965
966 assert(m);
967 assert(d);
968
969 if (!m->found || !m->node || !m->fstype)
970 return 0;
971
972 if (!streq(m->fstype, "crypto_LUKS"))
973 return 0;
974
bdd73ac5
ZJS
975 if (!passphrase)
976 return -ENOKEY;
977
4623e8e6
LP
978 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
979 if (r < 0)
980 return r;
18b5886e
LP
981
982 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
983 return -ENOMEM;
984
985 r = crypt_init(&cd, m->node);
986 if (r < 0)
715cbb81 987 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
18b5886e 988
dd59868b 989 r = crypt_load(cd, CRYPT_LUKS, NULL);
294bd454
ZJS
990 if (r < 0)
991 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
18b5886e
LP
992
993 r = crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
994 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
995 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
294bd454 996 if (r < 0) {
715cbb81 997 log_debug_errno(r, "Failed to activate LUKS device: %m");
294bd454 998 return r == -EPERM ? -EKEYREJECTED : r;
18b5886e 999 }
18b5886e 1000
1cc6c93a
YW
1001 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1002 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
18b5886e
LP
1003 d->n_decrypted++;
1004
1cc6c93a 1005 m->decrypted_node = TAKE_PTR(node);
18b5886e
LP
1006
1007 return 0;
4623e8e6
LP
1008}
1009
1010static int verity_partition(
1011 DissectedPartition *m,
1012 DissectedPartition *v,
1013 const void *root_hash,
1014 size_t root_hash_size,
1015 DissectImageFlags flags,
1016 DecryptedImage *d) {
1017
1018 _cleanup_free_ char *node = NULL, *name = NULL;
294bd454 1019 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
4623e8e6
LP
1020 int r;
1021
1022 assert(m);
1023 assert(v);
1024
1025 if (!root_hash)
1026 return 0;
1027
1028 if (!m->found || !m->node || !m->fstype)
1029 return 0;
1030 if (!v->found || !v->node || !v->fstype)
1031 return 0;
1032
1033 if (!streq(v->fstype, "DM_verity_hash"))
1034 return 0;
1035
1036 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
1037 if (r < 0)
1038 return r;
1039
1040 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1041 return -ENOMEM;
1042
1043 r = crypt_init(&cd, v->node);
1044 if (r < 0)
1045 return r;
1046
1047 r = crypt_load(cd, CRYPT_VERITY, NULL);
1048 if (r < 0)
294bd454 1049 return r;
4623e8e6
LP
1050
1051 r = crypt_set_data_device(cd, m->node);
1052 if (r < 0)
294bd454 1053 return r;
4623e8e6
LP
1054
1055 r = crypt_activate_by_volume_key(cd, name, root_hash, root_hash_size, CRYPT_ACTIVATE_READONLY);
1056 if (r < 0)
294bd454 1057 return r;
4623e8e6 1058
1cc6c93a
YW
1059 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1060 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
4623e8e6
LP
1061 d->n_decrypted++;
1062
1cc6c93a 1063 m->decrypted_node = TAKE_PTR(node);
4623e8e6
LP
1064
1065 return 0;
18b5886e
LP
1066}
1067#endif
1068
1069int dissected_image_decrypt(
1070 DissectedImage *m,
1071 const char *passphrase,
4623e8e6
LP
1072 const void *root_hash,
1073 size_t root_hash_size,
18b5886e
LP
1074 DissectImageFlags flags,
1075 DecryptedImage **ret) {
1076
349cc4a5 1077#if HAVE_LIBCRYPTSETUP
49b5b3b4 1078 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
18b5886e
LP
1079 unsigned i;
1080 int r;
1081#endif
1082
1083 assert(m);
4623e8e6 1084 assert(root_hash || root_hash_size == 0);
18b5886e
LP
1085
1086 /* Returns:
1087 *
1088 * = 0 → There was nothing to decrypt
1089 * > 0 → Decrypted successfully
d1c536f5 1090 * -ENOKEY → There's something to decrypt but no key was supplied
18b5886e
LP
1091 * -EKEYREJECTED → Passed key was not correct
1092 */
1093
4623e8e6
LP
1094 if (root_hash && root_hash_size < sizeof(sd_id128_t))
1095 return -EINVAL;
1096
1097 if (!m->encrypted && !m->verity) {
18b5886e
LP
1098 *ret = NULL;
1099 return 0;
1100 }
1101
349cc4a5 1102#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1103 d = new0(DecryptedImage, 1);
1104 if (!d)
1105 return -ENOMEM;
1106
1107 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1108 DissectedPartition *p = m->partitions + i;
4623e8e6 1109 int k;
18b5886e
LP
1110
1111 if (!p->found)
1112 continue;
1113
1114 r = decrypt_partition(p, passphrase, flags, d);
1115 if (r < 0)
1116 return r;
1117
4623e8e6
LP
1118 k = PARTITION_VERITY_OF(i);
1119 if (k >= 0) {
1120 r = verity_partition(p, m->partitions + k, root_hash, root_hash_size, flags, d);
1121 if (r < 0)
1122 return r;
1123 }
1124
18b5886e
LP
1125 if (!p->decrypted_fstype && p->decrypted_node) {
1126 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
7cc84b2c 1127 if (r < 0 && r != -EUCLEAN)
18b5886e
LP
1128 return r;
1129 }
1130 }
1131
1cc6c93a 1132 *ret = TAKE_PTR(d);
18b5886e
LP
1133
1134 return 1;
1135#else
1136 return -EOPNOTSUPP;
1137#endif
1138}
1139
1140int dissected_image_decrypt_interactively(
1141 DissectedImage *m,
1142 const char *passphrase,
4623e8e6
LP
1143 const void *root_hash,
1144 size_t root_hash_size,
18b5886e
LP
1145 DissectImageFlags flags,
1146 DecryptedImage **ret) {
1147
1148 _cleanup_strv_free_erase_ char **z = NULL;
1149 int n = 3, r;
1150
1151 if (passphrase)
1152 n--;
1153
1154 for (;;) {
4623e8e6 1155 r = dissected_image_decrypt(m, passphrase, root_hash, root_hash_size, flags, ret);
18b5886e
LP
1156 if (r >= 0)
1157 return r;
1158 if (r == -EKEYREJECTED)
1159 log_error_errno(r, "Incorrect passphrase, try again!");
fc95c359
YW
1160 else if (r != -ENOKEY)
1161 return log_error_errno(r, "Failed to decrypt image: %m");
18b5886e 1162
baaa35ad
ZJS
1163 if (--n < 0)
1164 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
1165 "Too many retries.");
18b5886e
LP
1166
1167 z = strv_free(z);
1168
a1c111c2 1169 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
18b5886e
LP
1170 if (r < 0)
1171 return log_error_errno(r, "Failed to query for passphrase: %m");
1172
1173 passphrase = z[0];
1174 }
1175}
1176
349cc4a5 1177#if HAVE_LIBCRYPTSETUP
18b5886e 1178static int deferred_remove(DecryptedPartition *p) {
18b5886e
LP
1179 struct dm_ioctl dm = {
1180 .version = {
1181 DM_VERSION_MAJOR,
1182 DM_VERSION_MINOR,
1183 DM_VERSION_PATCHLEVEL
1184 },
1185 .data_size = sizeof(dm),
1186 .flags = DM_DEFERRED_REMOVE,
1187 };
1188
1189 _cleanup_close_ int fd = -1;
1190
1191 assert(p);
1192
1193 /* Unfortunately, libcryptsetup doesn't provide a proper API for this, hence call the ioctl() directly. */
1194
1195 fd = open("/dev/mapper/control", O_RDWR|O_CLOEXEC);
1196 if (fd < 0)
1197 return -errno;
1198
cd8c98d7
ZJS
1199 if (strlen(p->name) > sizeof(dm.name))
1200 return -ENAMETOOLONG;
1201
18b5886e
LP
1202 strncpy(dm.name, p->name, sizeof(dm.name));
1203
1204 if (ioctl(fd, DM_DEV_REMOVE, &dm))
1205 return -errno;
1206
1207 return 0;
1208}
1209#endif
1210
1211int decrypted_image_relinquish(DecryptedImage *d) {
1212
349cc4a5 1213#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1214 size_t i;
1215 int r;
1216#endif
1217
1218 assert(d);
1219
1220 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1221 * that we don't clean it up ourselves either anymore */
1222
349cc4a5 1223#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1224 for (i = 0; i < d->n_decrypted; i++) {
1225 DecryptedPartition *p = d->decrypted + i;
1226
1227 if (p->relinquished)
1228 continue;
1229
1230 r = deferred_remove(p);
1231 if (r < 0)
1232 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
1233
1234 p->relinquished = true;
1235 }
1236#endif
1237
1238 return 0;
1239}
1240
78ebe980
LP
1241int root_hash_load(const char *image, void **ret, size_t *ret_size) {
1242 _cleanup_free_ char *text = NULL;
1243 _cleanup_free_ void *k = NULL;
78ebe980
LP
1244 size_t l;
1245 int r;
1246
1247 assert(image);
1248 assert(ret);
1249 assert(ret_size);
1250
1251 if (is_device_path(image)) {
1252 /* If we are asked to load the root hash for a device node, exit early */
1253 *ret = NULL;
1254 *ret_size = 0;
1255 return 0;
1256 }
1257
41488e1f
LP
1258 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
1259 if (r < 0) {
1260 char *fn, *e, *n;
78ebe980 1261
41488e1f
LP
1262 if (!IN_SET(r, -ENODATA, -EOPNOTSUPP, -ENOENT))
1263 return r;
78ebe980 1264
fbd0b64f 1265 fn = newa(char, strlen(image) + STRLEN(".roothash") + 1);
41488e1f
LP
1266 n = stpcpy(fn, image);
1267 e = endswith(fn, ".raw");
1268 if (e)
1269 n = e;
1270
1271 strcpy(n, ".roothash");
1272
1273 r = read_one_line_file(fn, &text);
1274 if (r == -ENOENT) {
1275 *ret = NULL;
1276 *ret_size = 0;
1277 return 0;
1278 }
1279 if (r < 0)
1280 return r;
78ebe980 1281 }
78ebe980
LP
1282
1283 r = unhexmem(text, strlen(text), &k, &l);
1284 if (r < 0)
1285 return r;
1286 if (l < sizeof(sd_id128_t))
1287 return -EINVAL;
1288
1cc6c93a 1289 *ret = TAKE_PTR(k);
78ebe980
LP
1290 *ret_size = l;
1291
78ebe980
LP
1292 return 1;
1293}
1294
3b925504
LP
1295int dissected_image_acquire_metadata(DissectedImage *m) {
1296
1297 enum {
1298 META_HOSTNAME,
1299 META_MACHINE_ID,
1300 META_MACHINE_INFO,
1301 META_OS_RELEASE,
1302 _META_MAX,
1303 };
1304
1305 static const char *const paths[_META_MAX] = {
1306 [META_HOSTNAME] = "/etc/hostname\0",
1307 [META_MACHINE_ID] = "/etc/machine-id\0",
1308 [META_MACHINE_INFO] = "/etc/machine-info\0",
1309 [META_OS_RELEASE] = "/etc/os-release\0/usr/lib/os-release\0",
1310 };
1311
1312 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL;
1313 _cleanup_(rmdir_and_freep) char *t = NULL;
1314 _cleanup_(sigkill_waitp) pid_t child = 0;
1315 sd_id128_t machine_id = SD_ID128_NULL;
1316 _cleanup_free_ char *hostname = NULL;
1317 unsigned n_meta_initialized = 0, k;
1318 int fds[2 * _META_MAX], r;
3b925504
LP
1319
1320 BLOCK_SIGNALS(SIGCHLD);
1321
1322 assert(m);
1323
1324 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++)
1325 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
1326 r = -errno;
1327 goto finish;
1328 }
1329
1330 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
1331 if (r < 0)
1332 goto finish;
1333
e2047ba9 1334 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
be39f6ee 1335 if (r < 0)
3b925504 1336 goto finish;
be39f6ee 1337 if (r == 0) {
03bcb6d4 1338 r = dissected_image_mount(m, t, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_VALIDATE_OS);
429d4e41
LP
1339 if (r < 0) {
1340 log_debug_errno(r, "Failed to mount dissected image: %m");
3b925504 1341 _exit(EXIT_FAILURE);
429d4e41 1342 }
3b925504
LP
1343
1344 for (k = 0; k < _META_MAX; k++) {
1345 _cleanup_close_ int fd = -1;
1346 const char *p;
1347
1348 fds[2*k] = safe_close(fds[2*k]);
1349
1350 NULSTR_FOREACH(p, paths[k]) {
36952d19 1351 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
3b925504
LP
1352 if (fd >= 0)
1353 break;
1354 }
36952d19
LP
1355 if (fd < 0) {
1356 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
3b925504 1357 continue;
36952d19 1358 }
3b925504
LP
1359
1360 r = copy_bytes(fd, fds[2*k+1], (uint64_t) -1, 0);
1361 if (r < 0)
1362 _exit(EXIT_FAILURE);
1363
1364 fds[2*k+1] = safe_close(fds[2*k+1]);
1365 }
1366
1367 _exit(EXIT_SUCCESS);
1368 }
1369
1370 for (k = 0; k < _META_MAX; k++) {
1371 _cleanup_fclose_ FILE *f = NULL;
1372
1373 fds[2*k+1] = safe_close(fds[2*k+1]);
1374
e92aaed3 1375 f = fdopen(fds[2*k], "r");
3b925504
LP
1376 if (!f) {
1377 r = -errno;
1378 goto finish;
1379 }
1380
1381 fds[2*k] = -1;
1382
1383 switch (k) {
1384
1385 case META_HOSTNAME:
1386 r = read_etc_hostname_stream(f, &hostname);
1387 if (r < 0)
1388 log_debug_errno(r, "Failed to read /etc/hostname: %m");
1389
1390 break;
1391
1392 case META_MACHINE_ID: {
1393 _cleanup_free_ char *line = NULL;
1394
1395 r = read_line(f, LONG_LINE_MAX, &line);
1396 if (r < 0)
1397 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
1398 else if (r == 33) {
1399 r = sd_id128_from_string(line, &machine_id);
1400 if (r < 0)
1401 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
1402 } else if (r == 0)
1403 log_debug("/etc/machine-id file is empty.");
1404 else
1405 log_debug("/etc/machine-id has unexpected length %i.", r);
1406
1407 break;
1408 }
1409
1410 case META_MACHINE_INFO:
aa8fbc74 1411 r = load_env_file_pairs(f, "machine-info", &machine_info);
3b925504
LP
1412 if (r < 0)
1413 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
1414
1415 break;
1416
1417 case META_OS_RELEASE:
aa8fbc74 1418 r = load_env_file_pairs(f, "os-release", &os_release);
3b925504
LP
1419 if (r < 0)
1420 log_debug_errno(r, "Failed to read OS release file: %m");
1421
1422 break;
1423 }
1424 }
1425
2e87a1fd 1426 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3b925504 1427 child = 0;
2e87a1fd 1428 if (r < 0)
3b925504 1429 goto finish;
2e87a1fd
LP
1430 if (r != EXIT_SUCCESS)
1431 return -EPROTO;
3b925504
LP
1432
1433 free_and_replace(m->hostname, hostname);
1434 m->machine_id = machine_id;
1435 strv_free_and_replace(m->machine_info, machine_info);
1436 strv_free_and_replace(m->os_release, os_release);
1437
1438finish:
1439 for (k = 0; k < n_meta_initialized; k++)
1440 safe_close_pair(fds + 2*k);
1441
1442 return r;
1443}
1444
4526113f
LP
1445int dissect_image_and_warn(
1446 int fd,
1447 const char *name,
1448 const void *root_hash,
1449 size_t root_hash_size,
1450 DissectImageFlags flags,
1451 DissectedImage **ret) {
1452
1453 _cleanup_free_ char *buffer = NULL;
1454 int r;
1455
1456 if (!name) {
1457 r = fd_get_path(fd, &buffer);
1458 if (r < 0)
1459 return r;
1460
1461 name = buffer;
1462 }
1463
1464 r = dissect_image(fd, root_hash, root_hash_size, flags, ret);
1465
1466 switch (r) {
1467
1468 case -EOPNOTSUPP:
1469 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
1470
1471 case -ENOPKG:
1472 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
1473
1474 case -EADDRNOTAVAIL:
1475 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
1476
1477 case -ENOTUNIQ:
1478 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
1479
1480 case -ENXIO:
1481 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
1482
1483 case -EPROTONOSUPPORT:
1484 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
1485
1486 default:
1487 if (r < 0)
1488 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
1489
1490 return r;
1491 }
1492}
1493
8c1be37e
LP
1494static const char *const partition_designator_table[] = {
1495 [PARTITION_ROOT] = "root",
1496 [PARTITION_ROOT_SECONDARY] = "root-secondary",
1497 [PARTITION_HOME] = "home",
1498 [PARTITION_SRV] = "srv",
1499 [PARTITION_ESP] = "esp",
1500 [PARTITION_SWAP] = "swap",
4623e8e6
LP
1501 [PARTITION_ROOT_VERITY] = "root-verity",
1502 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
8c1be37e
LP
1503};
1504
1505DEFINE_STRING_TABLE_LOOKUP(partition_designator, int);