]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/dissect-image.c
dissect-image: drop redundant check
[thirdparty/systemd.git] / src / shared / dissect-image.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
8c1be37e 2
10c1b188
LP
3#if HAVE_VALGRIND_MEMCHECK_H
4#include <valgrind/memcheck.h>
5#endif
6
01234e1f
YW
7#include <linux/dm-ioctl.h>
8#include <linux/loop.h>
8c1be37e 9#include <sys/mount.h>
3b925504
LP
10#include <sys/prctl.h>
11#include <sys/wait.h>
f5ea63a5 12#include <sysexits.h>
8c1be37e 13
3c1f2cee 14#include "sd-device.h"
dccca82b
LP
15#include "sd-id128.h"
16
8c1be37e 17#include "architecture.h"
18b5886e 18#include "ask-password-api.h"
8c1be37e 19#include "blkid-util.h"
18c528e9 20#include "blockdev-util.h"
3b925504 21#include "copy.h"
1e2f3230 22#include "cryptsetup-util.h"
3b925504 23#include "def.h"
553e15f2 24#include "device-nodes.h"
8437c059 25#include "device-util.h"
7718ac97 26#include "discover-image.h"
8c1be37e 27#include "dissect-image.h"
a709a315 28#include "dm-util.h"
686d13b9 29#include "env-file.h"
93f59701 30#include "extension-release.h"
18b5886e 31#include "fd-util.h"
78ebe980 32#include "fileio.h"
2eedfd2d 33#include "fs-util.h"
cf32c486 34#include "fsck-util.h"
8c1be37e 35#include "gpt.h"
78ebe980 36#include "hexdecoct.h"
e2054217 37#include "hostname-setup.h"
3b925504 38#include "id128-util.h"
593fe6c0 39#include "import-util.h"
6aa05ebd 40#include "mkdir.h"
8c1be37e 41#include "mount-util.h"
e4de7287 42#include "mountpoint-util.h"
6aa05ebd 43#include "namespace-util.h"
d8b4d14d 44#include "nulstr-util.h"
d58ad743 45#include "os-util.h"
8c1be37e 46#include "path-util.h"
3b925504
LP
47#include "process-util.h"
48#include "raw-clone.h"
81939d9d 49#include "resize-fs.h"
3b925504 50#include "signal-util.h"
8c1be37e 51#include "stat-util.h"
18b5886e 52#include "stdio-util.h"
8c1be37e
LP
53#include "string-table.h"
54#include "string-util.h"
2eedfd2d 55#include "strv.h"
e4de7287 56#include "tmpfile-util.h"
a8040b6d 57#include "udev-util.h"
2d3a5a73 58#include "user-util.h"
41488e1f 59#include "xattr-util.h"
8c1be37e 60
28e2641a
FF
61/* how many times to wait for the device nodes to appear */
62#define N_DEVICE_NODE_LIST_ATTEMPTS 10
63
c34b75a1 64int probe_filesystem(const char *node, char **ret_fstype) {
7cc84b2c 65 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
5238e957 66 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
7cc84b2c
ZJS
67 * different error otherwise. */
68
349cc4a5 69#if HAVE_BLKID
8e766630 70 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
18b5886e
LP
71 const char *fstype;
72 int r;
73
995fa2e5 74 errno = 0;
18b5886e
LP
75 b = blkid_new_probe_from_filename(node);
76 if (!b)
66855de7 77 return errno_or_else(ENOMEM);
18b5886e
LP
78
79 blkid_probe_enable_superblocks(b, 1);
80 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
81
82 errno = 0;
83 r = blkid_do_safeprobe(b);
7cc84b2c
ZJS
84 if (r == 1) {
85 log_debug("No type detected on partition %s", node);
18b5886e
LP
86 goto not_found;
87 }
58dfbfbd
LP
88 if (r == -2)
89 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
90 "Results ambiguous for partition %s", node);
b382db9f 91 if (r != 0)
66855de7 92 return errno_or_else(EIO);
18b5886e
LP
93
94 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
95
96 if (fstype) {
97 char *t;
98
99 t = strdup(fstype);
100 if (!t)
101 return -ENOMEM;
102
103 *ret_fstype = t;
104 return 1;
105 }
106
107not_found:
108 *ret_fstype = NULL;
109 return 0;
d1c536f5
ZJS
110#else
111 return -EOPNOTSUPP;
a75e27eb 112#endif
d1c536f5 113}
18b5886e 114
40c10d3f 115#if HAVE_BLKID
4ba86848
LP
116static int enumerator_for_parent(sd_device *d, sd_device_enumerator **ret) {
117 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
118 int r;
aae22eb3 119
f70e7f70 120 assert(d);
4ba86848 121 assert(ret);
f70e7f70 122
4ba86848
LP
123 r = sd_device_enumerator_new(&e);
124 if (r < 0)
125 return r;
3c1f2cee 126
210e1cd6
YW
127 r = sd_device_enumerator_add_match_subsystem(e, "block", true);
128 if (r < 0)
129 return r;
130
4ba86848
LP
131 r = sd_device_enumerator_add_match_parent(e, d);
132 if (r < 0)
133 return r;
134
210e1cd6
YW
135 r = sd_device_enumerator_add_match_sysattr(e, "partition", NULL, true);
136 if (r < 0)
137 return r;
138
4ba86848
LP
139 *ret = TAKE_PTR(e);
140 return 0;
cde942f6
JPRV
141}
142
c1737506
LP
143static int device_is_partition(
144 sd_device *d,
145 sd_device *expected_parent,
146 blkid_partition pp) {
147
0a8f9bc6 148 const char *v, *parent_syspath, *expected_parent_syspath;
4ba86848
LP
149 blkid_loff_t bsize, bstart;
150 uint64_t size, start;
151 int partno, bpartno, r;
0a8f9bc6 152 sd_device *parent;
aae22eb3 153
f70e7f70 154 assert(d);
0a8f9bc6 155 assert(expected_parent);
4ba86848 156 assert(pp);
f70e7f70 157
11368b69 158 r = sd_device_get_subsystem(d, &v);
4ba86848
LP
159 if (r < 0)
160 return r;
11368b69
YW
161 if (!streq(v, "block"))
162 return false;
163
164 if (sd_device_get_devtype(d, &v) < 0 || !streq(v, "partition"))
aae22eb3
LP
165 return false;
166
0a8f9bc6
YW
167 r = sd_device_get_parent(d, &parent);
168 if (r < 0)
169 return false; /* Doesn't have a parent? No relevant to us */
170
171 r = sd_device_get_syspath(parent, &parent_syspath); /* Check parent of device of this action */
172 if (r < 0)
173 return r;
174
175 r = sd_device_get_syspath(expected_parent, &expected_parent_syspath); /* Check parent of device we are looking for */
176 if (r < 0)
177 return r;
178
179 if (!path_equal(parent_syspath, expected_parent_syspath))
180 return false; /* Has a different parent than what we need, not interesting to us */
181
7d25c246
LP
182 /* On kernel uevents we may find the partition number in the PARTN= field. Let's use that preferably,
183 * since it's cheaper and more importantly: the sysfs attribute "partition" appears to become
c1737506
LP
184 * available late, hence let's use the property instead, which is available at the moment we see the
185 * uevent. */
186 r = sd_device_get_property_value(d, "PARTN", &v);
187 if (r == -ENOENT)
188 r = sd_device_get_sysattr_value(d, "partition", &v);
4ba86848
LP
189 if (r < 0)
190 return r;
c1737506 191
4ba86848
LP
192 r = safe_atoi(v, &partno);
193 if (r < 0)
194 return r;
ea887be0 195
4ba86848
LP
196 errno = 0;
197 bpartno = blkid_partition_get_partno(pp);
198 if (bpartno < 0)
199 return errno_or_else(EIO);
ea887be0 200
4ba86848
LP
201 if (partno != bpartno)
202 return false;
f70e7f70 203
4ba86848 204 r = sd_device_get_sysattr_value(d, "start", &v);
ea887be0
ZJS
205 if (r < 0)
206 return r;
4ba86848 207 r = safe_atou64(v, &start);
ea887be0
ZJS
208 if (r < 0)
209 return r;
210
4ba86848
LP
211 errno = 0;
212 bstart = blkid_partition_get_start(pp);
213 if (bstart < 0)
214 return errno_or_else(EIO);
215
216 if (start != (uint64_t) bstart)
217 return false;
218
219 r = sd_device_get_sysattr_value(d, "size", &v);
220 if (r < 0)
221 return r;
222 r = safe_atou64(v, &size);
ea887be0
ZJS
223 if (r < 0)
224 return r;
225
4ba86848
LP
226 errno = 0;
227 bsize = blkid_partition_get_size(pp);
228 if (bsize < 0)
229 return errno_or_else(EIO);
230
231 if (size != (uint64_t) bsize)
232 return false;
233
234 return true;
ea887be0
ZJS
235}
236
4ba86848
LP
237static int find_partition(
238 sd_device *parent,
239 blkid_partition pp,
4a62257d 240 usec_t timestamp_not_before,
3fe398ce 241 DissectImageFlags flags,
4ba86848 242 sd_device **ret) {
ea887be0
ZJS
243
244 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
245 sd_device *q;
ea887be0
ZJS
246 int r;
247
4ba86848
LP
248 assert(parent);
249 assert(pp);
250 assert(ret);
f70e7f70 251
4ba86848 252 r = enumerator_for_parent(parent, &e);
ea887be0
ZJS
253 if (r < 0)
254 return r;
255
ea887be0 256 FOREACH_DEVICE(e, q) {
4a62257d
LP
257 uint64_t usec;
258
3fe398ce
LP
259 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
260 r = sd_device_get_usec_initialized(q, &usec);
261 if (r == -EBUSY) /* Not initialized yet */
262 continue;
263 if (r < 0)
264 return r;
4a62257d 265
3fe398ce
LP
266 if (timestamp_not_before != USEC_INFINITY &&
267 usec < timestamp_not_before) /* udev database entry older than our attachment? Then it's not ours */
268 continue;
269 }
4a62257d 270
0a8f9bc6 271 r = device_is_partition(q, parent, pp);
4ba86848
LP
272 if (r < 0)
273 return r;
274 if (r > 0) {
275 *ret = sd_device_ref(q);
276 return 0;
052eaf5c 277 }
ea887be0
ZJS
278 }
279
4ba86848
LP
280 return -ENXIO;
281}
10c1b188 282
4ba86848
LP
283struct wait_data {
284 sd_device *parent_device;
285 blkid_partition blkidp;
286 sd_device *found;
a3642997 287 uint64_t diskseq;
75dc190d 288 uint64_t uevent_seqnum_not_before;
05c3c620
YW
289 usec_t timestamp_not_before;
290 DissectImageFlags flags;
4ba86848 291};
ea887be0 292
4ba86848
LP
293static inline void wait_data_done(struct wait_data *d) {
294 sd_device_unref(d->found);
295}
ea887be0 296
4ba86848 297static int device_monitor_handler(sd_device_monitor *monitor, sd_device *device, void *userdata) {
4ba86848 298 struct wait_data *w = userdata;
4ba86848
LP
299 int r;
300
301 assert(w);
302
a1130022 303 if (device_for_action(device, SD_DEVICE_REMOVE))
4ba86848
LP
304 return 0;
305
a3642997
LB
306 if (w->diskseq != 0) {
307 uint64_t diskseq;
308
309 /* If w->diskseq is non-zero, then we must have a disk seqnum */
310 r = sd_device_get_diskseq(device, &diskseq);
311 if (r < 0) {
312 log_debug_errno(r, "Dropping event because it has no diskseq, but waiting for %" PRIu64, w->diskseq);
313 return 0;
314 }
315 if (diskseq < w->diskseq) {
316 log_debug("Dropping event because diskseq too old (%" PRIu64 " < %" PRIu64 ")",
317 diskseq, w->diskseq);
318 return 0;
319 }
320 if (diskseq > w->diskseq) {
321 r = -EBUSY;
322 goto finish; /* Newer than what we were expecting, so we missed it, stop waiting */
323 }
324 } else if (w->uevent_seqnum_not_before != UINT64_MAX) {
75dc190d
LP
325 uint64_t seqnum;
326
327 r = sd_device_get_seqnum(device, &seqnum);
328 if (r < 0)
329 goto finish;
330
331 if (seqnum <= w->uevent_seqnum_not_before) { /* From an older use of this loop device */
332 log_debug("Dropping event because seqnum too old (%" PRIu64 " <= %" PRIu64 ")",
333 seqnum, w->uevent_seqnum_not_before);
334 return 0;
335 }
336 }
337
0a8f9bc6 338 r = device_is_partition(device, w->parent_device, w->blkidp);
4ba86848
LP
339 if (r < 0)
340 goto finish;
341 if (r == 0) /* Not the one we need */
342 return 0;
343
344 /* It's the one we need! Yay! */
345 assert(!w->found);
346 w->found = sd_device_ref(device);
347 r = 0;
348
349finish:
350 return sd_event_exit(sd_device_monitor_get_event(monitor), r);
ea887be0
ZJS
351}
352
05c3c620
YW
353static int timeout_handler(sd_event_source *s, uint64_t usec, void *userdata) {
354 struct wait_data *w = userdata;
355 int r;
356
357 assert(w);
358
359 /* Why partition not appeared within the timeout? We may lost some uevent, as some properties
360 * were not ready when we received uevent... Not sure, but anyway, let's try to find the
361 * partition again before give up. */
362
363 r = find_partition(w->parent_device, w->blkidp, w->timestamp_not_before, w->flags, &w->found);
364 if (r == -ENXIO)
365 return log_debug_errno(SYNTHETIC_ERRNO(ETIMEDOUT),
366 "Partition still not appeared after timeout reached.");
367 if (r < 0)
368 return log_debug_errno(r, "Failed to find partition: %m");
369
370 log_debug("Partition appeared after timeout reached.");
371 return sd_event_exit(sd_event_source_get_event(s), 0);
372}
373
61730746
YW
374static int retry_handler(sd_event_source *s, uint64_t usec, void *userdata) {
375 struct wait_data *w = userdata;
376 int r;
377
378 assert(w);
379
380 r = find_partition(w->parent_device, w->blkidp, w->timestamp_not_before, w->flags, &w->found);
381 if (r != -ENXIO) {
382 if (r < 0)
383 return log_debug_errno(r, "Failed to find partition: %m");
384
385 log_debug("Partition found by a periodic search.");
386 return sd_event_exit(sd_event_source_get_event(s), 0);
387 }
388
389 r = sd_event_source_set_time_relative(s, 500 * USEC_PER_MSEC);
390 if (r < 0)
391 return r;
392
393 return sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
394}
395
4ba86848
LP
396static int wait_for_partition_device(
397 sd_device *parent,
398 blkid_partition pp,
399 usec_t deadline,
a3642997 400 uint64_t diskseq,
75dc190d 401 uint64_t uevent_seqnum_not_before,
4a62257d 402 usec_t timestamp_not_before,
3fe398ce 403 DissectImageFlags flags,
4ba86848
LP
404 sd_device **ret) {
405
61730746 406 _cleanup_(sd_event_source_unrefp) sd_event_source *timeout_source = NULL, *retry_source = NULL;
4ba86848
LP
407 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
408 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
ea887be0
ZJS
409 int r;
410
4ba86848
LP
411 assert(parent);
412 assert(pp);
413 assert(ret);
414
3fe398ce 415 r = find_partition(parent, pp, timestamp_not_before, flags, ret);
4ba86848
LP
416 if (r != -ENXIO)
417 return r;
418
419 r = sd_event_new(&event);
420 if (r < 0)
421 return r;
422
423 r = sd_device_monitor_new(&monitor);
424 if (r < 0)
425 return r;
426
427 r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "block", "partition");
428 if (r < 0)
429 return r;
430
210e1cd6
YW
431 r = sd_device_monitor_filter_add_match_parent(monitor, parent, true);
432 if (r < 0)
433 return r;
434
435 r = sd_device_monitor_filter_add_match_sysattr(monitor, "partition", NULL, true);
436 if (r < 0)
437 return r;
438
4ba86848
LP
439 r = sd_device_monitor_attach_event(monitor, event);
440 if (r < 0)
441 return r;
442
443 _cleanup_(wait_data_done) struct wait_data w = {
444 .parent_device = parent,
445 .blkidp = pp,
a3642997 446 .diskseq = diskseq,
75dc190d 447 .uevent_seqnum_not_before = uevent_seqnum_not_before,
05c3c620
YW
448 .timestamp_not_before = timestamp_not_before,
449 .flags = flags,
4ba86848 450 };
f70e7f70 451
4ba86848
LP
452 r = sd_device_monitor_start(monitor, device_monitor_handler, &w);
453 if (r < 0)
454 return r;
a8040b6d 455
4ba86848 456 /* Check again, the partition might have appeared in the meantime */
3fe398ce 457 r = find_partition(parent, pp, timestamp_not_before, flags, ret);
4ba86848
LP
458 if (r != -ENXIO)
459 return r;
460
461 if (deadline != USEC_INFINITY) {
462 r = sd_event_add_time(
463 event, &timeout_source,
464 CLOCK_MONOTONIC, deadline, 0,
05c3c620
YW
465 timeout_handler, &w);
466 if (r < 0)
467 return r;
468
469 r = sd_event_source_set_exit_on_failure(timeout_source, true);
4ba86848 470 if (r < 0)
ea887be0
ZJS
471 return r;
472 }
473
a3642997
LB
474 /* If we don't have a disk sequence number then we cannot do exact matching,
475 * and we cannot know if we missed it or if it has not been sent yet, so set
476 * up additional retries to increase the chances of receiving the event. */
477 if (diskseq == 0) {
478 r = sd_event_add_time_relative(
479 event, &retry_source,
480 CLOCK_MONOTONIC, 500 * USEC_PER_MSEC, 0,
481 retry_handler, &w);
482 if (r < 0)
483 return r;
61730746 484
a3642997
LB
485 r = sd_event_source_set_exit_on_failure(retry_source, true);
486 if (r < 0)
487 return r;
488 }
61730746 489
4ba86848
LP
490 r = sd_event_loop(event);
491 if (r < 0)
492 return r;
493
494 assert(w.found);
495 *ret = TAKE_PTR(w.found);
496 return 0;
ea887be0
ZJS
497}
498
0f7c9a3d
LP
499static void check_partition_flags(
500 const char *node,
501 unsigned long long pflags,
502 unsigned long long supported) {
503
504 assert(node);
505
506 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
507 pflags &= ~(supported | GPT_FLAG_REQUIRED_PARTITION | GPT_FLAG_NO_BLOCK_IO_PROTOCOL | GPT_FLAG_LEGACY_BIOS_BOOTABLE);
508
509 if (pflags == 0)
510 return;
511
512 /* If there are other bits set, then log about it, to make things discoverable */
513 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
514 unsigned long long bit = 1ULL << i;
515 if (!FLAGS_SET(pflags, bit))
516 continue;
517
518 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
519 }
520}
521
786e3a52
LP
522static int device_wait_for_initialization_harder(
523 sd_device *device,
524 const char *subsystem,
525 usec_t deadline,
526 sd_device **ret) {
527
786e3a52
LP
528 usec_t start, left, retrigger_timeout;
529 int r;
530
531 start = now(CLOCK_MONOTONIC);
532 left = usec_sub_unsigned(deadline, start);
533
534 if (DEBUG_LOGGING) {
786e3a52
LP
535 const char *sn = NULL;
536
537 (void) sd_device_get_sysname(device, &sn);
b64c4ece 538 log_device_debug(device,
5291f26d 539 "Waiting for device '%s' to initialize for %s.", strna(sn), FORMAT_TIMESPAN(left, 0));
786e3a52
LP
540 }
541
542 if (left != USEC_INFINITY)
543 retrigger_timeout = CLAMP(left / 4, 1 * USEC_PER_SEC, 5 * USEC_PER_SEC); /* A fourth of the total timeout, but let's clamp to 1s…5s range */
544 else
545 retrigger_timeout = 2 * USEC_PER_SEC;
546
547 for (;;) {
548 usec_t local_deadline, n;
549 bool last_try;
550
551 n = now(CLOCK_MONOTONIC);
552 assert(n >= start);
553
554 /* Find next deadline, when we'll retrigger */
555 local_deadline = start +
556 DIV_ROUND_UP(n - start, retrigger_timeout) * retrigger_timeout;
557
558 if (deadline != USEC_INFINITY && deadline <= local_deadline) {
559 local_deadline = deadline;
560 last_try = true;
561 } else
562 last_try = false;
563
564 r = device_wait_for_initialization(device, subsystem, local_deadline, ret);
565 if (r >= 0 && DEBUG_LOGGING) {
786e3a52
LP
566 const char *sn = NULL;
567
568 (void) sd_device_get_sysname(device, &sn);
b64c4ece
LP
569 log_device_debug(device,
570 "Successfully waited for device '%s' to initialize for %s.",
571 strna(sn),
5291f26d 572 FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0));
786e3a52
LP
573
574 }
575 if (r != -ETIMEDOUT || last_try)
576 return r;
577
5291f26d 578 if (DEBUG_LOGGING)
b64c4ece
LP
579 log_device_debug(device,
580 "Device didn't initialize within %s, assuming lost event. Retriggering device.",
5291f26d 581 FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0));
786e3a52 582
b64c4ece 583 r = sd_device_trigger(device, SD_DEVICE_CHANGE);
786e3a52
LP
584 if (r < 0)
585 return r;
586 }
587}
40c10d3f 588#endif
aae22eb3 589
4ba86848
LP
590#define DEVICE_TIMEOUT_USEC (45 * USEC_PER_SEC)
591
08fe0a53
LP
592static void dissected_partition_done(DissectedPartition *p) {
593 assert(p);
594
595 free(p->fstype);
596 free(p->node);
597 free(p->label);
598 free(p->decrypted_fstype);
599 free(p->decrypted_node);
600 free(p->mount_options);
601
602 *p = (DissectedPartition) {
603 .partno = -1,
604 .architecture = -1
605 };
606}
607
4526113f
LP
608int dissect_image(
609 int fd,
89e62e0b 610 const VeritySettings *verity,
18d73705 611 const MountOptions *mount_options,
a3642997 612 uint64_t diskseq,
75dc190d 613 uint64_t uevent_seqnum_not_before,
4a62257d 614 usec_t timestamp_not_before,
4526113f
LP
615 DissectImageFlags flags,
616 DissectedImage **ret) {
8c1be37e 617
349cc4a5 618#if HAVE_BLKID
62ea0ed0
LP
619#ifdef GPT_ROOT_NATIVE
620 sd_id128_t root_uuid = SD_ID128_NULL, root_verity_uuid = SD_ID128_NULL;
621#endif
622#ifdef GPT_USR_NATIVE
623 sd_id128_t usr_uuid = SD_ID128_NULL, usr_verity_uuid = SD_ID128_NULL;
624#endif
1f8fb21c 625 bool is_gpt, is_mbr, multiple_generic = false,
de98f631
LP
626 generic_rw = false, /* initialize to appease gcc */
627 generic_growfs = false;
3c1f2cee 628 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
8c1be37e 629 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
8e766630 630 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
8c1be37e 631 _cleanup_free_ char *generic_node = NULL;
be30ad41 632 sd_id128_t generic_uuid = SD_ID128_NULL;
593fe6c0 633 const char *pttype = NULL, *sysname = NULL;
8c1be37e 634 blkid_partlist pl;
1f8fb21c 635 int r, generic_nr = -1, n_partitions;
8c1be37e 636 struct stat st;
4ba86848 637 usec_t deadline;
8c1be37e
LP
638
639 assert(fd >= 0);
640 assert(ret);
a0bff7ea 641 assert(!verity || verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
89e62e0b 642 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
a0bff7ea
LP
643 assert(!verity || verity->root_hash_sig || verity->root_hash_sig_size == 0);
644 assert(!verity || (verity->root_hash || !verity->root_hash_sig));
e7cbe5cb 645 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
8c1be37e
LP
646
647 /* Probes a disk image, and returns information about what it found in *ret.
648 *
4623e8e6 649 * Returns -ENOPKG if no suitable partition table or file system could be found.
2679f407
LP
650 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
651 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
652 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that */
4623e8e6 653
89e62e0b 654 if (verity && verity->root_hash) {
aee36b4e
LP
655 sd_id128_t fsuuid, vuuid;
656
657 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
658 * first 128bit of the root hash. And we use the verity partition that has a UUID that match
659 * the final 128bit. */
4623e8e6 660
89e62e0b 661 if (verity->root_hash_size < sizeof(sd_id128_t))
4623e8e6
LP
662 return -EINVAL;
663
aee36b4e
LP
664 memcpy(&fsuuid, verity->root_hash, sizeof(sd_id128_t));
665 memcpy(&vuuid, (const uint8_t*) verity->root_hash + verity->root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
4623e8e6 666
aee36b4e 667 if (sd_id128_is_null(fsuuid))
4623e8e6 668 return -EINVAL;
aee36b4e 669 if (sd_id128_is_null(vuuid))
4623e8e6 670 return -EINVAL;
aee36b4e
LP
671
672 /* If the verity data declares it's for the /usr partition, then search for that, in all
673 * other cases assume it's for the root partition. */
62ea0ed0 674#ifdef GPT_USR_NATIVE
aee36b4e
LP
675 if (verity->designator == PARTITION_USR) {
676 usr_uuid = fsuuid;
677 usr_verity_uuid = vuuid;
678 } else {
62ea0ed0
LP
679#endif
680#ifdef GPT_ROOT_NATIVE
aee36b4e
LP
681 root_uuid = fsuuid;
682 root_verity_uuid = vuuid;
62ea0ed0
LP
683#endif
684#ifdef GPT_USR_NATIVE
aee36b4e 685 }
62ea0ed0 686#endif
4623e8e6 687 }
8c1be37e
LP
688
689 if (fstat(fd, &st) < 0)
690 return -errno;
691
692 if (!S_ISBLK(st.st_mode))
693 return -ENOTBLK;
694
930aa88f 695 r = sd_device_new_from_stat_rdev(&d, &st);
6c544d14
LP
696 if (r < 0)
697 return r;
698
699 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
700 _cleanup_(sd_device_unrefp) sd_device *initialized = NULL;
701
702 /* If udev support is enabled, then let's wait for the device to be initialized before we doing anything. */
703
786e3a52
LP
704 r = device_wait_for_initialization_harder(
705 d,
706 "block",
707 usec_add(now(CLOCK_MONOTONIC), DEVICE_TIMEOUT_USEC),
708 &initialized);
6c544d14
LP
709 if (r < 0)
710 return r;
711
712 sd_device_unref(d);
713 d = TAKE_PTR(initialized);
714 }
715
8c1be37e
LP
716 b = blkid_new_probe();
717 if (!b)
718 return -ENOMEM;
719
720 errno = 0;
721 r = blkid_probe_set_device(b, fd, 0, 0);
b382db9f 722 if (r != 0)
66855de7 723 return errno_or_else(ENOMEM);
8c1be37e 724
9b6deb03
LP
725 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
726 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
727 blkid_probe_enable_superblocks(b, 1);
728 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
729 }
730
8c1be37e
LP
731 blkid_probe_enable_partitions(b, 1);
732 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
733
734 errno = 0;
735 r = blkid_do_safeprobe(b);
59ba6d0c
LP
736 if (IN_SET(r, -2, 1))
737 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
b382db9f 738 if (r != 0)
66855de7 739 return errno_or_else(EIO);
8c1be37e
LP
740
741 m = new0(DissectedImage, 1);
742 if (!m)
743 return -ENOMEM;
744
593fe6c0
LB
745 r = sd_device_get_sysname(d, &sysname);
746 if (r < 0)
747 return log_debug_errno(r, "Failed to get device sysname: %m");
748 if (startswith(sysname, "loop")) {
749 _cleanup_free_ char *name_stripped = NULL;
750 const char *full_path;
751
752 r = sd_device_get_sysattr_value(d, "loop/backing_file", &full_path);
753 if (r < 0)
754 log_debug_errno(r, "Failed to lookup image name via loop device backing file sysattr, ignoring: %m");
755 else {
756 r = raw_strip_suffixes(basename(full_path), &name_stripped);
757 if (r < 0)
758 return r;
759 }
760
761 free_and_replace(m->image_name, name_stripped);
762 } else {
763 r = free_and_strdup(&m->image_name, sysname);
764 if (r < 0)
765 return r;
766 }
767
768 if (!image_name_is_valid(m->image_name)) {
769 log_debug("Image name %s is not valid, ignoring", strempty(m->image_name));
770 m->image_name = mfree(m->image_name);
771 }
772
e7cbe5cb 773 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
4b5de5dd 774 (flags & DISSECT_IMAGE_GENERIC_ROOT)) ||
e7cbe5cb 775 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
9b6deb03 776 const char *usage = NULL;
8c1be37e 777
aee36b4e
LP
778 /* If flags permit this, also allow using non-partitioned single-filesystem images */
779
9b6deb03
LP
780 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
781 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
6c544d14 782 const char *fstype = NULL, *options = NULL, *devname = NULL;
18d73705 783 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
8c1be37e 784
9b6deb03
LP
785 /* OK, we have found a file system, that's our root partition then. */
786 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
8c1be37e 787
9b6deb03
LP
788 if (fstype) {
789 t = strdup(fstype);
790 if (!t)
791 return -ENOMEM;
792 }
793
6c544d14 794 r = sd_device_get_devname(d, &devname);
54b22b26
LP
795 if (r < 0)
796 return r;
8c1be37e 797
6c544d14
LP
798 n = strdup(devname);
799 if (!n)
800 return -ENOMEM;
801
e7cbe5cb 802 m->single_file_system = true;
c3c88d67
LP
803 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
804
805 m->has_verity = verity && verity->data_path;
806 m->verity_ready = m->has_verity &&
807 verity->root_hash &&
808 (verity->designator < 0 || verity->designator == PARTITION_ROOT);
e7cbe5cb 809
f5215bc8 810 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
18d73705
LB
811 if (options) {
812 o = strdup(options);
813 if (!o)
814 return -ENOMEM;
815 }
816
9b6deb03
LP
817 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
818 .found = true,
e0d53d52 819 .rw = !m->verity_ready && !fstype_is_ro(fstype),
9b6deb03
LP
820 .partno = -1,
821 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a
YW
822 .fstype = TAKE_PTR(t),
823 .node = TAKE_PTR(n),
18d73705 824 .mount_options = TAKE_PTR(o),
9b6deb03 825 };
8c1be37e 826
1cc6c93a 827 *ret = TAKE_PTR(m);
9b6deb03
LP
828 return 0;
829 }
8c1be37e
LP
830 }
831
832 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
833 if (!pttype)
834 return -ENOPKG;
835
836 is_gpt = streq_ptr(pttype, "gpt");
837 is_mbr = streq_ptr(pttype, "dos");
838
9b6deb03 839 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
8c1be37e
LP
840 return -ENOPKG;
841
0903fd26
LP
842 /* We support external verity data partitions only if the image has no partition table */
843 if (verity && verity->data_path)
844 return -EBADR;
845
4ba86848
LP
846 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
847 * do partition scanning. */
848 r = blockdev_partscan_enabled(fd);
849 if (r < 0)
850 return r;
851 if (r == 0)
852 return -EPROTONOSUPPORT;
853
8c1be37e
LP
854 errno = 0;
855 pl = blkid_probe_get_partitions(b);
b382db9f 856 if (!pl)
66855de7 857 return errno_or_else(ENOMEM);
8c1be37e 858
4ba86848
LP
859 errno = 0;
860 n_partitions = blkid_partlist_numof_partitions(pl);
861 if (n_partitions < 0)
862 return errno_or_else(EIO);
8c1be37e 863
4ba86848
LP
864 deadline = usec_add(now(CLOCK_MONOTONIC), DEVICE_TIMEOUT_USEC);
865 for (int i = 0; i < n_partitions; i++) {
866 _cleanup_(sd_device_unrefp) sd_device *q = NULL;
9b6deb03 867 unsigned long long pflags;
8c1be37e 868 blkid_partition pp;
cde942f6 869 const char *node;
8c1be37e
LP
870 int nr;
871
4ba86848
LP
872 errno = 0;
873 pp = blkid_partlist_get_partition(pl, i);
874 if (!pp)
875 return errno_or_else(EIO);
aae22eb3 876
a3642997 877 r = wait_for_partition_device(d, pp, deadline, diskseq, uevent_seqnum_not_before, timestamp_not_before, flags, &q);
4ba86848
LP
878 if (r < 0)
879 return r;
7be1420f 880
3c1f2cee
YW
881 r = sd_device_get_devname(q, &node);
882 if (r < 0)
4ba86848 883 return r;
8c1be37e 884
9b6deb03 885 pflags = blkid_partition_get_flags(pp);
8c1be37e 886
4ba86848 887 errno = 0;
8c1be37e
LP
888 nr = blkid_partition_get_partno(pp);
889 if (nr < 0)
4ba86848 890 return errno_or_else(EIO);
8c1be37e
LP
891
892 if (is_gpt) {
569a0e42
LP
893 PartitionDesignator designator = _PARTITION_DESIGNATOR_INVALID;
894 int architecture = _ARCHITECTURE_INVALID;
08fe0a53 895 const char *stype, *sid, *fstype = NULL, *label;
4623e8e6 896 sd_id128_t type_id, id;
de98f631 897 bool rw = true, growfs = false;
8c1be37e 898
4623e8e6
LP
899 sid = blkid_partition_get_uuid(pp);
900 if (!sid)
901 continue;
902 if (sd_id128_from_string(sid, &id) < 0)
903 continue;
904
8c1be37e
LP
905 stype = blkid_partition_get_type_string(pp);
906 if (!stype)
907 continue;
8c1be37e
LP
908 if (sd_id128_from_string(stype, &type_id) < 0)
909 continue;
910
08fe0a53
LP
911 label = blkid_partition_get_name(pp); /* libblkid returns NULL here if empty */
912
8c1be37e 913 if (sd_id128_equal(type_id, GPT_HOME)) {
a48dd347 914
de98f631 915 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
0f7c9a3d 916
a48dd347
LP
917 if (pflags & GPT_FLAG_NO_AUTO)
918 continue;
919
8c1be37e 920 designator = PARTITION_HOME;
9b6deb03 921 rw = !(pflags & GPT_FLAG_READ_ONLY);
de98f631 922 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
aee36b4e 923
8c1be37e 924 } else if (sd_id128_equal(type_id, GPT_SRV)) {
a48dd347 925
de98f631 926 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
0f7c9a3d 927
a48dd347
LP
928 if (pflags & GPT_FLAG_NO_AUTO)
929 continue;
930
8c1be37e 931 designator = PARTITION_SRV;
9b6deb03 932 rw = !(pflags & GPT_FLAG_READ_ONLY);
de98f631 933 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
aee36b4e 934
8c1be37e 935 } else if (sd_id128_equal(type_id, GPT_ESP)) {
a48dd347 936
aee36b4e
LP
937 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is
938 * not defined there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
939 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
940 * Partitions"). */
a48dd347
LP
941
942 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
943 continue;
944
8c1be37e
LP
945 designator = PARTITION_ESP;
946 fstype = "vfat";
a8c47660
LP
947
948 } else if (sd_id128_equal(type_id, GPT_XBOOTLDR)) {
949
de98f631 950 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
0f7c9a3d 951
a8c47660
LP
952 if (pflags & GPT_FLAG_NO_AUTO)
953 continue;
954
955 designator = PARTITION_XBOOTLDR;
956 rw = !(pflags & GPT_FLAG_READ_ONLY);
de98f631 957 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
8c1be37e
LP
958 }
959#ifdef GPT_ROOT_NATIVE
960 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
4623e8e6 961
de98f631 962 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
0f7c9a3d 963
a48dd347
LP
964 if (pflags & GPT_FLAG_NO_AUTO)
965 continue;
966
4623e8e6
LP
967 /* If a root ID is specified, ignore everything but the root id */
968 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
969 continue;
970
8c1be37e
LP
971 designator = PARTITION_ROOT;
972 architecture = native_architecture();
9b6deb03 973 rw = !(pflags & GPT_FLAG_READ_ONLY);
de98f631 974 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
aee36b4e 975
4f8b86e3 976 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
4623e8e6 977
0f7c9a3d
LP
978 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
979
a48dd347
LP
980 if (pflags & GPT_FLAG_NO_AUTO)
981 continue;
982
c3c88d67 983 m->has_verity = true;
4623e8e6
LP
984
985 /* Ignore verity unless a root hash is specified */
aee36b4e 986 if (sd_id128_is_null(root_verity_uuid) || !sd_id128_equal(root_verity_uuid, id))
4623e8e6
LP
987 continue;
988
989 designator = PARTITION_ROOT_VERITY;
990 fstype = "DM_verity_hash";
991 architecture = native_architecture();
992 rw = false;
993 }
994#endif
8c1be37e
LP
995#ifdef GPT_ROOT_SECONDARY
996 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
4623e8e6 997
de98f631 998 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
0f7c9a3d 999
a48dd347
LP
1000 if (pflags & GPT_FLAG_NO_AUTO)
1001 continue;
1002
4623e8e6
LP
1003 /* If a root ID is specified, ignore everything but the root id */
1004 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
1005 continue;
1006
8c1be37e
LP
1007 designator = PARTITION_ROOT_SECONDARY;
1008 architecture = SECONDARY_ARCHITECTURE;
9b6deb03 1009 rw = !(pflags & GPT_FLAG_READ_ONLY);
de98f631 1010 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
aee36b4e 1011
4f8b86e3 1012 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
a48dd347 1013
0f7c9a3d
LP
1014 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1015
a48dd347
LP
1016 if (pflags & GPT_FLAG_NO_AUTO)
1017 continue;
1018
c3c88d67 1019 m->has_verity = true;
4623e8e6
LP
1020
1021 /* Ignore verity unless root has is specified */
aee36b4e 1022 if (sd_id128_is_null(root_verity_uuid) || !sd_id128_equal(root_verity_uuid, id))
4623e8e6
LP
1023 continue;
1024
1025 designator = PARTITION_ROOT_SECONDARY_VERITY;
1026 fstype = "DM_verity_hash";
1027 architecture = SECONDARY_ARCHITECTURE;
1028 rw = false;
1029 }
aee36b4e
LP
1030#endif
1031#ifdef GPT_USR_NATIVE
1032 else if (sd_id128_equal(type_id, GPT_USR_NATIVE)) {
1033
de98f631 1034 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
aee36b4e
LP
1035
1036 if (pflags & GPT_FLAG_NO_AUTO)
1037 continue;
1038
1039 /* If a usr ID is specified, ignore everything but the usr id */
1040 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
1041 continue;
1042
1043 designator = PARTITION_USR;
1044 architecture = native_architecture();
1045 rw = !(pflags & GPT_FLAG_READ_ONLY);
de98f631 1046 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
aee36b4e
LP
1047
1048 } else if (sd_id128_equal(type_id, GPT_USR_NATIVE_VERITY)) {
1049
1050 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1051
1052 if (pflags & GPT_FLAG_NO_AUTO)
1053 continue;
1054
c3c88d67 1055 m->has_verity = true;
aee36b4e
LP
1056
1057 /* Ignore verity unless a usr hash is specified */
1058 if (sd_id128_is_null(usr_verity_uuid) || !sd_id128_equal(usr_verity_uuid, id))
1059 continue;
1060
1061 designator = PARTITION_USR_VERITY;
1062 fstype = "DM_verity_hash";
1063 architecture = native_architecture();
1064 rw = false;
1065 }
1066#endif
1067#ifdef GPT_USR_SECONDARY
1068 else if (sd_id128_equal(type_id, GPT_USR_SECONDARY)) {
1069
de98f631 1070 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
aee36b4e
LP
1071
1072 if (pflags & GPT_FLAG_NO_AUTO)
1073 continue;
1074
1075 /* If a usr ID is specified, ignore everything but the usr id */
1076 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
1077 continue;
1078
1079 designator = PARTITION_USR_SECONDARY;
1080 architecture = SECONDARY_ARCHITECTURE;
1081 rw = !(pflags & GPT_FLAG_READ_ONLY);
de98f631 1082 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
aee36b4e
LP
1083
1084 } else if (sd_id128_equal(type_id, GPT_USR_SECONDARY_VERITY)) {
1085
1086 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1087
1088 if (pflags & GPT_FLAG_NO_AUTO)
1089 continue;
1090
c3c88d67 1091 m->has_verity = true;
aee36b4e
LP
1092
1093 /* Ignore verity unless usr has is specified */
1094 if (sd_id128_is_null(usr_verity_uuid) || !sd_id128_equal(usr_verity_uuid, id))
1095 continue;
1096
1097 designator = PARTITION_USR_SECONDARY_VERITY;
1098 fstype = "DM_verity_hash";
1099 architecture = SECONDARY_ARCHITECTURE;
1100 rw = false;
1101 }
8c1be37e
LP
1102#endif
1103 else if (sd_id128_equal(type_id, GPT_SWAP)) {
a48dd347 1104
0f7c9a3d
LP
1105 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO);
1106
a48dd347
LP
1107 if (pflags & GPT_FLAG_NO_AUTO)
1108 continue;
1109
8c1be37e 1110 designator = PARTITION_SWAP;
aee36b4e 1111
8c1be37e
LP
1112 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
1113
de98f631 1114 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
0f7c9a3d 1115
a48dd347
LP
1116 if (pflags & GPT_FLAG_NO_AUTO)
1117 continue;
1118
8c1be37e
LP
1119 if (generic_node)
1120 multiple_generic = true;
1121 else {
1122 generic_nr = nr;
9b6deb03 1123 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
de98f631 1124 generic_growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
be30ad41 1125 generic_uuid = id;
8c1be37e
LP
1126 generic_node = strdup(node);
1127 if (!generic_node)
1128 return -ENOMEM;
1129 }
d4dffb85
LP
1130
1131 } else if (sd_id128_equal(type_id, GPT_TMP)) {
1132
de98f631 1133 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
0f7c9a3d 1134
d4dffb85
LP
1135 if (pflags & GPT_FLAG_NO_AUTO)
1136 continue;
1137
1138 designator = PARTITION_TMP;
1139 rw = !(pflags & GPT_FLAG_READ_ONLY);
de98f631 1140 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
d4dffb85
LP
1141
1142 } else if (sd_id128_equal(type_id, GPT_VAR)) {
1143
de98f631 1144 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
0f7c9a3d 1145
d4dffb85
LP
1146 if (pflags & GPT_FLAG_NO_AUTO)
1147 continue;
1148
1149 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
1150 sd_id128_t var_uuid;
1151
1152 /* For /var we insist that the uuid of the partition matches the
1153 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
1154 * ID. Why? Unlike the other partitions /var is inherently
1155 * installation specific, hence we need to be careful not to mount it
1156 * in the wrong installation. By hashing the partition UUID from
1157 * /etc/machine-id we can securely bind the partition to the
1158 * installation. */
1159
1160 r = sd_id128_get_machine_app_specific(GPT_VAR, &var_uuid);
1161 if (r < 0)
1162 return r;
1163
1164 if (!sd_id128_equal(var_uuid, id)) {
1165 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
1166 continue;
1167 }
1168 }
1169
1170 designator = PARTITION_VAR;
1171 rw = !(pflags & GPT_FLAG_READ_ONLY);
de98f631 1172 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
8c1be37e
LP
1173 }
1174
1175 if (designator != _PARTITION_DESIGNATOR_INVALID) {
08fe0a53 1176 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL, *l = NULL;
18d73705 1177 const char *options = NULL;
8c1be37e 1178
08fe0a53
LP
1179 if (m->partitions[designator].found) {
1180 /* For most partition types the first one we see wins. Except for the
1181 * rootfs and /usr, where we do a version compare of the label, and
1182 * let the newest version win. This permits a simple A/B versioning
1183 * scheme in OS images. */
1184
1185 if (!PARTITION_DESIGNATOR_VERSIONED(designator) ||
1186 strverscmp_improved(m->partitions[designator].label, label) >= 0)
1187 continue;
1188
1189 dissected_partition_done(m->partitions + designator);
1190 }
8c1be37e
LP
1191
1192 if (fstype) {
1193 t = strdup(fstype);
1194 if (!t)
1195 return -ENOMEM;
1196 }
1197
1198 n = strdup(node);
1199 if (!n)
1200 return -ENOMEM;
1201
08fe0a53
LP
1202 if (label) {
1203 l = strdup(label);
1204 if (!l)
1205 return -ENOMEM;
1206 }
1207
f5215bc8 1208 options = mount_options_from_designator(mount_options, designator);
18d73705
LB
1209 if (options) {
1210 o = strdup(options);
1211 if (!o)
1212 return -ENOMEM;
1213 }
1214
8c1be37e
LP
1215 m->partitions[designator] = (DissectedPartition) {
1216 .found = true,
1217 .partno = nr,
1218 .rw = rw,
de98f631 1219 .growfs = growfs,
8c1be37e 1220 .architecture = architecture,
1cc6c93a
YW
1221 .node = TAKE_PTR(n),
1222 .fstype = TAKE_PTR(t),
08fe0a53 1223 .label = TAKE_PTR(l),
be30ad41 1224 .uuid = id,
18d73705 1225 .mount_options = TAKE_PTR(o),
8c1be37e 1226 };
8c1be37e
LP
1227 }
1228
1229 } else if (is_mbr) {
1230
a8c47660 1231 switch (blkid_partition_get_type(pp)) {
8c1be37e 1232
a8c47660
LP
1233 case 0x83: /* Linux partition */
1234
1235 if (pflags != 0x80) /* Bootable flag */
1236 continue;
8c1be37e 1237
a8c47660
LP
1238 if (generic_node)
1239 multiple_generic = true;
1240 else {
1241 generic_nr = nr;
1242 generic_rw = true;
de98f631 1243 generic_growfs = false;
a8c47660
LP
1244 generic_node = strdup(node);
1245 if (!generic_node)
1246 return -ENOMEM;
1247 }
1248
1249 break;
1250
1251 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
18d73705 1252 _cleanup_free_ char *n = NULL, *o = NULL;
a8c47660 1253 sd_id128_t id = SD_ID128_NULL;
18d73705 1254 const char *sid, *options = NULL;
a8c47660
LP
1255
1256 /* First one wins */
1257 if (m->partitions[PARTITION_XBOOTLDR].found)
1258 continue;
1259
1260 sid = blkid_partition_get_uuid(pp);
1261 if (sid)
1262 (void) sd_id128_from_string(sid, &id);
1263
1264 n = strdup(node);
1265 if (!n)
8c1be37e 1266 return -ENOMEM;
a8c47660 1267
f5215bc8 1268 options = mount_options_from_designator(mount_options, PARTITION_XBOOTLDR);
18d73705
LB
1269 if (options) {
1270 o = strdup(options);
1271 if (!o)
1272 return -ENOMEM;
1273 }
1274
a8c47660
LP
1275 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
1276 .found = true,
1277 .partno = nr,
1278 .rw = true,
de98f631 1279 .growfs = false,
a8c47660
LP
1280 .architecture = _ARCHITECTURE_INVALID,
1281 .node = TAKE_PTR(n),
1282 .uuid = id,
18d73705 1283 .mount_options = TAKE_PTR(o),
a8c47660
LP
1284 };
1285
1286 break;
1287 }}
8c1be37e
LP
1288 }
1289 }
1290
74cb2db9
LP
1291 if (m->partitions[PARTITION_ROOT].found) {
1292 /* If we found the primary arch, then invalidate the secondary arch to avoid any ambiguities,
1293 * since we never want to mount the secondary arch in this case. */
1294 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
1295 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
aee36b4e
LP
1296 m->partitions[PARTITION_USR_SECONDARY].found = false;
1297 m->partitions[PARTITION_USR_SECONDARY_VERITY].found = false;
8c1be37e 1298
7cf66030
LP
1299 } else if (m->partitions[PARTITION_ROOT_VERITY].found)
1300 return -EADDRNOTAVAIL; /* Verity found but no matching rootfs? Something is off, refuse. */
4623e8e6 1301
7cf66030 1302 else if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
aee36b4e 1303
7cf66030
LP
1304 /* No root partition found but there's one for the secondary architecture? Then upgrade
1305 * secondary arch to first */
4623e8e6 1306
7cf66030
LP
1307 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
1308 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
1309 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
1310 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
aee36b4e 1311
7cf66030
LP
1312 m->partitions[PARTITION_USR] = m->partitions[PARTITION_USR_SECONDARY];
1313 zero(m->partitions[PARTITION_USR_SECONDARY]);
1314 m->partitions[PARTITION_USR_VERITY] = m->partitions[PARTITION_USR_SECONDARY_VERITY];
1315 zero(m->partitions[PARTITION_USR_SECONDARY_VERITY]);
e0f9e7bd 1316
7cf66030
LP
1317 } else if (m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found)
1318 return -EADDRNOTAVAIL; /* as above */
18d73705 1319
4ab51780 1320 if (m->partitions[PARTITION_USR].found) {
7cf66030
LP
1321
1322 /* Invalidate secondary arch /usr/ if we found the primary arch */
1323 m->partitions[PARTITION_USR_SECONDARY].found = false;
1324 m->partitions[PARTITION_USR_SECONDARY_VERITY].found = false;
1325
1326 } else if (m->partitions[PARTITION_USR_VERITY].found)
1327 return -EADDRNOTAVAIL; /* as above */
8c1be37e 1328
7cf66030 1329 else if (m->partitions[PARTITION_USR_SECONDARY].found) {
e0f9e7bd 1330
7cf66030
LP
1331 /* Upgrade secondary arch to primary */
1332 m->partitions[PARTITION_USR] = m->partitions[PARTITION_USR_SECONDARY];
1333 zero(m->partitions[PARTITION_USR_SECONDARY]);
1334 m->partitions[PARTITION_USR_VERITY] = m->partitions[PARTITION_USR_SECONDARY_VERITY];
1335 zero(m->partitions[PARTITION_USR_SECONDARY_VERITY]);
1336
1337 } else if (m->partitions[PARTITION_USR_SECONDARY_VERITY].found)
1338 return -EADDRNOTAVAIL; /* as above */
1339
cb241a69
LP
1340 /* If root and /usr are combined then insist that the architecture matches */
1341 if (m->partitions[PARTITION_ROOT].found &&
1342 m->partitions[PARTITION_USR].found &&
1343 (m->partitions[PARTITION_ROOT].architecture >= 0 &&
1344 m->partitions[PARTITION_USR].architecture >= 0 &&
1345 m->partitions[PARTITION_ROOT].architecture != m->partitions[PARTITION_USR].architecture))
1346 return -EADDRNOTAVAIL;
1347
4ab51780
LP
1348 if (!m->partitions[PARTITION_ROOT].found &&
1349 !m->partitions[PARTITION_USR].found &&
1350 (flags & DISSECT_IMAGE_GENERIC_ROOT) &&
00a8b34f 1351 (!verity || !verity->root_hash || verity->designator != PARTITION_USR)) {
7cf66030
LP
1352
1353 /* OK, we found nothing usable, then check if there's a single generic one distro, and use
4b5de5dd
LP
1354 * that. If the root hash was set however, then we won't fall back to a generic node, because
1355 * the root hash decides. */
7cf66030
LP
1356
1357 /* If we didn't find a properly marked root partition, but we did find a single suitable
1358 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1359 if (multiple_generic)
1360 return -ENOTUNIQ;
1361
4b5de5dd
LP
1362 /* If we didn't find a generic node, then we can't fix this up either */
1363 if (generic_node) {
1364 _cleanup_free_ char *o = NULL;
1365 const char *options;
8c1be37e 1366
f5215bc8 1367 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
18d73705
LB
1368 if (options) {
1369 o = strdup(options);
1370 if (!o)
1371 return -ENOMEM;
1372 }
1373
1f8fb21c 1374 assert(generic_nr >= 0);
8c1be37e
LP
1375 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
1376 .found = true,
1377 .rw = generic_rw,
de98f631 1378 .growfs = generic_growfs,
8c1be37e
LP
1379 .partno = generic_nr,
1380 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a 1381 .node = TAKE_PTR(generic_node),
be30ad41 1382 .uuid = generic_uuid,
18d73705 1383 .mount_options = TAKE_PTR(o),
8c1be37e 1384 };
e0f9e7bd 1385 }
8c1be37e
LP
1386 }
1387
4b5de5dd
LP
1388 /* Check if we have a root fs if we are told to do check. /usr alone is fine too, but only if appropriate flag for that is set too */
1389 if (FLAGS_SET(flags, DISSECT_IMAGE_REQUIRE_ROOT) &&
1390 !(m->partitions[PARTITION_ROOT].found || (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1391 return -ENXIO;
1392
aee36b4e 1393 /* Combinations of verity /usr with verity-less root is OK, but the reverse is not */
c848516f 1394 if (m->partitions[PARTITION_ROOT_VERITY].found && m->partitions[PARTITION_USR].found && !m->partitions[PARTITION_USR_VERITY].found)
aee36b4e
LP
1395 return -EADDRNOTAVAIL;
1396
89e62e0b 1397 if (verity && verity->root_hash) {
aee36b4e
LP
1398 if (verity->designator < 0 || verity->designator == PARTITION_ROOT) {
1399 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
1400 return -EADDRNOTAVAIL;
1401
1402 /* If we found a verity setup, then the root partition is necessarily read-only. */
1403 m->partitions[PARTITION_ROOT].rw = false;
c3c88d67 1404 m->verity_ready = true;
aee36b4e 1405 }
4623e8e6 1406
aee36b4e
LP
1407 if (verity->designator == PARTITION_USR) {
1408 if (!m->partitions[PARTITION_USR_VERITY].found || !m->partitions[PARTITION_USR].found)
1409 return -EADDRNOTAVAIL;
4623e8e6 1410
aee36b4e 1411 m->partitions[PARTITION_USR].rw = false;
c3c88d67 1412 m->verity_ready = true;
aee36b4e 1413 }
4623e8e6
LP
1414 }
1415
18b5886e
LP
1416 blkid_free_probe(b);
1417 b = NULL;
1418
8c1be37e 1419 /* Fill in file system types if we don't know them yet. */
569a0e42 1420 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 1421 DissectedPartition *p = m->partitions + i;
8c1be37e 1422
18b5886e 1423 if (!p->found)
8c1be37e
LP
1424 continue;
1425
18b5886e
LP
1426 if (!p->fstype && p->node) {
1427 r = probe_filesystem(p->node, &p->fstype);
7cc84b2c 1428 if (r < 0 && r != -EUCLEAN)
18b5886e 1429 return r;
8c1be37e
LP
1430 }
1431
18b5886e
LP
1432 if (streq_ptr(p->fstype, "crypto_LUKS"))
1433 m->encrypted = true;
896f937f
LP
1434
1435 if (p->fstype && fstype_is_ro(p->fstype))
1436 p->rw = false;
de98f631
LP
1437
1438 if (!p->rw)
1439 p->growfs = false;
8c1be37e
LP
1440 }
1441
1cc6c93a 1442 *ret = TAKE_PTR(m);
8c1be37e
LP
1443 return 0;
1444#else
1445 return -EOPNOTSUPP;
1446#endif
1447}
1448
1449DissectedImage* dissected_image_unref(DissectedImage *m) {
8c1be37e
LP
1450 if (!m)
1451 return NULL;
1452
08fe0a53
LP
1453 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
1454 dissected_partition_done(m->partitions + i);
8c1be37e 1455
593fe6c0 1456 free(m->image_name);
3b925504
LP
1457 free(m->hostname);
1458 strv_free(m->machine_info);
1459 strv_free(m->os_release);
7718ac97 1460 strv_free(m->extension_release);
3b925504 1461
5fecf46d 1462 return mfree(m);
8c1be37e
LP
1463}
1464
18b5886e 1465static int is_loop_device(const char *path) {
553e15f2 1466 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
18b5886e
LP
1467 struct stat st;
1468
1469 assert(path);
1470
1471 if (stat(path, &st) < 0)
1472 return -errno;
1473
1474 if (!S_ISBLK(st.st_mode))
1475 return -ENOTBLK;
1476
553e15f2 1477 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
18b5886e
LP
1478 if (access(s, F_OK) < 0) {
1479 if (errno != ENOENT)
1480 return -errno;
1481
1482 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
553e15f2 1483 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
18b5886e
LP
1484 if (access(s, F_OK) < 0)
1485 return errno == ENOENT ? false : -errno;
1486 }
1487
1488 return true;
1489}
1490
cf32c486
LP
1491static int run_fsck(const char *node, const char *fstype) {
1492 int r, exit_status;
1493 pid_t pid;
1494
1495 assert(node);
1496 assert(fstype);
1497
1498 r = fsck_exists(fstype);
1499 if (r < 0) {
1500 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
1501 return 0;
1502 }
1503 if (r == 0) {
1504 log_debug("Not checking partition %s, as fsck for %s does not exist.", node, fstype);
1505 return 0;
1506 }
1507
1508 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO, &pid);
1509 if (r < 0)
1510 return log_debug_errno(r, "Failed to fork off fsck: %m");
1511 if (r == 0) {
1512 /* Child */
1513 execl("/sbin/fsck", "/sbin/fsck", "-aT", node, NULL);
7e0ed2e9 1514 log_open();
cf32c486
LP
1515 log_debug_errno(errno, "Failed to execl() fsck: %m");
1516 _exit(FSCK_OPERATIONAL_ERROR);
1517 }
1518
1519 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
1520 if (exit_status < 0)
1521 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
1522
1523 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
1524 log_debug("fsck failed with exit status %i.", exit_status);
1525
1526 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
1527 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
1528
1529 log_debug("Ignoring fsck error.");
1530 }
1531
1532 return 0;
1533}
1534
81939d9d
LP
1535static int fs_grow(const char *node_path, const char *mount_path) {
1536 _cleanup_close_ int mount_fd = -1, node_fd = -1;
81939d9d
LP
1537 uint64_t size, newsize;
1538 int r;
1539
1540 node_fd = open(node_path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1541 if (node_fd < 0)
1542 return log_debug_errno(errno, "Failed to open node device %s: %m", node_path);
1543
1544 if (ioctl(node_fd, BLKGETSIZE64, &size) != 0)
1545 return log_debug_errno(errno, "Failed to get block device size of %s: %m", node_path);
1546
1547 mount_fd = open(mount_path, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
1548 if (mount_fd < 0)
1549 return log_debug_errno(errno, "Failed to open mountd file system %s: %m", mount_path);
1550
1551 log_debug("Resizing \"%s\" to %"PRIu64" bytes...", mount_path, size);
1552 r = resize_fs(mount_fd, size, &newsize);
1553 if (r < 0)
1554 return log_debug_errno(r, "Failed to resize \"%s\" to %"PRIu64" bytes: %m", mount_path, size);
1555
1556 if (newsize == size)
1557 log_debug("Successfully resized \"%s\" to %s bytes.",
2b59bf51 1558 mount_path, FORMAT_BYTES(newsize));
81939d9d
LP
1559 else {
1560 assert(newsize < size);
1561 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
2b59bf51 1562 mount_path, FORMAT_BYTES(newsize), size - newsize);
81939d9d
LP
1563 }
1564
1565 return 0;
1566}
1567
18b5886e
LP
1568static int mount_partition(
1569 DissectedPartition *m,
1570 const char *where,
1571 const char *directory,
2d3a5a73 1572 uid_t uid_shift,
21b61b1d 1573 uid_t uid_range,
18b5886e
LP
1574 DissectImageFlags flags) {
1575
2d3a5a73
LP
1576 _cleanup_free_ char *chased = NULL, *options = NULL;
1577 const char *p, *node, *fstype;
21b61b1d 1578 bool rw, remap_uid_gid = false;
2eedfd2d 1579 int r;
8c1be37e
LP
1580
1581 assert(m);
1582 assert(where);
1583
4dc28665 1584 /* Use decrypted node and matching fstype if available, otherwise use the original device */
18b5886e 1585 node = m->decrypted_node ?: m->node;
4dc28665 1586 fstype = m->decrypted_node ? m->decrypted_fstype: m->fstype;
18b5886e 1587
4dc28665 1588 if (!m->found || !node)
8c1be37e 1589 return 0;
4dc28665
LP
1590 if (!fstype)
1591 return -EAFNOSUPPORT;
8c1be37e 1592
fa45d12c 1593 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this case. */
4dc28665 1594 if (streq(fstype, "crypto_LUKS"))
fa45d12c 1595 return -EUNATCH;
18b5886e 1596
ef9c184d 1597 rw = m->rw && !(flags & DISSECT_IMAGE_MOUNT_READ_ONLY);
8c1be37e 1598
cf32c486
LP
1599 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
1600 r = run_fsck(node, fstype);
1601 if (r < 0)
1602 return r;
1603 }
1604
2eedfd2d 1605 if (directory) {
334eb5b0
LP
1606 /* Automatically create missing mount points inside the image, if necessary. */
1607 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
1608 if (r < 0 && r != -EROFS)
1609 return r;
1f0f82f1 1610
a5648b80 1611 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
2eedfd2d
LP
1612 if (r < 0)
1613 return r;
1614
1615 p = chased;
9842905e
LP
1616 } else {
1617 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1618 * image (as the branch above does) but the host hierarchy, and the created directory might
1619 * survive our mount in the host hierarchy hence. */
1620 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1621 r = mkdir_p(where, 0755);
1622 if (r < 0)
1623 return r;
1624 }
1625
8c1be37e 1626 p = where;
9842905e 1627 }
8c1be37e 1628
18b5886e 1629 /* If requested, turn on discard support. */
154d2269 1630 if (fstype_can_discard(fstype) &&
18b5886e 1631 ((flags & DISSECT_IMAGE_DISCARD) ||
3afda7c7 1632 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node) > 0))) {
2d3a5a73
LP
1633 options = strdup("discard");
1634 if (!options)
1635 return -ENOMEM;
1636 }
1637
21b61b1d 1638 if (uid_is_valid(uid_shift) && uid_shift != 0) {
2d3a5a73 1639
21b61b1d
LP
1640 if (fstype_can_uid_gid(fstype)) {
1641 _cleanup_free_ char *uid_option = NULL;
2d3a5a73 1642
21b61b1d
LP
1643 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1644 return -ENOMEM;
1645
1646 if (!strextend_with_separator(&options, ",", uid_option))
1647 return -ENOMEM;
1648 } else if (FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_IDMAPPED))
1649 remap_uid_gid = true;
2d3a5a73 1650 }
8c1be37e 1651
18d73705 1652 if (!isempty(m->mount_options))
c2bc710b 1653 if (!strextend_with_separator(&options, ",", m->mount_options))
18d73705
LB
1654 return -ENOMEM;
1655
b620bf33
LP
1656 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1657 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1658 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1659 * from the upper file system still get propagated through to the underlying file system,
1660 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1661 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1662 * carry a per file system table here.
1663 *
1664 * Note that this means that we might not be able to mount corrupted file systems as read-only
1665 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1666 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1667 * mount options for loopback devices this is the right choice, since otherwise using the same
1668 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The usecase of
1669 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1670 * access that actually modifies stuff work on such image files. Or to say this differently: if
1671 * people want their file systems to be fixed up they should just open them in writable mode, where
1672 * all these problems don't exist. */
1673 if (!rw && STRPTR_IN_SET(fstype, "ext3", "ext4", "xfs", "btrfs"))
1674 if (!strextend_with_separator(&options, ",", "norecovery"))
1675 return -ENOMEM;
1676
511a8cfe 1677 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
d9223c07
LP
1678 if (r < 0)
1679 return r;
1680
81939d9d
LP
1681 if (rw && m->growfs && FLAGS_SET(flags, DISSECT_IMAGE_GROWFS))
1682 (void) fs_grow(node, p);
1683
21b61b1d
LP
1684 if (remap_uid_gid) {
1685 r = remount_idmap(p, uid_shift, uid_range);
1686 if (r < 0)
1687 return r;
1688 }
1689
d9223c07 1690 return 1;
8c1be37e
LP
1691}
1692
7cf66030
LP
1693static int mount_root_tmpfs(const char *where, uid_t uid_shift, DissectImageFlags flags) {
1694 _cleanup_free_ char *options = NULL;
1695 int r;
1696
1697 assert(where);
1698
1699 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
1700
1701 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1702 r = mkdir_p(where, 0755);
1703 if (r < 0)
1704 return r;
1705 }
1706
1707 if (uid_is_valid(uid_shift)) {
1708 if (asprintf(&options, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1709 return -ENOMEM;
1710 }
1711
1712 r = mount_nofollow_verbose(LOG_DEBUG, "rootfs", where, "tmpfs", MS_NODEV, options);
1713 if (r < 0)
1714 return r;
1715
1716 return 1;
1717}
1718
21b61b1d
LP
1719int dissected_image_mount(
1720 DissectedImage *m,
1721 const char *where,
1722 uid_t uid_shift,
1723 uid_t uid_range,
1724 DissectImageFlags flags) {
1725
1f0f82f1 1726 int r, xbootldr_mounted;
8c1be37e
LP
1727
1728 assert(m);
1729 assert(where);
1730
fa45d12c
LP
1731 /* Returns:
1732 *
1733 * -ENXIO → No root partition found
7718ac97 1734 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
fa45d12c
LP
1735 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1736 * -EUCLEAN → fsck for file system failed
1737 * -EBUSY → File system already mounted/used elsewhere (kernel)
4dc28665 1738 * -EAFNOSUPPORT → File system type not supported or not known
fa45d12c
LP
1739 */
1740
7cf66030
LP
1741 if (!(m->partitions[PARTITION_ROOT].found ||
1742 (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1743 return -ENXIO; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
8c1be37e 1744
2d3a5a73 1745 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
7cf66030
LP
1746
1747 /* First mount the root fs. If there's none we use a tmpfs. */
1748 if (m->partitions[PARTITION_ROOT].found)
21b61b1d 1749 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, uid_range, flags);
7cf66030
LP
1750 else
1751 r = mount_root_tmpfs(where, uid_shift, flags);
2d3a5a73
LP
1752 if (r < 0)
1753 return r;
aee36b4e 1754
aee36b4e 1755 /* For us mounting root always means mounting /usr as well */
21b61b1d 1756 r = mount_partition(m->partitions + PARTITION_USR, where, "/usr", uid_shift, uid_range, flags);
aee36b4e
LP
1757 if (r < 0)
1758 return r;
03bcb6d4 1759
9ccb531a
LB
1760 if ((flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0) {
1761 /* If either one of the validation flags are set, ensure that the image qualifies
1762 * as one or the other (or both). */
1763 bool ok = false;
1764
1765 if (FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS)) {
1766 r = path_is_os_tree(where);
1767 if (r < 0)
1768 return r;
1769 if (r > 0)
1770 ok = true;
1771 }
1772 if (!ok && FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS_EXT)) {
7718ac97
LB
1773 r = path_is_extension_tree(where, m->image_name);
1774 if (r < 0)
1775 return r;
9ccb531a
LB
1776 if (r > 0)
1777 ok = true;
7718ac97 1778 }
9ccb531a
LB
1779
1780 if (!ok)
1781 return -ENOMEDIUM;
03bcb6d4 1782 }
2d3a5a73
LP
1783 }
1784
705727fd 1785 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2d3a5a73 1786 return 0;
8c1be37e 1787
21b61b1d 1788 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, uid_range, flags);
8c1be37e
LP
1789 if (r < 0)
1790 return r;
1791
21b61b1d 1792 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, uid_range, flags);
8c1be37e
LP
1793 if (r < 0)
1794 return r;
1795
21b61b1d 1796 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, uid_range, flags);
d4dffb85
LP
1797 if (r < 0)
1798 return r;
1799
21b61b1d 1800 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, uid_range, flags);
d4dffb85
LP
1801 if (r < 0)
1802 return r;
1803
21b61b1d 1804 xbootldr_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, uid_range, flags);
1f0f82f1
LP
1805 if (xbootldr_mounted < 0)
1806 return xbootldr_mounted;
d9223c07 1807
8c1be37e 1808 if (m->partitions[PARTITION_ESP].found) {
1f0f82f1
LP
1809 int esp_done = false;
1810
d9223c07
LP
1811 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1812 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
8c1be37e 1813
a5648b80 1814 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
1f0f82f1
LP
1815 if (r < 0) {
1816 if (r != -ENOENT)
d9223c07 1817 return r;
8c1be37e 1818
1f0f82f1
LP
1819 /* /efi doesn't exist. Let's see if /boot is suitable then */
1820
1821 if (!xbootldr_mounted) {
1822 _cleanup_free_ char *p = NULL;
2eedfd2d 1823
1f0f82f1
LP
1824 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
1825 if (r < 0) {
1826 if (r != -ENOENT)
1827 return r;
1828 } else if (dir_is_empty(p) > 0) {
1829 /* It exists and is an empty directory. Let's mount the ESP there. */
21b61b1d 1830 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, uid_range, flags);
1f0f82f1
LP
1831 if (r < 0)
1832 return r;
1833
1834 esp_done = true;
1835 }
2eedfd2d 1836 }
8c1be37e 1837 }
1f0f82f1
LP
1838
1839 if (!esp_done) {
1840 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1841
21b61b1d 1842 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, uid_range, flags);
1f0f82f1
LP
1843 if (r < 0)
1844 return r;
1845 }
8c1be37e
LP
1846 }
1847
1848 return 0;
1849}
1850
21b61b1d
LP
1851int dissected_image_mount_and_warn(
1852 DissectedImage *m,
1853 const char *where,
1854 uid_t uid_shift,
1855 uid_t uid_range,
1856 DissectImageFlags flags) {
1857
af187ab2
LP
1858 int r;
1859
1860 assert(m);
1861 assert(where);
1862
21b61b1d 1863 r = dissected_image_mount(m, where, uid_shift, uid_range, flags);
af187ab2
LP
1864 if (r == -ENXIO)
1865 return log_error_errno(r, "Not root file system found in image.");
1866 if (r == -EMEDIUMTYPE)
7718ac97 1867 return log_error_errno(r, "No suitable os-release/extension-release file in image found.");
af187ab2
LP
1868 if (r == -EUNATCH)
1869 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
1870 if (r == -EUCLEAN)
1871 return log_error_errno(r, "File system check on image failed.");
1872 if (r == -EBUSY)
1873 return log_error_errno(r, "File system already mounted elsewhere.");
4dc28665
LP
1874 if (r == -EAFNOSUPPORT)
1875 return log_error_errno(r, "File system type not supported or not known.");
af187ab2
LP
1876 if (r < 0)
1877 return log_error_errno(r, "Failed to mount image: %m");
1878
1879 return r;
1880}
1881
349cc4a5 1882#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1883typedef struct DecryptedPartition {
1884 struct crypt_device *device;
1885 char *name;
1886 bool relinquished;
1887} DecryptedPartition;
1888
1889struct DecryptedImage {
1890 DecryptedPartition *decrypted;
1891 size_t n_decrypted;
18b5886e
LP
1892};
1893#endif
1894
1895DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
349cc4a5 1896#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1897 int r;
1898
1899 if (!d)
1900 return NULL;
1901
67f63ee5 1902 for (size_t i = 0; i < d->n_decrypted; i++) {
18b5886e
LP
1903 DecryptedPartition *p = d->decrypted + i;
1904
1905 if (p->device && p->name && !p->relinquished) {
0d12936d 1906 r = sym_crypt_deactivate_by_name(p->device, p->name, 0);
18b5886e
LP
1907 if (r < 0)
1908 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
1909 }
1910
1911 if (p->device)
0d12936d 1912 sym_crypt_free(p->device);
18b5886e
LP
1913 free(p->name);
1914 }
1915
f91861e4 1916 free(d->decrypted);
18b5886e
LP
1917 free(d);
1918#endif
1919 return NULL;
1920}
1921
349cc4a5 1922#if HAVE_LIBCRYPTSETUP
4623e8e6
LP
1923
1924static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
1925 _cleanup_free_ char *name = NULL, *node = NULL;
1926 const char *base;
1927
1928 assert(original_node);
1929 assert(suffix);
1930 assert(ret_name);
1931 assert(ret_node);
1932
1933 base = strrchr(original_node, '/');
1934 if (!base)
ac1f3ad0
LB
1935 base = original_node;
1936 else
1937 base++;
4623e8e6
LP
1938 if (isempty(base))
1939 return -EINVAL;
1940
1941 name = strjoin(base, suffix);
1942 if (!name)
1943 return -ENOMEM;
1944 if (!filename_is_valid(name))
1945 return -EINVAL;
1946
0d12936d 1947 node = path_join(sym_crypt_get_dir(), name);
4623e8e6
LP
1948 if (!node)
1949 return -ENOMEM;
1950
1cc6c93a
YW
1951 *ret_name = TAKE_PTR(name);
1952 *ret_node = TAKE_PTR(node);
4623e8e6 1953
4623e8e6
LP
1954 return 0;
1955}
1956
18b5886e
LP
1957static int decrypt_partition(
1958 DissectedPartition *m,
1959 const char *passphrase,
1960 DissectImageFlags flags,
1961 DecryptedImage *d) {
1962
1963 _cleanup_free_ char *node = NULL, *name = NULL;
0d12936d 1964 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
18b5886e
LP
1965 int r;
1966
1967 assert(m);
1968 assert(d);
1969
1970 if (!m->found || !m->node || !m->fstype)
1971 return 0;
1972
1973 if (!streq(m->fstype, "crypto_LUKS"))
1974 return 0;
1975
bdd73ac5
ZJS
1976 if (!passphrase)
1977 return -ENOKEY;
1978
0d12936d
LP
1979 r = dlopen_cryptsetup();
1980 if (r < 0)
1981 return r;
1982
4623e8e6
LP
1983 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1984 if (r < 0)
1985 return r;
18b5886e 1986
319a4f4b 1987 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
18b5886e
LP
1988 return -ENOMEM;
1989
0d12936d 1990 r = sym_crypt_init(&cd, m->node);
18b5886e 1991 if (r < 0)
715cbb81 1992 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
18b5886e 1993
efc3b12f 1994 cryptsetup_enable_logging(cd);
1887032f 1995
0d12936d 1996 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
294bd454
ZJS
1997 if (r < 0)
1998 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
18b5886e 1999
0d12936d 2000 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
ef9c184d 2001 ((flags & DISSECT_IMAGE_DEVICE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
0d12936d 2002 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
294bd454 2003 if (r < 0) {
715cbb81 2004 log_debug_errno(r, "Failed to activate LUKS device: %m");
294bd454 2005 return r == -EPERM ? -EKEYREJECTED : r;
18b5886e 2006 }
18b5886e 2007
94344385
LP
2008 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2009 .name = TAKE_PTR(name),
2010 .device = TAKE_PTR(cd),
2011 };
18b5886e 2012
1cc6c93a 2013 m->decrypted_node = TAKE_PTR(node);
18b5886e
LP
2014
2015 return 0;
4623e8e6
LP
2016}
2017
89e62e0b
LP
2018static int verity_can_reuse(
2019 const VeritySettings *verity,
2020 const char *name,
2021 struct crypt_device **ret_cd) {
2022
ac1f3ad0
LB
2023 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
2024 _cleanup_free_ char *root_hash_existing = NULL;
0d12936d 2025 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 2026 struct crypt_params_verity crypt_params = {};
89e62e0b 2027 size_t root_hash_existing_size;
ac1f3ad0
LB
2028 int r;
2029
89e62e0b
LP
2030 assert(verity);
2031 assert(name);
ac1f3ad0
LB
2032 assert(ret_cd);
2033
0d12936d 2034 r = sym_crypt_init_by_name(&cd, name);
ac1f3ad0
LB
2035 if (r < 0)
2036 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
0d12936d 2037
c719805e
LP
2038 cryptsetup_enable_logging(cd);
2039
0d12936d 2040 r = sym_crypt_get_verity_info(cd, &crypt_params);
ac1f3ad0
LB
2041 if (r < 0)
2042 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
0d12936d 2043
89e62e0b
LP
2044 root_hash_existing_size = verity->root_hash_size;
2045 root_hash_existing = malloc0(root_hash_existing_size);
ac1f3ad0
LB
2046 if (!root_hash_existing)
2047 return -ENOMEM;
0d12936d
LP
2048
2049 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
ac1f3ad0
LB
2050 if (r < 0)
2051 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
89e62e0b
LP
2052 if (verity->root_hash_size != root_hash_existing_size ||
2053 memcmp(root_hash_existing, verity->root_hash, verity->root_hash_size) != 0)
ac1f3ad0 2054 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
89e62e0b 2055
ac1f3ad0 2056#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
89e62e0b
LP
2057 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
2058 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
28423d9a 2059 * signing for the new one, and vice versa. */
89e62e0b 2060 if (!!verity->root_hash_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
ac1f3ad0
LB
2061 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
2062#endif
2063
2064 *ret_cd = TAKE_PTR(cd);
2065 return 0;
2066}
2067
75db809a 2068static inline char* dm_deferred_remove_clean(char *name) {
ac1f3ad0 2069 if (!name)
75db809a 2070 return NULL;
0d12936d
LP
2071
2072 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
75db809a 2073 return mfree(name);
ac1f3ad0
LB
2074}
2075DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
2076
4623e8e6 2077static int verity_partition(
aee36b4e 2078 PartitionDesignator designator,
4623e8e6
LP
2079 DissectedPartition *m,
2080 DissectedPartition *v,
89e62e0b 2081 const VeritySettings *verity,
4623e8e6
LP
2082 DissectImageFlags flags,
2083 DecryptedImage *d) {
2084
0d12936d 2085 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 2086 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
89e62e0b 2087 _cleanup_free_ char *node = NULL, *name = NULL;
4623e8e6
LP
2088 int r;
2089
2090 assert(m);
89e62e0b 2091 assert(v || (verity && verity->data_path));
4623e8e6 2092
89e62e0b 2093 if (!verity || !verity->root_hash)
4623e8e6 2094 return 0;
aee36b4e
LP
2095 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
2096 (verity->designator == designator)))
2097 return 0;
4623e8e6
LP
2098
2099 if (!m->found || !m->node || !m->fstype)
2100 return 0;
89e62e0b 2101 if (!verity->data_path) {
e7cbe5cb
LB
2102 if (!v->found || !v->node || !v->fstype)
2103 return 0;
4623e8e6 2104
e7cbe5cb
LB
2105 if (!streq(v->fstype, "DM_verity_hash"))
2106 return 0;
2107 }
4623e8e6 2108
0d12936d
LP
2109 r = dlopen_cryptsetup();
2110 if (r < 0)
2111 return r;
2112
ac1f3ad0
LB
2113 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2114 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2115 _cleanup_free_ char *root_hash_encoded = NULL;
0d12936d 2116
89e62e0b 2117 root_hash_encoded = hexmem(verity->root_hash, verity->root_hash_size);
ac1f3ad0
LB
2118 if (!root_hash_encoded)
2119 return -ENOMEM;
aee36b4e 2120
ac1f3ad0
LB
2121 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
2122 } else
2123 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
4623e8e6
LP
2124 if (r < 0)
2125 return r;
2126
89e62e0b 2127 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
4623e8e6
LP
2128 if (r < 0)
2129 return r;
2130
efc3b12f 2131 cryptsetup_enable_logging(cd);
1887032f 2132
0d12936d 2133 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
4623e8e6 2134 if (r < 0)
294bd454 2135 return r;
4623e8e6 2136
0d12936d 2137 r = sym_crypt_set_data_device(cd, m->node);
4623e8e6 2138 if (r < 0)
294bd454 2139 return r;
4623e8e6 2140
319a4f4b 2141 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
ac1f3ad0
LB
2142 return -ENOMEM;
2143
2144 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2145 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2146 * retry a few times before giving up. */
2147 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
89e62e0b 2148 if (verity->root_hash_sig) {
c2923fdc 2149#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
89e62e0b
LP
2150 r = sym_crypt_activate_by_signed_key(
2151 cd,
2152 name,
2153 verity->root_hash,
2154 verity->root_hash_size,
2155 verity->root_hash_sig,
2156 verity->root_hash_sig_size,
2157 CRYPT_ACTIVATE_READONLY);
ac1f3ad0 2158#else
22043172
LP
2159 r = log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2160 "Activation of verity device with signature requested, but not supported by %s due to missing crypt_activate_by_signed_key().", program_invocation_short_name);
ac1f3ad0
LB
2161#endif
2162 } else
89e62e0b
LP
2163 r = sym_crypt_activate_by_volume_key(
2164 cd,
2165 name,
2166 verity->root_hash,
2167 verity->root_hash_size,
2168 CRYPT_ACTIVATE_READONLY);
ac1f3ad0
LB
2169 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2170 * There's no way to distinguish this situation from a genuine error due to invalid
2aed63f4 2171 * parameters, so immediately fall back to activating the device with a unique name.
89e62e0b
LP
2172 * Improvements in libcrypsetup can ensure this never happens:
2173 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
ac1f3ad0 2174 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
aee36b4e 2175 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
9ecb5c10 2176 if (!IN_SET(r,
22043172 2177 0, /* Success */
9ecb5c10 2178 -EEXIST, /* Volume is already open and ready to be used */
22043172
LP
2179 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name can fetch details */
2180 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */))
ac1f3ad0 2181 return r;
9ecb5c10 2182 if (IN_SET(r, -EEXIST, -EBUSY)) {
ac1f3ad0 2183 struct crypt_device *existing_cd = NULL;
c2923fdc 2184
ac1f3ad0
LB
2185 if (!restore_deferred_remove){
2186 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2187 r = dm_deferred_remove_cancel(name);
9ecb5c10
LB
2188 /* If activation returns EBUSY there might be no deferred removal to cancel, that's fine */
2189 if (r < 0 && r != -ENXIO)
ac1f3ad0 2190 return log_debug_errno(r, "Disabling automated deferred removal for verity device %s failed: %m", node);
9ecb5c10
LB
2191 if (r == 0) {
2192 restore_deferred_remove = strdup(name);
2193 if (!restore_deferred_remove)
2194 return -ENOMEM;
2195 }
ac1f3ad0 2196 }
c2923fdc 2197
89e62e0b 2198 r = verity_can_reuse(verity, name, &existing_cd);
ac1f3ad0
LB
2199 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2200 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
aee36b4e 2201 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
9ecb5c10 2202 if (!IN_SET(r, 0, -ENODEV, -ENOENT, -EBUSY))
ac1f3ad0
LB
2203 return log_debug_errno(r, "Checking whether existing verity device %s can be reused failed: %m", node);
2204 if (r == 0) {
c419b6f0
LB
2205 /* devmapper might say that the device exists, but the devlink might not yet have been
2206 * created. Check and wait for the udev event in that case. */
9e3d9067 2207 r = device_wait_for_devlink(node, "block", usec_add(now(CLOCK_MONOTONIC), 100 * USEC_PER_MSEC), NULL);
c419b6f0
LB
2208 /* Fallback to activation with a unique device if it's taking too long */
2209 if (r == -ETIMEDOUT)
2210 break;
2211 if (r < 0)
2212 return r;
2213
ac1f3ad0 2214 if (cd)
0d12936d 2215 sym_crypt_free(cd);
ac1f3ad0
LB
2216 cd = existing_cd;
2217 }
c2923fdc 2218 }
ac1f3ad0
LB
2219 if (r == 0)
2220 break;
ecab4c47
LB
2221
2222 /* Device is being opened by another process, but it has not finished yet, yield for 2ms */
2223 (void) usleep(2 * USEC_PER_MSEC);
ac1f3ad0
LB
2224 }
2225
ac1f3ad0
LB
2226 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
2227 * Fall back to activating it with a unique device name. */
2228 if (r != 0 && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
aee36b4e 2229 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
ac1f3ad0
LB
2230
2231 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2232 restore_deferred_remove = mfree(restore_deferred_remove);
4623e8e6 2233
94344385
LP
2234 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2235 .name = TAKE_PTR(name),
2236 .device = TAKE_PTR(cd),
2237 };
4623e8e6 2238
1cc6c93a 2239 m->decrypted_node = TAKE_PTR(node);
4623e8e6
LP
2240
2241 return 0;
18b5886e
LP
2242}
2243#endif
2244
2245int dissected_image_decrypt(
2246 DissectedImage *m,
2247 const char *passphrase,
89e62e0b 2248 const VeritySettings *verity,
18b5886e
LP
2249 DissectImageFlags flags,
2250 DecryptedImage **ret) {
2251
349cc4a5 2252#if HAVE_LIBCRYPTSETUP
49b5b3b4 2253 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
18b5886e
LP
2254 int r;
2255#endif
2256
2257 assert(m);
89e62e0b 2258 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
18b5886e
LP
2259
2260 /* Returns:
2261 *
2262 * = 0 → There was nothing to decrypt
2263 * > 0 → Decrypted successfully
d1c536f5 2264 * -ENOKEY → There's something to decrypt but no key was supplied
18b5886e
LP
2265 * -EKEYREJECTED → Passed key was not correct
2266 */
2267
89e62e0b 2268 if (verity && verity->root_hash && verity->root_hash_size < sizeof(sd_id128_t))
4623e8e6
LP
2269 return -EINVAL;
2270
c3c88d67 2271 if (!m->encrypted && !m->verity_ready) {
18b5886e
LP
2272 *ret = NULL;
2273 return 0;
2274 }
2275
349cc4a5 2276#if HAVE_LIBCRYPTSETUP
18b5886e
LP
2277 d = new0(DecryptedImage, 1);
2278 if (!d)
2279 return -ENOMEM;
2280
569a0e42 2281 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 2282 DissectedPartition *p = m->partitions + i;
22043172 2283 PartitionDesignator k;
18b5886e
LP
2284
2285 if (!p->found)
2286 continue;
2287
2288 r = decrypt_partition(p, passphrase, flags, d);
2289 if (r < 0)
2290 return r;
2291
4623e8e6
LP
2292 k = PARTITION_VERITY_OF(i);
2293 if (k >= 0) {
aee36b4e 2294 r = verity_partition(i, p, m->partitions + k, verity, flags | DISSECT_IMAGE_VERITY_SHARE, d);
4623e8e6
LP
2295 if (r < 0)
2296 return r;
2297 }
2298
18b5886e
LP
2299 if (!p->decrypted_fstype && p->decrypted_node) {
2300 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
7cc84b2c 2301 if (r < 0 && r != -EUCLEAN)
18b5886e
LP
2302 return r;
2303 }
2304 }
2305
1cc6c93a 2306 *ret = TAKE_PTR(d);
18b5886e
LP
2307
2308 return 1;
2309#else
2310 return -EOPNOTSUPP;
2311#endif
2312}
2313
2314int dissected_image_decrypt_interactively(
2315 DissectedImage *m,
2316 const char *passphrase,
89e62e0b 2317 const VeritySettings *verity,
18b5886e
LP
2318 DissectImageFlags flags,
2319 DecryptedImage **ret) {
2320
2321 _cleanup_strv_free_erase_ char **z = NULL;
2322 int n = 3, r;
2323
2324 if (passphrase)
2325 n--;
2326
2327 for (;;) {
89e62e0b 2328 r = dissected_image_decrypt(m, passphrase, verity, flags, ret);
18b5886e
LP
2329 if (r >= 0)
2330 return r;
2331 if (r == -EKEYREJECTED)
2332 log_error_errno(r, "Incorrect passphrase, try again!");
fc95c359
YW
2333 else if (r != -ENOKEY)
2334 return log_error_errno(r, "Failed to decrypt image: %m");
18b5886e 2335
baaa35ad
ZJS
2336 if (--n < 0)
2337 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
2338 "Too many retries.");
18b5886e
LP
2339
2340 z = strv_free(z);
2341
8806bb4b 2342 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", "dissect.passphrase", USEC_INFINITY, 0, &z);
18b5886e
LP
2343 if (r < 0)
2344 return log_error_errno(r, "Failed to query for passphrase: %m");
2345
2346 passphrase = z[0];
2347 }
2348}
2349
18b5886e 2350int decrypted_image_relinquish(DecryptedImage *d) {
18b5886e
LP
2351 assert(d);
2352
67f63ee5
ZJS
2353 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2354 * boolean so that we don't clean it up ourselves either anymore */
18b5886e 2355
349cc4a5 2356#if HAVE_LIBCRYPTSETUP
67f63ee5
ZJS
2357 int r;
2358
2359 for (size_t i = 0; i < d->n_decrypted; i++) {
18b5886e
LP
2360 DecryptedPartition *p = d->decrypted + i;
2361
2362 if (p->relinquished)
2363 continue;
2364
0d12936d 2365 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
18b5886e
LP
2366 if (r < 0)
2367 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
2368
2369 p->relinquished = true;
2370 }
2371#endif
2372
2373 return 0;
2374}
2375
89e62e0b
LP
2376static char *build_auxiliary_path(const char *image, const char *suffix) {
2377 const char *e;
2378 char *n;
2379
2380 assert(image);
2381 assert(suffix);
2382
2383 e = endswith(image, ".raw");
2384 if (!e)
2385 return strjoin(e, suffix);
2386
2387 n = new(char, e - image + strlen(suffix) + 1);
2388 if (!n)
2389 return NULL;
2390
2391 strcpy(mempcpy(n, image, e - image), suffix);
2392 return n;
2393}
2394
2395void verity_settings_done(VeritySettings *v) {
2396 assert(v);
2397
2398 v->root_hash = mfree(v->root_hash);
2399 v->root_hash_size = 0;
2400
2401 v->root_hash_sig = mfree(v->root_hash_sig);
2402 v->root_hash_sig_size = 0;
2403
2404 v->data_path = mfree(v->data_path);
2405}
2406
2407int verity_settings_load(
2408 VeritySettings *verity,
f5ea63a5
LP
2409 const char *image,
2410 const char *root_hash_path,
89e62e0b
LP
2411 const char *root_hash_sig_path) {
2412
2413 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
2414 size_t root_hash_size = 0, root_hash_sig_size = 0;
2415 _cleanup_free_ char *verity_data_path = NULL;
aee36b4e 2416 PartitionDesignator designator;
78ebe980
LP
2417 int r;
2418
89e62e0b 2419 assert(verity);
78ebe980 2420 assert(image);
aee36b4e 2421 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
78ebe980 2422
89e62e0b
LP
2423 /* If we are asked to load the root hash for a device node, exit early */
2424 if (is_device_path(image))
78ebe980 2425 return 0;
78ebe980 2426
aee36b4e
LP
2427 designator = verity->designator;
2428
89e62e0b 2429 /* We only fill in what isn't already filled in */
c2923fdc 2430
89e62e0b 2431 if (!verity->root_hash) {
e7cbe5cb 2432 _cleanup_free_ char *text = NULL;
e7cbe5cb 2433
0389f4fa 2434 if (root_hash_path) {
aee36b4e 2435 /* If explicitly specified it takes precedence */
0389f4fa
LB
2436 r = read_one_line_file(root_hash_path, &text);
2437 if (r < 0)
e7cbe5cb 2438 return r;
aee36b4e
LP
2439
2440 if (designator < 0)
2441 designator = PARTITION_ROOT;
0389f4fa 2442 } else {
aee36b4e
LP
2443 /* Otherwise look for xattr and separate file, and first for the data for root and if
2444 * that doesn't exist for /usr */
0389f4fa 2445
aee36b4e
LP
2446 if (designator < 0 || designator == PARTITION_ROOT) {
2447 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
2448 if (r < 0) {
2449 _cleanup_free_ char *p = NULL;
78ebe980 2450
aee36b4e
LP
2451 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
2452 return r;
e7cbe5cb 2453
aee36b4e
LP
2454 p = build_auxiliary_path(image, ".roothash");
2455 if (!p)
2456 return -ENOMEM;
2457
2458 r = read_one_line_file(p, &text);
2459 if (r < 0 && r != -ENOENT)
2460 return r;
2461 }
2462
2463 if (text)
2464 designator = PARTITION_ROOT;
2465 }
2466
2467 if (!text && (designator < 0 || designator == PARTITION_USR)) {
2468 /* So in the "roothash" xattr/file name above the "root" of course primarily
2469 * refers to the root of the Verity Merkle tree. But coincidentally it also
2470 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2471 * two distinct concepts called "root". Taking benefit of this happy
2472 * coincidence we call the file with the root hash for the /usr/ file system
2473 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2474 * confusing. We thus drop the reference to the root of the Merkle tree, and
2475 * just indicate which file system it's about. */
2476 r = getxattr_malloc(image, "user.verity.usrhash", &text, true);
2477 if (r < 0) {
2478 _cleanup_free_ char *p = NULL;
2479
2480 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
2481 return r;
2482
2483 p = build_auxiliary_path(image, ".usrhash");
2484 if (!p)
2485 return -ENOMEM;
2486
2487 r = read_one_line_file(p, &text);
2488 if (r < 0 && r != -ENOENT)
2489 return r;
2490 }
2491
2492 if (text)
2493 designator = PARTITION_USR;
0389f4fa 2494 }
e7cbe5cb
LB
2495 }
2496
2497 if (text) {
89e62e0b 2498 r = unhexmem(text, strlen(text), &root_hash, &root_hash_size);
e7cbe5cb
LB
2499 if (r < 0)
2500 return r;
89e62e0b 2501 if (root_hash_size < sizeof(sd_id128_t))
e7cbe5cb
LB
2502 return -EINVAL;
2503 }
2504 }
2505
90f98986 2506 if ((root_hash || verity->root_hash) && !verity->root_hash_sig) {
aee36b4e 2507 if (root_hash_sig_path) {
ae9cf30b 2508 r = read_full_file(root_hash_sig_path, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2509 if (r < 0 && r != -ENOENT)
2510 return r;
2511
2512 if (designator < 0)
2513 designator = PARTITION_ROOT;
2514 } else {
2515 if (designator < 0 || designator == PARTITION_ROOT) {
2516 _cleanup_free_ char *p = NULL;
2517
2518 /* Follow naming convention recommended by the relevant RFC:
2519 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2520 p = build_auxiliary_path(image, ".roothash.p7s");
2521 if (!p)
2522 return -ENOMEM;
89e62e0b 2523
ae9cf30b 2524 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2525 if (r < 0 && r != -ENOENT)
2526 return r;
2527 if (r >= 0)
2528 designator = PARTITION_ROOT;
2529 }
2530
2531 if (!root_hash_sig && (designator < 0 || designator == PARTITION_USR)) {
2532 _cleanup_free_ char *p = NULL;
2533
2534 p = build_auxiliary_path(image, ".usrhash.p7s");
2535 if (!p)
2536 return -ENOMEM;
89e62e0b 2537
ae9cf30b 2538 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2539 if (r < 0 && r != -ENOENT)
2540 return r;
2541 if (r >= 0)
2542 designator = PARTITION_USR;
2543 }
89e62e0b
LP
2544 }
2545
aee36b4e 2546 if (root_hash_sig && root_hash_sig_size == 0) /* refuse empty size signatures */
89e62e0b
LP
2547 return -EINVAL;
2548 }
2549
2550 if (!verity->data_path) {
2551 _cleanup_free_ char *p = NULL;
2552
2553 p = build_auxiliary_path(image, ".verity");
2554 if (!p)
2555 return -ENOMEM;
2556
2557 if (access(p, F_OK) < 0) {
2558 if (errno != ENOENT)
2559 return -errno;
2560 } else
2561 verity_data_path = TAKE_PTR(p);
2562 }
2563
2564 if (root_hash) {
2565 verity->root_hash = TAKE_PTR(root_hash);
2566 verity->root_hash_size = root_hash_size;
2567 }
2568
2569 if (root_hash_sig) {
2570 verity->root_hash_sig = TAKE_PTR(root_hash_sig);
2571 verity->root_hash_sig_size = root_hash_sig_size;
e7cbe5cb 2572 }
89e62e0b
LP
2573
2574 if (verity_data_path)
2575 verity->data_path = TAKE_PTR(verity_data_path);
78ebe980 2576
aee36b4e
LP
2577 if (verity->designator < 0)
2578 verity->designator = designator;
2579
78ebe980
LP
2580 return 1;
2581}
2582
3b925504
LP
2583int dissected_image_acquire_metadata(DissectedImage *m) {
2584
2585 enum {
2586 META_HOSTNAME,
2587 META_MACHINE_ID,
2588 META_MACHINE_INFO,
2589 META_OS_RELEASE,
7718ac97 2590 META_EXTENSION_RELEASE,
3b925504
LP
2591 _META_MAX,
2592 };
2593
9a4b883b 2594 static const char *const paths[_META_MAX] = {
7718ac97
LB
2595 [META_HOSTNAME] = "/etc/hostname\0",
2596 [META_MACHINE_ID] = "/etc/machine-id\0",
2597 [META_MACHINE_INFO] = "/etc/machine-info\0",
9a4b883b
LB
2598 [META_OS_RELEASE] = ("/etc/os-release\0"
2599 "/usr/lib/os-release\0"),
2600 [META_EXTENSION_RELEASE] = "extension-release\0", /* Used only for logging. */
3b925504
LP
2601 };
2602
7718ac97 2603 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **extension_release = NULL;
af8219d5 2604 _cleanup_close_pair_ int error_pipe[2] = { -1, -1 };
3b925504
LP
2605 _cleanup_(rmdir_and_freep) char *t = NULL;
2606 _cleanup_(sigkill_waitp) pid_t child = 0;
2607 sd_id128_t machine_id = SD_ID128_NULL;
2608 _cleanup_free_ char *hostname = NULL;
67f63ee5 2609 unsigned n_meta_initialized = 0;
af8219d5
LP
2610 int fds[2 * _META_MAX], r, v;
2611 ssize_t n;
3b925504
LP
2612
2613 BLOCK_SIGNALS(SIGCHLD);
2614
2615 assert(m);
2616
7718ac97 2617 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++) {
d9119c00
LP
2618 if (!paths[n_meta_initialized]) {
2619 fds[2*n_meta_initialized] = fds[2*n_meta_initialized+1] = -1;
7718ac97 2620 continue;
d9119c00
LP
2621 }
2622
3b925504
LP
2623 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
2624 r = -errno;
2625 goto finish;
2626 }
7718ac97 2627 }
3b925504
LP
2628
2629 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
2630 if (r < 0)
2631 goto finish;
2632
af8219d5
LP
2633 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
2634 r = -errno;
2635 goto finish;
2636 }
2637
e2047ba9 2638 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
be39f6ee 2639 if (r < 0)
3b925504 2640 goto finish;
be39f6ee 2641 if (r == 0) {
af8219d5
LP
2642 error_pipe[0] = safe_close(error_pipe[0]);
2643
7cf66030
LP
2644 r = dissected_image_mount(
2645 m,
2646 t,
2647 UID_INVALID,
21b61b1d 2648 UID_INVALID,
7cf66030
LP
2649 DISSECT_IMAGE_READ_ONLY|
2650 DISSECT_IMAGE_MOUNT_ROOT_ONLY|
2651 DISSECT_IMAGE_VALIDATE_OS|
9ccb531a 2652 DISSECT_IMAGE_VALIDATE_OS_EXT|
7cf66030 2653 DISSECT_IMAGE_USR_NO_ROOT);
429d4e41 2654 if (r < 0) {
af8219d5
LP
2655 /* Let parent know the error */
2656 (void) write(error_pipe[1], &r, sizeof(r));
2657
429d4e41 2658 log_debug_errno(r, "Failed to mount dissected image: %m");
3b925504 2659 _exit(EXIT_FAILURE);
429d4e41 2660 }
3b925504 2661
67f63ee5 2662 for (unsigned k = 0; k < _META_MAX; k++) {
37e44c3f 2663 _cleanup_close_ int fd = -ENOENT;
3b925504
LP
2664 const char *p;
2665
7718ac97
LB
2666 if (!paths[k])
2667 continue;
2668
3b925504
LP
2669 fds[2*k] = safe_close(fds[2*k]);
2670
9a4b883b
LB
2671 if (k == META_EXTENSION_RELEASE) {
2672 /* As per the os-release spec, if the image is an extension it will have a file
2673 * named after the image name in extension-release.d/ - we use the image name
2674 * and try to resolve it with the extension-release helpers, as sometimes
2675 * the image names are mangled on deployment and do not match anymore.
2676 * Unlike other paths this is not fixed, and the image name
2677 * can be mangled on deployment, so by calling into the helper
2678 * we allow a fallback that matches on the first extension-release
2679 * file found in the directory, if one named after the image cannot
2680 * be found first. */
2681 r = open_extension_release(t, m->image_name, NULL, &fd);
2682 if (r < 0)
2683 fd = r; /* Propagate the error. */
2684 } else
2685 NULSTR_FOREACH(p, paths[k]) {
2686 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
2687 if (fd >= 0)
2688 break;
2689 }
36952d19
LP
2690 if (fd < 0) {
2691 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
37e44c3f 2692 fds[2*k+1] = safe_close(fds[2*k+1]);
3b925504 2693 continue;
36952d19 2694 }
3b925504 2695
f5fbe71d 2696 r = copy_bytes(fd, fds[2*k+1], UINT64_MAX, 0);
af8219d5
LP
2697 if (r < 0) {
2698 (void) write(error_pipe[1], &r, sizeof(r));
3b925504 2699 _exit(EXIT_FAILURE);
af8219d5 2700 }
3b925504
LP
2701
2702 fds[2*k+1] = safe_close(fds[2*k+1]);
2703 }
2704
2705 _exit(EXIT_SUCCESS);
2706 }
2707
af8219d5
LP
2708 error_pipe[1] = safe_close(error_pipe[1]);
2709
67f63ee5 2710 for (unsigned k = 0; k < _META_MAX; k++) {
3b925504
LP
2711 _cleanup_fclose_ FILE *f = NULL;
2712
7718ac97
LB
2713 if (!paths[k])
2714 continue;
2715
3b925504
LP
2716 fds[2*k+1] = safe_close(fds[2*k+1]);
2717
4fa744a3 2718 f = take_fdopen(&fds[2*k], "r");
3b925504
LP
2719 if (!f) {
2720 r = -errno;
2721 goto finish;
2722 }
2723
3b925504
LP
2724 switch (k) {
2725
2726 case META_HOSTNAME:
2727 r = read_etc_hostname_stream(f, &hostname);
2728 if (r < 0)
2729 log_debug_errno(r, "Failed to read /etc/hostname: %m");
2730
2731 break;
2732
2733 case META_MACHINE_ID: {
2734 _cleanup_free_ char *line = NULL;
2735
2736 r = read_line(f, LONG_LINE_MAX, &line);
2737 if (r < 0)
2738 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
2739 else if (r == 33) {
2740 r = sd_id128_from_string(line, &machine_id);
2741 if (r < 0)
2742 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
2743 } else if (r == 0)
2744 log_debug("/etc/machine-id file is empty.");
ab763cb2
HS
2745 else if (streq(line, "uninitialized"))
2746 log_debug("/etc/machine-id file is uninitialized (likely aborted first boot).");
3b925504
LP
2747 else
2748 log_debug("/etc/machine-id has unexpected length %i.", r);
2749
2750 break;
2751 }
2752
2753 case META_MACHINE_INFO:
aa8fbc74 2754 r = load_env_file_pairs(f, "machine-info", &machine_info);
3b925504
LP
2755 if (r < 0)
2756 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
2757
2758 break;
2759
2760 case META_OS_RELEASE:
aa8fbc74 2761 r = load_env_file_pairs(f, "os-release", &os_release);
3b925504
LP
2762 if (r < 0)
2763 log_debug_errno(r, "Failed to read OS release file: %m");
2764
2765 break;
7718ac97
LB
2766
2767 case META_EXTENSION_RELEASE:
2768 r = load_env_file_pairs(f, "extension-release", &extension_release);
2769 if (r < 0)
2770 log_debug_errno(r, "Failed to read extension release file: %m");
2771
2772 break;
3b925504
LP
2773 }
2774 }
2775
2e87a1fd 2776 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3b925504 2777 child = 0;
2e87a1fd 2778 if (r < 0)
af8219d5
LP
2779 return r;
2780
2781 n = read(error_pipe[0], &v, sizeof(v));
2782 if (n < 0)
2783 return -errno;
2784 if (n == sizeof(v))
2785 return v; /* propagate error sent to us from child */
2786 if (n != 0)
2787 return -EIO;
2788
2e87a1fd
LP
2789 if (r != EXIT_SUCCESS)
2790 return -EPROTO;
3b925504
LP
2791
2792 free_and_replace(m->hostname, hostname);
2793 m->machine_id = machine_id;
2794 strv_free_and_replace(m->machine_info, machine_info);
2795 strv_free_and_replace(m->os_release, os_release);
7718ac97 2796 strv_free_and_replace(m->extension_release, extension_release);
3b925504
LP
2797
2798finish:
67f63ee5 2799 for (unsigned k = 0; k < n_meta_initialized; k++)
3b925504
LP
2800 safe_close_pair(fds + 2*k);
2801
2802 return r;
2803}
2804
4526113f
LP
2805int dissect_image_and_warn(
2806 int fd,
2807 const char *name,
89e62e0b 2808 const VeritySettings *verity,
18d73705 2809 const MountOptions *mount_options,
a3642997 2810 uint64_t diskseq,
75dc190d 2811 uint64_t uevent_seqnum_not_before,
4a62257d 2812 usec_t timestamp_not_before,
4526113f
LP
2813 DissectImageFlags flags,
2814 DissectedImage **ret) {
2815
2816 _cleanup_free_ char *buffer = NULL;
2817 int r;
2818
2819 if (!name) {
2820 r = fd_get_path(fd, &buffer);
2821 if (r < 0)
2822 return r;
2823
2824 name = buffer;
2825 }
2826
a3642997 2827 r = dissect_image(fd, verity, mount_options, diskseq, uevent_seqnum_not_before, timestamp_not_before, flags, ret);
4526113f
LP
2828 switch (r) {
2829
2830 case -EOPNOTSUPP:
2831 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
2832
2833 case -ENOPKG:
2834 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
2835
2836 case -EADDRNOTAVAIL:
2837 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
2838
2839 case -ENOTUNIQ:
2840 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
2841
2842 case -ENXIO:
2843 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
2844
2845 case -EPROTONOSUPPORT:
2846 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
2847
2848 default:
2849 if (r < 0)
2850 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
2851
2852 return r;
2853 }
2854}
2855
49536766
LP
2856bool dissected_image_verity_candidate(const DissectedImage *image, PartitionDesignator partition_designator) {
2857 assert(image);
2858
2859 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
2860 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
2861 * images we only check the partition type.
2862 *
2863 * This call is used to decide whether to suppress or show a verity column in tabular output of the
2864 * image. */
2865
e7cbe5cb 2866 if (image->single_file_system)
c3c88d67 2867 return partition_designator == PARTITION_ROOT && image->has_verity;
e7cbe5cb
LB
2868
2869 return PARTITION_VERITY_OF(partition_designator) >= 0;
2870}
2871
49536766
LP
2872bool dissected_image_verity_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
2873 PartitionDesignator k;
2874
2875 assert(image);
2876
2877 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
2878 * works for the root partition, for others only if the associated verity partition was found. */
2879
2880 if (!image->verity_ready)
2881 return false;
e7cbe5cb
LB
2882
2883 if (image->single_file_system)
49536766 2884 return partition_designator == PARTITION_ROOT;
e7cbe5cb
LB
2885
2886 k = PARTITION_VERITY_OF(partition_designator);
2887 return k >= 0 && image->partitions[k].found;
2888}
2889
18d73705
LB
2890MountOptions* mount_options_free_all(MountOptions *options) {
2891 MountOptions *m;
2892
2893 while ((m = options)) {
2894 LIST_REMOVE(mount_options, options, m);
2895 free(m->options);
2896 free(m);
2897 }
2898
2899 return NULL;
2900}
2901
569a0e42 2902const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
f5215bc8 2903 const MountOptions *m;
18d73705 2904
f5215bc8 2905 LIST_FOREACH(mount_options, m, options)
9ece6444 2906 if (designator == m->partition_designator && !isempty(m->options))
18d73705 2907 return m->options;
6aa05ebd 2908
18d73705
LB
2909 return NULL;
2910}
2911
6aa05ebd
LP
2912int mount_image_privately_interactively(
2913 const char *image,
2914 DissectImageFlags flags,
2915 char **ret_directory,
2916 LoopDevice **ret_loop_device,
2917 DecryptedImage **ret_decrypted_image) {
2918
27ec815e 2919 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
6aa05ebd
LP
2920 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
2921 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
2922 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
2923 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
2924 _cleanup_free_ char *temp = NULL;
2925 int r;
2926
2927 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
2928 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
2929 * easily. */
2930
2931 assert(image);
2932 assert(ret_directory);
2933 assert(ret_loop_device);
2934 assert(ret_decrypted_image);
2935
27ec815e
LP
2936 r = verity_settings_load(&verity, image, NULL, NULL);
2937 if (r < 0)
2938 return log_error_errno(r, "Failed to load root hash data: %m");
2939
6aa05ebd
LP
2940 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
2941 if (r < 0)
2942 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
2943
2944 r = loop_device_make_by_path(
2945 image,
ef9c184d 2946 FLAGS_SET(flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : O_RDWR,
6aa05ebd
LP
2947 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
2948 &d);
2949 if (r < 0)
7b87fe4c 2950 return log_error_errno(r, "Failed to set up loopback device for %s: %m", image);
6aa05ebd 2951
a3642997 2952 r = dissect_image_and_warn(d->fd, image, &verity, NULL, d->diskseq, d->uevent_seqnum_not_before, d->timestamp_not_before, flags, &dissected_image);
6aa05ebd
LP
2953 if (r < 0)
2954 return r;
2955
27ec815e 2956 r = dissected_image_decrypt_interactively(dissected_image, NULL, &verity, flags, &decrypted_image);
6aa05ebd
LP
2957 if (r < 0)
2958 return r;
2959
2960 r = detach_mount_namespace();
2961 if (r < 0)
2962 return log_error_errno(r, "Failed to detach mount namespace: %m");
2963
2964 r = mkdir_p(temp, 0700);
2965 if (r < 0)
2966 return log_error_errno(r, "Failed to create mount point: %m");
2967
2968 created_dir = TAKE_PTR(temp);
2969
21b61b1d 2970 r = dissected_image_mount_and_warn(dissected_image, created_dir, UID_INVALID, UID_INVALID, flags);
6aa05ebd 2971 if (r < 0)
af187ab2 2972 return r;
6aa05ebd
LP
2973
2974 if (decrypted_image) {
2975 r = decrypted_image_relinquish(decrypted_image);
2976 if (r < 0)
2977 return log_error_errno(r, "Failed to relinquish DM devices: %m");
2978 }
2979
2980 loop_device_relinquish(d);
2981
2982 *ret_directory = TAKE_PTR(created_dir);
2983 *ret_loop_device = TAKE_PTR(d);
2984 *ret_decrypted_image = TAKE_PTR(decrypted_image);
2985
2986 return 0;
2987}
2988
8c1be37e
LP
2989static const char *const partition_designator_table[] = {
2990 [PARTITION_ROOT] = "root",
2991 [PARTITION_ROOT_SECONDARY] = "root-secondary",
aee36b4e
LP
2992 [PARTITION_USR] = "usr",
2993 [PARTITION_USR_SECONDARY] = "usr-secondary",
8c1be37e
LP
2994 [PARTITION_HOME] = "home",
2995 [PARTITION_SRV] = "srv",
2996 [PARTITION_ESP] = "esp",
a8c47660 2997 [PARTITION_XBOOTLDR] = "xbootldr",
8c1be37e 2998 [PARTITION_SWAP] = "swap",
4623e8e6
LP
2999 [PARTITION_ROOT_VERITY] = "root-verity",
3000 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
aee36b4e
LP
3001 [PARTITION_USR_VERITY] = "usr-verity",
3002 [PARTITION_USR_SECONDARY_VERITY] = "usr-secondary-verity",
d4dffb85
LP
3003 [PARTITION_TMP] = "tmp",
3004 [PARTITION_VAR] = "var",
8c1be37e
LP
3005};
3006
93f59701
LB
3007int verity_dissect_and_mount(
3008 const char *src,
3009 const char *dest,
3010 const MountOptions *options,
3011 const char *required_host_os_release_id,
3012 const char *required_host_os_release_version_id,
3013 const char *required_host_os_release_sysext_level) {
3014
4beda316
LB
3015 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
3016 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
3017 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3018 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3019 DissectImageFlags dissect_image_flags;
3020 int r;
3021
3022 assert(src);
3023 assert(dest);
3024
3025 r = verity_settings_load(&verity, src, NULL, NULL);
3026 if (r < 0)
3027 return log_debug_errno(r, "Failed to load root hash: %m");
3028
3029 dissect_image_flags = verity.data_path ? DISSECT_IMAGE_NO_PARTITION_TABLE : 0;
3030
3031 r = loop_device_make_by_path(
3032 src,
3033 -1,
3034 verity.data_path ? 0 : LO_FLAGS_PARTSCAN,
3035 &loop_device);
3036 if (r < 0)
3037 return log_debug_errno(r, "Failed to create loop device for image: %m");
3038
3039 r = dissect_image(
3040 loop_device->fd,
3041 &verity,
3042 options,
a3642997 3043 loop_device->diskseq,
75dc190d 3044 loop_device->uevent_seqnum_not_before,
4a62257d 3045 loop_device->timestamp_not_before,
4beda316
LB
3046 dissect_image_flags,
3047 &dissected_image);
3048 /* No partition table? Might be a single-filesystem image, try again */
3049 if (!verity.data_path && r == -ENOPKG)
3050 r = dissect_image(
3051 loop_device->fd,
3052 &verity,
3053 options,
a3642997 3054 loop_device->diskseq,
75dc190d 3055 loop_device->uevent_seqnum_not_before,
4a62257d 3056 loop_device->timestamp_not_before,
75dc190d 3057 dissect_image_flags | DISSECT_IMAGE_NO_PARTITION_TABLE,
4beda316
LB
3058 &dissected_image);
3059 if (r < 0)
3060 return log_debug_errno(r, "Failed to dissect image: %m");
3061
3062 r = dissected_image_decrypt(
3063 dissected_image,
3064 NULL,
3065 &verity,
3066 dissect_image_flags,
3067 &decrypted_image);
3068 if (r < 0)
3069 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
3070
3071 r = mkdir_p_label(dest, 0755);
3072 if (r < 0)
3073 return log_debug_errno(r, "Failed to create destination directory %s: %m", dest);
3074 r = umount_recursive(dest, 0);
3075 if (r < 0)
3076 return log_debug_errno(r, "Failed to umount under destination directory %s: %m", dest);
3077
21b61b1d 3078 r = dissected_image_mount(dissected_image, dest, UID_INVALID, UID_INVALID, dissect_image_flags);
4beda316
LB
3079 if (r < 0)
3080 return log_debug_errno(r, "Failed to mount image: %m");
3081
93f59701
LB
3082 /* If we got os-release values from the caller, then we need to match them with the image's
3083 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
3084 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
3085 * available, or else fallback to VERSION_ID. */
3086 if (required_host_os_release_id &&
3087 (required_host_os_release_version_id || required_host_os_release_sysext_level)) {
3088 _cleanup_strv_free_ char **extension_release = NULL;
3089
3090 r = load_extension_release_pairs(dest, dissected_image->image_name, &extension_release);
3091 if (r < 0)
3092 return log_debug_errno(r, "Failed to parse image %s extension-release metadata: %m", dissected_image->image_name);
3093
3094 r = extension_release_validate(
3095 dissected_image->image_name,
3096 required_host_os_release_id,
3097 required_host_os_release_version_id,
3098 required_host_os_release_sysext_level,
3099 extension_release);
3100 if (r == 0)
3101 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", dissected_image->image_name);
3102 if (r < 0)
3103 return log_debug_errno(r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image->image_name);
3104 }
3105
4beda316
LB
3106 if (decrypted_image) {
3107 r = decrypted_image_relinquish(decrypted_image);
3108 if (r < 0)
3109 return log_debug_errno(r, "Failed to relinquish decrypted image: %m");
3110 }
3111
3112 loop_device_relinquish(loop_device);
3113
3114 return 0;
3115}
3116
569a0e42 3117DEFINE_STRING_TABLE_LOOKUP(partition_designator, PartitionDesignator);