]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/dissect-image.c
Merge pull request #11827 from keszybz/pkgconfig-variables
[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);
4c701096 346 if (IN_SET(r, -2, 1)) {
8c1be37e
LP
347 log_debug("Failed to identify any partition table.");
348 return -ENOPKG;
349 }
b382db9f
ZJS
350 if (r != 0)
351 return -errno ?: -EIO;
8c1be37e
LP
352
353 m = new0(DissectedImage, 1);
354 if (!m)
355 return -ENOMEM;
356
b887c8b8
ZJS
357 r = sd_device_new_from_devnum(&d, 'b', st.st_rdev);
358 if (r < 0)
359 return r;
360
e0f9e7bd
LP
361 if (!(flags & DISSECT_IMAGE_GPT_ONLY) &&
362 (flags & DISSECT_IMAGE_REQUIRE_ROOT)) {
9b6deb03 363 const char *usage = NULL;
8c1be37e 364
9b6deb03
LP
365 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
366 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
367 _cleanup_free_ char *t = NULL, *n = NULL;
368 const char *fstype = NULL;
8c1be37e 369
9b6deb03
LP
370 /* OK, we have found a file system, that's our root partition then. */
371 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
8c1be37e 372
9b6deb03
LP
373 if (fstype) {
374 t = strdup(fstype);
375 if (!t)
376 return -ENOMEM;
377 }
378
54b22b26
LP
379 r = device_path_make_major_minor(st.st_mode, st.st_rdev, &n);
380 if (r < 0)
381 return r;
8c1be37e 382
9b6deb03
LP
383 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
384 .found = true,
385 .rw = true,
386 .partno = -1,
387 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a
YW
388 .fstype = TAKE_PTR(t),
389 .node = TAKE_PTR(n),
9b6deb03 390 };
8c1be37e 391
4db1879a 392 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
18b5886e 393
052eaf5c 394 r = loop_wait_for_partitions_to_appear(fd, d, 0, flags, &e);
b887c8b8
ZJS
395 if (r < 0)
396 return r;
397
1cc6c93a 398 *ret = TAKE_PTR(m);
8c1be37e 399
9b6deb03
LP
400 return 0;
401 }
8c1be37e
LP
402 }
403
404 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
405 if (!pttype)
406 return -ENOPKG;
407
408 is_gpt = streq_ptr(pttype, "gpt");
409 is_mbr = streq_ptr(pttype, "dos");
410
9b6deb03 411 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
8c1be37e
LP
412 return -ENOPKG;
413
414 errno = 0;
415 pl = blkid_probe_get_partitions(b);
b382db9f
ZJS
416 if (!pl)
417 return -errno ?: -ENOMEM;
8c1be37e 418
052eaf5c 419 r = loop_wait_for_partitions_to_appear(fd, d, blkid_partlist_numof_partitions(pl), flags, &e);
ea887be0
ZJS
420 if (r < 0)
421 return r;
8c1be37e 422
8437c059 423 FOREACH_DEVICE(e, q) {
9b6deb03 424 unsigned long long pflags;
8c1be37e 425 blkid_partition pp;
cde942f6 426 const char *node;
8c1be37e
LP
427 dev_t qn;
428 int nr;
429
3c1f2cee
YW
430 r = sd_device_get_devnum(q, &qn);
431 if (r < 0)
8c1be37e
LP
432 continue;
433
434 if (st.st_rdev == qn)
435 continue;
436
aae22eb3
LP
437 if (!device_is_block(q))
438 continue;
439
cde942f6 440 if (device_is_mmc_special_partition(q))
7be1420f
LP
441 continue;
442
3c1f2cee
YW
443 r = sd_device_get_devname(q, &node);
444 if (r < 0)
8c1be37e
LP
445 continue;
446
447 pp = blkid_partlist_devno_to_partition(pl, qn);
448 if (!pp)
449 continue;
450
9b6deb03 451 pflags = blkid_partition_get_flags(pp);
8c1be37e
LP
452
453 nr = blkid_partition_get_partno(pp);
454 if (nr < 0)
455 continue;
456
457 if (is_gpt) {
458 int designator = _PARTITION_DESIGNATOR_INVALID, architecture = _ARCHITECTURE_INVALID;
4623e8e6
LP
459 const char *stype, *sid, *fstype = NULL;
460 sd_id128_t type_id, id;
8c1be37e
LP
461 bool rw = true;
462
4623e8e6
LP
463 sid = blkid_partition_get_uuid(pp);
464 if (!sid)
465 continue;
466 if (sd_id128_from_string(sid, &id) < 0)
467 continue;
468
8c1be37e
LP
469 stype = blkid_partition_get_type_string(pp);
470 if (!stype)
471 continue;
8c1be37e
LP
472 if (sd_id128_from_string(stype, &type_id) < 0)
473 continue;
474
475 if (sd_id128_equal(type_id, GPT_HOME)) {
a48dd347
LP
476
477 if (pflags & GPT_FLAG_NO_AUTO)
478 continue;
479
8c1be37e 480 designator = PARTITION_HOME;
9b6deb03 481 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e 482 } else if (sd_id128_equal(type_id, GPT_SRV)) {
a48dd347
LP
483
484 if (pflags & GPT_FLAG_NO_AUTO)
485 continue;
486
8c1be37e 487 designator = PARTITION_SRV;
9b6deb03 488 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e 489 } else if (sd_id128_equal(type_id, GPT_ESP)) {
a48dd347
LP
490
491 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
492 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
493 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
494
495 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
496 continue;
497
8c1be37e
LP
498 designator = PARTITION_ESP;
499 fstype = "vfat";
500 }
501#ifdef GPT_ROOT_NATIVE
502 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
4623e8e6 503
a48dd347
LP
504 if (pflags & GPT_FLAG_NO_AUTO)
505 continue;
506
4623e8e6
LP
507 /* If a root ID is specified, ignore everything but the root id */
508 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
509 continue;
510
8c1be37e
LP
511 designator = PARTITION_ROOT;
512 architecture = native_architecture();
9b6deb03 513 rw = !(pflags & GPT_FLAG_READ_ONLY);
4f8b86e3 514 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
4623e8e6 515
a48dd347
LP
516 if (pflags & GPT_FLAG_NO_AUTO)
517 continue;
518
4623e8e6
LP
519 m->can_verity = true;
520
521 /* Ignore verity unless a root hash is specified */
522 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
523 continue;
524
525 designator = PARTITION_ROOT_VERITY;
526 fstype = "DM_verity_hash";
527 architecture = native_architecture();
528 rw = false;
529 }
530#endif
8c1be37e
LP
531#ifdef GPT_ROOT_SECONDARY
532 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
4623e8e6 533
a48dd347
LP
534 if (pflags & GPT_FLAG_NO_AUTO)
535 continue;
536
4623e8e6
LP
537 /* If a root ID is specified, ignore everything but the root id */
538 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
539 continue;
540
8c1be37e
LP
541 designator = PARTITION_ROOT_SECONDARY;
542 architecture = SECONDARY_ARCHITECTURE;
9b6deb03 543 rw = !(pflags & GPT_FLAG_READ_ONLY);
4f8b86e3 544 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
a48dd347
LP
545
546 if (pflags & GPT_FLAG_NO_AUTO)
547 continue;
548
4623e8e6
LP
549 m->can_verity = true;
550
551 /* Ignore verity unless root has is specified */
552 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
553 continue;
554
555 designator = PARTITION_ROOT_SECONDARY_VERITY;
556 fstype = "DM_verity_hash";
557 architecture = SECONDARY_ARCHITECTURE;
558 rw = false;
559 }
8c1be37e
LP
560#endif
561 else if (sd_id128_equal(type_id, GPT_SWAP)) {
a48dd347
LP
562
563 if (pflags & GPT_FLAG_NO_AUTO)
564 continue;
565
8c1be37e
LP
566 designator = PARTITION_SWAP;
567 fstype = "swap";
568 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
569
a48dd347
LP
570 if (pflags & GPT_FLAG_NO_AUTO)
571 continue;
572
8c1be37e
LP
573 if (generic_node)
574 multiple_generic = true;
575 else {
576 generic_nr = nr;
9b6deb03 577 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
be30ad41 578 generic_uuid = id;
8c1be37e
LP
579 generic_node = strdup(node);
580 if (!generic_node)
581 return -ENOMEM;
582 }
583 }
584
585 if (designator != _PARTITION_DESIGNATOR_INVALID) {
586 _cleanup_free_ char *t = NULL, *n = NULL;
587
588 /* First one wins */
589 if (m->partitions[designator].found)
590 continue;
591
592 if (fstype) {
593 t = strdup(fstype);
594 if (!t)
595 return -ENOMEM;
596 }
597
598 n = strdup(node);
599 if (!n)
600 return -ENOMEM;
601
602 m->partitions[designator] = (DissectedPartition) {
603 .found = true,
604 .partno = nr,
605 .rw = rw,
606 .architecture = architecture,
1cc6c93a
YW
607 .node = TAKE_PTR(n),
608 .fstype = TAKE_PTR(t),
be30ad41 609 .uuid = id,
8c1be37e 610 };
8c1be37e
LP
611 }
612
613 } else if (is_mbr) {
614
9b6deb03 615 if (pflags != 0x80) /* Bootable flag */
8c1be37e
LP
616 continue;
617
618 if (blkid_partition_get_type(pp) != 0x83) /* Linux partition */
619 continue;
620
621 if (generic_node)
622 multiple_generic = true;
623 else {
624 generic_nr = nr;
625 generic_rw = true;
626 generic_node = strdup(node);
627 if (!generic_node)
628 return -ENOMEM;
629 }
630 }
631 }
632
633 if (!m->partitions[PARTITION_ROOT].found) {
634 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
635 * either, then check if there's a single generic one, and use that. */
636
4623e8e6 637 if (m->partitions[PARTITION_ROOT_VERITY].found)
e0f9e7bd 638 return -EADDRNOTAVAIL;
4623e8e6 639
8c1be37e
LP
640 if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
641 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
642 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
4623e8e6
LP
643
644 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
645 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
646
e0f9e7bd
LP
647 } else if (flags & DISSECT_IMAGE_REQUIRE_ROOT) {
648
649 /* If the root has was set, then we won't fallback to a generic node, because the root hash
650 * decides */
651 if (root_hash)
652 return -EADDRNOTAVAIL;
8c1be37e 653
e0f9e7bd
LP
654 /* If we didn't find a generic node, then we can't fix this up either */
655 if (!generic_node)
656 return -ENXIO;
657
658 /* If we didn't find a properly marked root partition, but we did find a single suitable
659 * generic Linux partition, then use this as root partition, if the caller asked for it. */
8c1be37e
LP
660 if (multiple_generic)
661 return -ENOTUNIQ;
662
663 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
664 .found = true,
665 .rw = generic_rw,
666 .partno = generic_nr,
667 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a 668 .node = TAKE_PTR(generic_node),
be30ad41 669 .uuid = generic_uuid,
8c1be37e 670 };
e0f9e7bd 671 }
8c1be37e
LP
672 }
673
4623e8e6 674 if (root_hash) {
e0f9e7bd 675 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
4623e8e6
LP
676 return -EADDRNOTAVAIL;
677
678 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
679 * (which would be weird, after all the root hash should only be assigned to one pair of
680 * partitions... */
681 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
682 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
683
684 /* If we found a verity setup, then the root partition is necessarily read-only. */
685 m->partitions[PARTITION_ROOT].rw = false;
686
687 m->verity = true;
688 }
689
18b5886e
LP
690 blkid_free_probe(b);
691 b = NULL;
692
8c1be37e
LP
693 /* Fill in file system types if we don't know them yet. */
694 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 695 DissectedPartition *p = m->partitions + i;
8c1be37e 696
18b5886e 697 if (!p->found)
8c1be37e
LP
698 continue;
699
18b5886e
LP
700 if (!p->fstype && p->node) {
701 r = probe_filesystem(p->node, &p->fstype);
7cc84b2c 702 if (r < 0 && r != -EUCLEAN)
18b5886e 703 return r;
8c1be37e
LP
704 }
705
18b5886e
LP
706 if (streq_ptr(p->fstype, "crypto_LUKS"))
707 m->encrypted = true;
896f937f
LP
708
709 if (p->fstype && fstype_is_ro(p->fstype))
710 p->rw = false;
8c1be37e
LP
711 }
712
1cc6c93a 713 *ret = TAKE_PTR(m);
8c1be37e
LP
714
715 return 0;
716#else
717 return -EOPNOTSUPP;
718#endif
719}
720
721DissectedImage* dissected_image_unref(DissectedImage *m) {
722 unsigned i;
723
724 if (!m)
725 return NULL;
726
727 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
728 free(m->partitions[i].fstype);
729 free(m->partitions[i].node);
18b5886e
LP
730 free(m->partitions[i].decrypted_fstype);
731 free(m->partitions[i].decrypted_node);
8c1be37e
LP
732 }
733
3b925504
LP
734 free(m->hostname);
735 strv_free(m->machine_info);
736 strv_free(m->os_release);
737
5fecf46d 738 return mfree(m);
8c1be37e
LP
739}
740
18b5886e 741static int is_loop_device(const char *path) {
553e15f2 742 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
18b5886e
LP
743 struct stat st;
744
745 assert(path);
746
747 if (stat(path, &st) < 0)
748 return -errno;
749
750 if (!S_ISBLK(st.st_mode))
751 return -ENOTBLK;
752
553e15f2 753 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
18b5886e
LP
754 if (access(s, F_OK) < 0) {
755 if (errno != ENOENT)
756 return -errno;
757
758 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
553e15f2 759 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
18b5886e
LP
760 if (access(s, F_OK) < 0)
761 return errno == ENOENT ? false : -errno;
762 }
763
764 return true;
765}
766
767static int mount_partition(
768 DissectedPartition *m,
769 const char *where,
770 const char *directory,
2d3a5a73 771 uid_t uid_shift,
18b5886e
LP
772 DissectImageFlags flags) {
773
2d3a5a73
LP
774 _cleanup_free_ char *chased = NULL, *options = NULL;
775 const char *p, *node, *fstype;
8c1be37e 776 bool rw;
2eedfd2d 777 int r;
8c1be37e
LP
778
779 assert(m);
780 assert(where);
781
18b5886e
LP
782 node = m->decrypted_node ?: m->node;
783 fstype = m->decrypted_fstype ?: m->fstype;
784
785 if (!m->found || !node || !fstype)
8c1be37e
LP
786 return 0;
787
18b5886e
LP
788 /* Stacked encryption? Yuck */
789 if (streq_ptr(fstype, "crypto_LUKS"))
790 return -ELOOP;
791
792 rw = m->rw && !(flags & DISSECT_IMAGE_READ_ONLY);
8c1be37e 793
2eedfd2d
LP
794 if (directory) {
795 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased);
796 if (r < 0)
797 return r;
798
799 p = chased;
800 } else
8c1be37e
LP
801 p = where;
802
18b5886e 803 /* If requested, turn on discard support. */
154d2269 804 if (fstype_can_discard(fstype) &&
18b5886e 805 ((flags & DISSECT_IMAGE_DISCARD) ||
2d3a5a73
LP
806 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node)))) {
807 options = strdup("discard");
808 if (!options)
809 return -ENOMEM;
810 }
811
812 if (uid_is_valid(uid_shift) && uid_shift != 0 && fstype_can_uid_gid(fstype)) {
813 _cleanup_free_ char *uid_option = NULL;
814
815 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
816 return -ENOMEM;
817
818 if (!strextend_with_separator(&options, ",", uid_option, NULL))
819 return -ENOMEM;
820 }
8c1be37e 821
18b5886e 822 return mount_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
8c1be37e
LP
823}
824
2d3a5a73 825int dissected_image_mount(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
8c1be37e
LP
826 int r;
827
828 assert(m);
829 assert(where);
830
831 if (!m->partitions[PARTITION_ROOT].found)
832 return -ENXIO;
833
2d3a5a73
LP
834 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
835 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, flags);
836 if (r < 0)
837 return r;
03bcb6d4
LP
838
839 if (flags & DISSECT_IMAGE_VALIDATE_OS) {
840 r = path_is_os_tree(where);
841 if (r < 0)
842 return r;
843 if (r == 0)
844 return -EMEDIUMTYPE;
845 }
2d3a5a73
LP
846 }
847
705727fd 848 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2d3a5a73 849 return 0;
8c1be37e 850
2d3a5a73 851 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, flags);
8c1be37e
LP
852 if (r < 0)
853 return r;
854
2d3a5a73 855 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, flags);
8c1be37e
LP
856 if (r < 0)
857 return r;
858
859 if (m->partitions[PARTITION_ESP].found) {
2eedfd2d 860 const char *mp;
8c1be37e
LP
861
862 /* Mount the ESP to /efi if it exists and is empty. If it doesn't exist, use /boot instead. */
863
2eedfd2d
LP
864 FOREACH_STRING(mp, "/efi", "/boot") {
865 _cleanup_free_ char *p = NULL;
866
867 r = chase_symlinks(mp, where, CHASE_PREFIX_ROOT, &p);
8c1be37e 868 if (r < 0)
2eedfd2d
LP
869 continue;
870
871 r = dir_is_empty(p);
872 if (r > 0) {
2d3a5a73 873 r = mount_partition(m->partitions + PARTITION_ESP, where, mp, uid_shift, flags);
2eedfd2d
LP
874 if (r < 0)
875 return r;
876 }
8c1be37e
LP
877 }
878 }
879
880 return 0;
881}
882
349cc4a5 883#if HAVE_LIBCRYPTSETUP
18b5886e
LP
884typedef struct DecryptedPartition {
885 struct crypt_device *device;
886 char *name;
887 bool relinquished;
888} DecryptedPartition;
889
890struct DecryptedImage {
891 DecryptedPartition *decrypted;
892 size_t n_decrypted;
893 size_t n_allocated;
894};
895#endif
896
897DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
349cc4a5 898#if HAVE_LIBCRYPTSETUP
18b5886e
LP
899 size_t i;
900 int r;
901
902 if (!d)
903 return NULL;
904
905 for (i = 0; i < d->n_decrypted; i++) {
906 DecryptedPartition *p = d->decrypted + i;
907
908 if (p->device && p->name && !p->relinquished) {
909 r = crypt_deactivate(p->device, p->name);
910 if (r < 0)
911 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
912 }
913
914 if (p->device)
915 crypt_free(p->device);
916 free(p->name);
917 }
918
919 free(d);
920#endif
921 return NULL;
922}
923
349cc4a5 924#if HAVE_LIBCRYPTSETUP
4623e8e6
LP
925
926static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
927 _cleanup_free_ char *name = NULL, *node = NULL;
928 const char *base;
929
930 assert(original_node);
931 assert(suffix);
932 assert(ret_name);
933 assert(ret_node);
934
935 base = strrchr(original_node, '/');
936 if (!base)
937 return -EINVAL;
938 base++;
939 if (isempty(base))
940 return -EINVAL;
941
942 name = strjoin(base, suffix);
943 if (!name)
944 return -ENOMEM;
945 if (!filename_is_valid(name))
946 return -EINVAL;
947
948 node = strjoin(crypt_get_dir(), "/", name);
949 if (!node)
950 return -ENOMEM;
951
1cc6c93a
YW
952 *ret_name = TAKE_PTR(name);
953 *ret_node = TAKE_PTR(node);
4623e8e6 954
4623e8e6
LP
955 return 0;
956}
957
18b5886e
LP
958static int decrypt_partition(
959 DissectedPartition *m,
960 const char *passphrase,
961 DissectImageFlags flags,
962 DecryptedImage *d) {
963
964 _cleanup_free_ char *node = NULL, *name = NULL;
294bd454 965 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
18b5886e
LP
966 int r;
967
968 assert(m);
969 assert(d);
970
971 if (!m->found || !m->node || !m->fstype)
972 return 0;
973
974 if (!streq(m->fstype, "crypto_LUKS"))
975 return 0;
976
bdd73ac5
ZJS
977 if (!passphrase)
978 return -ENOKEY;
979
4623e8e6
LP
980 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
981 if (r < 0)
982 return r;
18b5886e
LP
983
984 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
985 return -ENOMEM;
986
987 r = crypt_init(&cd, m->node);
988 if (r < 0)
715cbb81 989 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
18b5886e 990
dd59868b 991 r = crypt_load(cd, CRYPT_LUKS, NULL);
294bd454
ZJS
992 if (r < 0)
993 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
18b5886e
LP
994
995 r = crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
996 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
997 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
294bd454 998 if (r < 0) {
715cbb81 999 log_debug_errno(r, "Failed to activate LUKS device: %m");
294bd454 1000 return r == -EPERM ? -EKEYREJECTED : r;
18b5886e 1001 }
18b5886e 1002
1cc6c93a
YW
1003 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1004 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
18b5886e
LP
1005 d->n_decrypted++;
1006
1cc6c93a 1007 m->decrypted_node = TAKE_PTR(node);
18b5886e
LP
1008
1009 return 0;
4623e8e6
LP
1010}
1011
1012static int verity_partition(
1013 DissectedPartition *m,
1014 DissectedPartition *v,
1015 const void *root_hash,
1016 size_t root_hash_size,
1017 DissectImageFlags flags,
1018 DecryptedImage *d) {
1019
1020 _cleanup_free_ char *node = NULL, *name = NULL;
294bd454 1021 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
4623e8e6
LP
1022 int r;
1023
1024 assert(m);
1025 assert(v);
1026
1027 if (!root_hash)
1028 return 0;
1029
1030 if (!m->found || !m->node || !m->fstype)
1031 return 0;
1032 if (!v->found || !v->node || !v->fstype)
1033 return 0;
1034
1035 if (!streq(v->fstype, "DM_verity_hash"))
1036 return 0;
1037
1038 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
1039 if (r < 0)
1040 return r;
1041
1042 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1043 return -ENOMEM;
1044
1045 r = crypt_init(&cd, v->node);
1046 if (r < 0)
1047 return r;
1048
1049 r = crypt_load(cd, CRYPT_VERITY, NULL);
1050 if (r < 0)
294bd454 1051 return r;
4623e8e6
LP
1052
1053 r = crypt_set_data_device(cd, m->node);
1054 if (r < 0)
294bd454 1055 return r;
4623e8e6
LP
1056
1057 r = crypt_activate_by_volume_key(cd, name, root_hash, root_hash_size, CRYPT_ACTIVATE_READONLY);
1058 if (r < 0)
294bd454 1059 return r;
4623e8e6 1060
1cc6c93a
YW
1061 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1062 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
4623e8e6
LP
1063 d->n_decrypted++;
1064
1cc6c93a 1065 m->decrypted_node = TAKE_PTR(node);
4623e8e6
LP
1066
1067 return 0;
18b5886e
LP
1068}
1069#endif
1070
1071int dissected_image_decrypt(
1072 DissectedImage *m,
1073 const char *passphrase,
4623e8e6
LP
1074 const void *root_hash,
1075 size_t root_hash_size,
18b5886e
LP
1076 DissectImageFlags flags,
1077 DecryptedImage **ret) {
1078
349cc4a5 1079#if HAVE_LIBCRYPTSETUP
49b5b3b4 1080 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
18b5886e
LP
1081 unsigned i;
1082 int r;
1083#endif
1084
1085 assert(m);
4623e8e6 1086 assert(root_hash || root_hash_size == 0);
18b5886e
LP
1087
1088 /* Returns:
1089 *
1090 * = 0 → There was nothing to decrypt
1091 * > 0 → Decrypted successfully
d1c536f5 1092 * -ENOKEY → There's something to decrypt but no key was supplied
18b5886e
LP
1093 * -EKEYREJECTED → Passed key was not correct
1094 */
1095
4623e8e6
LP
1096 if (root_hash && root_hash_size < sizeof(sd_id128_t))
1097 return -EINVAL;
1098
1099 if (!m->encrypted && !m->verity) {
18b5886e
LP
1100 *ret = NULL;
1101 return 0;
1102 }
1103
349cc4a5 1104#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1105 d = new0(DecryptedImage, 1);
1106 if (!d)
1107 return -ENOMEM;
1108
1109 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1110 DissectedPartition *p = m->partitions + i;
4623e8e6 1111 int k;
18b5886e
LP
1112
1113 if (!p->found)
1114 continue;
1115
1116 r = decrypt_partition(p, passphrase, flags, d);
1117 if (r < 0)
1118 return r;
1119
4623e8e6
LP
1120 k = PARTITION_VERITY_OF(i);
1121 if (k >= 0) {
1122 r = verity_partition(p, m->partitions + k, root_hash, root_hash_size, flags, d);
1123 if (r < 0)
1124 return r;
1125 }
1126
18b5886e
LP
1127 if (!p->decrypted_fstype && p->decrypted_node) {
1128 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
7cc84b2c 1129 if (r < 0 && r != -EUCLEAN)
18b5886e
LP
1130 return r;
1131 }
1132 }
1133
1cc6c93a 1134 *ret = TAKE_PTR(d);
18b5886e
LP
1135
1136 return 1;
1137#else
1138 return -EOPNOTSUPP;
1139#endif
1140}
1141
1142int dissected_image_decrypt_interactively(
1143 DissectedImage *m,
1144 const char *passphrase,
4623e8e6
LP
1145 const void *root_hash,
1146 size_t root_hash_size,
18b5886e
LP
1147 DissectImageFlags flags,
1148 DecryptedImage **ret) {
1149
1150 _cleanup_strv_free_erase_ char **z = NULL;
1151 int n = 3, r;
1152
1153 if (passphrase)
1154 n--;
1155
1156 for (;;) {
4623e8e6 1157 r = dissected_image_decrypt(m, passphrase, root_hash, root_hash_size, flags, ret);
18b5886e
LP
1158 if (r >= 0)
1159 return r;
1160 if (r == -EKEYREJECTED)
1161 log_error_errno(r, "Incorrect passphrase, try again!");
fc95c359
YW
1162 else if (r != -ENOKEY)
1163 return log_error_errno(r, "Failed to decrypt image: %m");
18b5886e 1164
baaa35ad
ZJS
1165 if (--n < 0)
1166 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
1167 "Too many retries.");
18b5886e
LP
1168
1169 z = strv_free(z);
1170
a1c111c2 1171 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
18b5886e
LP
1172 if (r < 0)
1173 return log_error_errno(r, "Failed to query for passphrase: %m");
1174
1175 passphrase = z[0];
1176 }
1177}
1178
349cc4a5 1179#if HAVE_LIBCRYPTSETUP
18b5886e 1180static int deferred_remove(DecryptedPartition *p) {
18b5886e
LP
1181 struct dm_ioctl dm = {
1182 .version = {
1183 DM_VERSION_MAJOR,
1184 DM_VERSION_MINOR,
1185 DM_VERSION_PATCHLEVEL
1186 },
1187 .data_size = sizeof(dm),
1188 .flags = DM_DEFERRED_REMOVE,
1189 };
1190
1191 _cleanup_close_ int fd = -1;
1192
1193 assert(p);
1194
1195 /* Unfortunately, libcryptsetup doesn't provide a proper API for this, hence call the ioctl() directly. */
1196
1197 fd = open("/dev/mapper/control", O_RDWR|O_CLOEXEC);
1198 if (fd < 0)
1199 return -errno;
1200
cd8c98d7
ZJS
1201 if (strlen(p->name) > sizeof(dm.name))
1202 return -ENAMETOOLONG;
1203
18b5886e
LP
1204 strncpy(dm.name, p->name, sizeof(dm.name));
1205
1206 if (ioctl(fd, DM_DEV_REMOVE, &dm))
1207 return -errno;
1208
1209 return 0;
1210}
1211#endif
1212
1213int decrypted_image_relinquish(DecryptedImage *d) {
1214
349cc4a5 1215#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1216 size_t i;
1217 int r;
1218#endif
1219
1220 assert(d);
1221
1222 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1223 * that we don't clean it up ourselves either anymore */
1224
349cc4a5 1225#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1226 for (i = 0; i < d->n_decrypted; i++) {
1227 DecryptedPartition *p = d->decrypted + i;
1228
1229 if (p->relinquished)
1230 continue;
1231
1232 r = deferred_remove(p);
1233 if (r < 0)
1234 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
1235
1236 p->relinquished = true;
1237 }
1238#endif
1239
1240 return 0;
1241}
1242
78ebe980
LP
1243int root_hash_load(const char *image, void **ret, size_t *ret_size) {
1244 _cleanup_free_ char *text = NULL;
1245 _cleanup_free_ void *k = NULL;
78ebe980
LP
1246 size_t l;
1247 int r;
1248
1249 assert(image);
1250 assert(ret);
1251 assert(ret_size);
1252
1253 if (is_device_path(image)) {
1254 /* If we are asked to load the root hash for a device node, exit early */
1255 *ret = NULL;
1256 *ret_size = 0;
1257 return 0;
1258 }
1259
41488e1f
LP
1260 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
1261 if (r < 0) {
1262 char *fn, *e, *n;
78ebe980 1263
41488e1f
LP
1264 if (!IN_SET(r, -ENODATA, -EOPNOTSUPP, -ENOENT))
1265 return r;
78ebe980 1266
fbd0b64f 1267 fn = newa(char, strlen(image) + STRLEN(".roothash") + 1);
41488e1f
LP
1268 n = stpcpy(fn, image);
1269 e = endswith(fn, ".raw");
1270 if (e)
1271 n = e;
1272
1273 strcpy(n, ".roothash");
1274
1275 r = read_one_line_file(fn, &text);
1276 if (r == -ENOENT) {
1277 *ret = NULL;
1278 *ret_size = 0;
1279 return 0;
1280 }
1281 if (r < 0)
1282 return r;
78ebe980 1283 }
78ebe980
LP
1284
1285 r = unhexmem(text, strlen(text), &k, &l);
1286 if (r < 0)
1287 return r;
1288 if (l < sizeof(sd_id128_t))
1289 return -EINVAL;
1290
1cc6c93a 1291 *ret = TAKE_PTR(k);
78ebe980
LP
1292 *ret_size = l;
1293
78ebe980
LP
1294 return 1;
1295}
1296
3b925504
LP
1297int dissected_image_acquire_metadata(DissectedImage *m) {
1298
1299 enum {
1300 META_HOSTNAME,
1301 META_MACHINE_ID,
1302 META_MACHINE_INFO,
1303 META_OS_RELEASE,
1304 _META_MAX,
1305 };
1306
1307 static const char *const paths[_META_MAX] = {
1308 [META_HOSTNAME] = "/etc/hostname\0",
1309 [META_MACHINE_ID] = "/etc/machine-id\0",
1310 [META_MACHINE_INFO] = "/etc/machine-info\0",
1311 [META_OS_RELEASE] = "/etc/os-release\0/usr/lib/os-release\0",
1312 };
1313
1314 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL;
1315 _cleanup_(rmdir_and_freep) char *t = NULL;
1316 _cleanup_(sigkill_waitp) pid_t child = 0;
1317 sd_id128_t machine_id = SD_ID128_NULL;
1318 _cleanup_free_ char *hostname = NULL;
1319 unsigned n_meta_initialized = 0, k;
1320 int fds[2 * _META_MAX], r;
3b925504
LP
1321
1322 BLOCK_SIGNALS(SIGCHLD);
1323
1324 assert(m);
1325
1326 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++)
1327 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
1328 r = -errno;
1329 goto finish;
1330 }
1331
1332 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
1333 if (r < 0)
1334 goto finish;
1335
e2047ba9 1336 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
be39f6ee 1337 if (r < 0)
3b925504 1338 goto finish;
be39f6ee 1339 if (r == 0) {
03bcb6d4 1340 r = dissected_image_mount(m, t, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_VALIDATE_OS);
429d4e41
LP
1341 if (r < 0) {
1342 log_debug_errno(r, "Failed to mount dissected image: %m");
3b925504 1343 _exit(EXIT_FAILURE);
429d4e41 1344 }
3b925504
LP
1345
1346 for (k = 0; k < _META_MAX; k++) {
1347 _cleanup_close_ int fd = -1;
1348 const char *p;
1349
1350 fds[2*k] = safe_close(fds[2*k]);
1351
1352 NULSTR_FOREACH(p, paths[k]) {
36952d19 1353 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
3b925504
LP
1354 if (fd >= 0)
1355 break;
1356 }
36952d19
LP
1357 if (fd < 0) {
1358 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
3b925504 1359 continue;
36952d19 1360 }
3b925504
LP
1361
1362 r = copy_bytes(fd, fds[2*k+1], (uint64_t) -1, 0);
1363 if (r < 0)
1364 _exit(EXIT_FAILURE);
1365
1366 fds[2*k+1] = safe_close(fds[2*k+1]);
1367 }
1368
1369 _exit(EXIT_SUCCESS);
1370 }
1371
1372 for (k = 0; k < _META_MAX; k++) {
1373 _cleanup_fclose_ FILE *f = NULL;
1374
1375 fds[2*k+1] = safe_close(fds[2*k+1]);
1376
e92aaed3 1377 f = fdopen(fds[2*k], "r");
3b925504
LP
1378 if (!f) {
1379 r = -errno;
1380 goto finish;
1381 }
1382
1383 fds[2*k] = -1;
1384
1385 switch (k) {
1386
1387 case META_HOSTNAME:
1388 r = read_etc_hostname_stream(f, &hostname);
1389 if (r < 0)
1390 log_debug_errno(r, "Failed to read /etc/hostname: %m");
1391
1392 break;
1393
1394 case META_MACHINE_ID: {
1395 _cleanup_free_ char *line = NULL;
1396
1397 r = read_line(f, LONG_LINE_MAX, &line);
1398 if (r < 0)
1399 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
1400 else if (r == 33) {
1401 r = sd_id128_from_string(line, &machine_id);
1402 if (r < 0)
1403 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
1404 } else if (r == 0)
1405 log_debug("/etc/machine-id file is empty.");
1406 else
1407 log_debug("/etc/machine-id has unexpected length %i.", r);
1408
1409 break;
1410 }
1411
1412 case META_MACHINE_INFO:
aa8fbc74 1413 r = load_env_file_pairs(f, "machine-info", &machine_info);
3b925504
LP
1414 if (r < 0)
1415 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
1416
1417 break;
1418
1419 case META_OS_RELEASE:
aa8fbc74 1420 r = load_env_file_pairs(f, "os-release", &os_release);
3b925504
LP
1421 if (r < 0)
1422 log_debug_errno(r, "Failed to read OS release file: %m");
1423
1424 break;
1425 }
1426 }
1427
2e87a1fd 1428 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3b925504 1429 child = 0;
2e87a1fd 1430 if (r < 0)
3b925504 1431 goto finish;
2e87a1fd
LP
1432 if (r != EXIT_SUCCESS)
1433 return -EPROTO;
3b925504
LP
1434
1435 free_and_replace(m->hostname, hostname);
1436 m->machine_id = machine_id;
1437 strv_free_and_replace(m->machine_info, machine_info);
1438 strv_free_and_replace(m->os_release, os_release);
1439
1440finish:
1441 for (k = 0; k < n_meta_initialized; k++)
1442 safe_close_pair(fds + 2*k);
1443
1444 return r;
1445}
1446
4526113f
LP
1447int dissect_image_and_warn(
1448 int fd,
1449 const char *name,
1450 const void *root_hash,
1451 size_t root_hash_size,
1452 DissectImageFlags flags,
1453 DissectedImage **ret) {
1454
1455 _cleanup_free_ char *buffer = NULL;
1456 int r;
1457
1458 if (!name) {
1459 r = fd_get_path(fd, &buffer);
1460 if (r < 0)
1461 return r;
1462
1463 name = buffer;
1464 }
1465
1466 r = dissect_image(fd, root_hash, root_hash_size, flags, ret);
1467
1468 switch (r) {
1469
1470 case -EOPNOTSUPP:
1471 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
1472
1473 case -ENOPKG:
1474 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
1475
1476 case -EADDRNOTAVAIL:
1477 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
1478
1479 case -ENOTUNIQ:
1480 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
1481
1482 case -ENXIO:
1483 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
1484
1485 case -EPROTONOSUPPORT:
1486 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
1487
1488 default:
1489 if (r < 0)
1490 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
1491
1492 return r;
1493 }
1494}
1495
8c1be37e
LP
1496static const char *const partition_designator_table[] = {
1497 [PARTITION_ROOT] = "root",
1498 [PARTITION_ROOT_SECONDARY] = "root-secondary",
1499 [PARTITION_HOME] = "home",
1500 [PARTITION_SRV] = "srv",
1501 [PARTITION_ESP] = "esp",
1502 [PARTITION_SWAP] = "swap",
4623e8e6
LP
1503 [PARTITION_ROOT_VERITY] = "root-verity",
1504 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
8c1be37e
LP
1505};
1506
1507DEFINE_STRING_TABLE_LOOKUP(partition_designator, int);