]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/partition/repart.c
gpt: Add gpt_partition_type_mountpoint_nulstr()
[thirdparty/systemd.git] / src / partition / repart.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
e594a3b1
LP
2
3#if HAVE_VALGRIND_MEMCHECK_H
4#include <valgrind/memcheck.h>
5#endif
6
7#include <fcntl.h>
8#include <getopt.h>
e594a3b1
LP
9#include <linux/fs.h>
10#include <linux/loop.h>
11#include <sys/file.h>
12#include <sys/ioctl.h>
13#include <sys/stat.h>
14
1a037ba2 15#include "sd-device.h"
e594a3b1
LP
16#include "sd-id128.h"
17
18#include "alloc-util.h"
19#include "blkid-util.h"
20#include "blockdev-util.h"
21#include "btrfs-util.h"
d6b4d1c7 22#include "build.h"
f4351959 23#include "chase-symlinks.h"
e594a3b1
LP
24#include "conf-files.h"
25#include "conf-parser.h"
28db6fbf 26#include "constants.h"
1e2f3230 27#include "cryptsetup-util.h"
ca822829 28#include "device-util.h"
7176f06c 29#include "devnum-util.h"
5c08da58 30#include "dirent-util.h"
e594a3b1
LP
31#include "efivars.h"
32#include "errno-util.h"
33#include "fd-util.h"
4dc07c3a 34#include "fdisk-util.h"
b9df3536 35#include "fileio.h"
e594a3b1
LP
36#include "format-table.h"
37#include "format-util.h"
38#include "fs-util.h"
d8e32c47 39#include "glyph-util.h"
e594a3b1 40#include "gpt.h"
889914ef 41#include "hexdecoct.h"
ade99252 42#include "hmac.h"
e594a3b1 43#include "id128-util.h"
baa6a42d 44#include "initrd-util.h"
b456191d 45#include "io-util.h"
a015fbe7 46#include "json.h"
e594a3b1 47#include "list.h"
53171c04 48#include "loop-util.h"
e594a3b1 49#include "main-func.h"
8a794850 50#include "mkdir.h"
53171c04 51#include "mkfs-util.h"
8a794850 52#include "mount-util.h"
5c08da58 53#include "mountpoint-util.h"
b456191d 54#include "openssl-util.h"
614b022c 55#include "parse-argument.h"
c3eaba2d 56#include "parse-helpers.h"
e594a3b1
LP
57#include "pretty-print.h"
58#include "proc-cmdline.h"
8a794850 59#include "process-util.h"
b9df3536 60#include "random-util.h"
170c9823 61#include "resize-fs.h"
95bfd3cd 62#include "rm-rf.h"
e594a3b1 63#include "sort-util.h"
e031166e 64#include "specifier.h"
e594a3b1 65#include "stdio-util.h"
889914ef 66#include "string-table.h"
e594a3b1
LP
67#include "string-util.h"
68#include "strv.h"
bf819d3a 69#include "sync-util.h"
95bfd3cd 70#include "tmpfile-util.h"
e594a3b1 71#include "terminal-util.h"
02ef97cd 72#include "tpm-pcr.h"
889914ef 73#include "tpm2-util.h"
8a794850 74#include "user-util.h"
e594a3b1
LP
75#include "utf8.h"
76
fb08381c
LP
77/* If not configured otherwise use a minimal partition size of 10M */
78#define DEFAULT_MIN_SIZE (10*1024*1024)
79
80/* Hard lower limit for new partition sizes */
81#define HARD_MIN_SIZE 4096
82
b456191d
DDM
83/* We know up front we're never going to put more than this in a verity sig partition. */
84#define VERITY_SIG_SIZE (HARD_MIN_SIZE * 4)
85
69e3234d 86/* libfdisk takes off slightly more than 1M of the disk size when creating a GPT disk label */
170c9823
LP
87#define GPT_METADATA_SIZE (1044*1024)
88
89/* LUKS2 takes off 16M of the partition size with its metadata by default */
90#define LUKS2_METADATA_SIZE (16*1024*1024)
91
e594a3b1
LP
92/* Note: When growing and placing new partitions we always align to 4K sector size. It's how newer hard disks
93 * are designed, and if everything is aligned to that performance is best. And for older hard disks with 512B
94 * sector size devices were generally assumed to have an even number of sectors, hence at the worst we'll
95 * waste 3K per partition, which is probably fine. */
96
97static enum {
98 EMPTY_REFUSE, /* refuse empty disks, never create a partition table */
99 EMPTY_ALLOW, /* allow empty disks, create partition table if necessary */
100 EMPTY_REQUIRE, /* require an empty disk, create a partition table */
101 EMPTY_FORCE, /* make disk empty, erase everything, create a partition table always */
a26f4a49 102 EMPTY_CREATE, /* create disk as loopback file, create a partition table always */
e594a3b1
LP
103} arg_empty = EMPTY_REFUSE;
104
105static bool arg_dry_run = true;
106static const char *arg_node = NULL;
107static char *arg_root = NULL;
252d6267 108static char *arg_image = NULL;
224c853f 109static char **arg_definitions = NULL;
e594a3b1
LP
110static bool arg_discard = true;
111static bool arg_can_factory_reset = false;
112static int arg_factory_reset = -1;
113static sd_id128_t arg_seed = SD_ID128_NULL;
114static bool arg_randomize = false;
115static int arg_pretty = -1;
a26f4a49 116static uint64_t arg_size = UINT64_MAX;
170c9823 117static bool arg_size_auto = false;
6a01ea4a 118static JsonFormatFlags arg_json_format_flags = JSON_FORMAT_OFF;
896e678b
LP
119static PagerFlags arg_pager_flags = 0;
120static bool arg_legend = true;
b9df3536
LP
121static void *arg_key = NULL;
122static size_t arg_key_size = 0;
b456191d
DDM
123static EVP_PKEY *arg_private_key = NULL;
124static X509 *arg_certificate = NULL;
889914ef
LP
125static char *arg_tpm2_device = NULL;
126static uint32_t arg_tpm2_pcr_mask = UINT32_MAX;
02ef97cd
LP
127static char *arg_tpm2_public_key = NULL;
128static uint32_t arg_tpm2_public_key_pcr_mask = UINT32_MAX;
4cee8333 129static bool arg_split = false;
e594a3b1
LP
130
131STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
252d6267 132STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
224c853f 133STATIC_DESTRUCTOR_REGISTER(arg_definitions, strv_freep);
b9df3536 134STATIC_DESTRUCTOR_REGISTER(arg_key, erase_and_freep);
b456191d
DDM
135STATIC_DESTRUCTOR_REGISTER(arg_private_key, EVP_PKEY_freep);
136STATIC_DESTRUCTOR_REGISTER(arg_certificate, X509_freep);
889914ef 137STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
02ef97cd 138STATIC_DESTRUCTOR_REGISTER(arg_tpm2_public_key, freep);
e594a3b1
LP
139
140typedef struct Partition Partition;
141typedef struct FreeArea FreeArea;
142typedef struct Context Context;
143
889914ef
LP
144typedef enum EncryptMode {
145 ENCRYPT_OFF,
146 ENCRYPT_KEY_FILE,
147 ENCRYPT_TPM2,
148 ENCRYPT_KEY_FILE_TPM2,
149 _ENCRYPT_MODE_MAX,
2d93c20e 150 _ENCRYPT_MODE_INVALID = -EINVAL,
889914ef
LP
151} EncryptMode;
152
b5b7879a
DDM
153typedef enum VerityMode {
154 VERITY_OFF,
155 VERITY_DATA,
156 VERITY_HASH,
b456191d 157 VERITY_SIG,
b5b7879a
DDM
158 _VERITY_MODE_MAX,
159 _VERITY_MODE_INVALID = -EINVAL,
160} VerityMode;
161
e594a3b1
LP
162struct Partition {
163 char *definition_path;
39fc0174 164 char **drop_in_files;
e594a3b1
LP
165
166 sd_id128_t type_uuid;
167 sd_id128_t current_uuid, new_uuid;
11749b61 168 bool new_uuid_is_set;
e594a3b1
LP
169 char *current_label, *new_label;
170
171 bool dropped;
172 bool factory_reset;
173 int32_t priority;
174
175 uint32_t weight, padding_weight;
176
177 uint64_t current_size, new_size;
178 uint64_t size_min, size_max;
179
180 uint64_t current_padding, new_padding;
181 uint64_t padding_min, padding_max;
182
183 uint64_t partno;
184 uint64_t offset;
185
186 struct fdisk_partition *current_partition;
187 struct fdisk_partition *new_partition;
188 FreeArea *padding_area;
189 FreeArea *allocated_to_area;
190
757bc2e4 191 char *copy_blocks_path;
5c08da58 192 bool copy_blocks_auto;
757bc2e4
LP
193 int copy_blocks_fd;
194 uint64_t copy_blocks_size;
195
53171c04 196 char *format;
8a794850 197 char **copy_files;
d83d8048 198 char **make_directories;
889914ef 199 EncryptMode encrypt;
b5b7879a
DDM
200 VerityMode verity;
201 char *verity_match_key;
53171c04 202
e73309c5 203 uint64_t gpt_flags;
ff0771bf 204 int no_auto;
e73309c5 205 int read_only;
1c41c1dc 206 int growfs;
e73309c5 207
b5b7879a
DDM
208 uint8_t *roothash;
209 size_t roothash_size;
210
4cee8333
DDM
211 char *split_name_format;
212 char *split_name_resolved;
213
b5b7879a
DDM
214 Partition *siblings[_VERITY_MODE_MAX];
215
e594a3b1
LP
216 LIST_FIELDS(Partition, partitions);
217};
218
219#define PARTITION_IS_FOREIGN(p) (!(p)->definition_path)
220#define PARTITION_EXISTS(p) (!!(p)->current_partition)
221
222struct FreeArea {
223 Partition *after;
224 uint64_t size;
225 uint64_t allocated;
226};
227
228struct Context {
229 LIST_HEAD(Partition, partitions);
230 size_t n_partitions;
231
232 FreeArea **free_areas;
319a4f4b 233 size_t n_free_areas;
e594a3b1
LP
234
235 uint64_t start, end, total;
236
237 struct fdisk_context *fdisk_context;
994b3031
LP
238 uint64_t sector_size;
239 uint64_t grain_size;
e594a3b1
LP
240
241 sd_id128_t seed;
242};
243
889914ef
LP
244static const char *encrypt_mode_table[_ENCRYPT_MODE_MAX] = {
245 [ENCRYPT_OFF] = "off",
246 [ENCRYPT_KEY_FILE] = "key-file",
247 [ENCRYPT_TPM2] = "tpm2",
248 [ENCRYPT_KEY_FILE_TPM2] = "key-file+tpm2",
249};
250
b5b7879a
DDM
251static const char *verity_mode_table[_VERITY_MODE_MAX] = {
252 [VERITY_OFF] = "off",
253 [VERITY_DATA] = "data",
254 [VERITY_HASH] = "hash",
b456191d 255 [VERITY_SIG] = "signature",
b5b7879a
DDM
256};
257
2709d029 258#if HAVE_LIBCRYPTSETUP
889914ef 259DEFINE_PRIVATE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(encrypt_mode, EncryptMode, ENCRYPT_KEY_FILE);
2709d029
MH
260#else
261DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(encrypt_mode, EncryptMode, ENCRYPT_KEY_FILE);
262#endif
263
86bebe38 264DEFINE_PRIVATE_STRING_TABLE_LOOKUP(verity_mode, VerityMode);
889914ef 265
e594a3b1
LP
266static uint64_t round_down_size(uint64_t v, uint64_t p) {
267 return (v / p) * p;
268}
269
270static uint64_t round_up_size(uint64_t v, uint64_t p) {
271
272 v = DIV_ROUND_UP(v, p);
273
274 if (v > UINT64_MAX / p)
275 return UINT64_MAX; /* overflow */
276
277 return v * p;
278}
279
280static Partition *partition_new(void) {
281 Partition *p;
282
283 p = new(Partition, 1);
284 if (!p)
285 return NULL;
286
287 *p = (Partition) {
288 .weight = 1000,
289 .padding_weight = 0,
290 .current_size = UINT64_MAX,
291 .new_size = UINT64_MAX,
292 .size_min = UINT64_MAX,
293 .size_max = UINT64_MAX,
294 .current_padding = UINT64_MAX,
295 .new_padding = UINT64_MAX,
296 .padding_min = UINT64_MAX,
297 .padding_max = UINT64_MAX,
298 .partno = UINT64_MAX,
299 .offset = UINT64_MAX,
757bc2e4
LP
300 .copy_blocks_fd = -1,
301 .copy_blocks_size = UINT64_MAX,
ff0771bf 302 .no_auto = -1,
e73309c5 303 .read_only = -1,
1c41c1dc 304 .growfs = -1,
e594a3b1
LP
305 };
306
307 return p;
308}
309
310static Partition* partition_free(Partition *p) {
311 if (!p)
312 return NULL;
313
314 free(p->current_label);
315 free(p->new_label);
316 free(p->definition_path);
39fc0174 317 strv_free(p->drop_in_files);
e594a3b1
LP
318
319 if (p->current_partition)
320 fdisk_unref_partition(p->current_partition);
321 if (p->new_partition)
322 fdisk_unref_partition(p->new_partition);
323
757bc2e4
LP
324 free(p->copy_blocks_path);
325 safe_close(p->copy_blocks_fd);
326
53171c04 327 free(p->format);
8a794850 328 strv_free(p->copy_files);
d83d8048 329 strv_free(p->make_directories);
b5b7879a
DDM
330 free(p->verity_match_key);
331
332 free(p->roothash);
53171c04 333
4cee8333
DDM
334 free(p->split_name_format);
335 free(p->split_name_resolved);
336
e594a3b1
LP
337 return mfree(p);
338}
339
9ccceb9d
YW
340static void partition_foreignize(Partition *p) {
341 assert(p);
342 assert(PARTITION_EXISTS(p));
343
344 /* Reset several parameters set through definition file to make the partition foreign. */
345
346 p->new_label = mfree(p->new_label);
347 p->definition_path = mfree(p->definition_path);
348 p->drop_in_files = strv_free(p->drop_in_files);
349
350 p->copy_blocks_path = mfree(p->copy_blocks_path);
351 p->copy_blocks_fd = safe_close(p->copy_blocks_fd);
352
353 p->format = mfree(p->format);
354 p->copy_files = strv_free(p->copy_files);
355 p->make_directories = strv_free(p->make_directories);
356 p->verity_match_key = mfree(p->verity_match_key);
357
358 p->new_uuid = SD_ID128_NULL;
359 p->new_uuid_is_set = false;
360 p->priority = 0;
361 p->weight = 1000;
362 p->padding_weight = 0;
363 p->size_min = UINT64_MAX;
364 p->size_max = UINT64_MAX;
365 p->padding_min = UINT64_MAX;
366 p->padding_max = UINT64_MAX;
367 p->no_auto = -1;
368 p->read_only = -1;
369 p->growfs = -1;
370 p->verity = VERITY_OFF;
371}
372
e594a3b1
LP
373static Partition* partition_unlink_and_free(Context *context, Partition *p) {
374 if (!p)
375 return NULL;
376
377 LIST_REMOVE(partitions, context->partitions, p);
378
379 assert(context->n_partitions > 0);
380 context->n_partitions--;
381
382 return partition_free(p);
383}
384
385DEFINE_TRIVIAL_CLEANUP_FUNC(Partition*, partition_free);
386
387static Context *context_new(sd_id128_t seed) {
388 Context *context;
389
390 context = new(Context, 1);
391 if (!context)
392 return NULL;
393
394 *context = (Context) {
395 .start = UINT64_MAX,
396 .end = UINT64_MAX,
397 .total = UINT64_MAX,
398 .seed = seed,
399 };
400
401 return context;
402}
403
404static void context_free_free_areas(Context *context) {
405 assert(context);
406
407 for (size_t i = 0; i < context->n_free_areas; i++)
408 free(context->free_areas[i]);
409
410 context->free_areas = mfree(context->free_areas);
411 context->n_free_areas = 0;
e594a3b1
LP
412}
413
414static Context *context_free(Context *context) {
415 if (!context)
416 return NULL;
417
418 while (context->partitions)
419 partition_unlink_and_free(context, context->partitions);
420 assert(context->n_partitions == 0);
421
422 context_free_free_areas(context);
423
424 if (context->fdisk_context)
425 fdisk_unref_context(context->fdisk_context);
426
427 return mfree(context);
428}
429
430DEFINE_TRIVIAL_CLEANUP_FUNC(Context*, context_free);
431
432static int context_add_free_area(
433 Context *context,
434 uint64_t size,
435 Partition *after) {
436
437 FreeArea *a;
438
439 assert(context);
440 assert(!after || !after->padding_area);
441
319a4f4b 442 if (!GREEDY_REALLOC(context->free_areas, context->n_free_areas + 1))
e594a3b1
LP
443 return -ENOMEM;
444
445 a = new(FreeArea, 1);
446 if (!a)
447 return -ENOMEM;
448
449 *a = (FreeArea) {
450 .size = size,
451 .after = after,
452 };
453
454 context->free_areas[context->n_free_areas++] = a;
455
456 if (after)
457 after->padding_area = a;
458
459 return 0;
460}
461
9ccceb9d
YW
462static void partition_drop_or_foreignize(Partition *p) {
463 if (!p || p->dropped || PARTITION_IS_FOREIGN(p))
464 return;
465
466 if (PARTITION_EXISTS(p)) {
467 log_info("Can't grow existing partition %s of priority %" PRIi32 ", ignoring.",
468 strna(p->current_label ?: p->new_label), p->priority);
469
470 /* Handle the partition as foreign. Do not set dropped flag. */
471 partition_foreignize(p);
472 } else {
473 log_info("Can't fit partition %s of priority %" PRIi32 ", dropping.",
474 p->definition_path, p->priority);
475
476 p->dropped = true;
477 p->allocated_to_area = NULL;
478 }
479}
480
481static bool context_drop_or_foreignize_one_priority(Context *context) {
e594a3b1 482 int32_t priority = 0;
e594a3b1
LP
483
484 LIST_FOREACH(partitions, p, context->partitions) {
485 if (p->dropped)
486 continue;
e594a3b1 487
9ccceb9d 488 priority = MAX(priority, p->priority);
e594a3b1
LP
489 }
490
491 /* Refuse to drop partitions with 0 or negative priorities or partitions of priorities that have at
492 * least one existing priority */
9ccceb9d 493 if (priority <= 0)
e594a3b1
LP
494 return false;
495
496 LIST_FOREACH(partitions, p, context->partitions) {
497 if (p->priority < priority)
498 continue;
499
9ccceb9d 500 partition_drop_or_foreignize(p);
b5b7879a
DDM
501
502 /* We ensure that all verity sibling partitions have the same priority, so it's safe
503 * to drop all siblings here as well. */
504
9ccceb9d
YW
505 for (VerityMode mode = VERITY_OFF + 1; mode < _VERITY_MODE_MAX; mode++)
506 partition_drop_or_foreignize(p->siblings[mode]);
e594a3b1
LP
507 }
508
509 return true;
510}
511
a80701e6 512static uint64_t partition_min_size(const Context *context, const Partition *p) {
e594a3b1
LP
513 uint64_t sz;
514
994b3031
LP
515 assert(context);
516 assert(p);
517
e594a3b1
LP
518 /* Calculate the disk space we really need at minimum for this partition. If the partition already
519 * exists the current size is what we really need. If it doesn't exist yet refuse to allocate less
fb08381c
LP
520 * than 4K.
521 *
522 * DEFAULT_MIN_SIZE is the default SizeMin= we configure if nothing else is specified. */
e594a3b1
LP
523
524 if (PARTITION_IS_FOREIGN(p)) {
525 /* Don't allow changing size of partitions not managed by us */
526 assert(p->current_size != UINT64_MAX);
527 return p->current_size;
528 }
529
b456191d
DDM
530 if (p->verity == VERITY_SIG)
531 return VERITY_SIG_SIZE;
532
fb08381c 533 sz = p->current_size != UINT64_MAX ? p->current_size : HARD_MIN_SIZE;
757bc2e4 534
170c9823
LP
535 if (!PARTITION_EXISTS(p)) {
536 uint64_t d = 0;
537
889914ef 538 if (p->encrypt != ENCRYPT_OFF)
994b3031 539 d += round_up_size(LUKS2_METADATA_SIZE, context->grain_size);
170c9823
LP
540
541 if (p->copy_blocks_size != UINT64_MAX)
994b3031 542 d += round_up_size(p->copy_blocks_size, context->grain_size);
889914ef 543 else if (p->format || p->encrypt != ENCRYPT_OFF) {
170c9823
LP
544 uint64_t f;
545
546 /* If we shall synthesize a file system, take minimal fs size into account (assumed to be 4K if not known) */
994b3031
LP
547 f = p->format ? round_up_size(minimal_size_by_fs_name(p->format), context->grain_size) : UINT64_MAX;
548 d += f == UINT64_MAX ? context->grain_size : f;
170c9823
LP
549 }
550
551 if (d > sz)
552 sz = d;
553 }
757bc2e4 554
994b3031 555 return MAX(round_up_size(p->size_min != UINT64_MAX ? p->size_min : DEFAULT_MIN_SIZE, context->grain_size), sz);
e594a3b1
LP
556}
557
994b3031
LP
558static uint64_t partition_max_size(const Context *context, const Partition *p) {
559 uint64_t sm;
560
e594a3b1
LP
561 /* Calculate how large the partition may become at max. This is generally the configured maximum
562 * size, except when it already exists and is larger than that. In that case it's the existing size,
563 * since we never want to shrink partitions. */
564
994b3031
LP
565 assert(context);
566 assert(p);
567
e594a3b1
LP
568 if (PARTITION_IS_FOREIGN(p)) {
569 /* Don't allow changing size of partitions not managed by us */
570 assert(p->current_size != UINT64_MAX);
571 return p->current_size;
572 }
573
b456191d
DDM
574 if (p->verity == VERITY_SIG)
575 return VERITY_SIG_SIZE;
576
822d9b9a
YW
577 if (p->size_max == UINT64_MAX)
578 return UINT64_MAX;
579
994b3031
LP
580 sm = round_down_size(p->size_max, context->grain_size);
581
e594a3b1 582 if (p->current_size != UINT64_MAX)
b0fbf90b 583 sm = MAX(p->current_size, sm);
e594a3b1 584
b0fbf90b 585 return MAX(partition_min_size(context, p), sm);
e594a3b1
LP
586}
587
a801bb01
YW
588static uint64_t partition_min_padding(const Partition *p) {
589 assert(p);
590 return p->padding_min != UINT64_MAX ? p->padding_min : 0;
591}
592
593static uint64_t partition_max_padding(const Partition *p) {
594 assert(p);
595 return p->padding_max;
596}
597
994b3031 598static uint64_t partition_min_size_with_padding(Context *context, const Partition *p) {
e594a3b1
LP
599 uint64_t sz;
600
601 /* Calculate the disk space we need for this partition plus any free space coming after it. This
602 * takes user configured padding into account as well as any additional whitespace needed to align
603 * the next partition to 4K again. */
604
994b3031
LP
605 assert(context);
606 assert(p);
607
a801bb01 608 sz = partition_min_size(context, p) + partition_min_padding(p);
e594a3b1
LP
609
610 if (PARTITION_EXISTS(p)) {
611 /* If the partition wasn't aligned, add extra space so that any we might add will be aligned */
612 assert(p->offset != UINT64_MAX);
994b3031 613 return round_up_size(p->offset + sz, context->grain_size) - p->offset;
e594a3b1
LP
614 }
615
616 /* If this is a new partition we'll place it aligned, hence we just need to round up the required size here */
994b3031 617 return round_up_size(sz, context->grain_size);
e594a3b1
LP
618}
619
620static uint64_t free_area_available(const FreeArea *a) {
621 assert(a);
622
623 /* Determines how much of this free area is not allocated yet */
624
625 assert(a->size >= a->allocated);
626 return a->size - a->allocated;
627}
628
58b06ac1 629static uint64_t free_area_current_end(Context *context, const FreeArea *a) {
994b3031
LP
630 assert(context);
631 assert(a);
632
58b06ac1
YW
633 if (!a->after)
634 return free_area_available(a);
e594a3b1 635
58b06ac1
YW
636 assert(a->after->offset != UINT64_MAX);
637 assert(a->after->current_size != UINT64_MAX);
e594a3b1 638
58b06ac1
YW
639 /* Calculate where the free area ends, based on the offset of the partition preceding it. */
640 return round_up_size(a->after->offset + a->after->current_size, context->grain_size) + free_area_available(a);
641}
e594a3b1 642
58b06ac1
YW
643static uint64_t free_area_min_end(Context *context, const FreeArea *a) {
644 assert(context);
645 assert(a);
e594a3b1 646
58b06ac1
YW
647 if (!a->after)
648 return 0;
e594a3b1 649
58b06ac1
YW
650 assert(a->after->offset != UINT64_MAX);
651 assert(a->after->current_size != UINT64_MAX);
1052a114 652
58b06ac1
YW
653 /* Calculate where the partition would end when we give it as much as it needs. */
654 return round_up_size(a->after->offset + partition_min_size_with_padding(context, a->after), context->grain_size);
655}
656
657static uint64_t free_area_available_for_new_partitions(Context *context, const FreeArea *a) {
658 assert(context);
659 assert(a);
660
661 /* Similar to free_area_available(), but takes into account that the required size and padding of the
662 * preceding partition is honoured. */
e594a3b1 663
58b06ac1 664 return LESS_BY(free_area_current_end(context, a), free_area_min_end(context, a));
e594a3b1
LP
665}
666
994b3031
LP
667static int free_area_compare(FreeArea *const *a, FreeArea *const*b, Context *context) {
668 assert(context);
669
670 return CMP(free_area_available_for_new_partitions(context, *a),
671 free_area_available_for_new_partitions(context, *b));
e594a3b1
LP
672}
673
994b3031
LP
674static uint64_t charge_size(Context *context, uint64_t total, uint64_t amount) {
675 assert(context);
e594a3b1 676 /* Subtract the specified amount from total, rounding up to multiple of 4K if there's room */
184cf99a 677 assert(amount <= total);
994b3031 678 return LESS_BY(total, round_up_size(amount, context->grain_size));
e594a3b1
LP
679}
680
681static uint64_t charge_weight(uint64_t total, uint64_t amount) {
682 assert(amount <= total);
683 return total - amount;
684}
685
14a4c4ed 686static bool context_allocate_partitions(Context *context, uint64_t *ret_largest_free_area) {
e594a3b1
LP
687 assert(context);
688
f39cf264
YW
689 /* This may be called multiple times. Reset previous assignments. */
690 for (size_t i = 0; i < context->n_free_areas; i++)
691 context->free_areas[i]->allocated = 0;
692
14a4c4ed 693 /* Sort free areas by size, putting smallest first */
994b3031 694 typesafe_qsort_r(context->free_areas, context->n_free_areas, free_area_compare, context);
e594a3b1 695
14a4c4ed
LP
696 /* In any case return size of the largest free area (i.e. not the size of all free areas
697 * combined!) */
698 if (ret_largest_free_area)
699 *ret_largest_free_area =
700 context->n_free_areas == 0 ? 0 :
994b3031 701 free_area_available_for_new_partitions(context, context->free_areas[context->n_free_areas-1]);
14a4c4ed 702
cdbcc339
YW
703 /* Check that each existing partition can fit its area. */
704 for (size_t i = 0; i < context->n_free_areas; i++)
705 if (free_area_current_end(context, context->free_areas[i]) <
706 free_area_min_end(context, context->free_areas[i]))
707 return false;
708
14a4c4ed 709 /* A simple first-fit algorithm. We return true if we can fit the partitions in, otherwise false. */
e594a3b1
LP
710 LIST_FOREACH(partitions, p, context->partitions) {
711 bool fits = false;
712 uint64_t required;
713 FreeArea *a = NULL;
714
715 /* Skip partitions we already dropped or that already exist */
716 if (p->dropped || PARTITION_EXISTS(p))
717 continue;
718
e594a3b1 719 /* How much do we need to fit? */
994b3031
LP
720 required = partition_min_size_with_padding(context, p);
721 assert(required % context->grain_size == 0);
e594a3b1
LP
722
723 for (size_t i = 0; i < context->n_free_areas; i++) {
724 a = context->free_areas[i];
725
994b3031 726 if (free_area_available_for_new_partitions(context, a) >= required) {
e594a3b1
LP
727 fits = true;
728 break;
729 }
730 }
731
732 if (!fits)
733 return false; /* 😢 Oh no! We can't fit this partition into any free area! */
734
735 /* Assign the partition to this free area */
736 p->allocated_to_area = a;
737
738 /* Budget the minimal partition size */
739 a->allocated += required;
740 }
741
742 return true;
743}
744
745static int context_sum_weights(Context *context, FreeArea *a, uint64_t *ret) {
746 uint64_t weight_sum = 0;
e594a3b1
LP
747
748 assert(context);
749 assert(a);
750 assert(ret);
751
752 /* Determine the sum of the weights of all partitions placed in or before the specified free area */
753
754 LIST_FOREACH(partitions, p, context->partitions) {
755 if (p->padding_area != a && p->allocated_to_area != a)
756 continue;
757
758 if (p->weight > UINT64_MAX - weight_sum)
759 goto overflow_sum;
760 weight_sum += p->weight;
761
762 if (p->padding_weight > UINT64_MAX - weight_sum)
763 goto overflow_sum;
764 weight_sum += p->padding_weight;
765 }
766
767 *ret = weight_sum;
768 return 0;
769
770overflow_sum:
771 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Combined weight of partition exceeds unsigned 64bit range, refusing.");
772}
773
0245e15a 774static uint64_t scale_by_weight(uint64_t value, uint64_t weight, uint64_t weight_sum) {
e594a3b1 775 assert(weight_sum >= weight);
e594a3b1 776
0245e15a
YW
777 for (;;) {
778 if (weight == 0)
779 return 0;
780 if (weight == weight_sum)
781 return value;
782 if (value <= UINT64_MAX / weight)
783 return value * weight / weight_sum;
784
785 /* Rescale weight and weight_sum to make not the calculation overflow. To satisfy the
786 * following conditions, 'weight_sum' is rounded up but 'weight' is rounded down:
787 * - the sum of scale_by_weight() for all weights must not be larger than the input value,
788 * - scale_by_weight() must not be larger than the ideal value (i.e. calculated with uint128_t). */
789 weight_sum = DIV_ROUND_UP(weight_sum, 2);
790 weight /= 2;
e594a3b1 791 }
e594a3b1
LP
792}
793
794typedef enum GrowPartitionPhase {
bf99aed6
YW
795 /* The zeroth phase: do not touch foreign partitions (i.e. those we don't manage). */
796 PHASE_FOREIGN,
797
e594a3b1
LP
798 /* The first phase: we charge partitions which need more (according to constraints) than their weight-based share. */
799 PHASE_OVERCHARGE,
800
801 /* The second phase: we charge partitions which need less (according to constraints) than their weight-based share. */
802 PHASE_UNDERCHARGE,
803
804 /* The third phase: we distribute what remains among the remaining partitions, according to the weights */
805 PHASE_DISTRIBUTE,
ae0613c6
LP
806
807 _GROW_PARTITION_PHASE_MAX,
e594a3b1
LP
808} GrowPartitionPhase;
809
0245e15a 810static bool context_grow_partitions_phase(
e594a3b1
LP
811 Context *context,
812 FreeArea *a,
813 GrowPartitionPhase phase,
814 uint64_t *span,
815 uint64_t *weight_sum) {
816
2a503ad2
YW
817 bool try_again = false;
818
e594a3b1
LP
819 assert(context);
820 assert(a);
0245e15a
YW
821 assert(span);
822 assert(weight_sum);
e594a3b1
LP
823
824 /* Now let's look at the intended weights and adjust them taking the minimum space assignments into
825 * account. i.e. if a partition has a small weight but a high minimum space value set it should not
826 * get any additional room from the left-overs. Similar, if two partitions have the same weight they
827 * should get the same space if possible, even if one has a smaller minimum size than the other. */
828 LIST_FOREACH(partitions, p, context->partitions) {
829
830 /* Look only at partitions associated with this free area, i.e. immediately
162392b7 831 * preceding it, or allocated into it */
e594a3b1
LP
832 if (p->allocated_to_area != a && p->padding_area != a)
833 continue;
834
835 if (p->new_size == UINT64_MAX) {
e594a3b1 836 uint64_t share, rsz, xsz;
2a503ad2 837 bool charge = false;
e594a3b1
LP
838
839 /* Calculate how much this space this partition needs if everyone would get
840 * the weight based share */
0245e15a 841 share = scale_by_weight(*span, p->weight, *weight_sum);
e594a3b1 842
994b3031
LP
843 rsz = partition_min_size(context, p);
844 xsz = partition_max_size(context, p);
e594a3b1 845
bf99aed6
YW
846 if (phase == PHASE_FOREIGN && PARTITION_IS_FOREIGN(p)) {
847 /* Never change of foreign partitions (i.e. those we don't manage) */
848
849 p->new_size = p->current_size;
850 charge = true;
851
852 } else if (phase == PHASE_OVERCHARGE && rsz > share) {
e594a3b1
LP
853 /* This partition needs more than its calculated share. Let's assign
854 * it that, and take this partition out of all calculations and start
855 * again. */
856
857 p->new_size = rsz;
858 charge = try_again = true;
859
822d9b9a 860 } else if (phase == PHASE_UNDERCHARGE && xsz < share) {
e594a3b1
LP
861 /* This partition accepts less than its calculated
862 * share. Let's assign it that, and take this partition out
863 * of all calculations and start again. */
864
865 p->new_size = xsz;
866 charge = try_again = true;
867
868 } else if (phase == PHASE_DISTRIBUTE) {
869 /* This partition can accept its calculated share. Let's
870 * assign it. There's no need to restart things here since
871 * assigning this shouldn't impact the shares of the other
872 * partitions. */
873
d7c46b5e
YW
874 assert(share >= rsz);
875 p->new_size = CLAMP(round_down_size(share, context->grain_size), rsz, xsz);
e594a3b1
LP
876 charge = true;
877 }
878
879 if (charge) {
994b3031 880 *span = charge_size(context, *span, p->new_size);
e594a3b1
LP
881 *weight_sum = charge_weight(*weight_sum, p->weight);
882 }
e594a3b1
LP
883 }
884
885 if (p->new_padding == UINT64_MAX) {
a801bb01 886 uint64_t share, rsz, xsz;
2a503ad2 887 bool charge = false;
e594a3b1 888
0245e15a 889 share = scale_by_weight(*span, p->padding_weight, *weight_sum);
e594a3b1 890
a801bb01
YW
891 rsz = partition_min_padding(p);
892 xsz = partition_max_padding(p);
893
894 if (phase == PHASE_OVERCHARGE && rsz > share) {
895 p->new_padding = rsz;
e594a3b1 896 charge = try_again = true;
a801bb01
YW
897 } else if (phase == PHASE_UNDERCHARGE && xsz < share) {
898 p->new_padding = xsz;
e594a3b1
LP
899 charge = try_again = true;
900 } else if (phase == PHASE_DISTRIBUTE) {
d7c46b5e
YW
901 assert(share >= rsz);
902 p->new_padding = CLAMP(round_down_size(share, context->grain_size), rsz, xsz);
e594a3b1
LP
903 charge = true;
904 }
905
906 if (charge) {
994b3031 907 *span = charge_size(context, *span, p->new_padding);
e594a3b1
LP
908 *weight_sum = charge_weight(*weight_sum, p->padding_weight);
909 }
e594a3b1
LP
910 }
911 }
912
2a503ad2 913 return !try_again;
e594a3b1
LP
914}
915
19903a43
YW
916static void context_grow_partition_one(Context *context, FreeArea *a, Partition *p, uint64_t *span) {
917 uint64_t m;
918
919 assert(context);
920 assert(a);
921 assert(p);
922 assert(span);
923
924 if (*span == 0)
925 return;
926
927 if (p->allocated_to_area != a)
928 return;
929
930 if (PARTITION_IS_FOREIGN(p))
931 return;
932
933 assert(p->new_size != UINT64_MAX);
934
935 /* Calculate new size and align. */
936 m = round_down_size(p->new_size + *span, context->grain_size);
937 /* But ensure this doesn't shrink the size. */
938 m = MAX(m, p->new_size);
939 /* And ensure this doesn't exceed the maximum size. */
940 m = MIN(m, partition_max_size(context, p));
941
942 assert(m >= p->new_size);
943
944 *span = charge_size(context, *span, m - p->new_size);
945 p->new_size = m;
946}
947
e594a3b1
LP
948static int context_grow_partitions_on_free_area(Context *context, FreeArea *a) {
949 uint64_t weight_sum = 0, span;
950 int r;
951
952 assert(context);
953 assert(a);
954
955 r = context_sum_weights(context, a, &weight_sum);
956 if (r < 0)
957 return r;
958
959 /* Let's calculate the total area covered by this free area and the partition before it */
960 span = a->size;
961 if (a->after) {
962 assert(a->after->offset != UINT64_MAX);
963 assert(a->after->current_size != UINT64_MAX);
964
994b3031 965 span += round_up_size(a->after->offset + a->after->current_size, context->grain_size) - a->after->offset;
e594a3b1
LP
966 }
967
0245e15a
YW
968 for (GrowPartitionPhase phase = 0; phase < _GROW_PARTITION_PHASE_MAX;)
969 if (context_grow_partitions_phase(context, a, phase, &span, &weight_sum))
970 phase++; /* go to the next phase */
e594a3b1 971
162392b7 972 /* We still have space left over? Donate to preceding partition if we have one */
19903a43
YW
973 if (span > 0 && a->after)
974 context_grow_partition_one(context, a, a->after, &span);
e594a3b1 975
162392b7 976 /* What? Even still some space left (maybe because there was no preceding partition, or it had a
e594a3b1 977 * size limit), then let's donate it to whoever wants it. */
03677889 978 if (span > 0)
e594a3b1 979 LIST_FOREACH(partitions, p, context->partitions) {
19903a43 980 context_grow_partition_one(context, a, p, &span);
e594a3b1
LP
981 if (span == 0)
982 break;
983 }
e594a3b1 984
162392b7 985 /* Yuck, still no one? Then make it padding */
e594a3b1
LP
986 if (span > 0 && a->after) {
987 assert(a->after->new_padding != UINT64_MAX);
988 a->after->new_padding += span;
989 }
990
991 return 0;
992}
993
994static int context_grow_partitions(Context *context) {
e594a3b1
LP
995 int r;
996
997 assert(context);
998
999 for (size_t i = 0; i < context->n_free_areas; i++) {
1000 r = context_grow_partitions_on_free_area(context, context->free_areas[i]);
1001 if (r < 0)
1002 return r;
1003 }
1004
1005 /* All existing partitions that have no free space after them can't change size */
1006 LIST_FOREACH(partitions, p, context->partitions) {
1007 if (p->dropped)
1008 continue;
1009
1010 if (!PARTITION_EXISTS(p) || p->padding_area) {
1011 /* The algorithm above must have initialized this already */
1012 assert(p->new_size != UINT64_MAX);
1013 continue;
1014 }
1015
1016 assert(p->new_size == UINT64_MAX);
1017 p->new_size = p->current_size;
1018
1019 assert(p->new_padding == UINT64_MAX);
1020 p->new_padding = p->current_padding;
1021 }
1022
1023 return 0;
1024}
1025
1026static void context_place_partitions(Context *context) {
1027 uint64_t partno = 0;
e594a3b1
LP
1028
1029 assert(context);
1030
1031 /* Determine next partition number to assign */
1032 LIST_FOREACH(partitions, p, context->partitions) {
1033 if (!PARTITION_EXISTS(p))
1034 continue;
1035
1036 assert(p->partno != UINT64_MAX);
1037 if (p->partno >= partno)
1038 partno = p->partno + 1;
1039 }
1040
1041 for (size_t i = 0; i < context->n_free_areas; i++) {
1042 FreeArea *a = context->free_areas[i];
2ea7eb00
FS
1043 _unused_ uint64_t left;
1044 uint64_t start;
e594a3b1
LP
1045
1046 if (a->after) {
1047 assert(a->after->offset != UINT64_MAX);
1048 assert(a->after->new_size != UINT64_MAX);
1049 assert(a->after->new_padding != UINT64_MAX);
1050
1051 start = a->after->offset + a->after->new_size + a->after->new_padding;
1052 } else
1053 start = context->start;
1054
994b3031 1055 start = round_up_size(start, context->grain_size);
e594a3b1
LP
1056 left = a->size;
1057
1058 LIST_FOREACH(partitions, p, context->partitions) {
1059 if (p->allocated_to_area != a)
1060 continue;
1061
1062 p->offset = start;
1063 p->partno = partno++;
1064
1065 assert(left >= p->new_size);
1066 start += p->new_size;
1067 left -= p->new_size;
1068
1069 assert(left >= p->new_padding);
1070 start += p->new_padding;
1071 left -= p->new_padding;
1072 }
1073 }
1074}
1075
e594a3b1
LP
1076static int config_parse_type(
1077 const char *unit,
1078 const char *filename,
1079 unsigned line,
1080 const char *section,
1081 unsigned section_line,
1082 const char *lvalue,
1083 int ltype,
1084 const char *rvalue,
1085 void *data,
1086 void *userdata) {
1087
99534007 1088 sd_id128_t *type_uuid = ASSERT_PTR(data);
e594a3b1
LP
1089 int r;
1090
1091 assert(rvalue);
e594a3b1
LP
1092
1093 r = gpt_partition_type_uuid_from_string(rvalue, type_uuid);
1094 if (r < 0)
1095 return log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse partition type: %s", rvalue);
1096
1097 return 0;
1098}
1099
1100static int config_parse_label(
1101 const char *unit,
1102 const char *filename,
1103 unsigned line,
1104 const char *section,
1105 unsigned section_line,
1106 const char *lvalue,
1107 int ltype,
1108 const char *rvalue,
1109 void *data,
1110 void *userdata) {
1111
e031166e 1112 _cleanup_free_ char *resolved = NULL;
99534007 1113 char **label = ASSERT_PTR(data);
e594a3b1
LP
1114 int r;
1115
1116 assert(rvalue);
e594a3b1 1117
be9ce018
LP
1118 /* Nota bene: the empty label is a totally valid one. Let's hence not follow our usual rule of
1119 * assigning the empty string to reset to default here, but really accept it as label to set. */
1120
de61a04b 1121 r = specifier_printf(rvalue, GPT_LABEL_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved);
e031166e 1122 if (r < 0) {
e459258f 1123 log_syntax(unit, LOG_WARNING, filename, line, r,
e031166e
LP
1124 "Failed to expand specifiers in Label=, ignoring: %s", rvalue);
1125 return 0;
1126 }
1127
1128 if (!utf8_is_valid(resolved)) {
e594a3b1
LP
1129 log_syntax(unit, LOG_WARNING, filename, line, 0,
1130 "Partition label not valid UTF-8, ignoring: %s", rvalue);
1131 return 0;
1132 }
1133
22a0a36e
LP
1134 r = gpt_partition_label_valid(resolved);
1135 if (r < 0) {
1136 log_syntax(unit, LOG_WARNING, filename, line, r,
1137 "Failed to check if string is valid as GPT partition label, ignoring: \"%s\" (from \"%s\")",
1138 resolved, rvalue);
1139 return 0;
1140 }
1141 if (!r) {
e594a3b1 1142 log_syntax(unit, LOG_WARNING, filename, line, 0,
46072ae3
ZJS
1143 "Partition label too long for GPT table, ignoring: \"%s\" (from \"%s\")",
1144 resolved, rvalue);
e594a3b1
LP
1145 return 0;
1146 }
1147
e031166e 1148 free_and_replace(*label, resolved);
e594a3b1
LP
1149 return 0;
1150}
1151
1152static int config_parse_weight(
1153 const char *unit,
1154 const char *filename,
1155 unsigned line,
1156 const char *section,
1157 unsigned section_line,
1158 const char *lvalue,
1159 int ltype,
1160 const char *rvalue,
1161 void *data,
1162 void *userdata) {
1163
f126038f 1164 uint32_t *w = ASSERT_PTR(data), v;
e594a3b1
LP
1165 int r;
1166
1167 assert(rvalue);
e594a3b1
LP
1168
1169 r = safe_atou32(rvalue, &v);
1170 if (r < 0) {
1171 log_syntax(unit, LOG_WARNING, filename, line, r,
1172 "Failed to parse weight value, ignoring: %s", rvalue);
1173 return 0;
1174 }
1175
1176 if (v > 1000U*1000U) {
c8f3d767 1177 log_syntax(unit, LOG_WARNING, filename, line, 0,
e594a3b1
LP
1178 "Weight needs to be in range 0…10000000, ignoring: %" PRIu32, v);
1179 return 0;
1180 }
1181
f126038f 1182 *w = v;
e594a3b1
LP
1183 return 0;
1184}
1185
1186static int config_parse_size4096(
1187 const char *unit,
1188 const char *filename,
1189 unsigned line,
1190 const char *section,
1191 unsigned section_line,
1192 const char *lvalue,
1193 int ltype,
1194 const char *rvalue,
1195 void *data,
1196 void *userdata) {
1197
1198 uint64_t *sz = data, parsed;
1199 int r;
1200
1201 assert(rvalue);
1202 assert(data);
1203
1204 r = parse_size(rvalue, 1024, &parsed);
1205 if (r < 0)
c8f3d767 1206 return log_syntax(unit, LOG_ERR, filename, line, r,
e594a3b1
LP
1207 "Failed to parse size value: %s", rvalue);
1208
1209 if (ltype > 0)
1210 *sz = round_up_size(parsed, 4096);
1211 else if (ltype < 0)
1212 *sz = round_down_size(parsed, 4096);
1213 else
1214 *sz = parsed;
1215
1216 if (*sz != parsed)
e2341b6b
DT
1217 log_syntax(unit, LOG_NOTICE, filename, line, r, "Rounded %s= size %" PRIu64 " %s %" PRIu64 ", a multiple of 4096.",
1218 lvalue, parsed, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), *sz);
e594a3b1
LP
1219
1220 return 0;
1221}
1222
53171c04
LP
1223static int config_parse_fstype(
1224 const char *unit,
1225 const char *filename,
1226 unsigned line,
1227 const char *section,
1228 unsigned section_line,
1229 const char *lvalue,
1230 int ltype,
1231 const char *rvalue,
1232 void *data,
1233 void *userdata) {
1234
99534007 1235 char **fstype = ASSERT_PTR(data);
53171c04
LP
1236
1237 assert(rvalue);
53171c04
LP
1238
1239 if (!filename_is_valid(rvalue))
1240 return log_syntax(unit, LOG_ERR, filename, line, 0,
1241 "File system type is not valid, refusing: %s", rvalue);
1242
1243 return free_and_strdup_warn(fstype, rvalue);
1244}
1245
8a794850
LP
1246static int config_parse_copy_files(
1247 const char *unit,
1248 const char *filename,
1249 unsigned line,
1250 const char *section,
1251 unsigned section_line,
1252 const char *lvalue,
1253 int ltype,
1254 const char *rvalue,
1255 void *data,
1256 void *userdata) {
1257
1258 _cleanup_free_ char *source = NULL, *buffer = NULL, *resolved_source = NULL, *resolved_target = NULL;
1259 const char *p = rvalue, *target;
99534007 1260 Partition *partition = ASSERT_PTR(data);
8a794850
LP
1261 int r;
1262
1263 assert(rvalue);
8a794850
LP
1264
1265 r = extract_first_word(&p, &source, ":", EXTRACT_CUNESCAPE|EXTRACT_DONT_COALESCE_SEPARATORS);
1266 if (r < 0)
1267 return log_syntax(unit, LOG_ERR, filename, line, r, "Failed to extract source path: %s", rvalue);
1268 if (r == 0) {
1269 log_syntax(unit, LOG_WARNING, filename, line, 0, "No argument specified: %s", rvalue);
1270 return 0;
1271 }
1272
1273 r = extract_first_word(&p, &buffer, ":", EXTRACT_CUNESCAPE|EXTRACT_DONT_COALESCE_SEPARATORS);
1274 if (r < 0)
1275 return log_syntax(unit, LOG_ERR, filename, line, r, "Failed to extract target path: %s", rvalue);
1276 if (r == 0)
1277 target = source; /* No target, then it's the same as the source */
1278 else
1279 target = buffer;
1280
1281 if (!isempty(p))
1282 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL), "Too many arguments: %s", rvalue);
1283
de61a04b 1284 r = specifier_printf(source, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_source);
8a794850
LP
1285 if (r < 0) {
1286 log_syntax(unit, LOG_WARNING, filename, line, r,
1287 "Failed to expand specifiers in CopyFiles= source, ignoring: %s", rvalue);
1288 return 0;
1289 }
1290
0ade2213
LP
1291 r = path_simplify_and_warn(resolved_source, PATH_CHECK_ABSOLUTE, unit, filename, line, lvalue);
1292 if (r < 0)
8a794850 1293 return 0;
8a794850 1294
de61a04b 1295 r = specifier_printf(target, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_target);
8a794850
LP
1296 if (r < 0) {
1297 log_syntax(unit, LOG_WARNING, filename, line, r,
1298 "Failed to expand specifiers in CopyFiles= target, ignoring: %s", resolved_target);
1299 return 0;
1300 }
1301
0ade2213
LP
1302 r = path_simplify_and_warn(resolved_target, PATH_CHECK_ABSOLUTE, unit, filename, line, lvalue);
1303 if (r < 0)
8a794850 1304 return 0;
8a794850
LP
1305
1306 r = strv_consume_pair(&partition->copy_files, TAKE_PTR(resolved_source), TAKE_PTR(resolved_target));
1307 if (r < 0)
1308 return log_oom();
1309
1310 return 0;
1311}
1312
5c08da58
LP
1313static int config_parse_copy_blocks(
1314 const char *unit,
1315 const char *filename,
1316 unsigned line,
1317 const char *section,
1318 unsigned section_line,
1319 const char *lvalue,
1320 int ltype,
1321 const char *rvalue,
1322 void *data,
1323 void *userdata) {
1324
1325 _cleanup_free_ char *d = NULL;
99534007 1326 Partition *partition = ASSERT_PTR(data);
5c08da58
LP
1327 int r;
1328
1329 assert(rvalue);
5c08da58
LP
1330
1331 if (isempty(rvalue)) {
1332 partition->copy_blocks_path = mfree(partition->copy_blocks_path);
1333 partition->copy_blocks_auto = false;
1334 return 0;
1335 }
1336
1337 if (streq(rvalue, "auto")) {
1338 partition->copy_blocks_path = mfree(partition->copy_blocks_path);
1339 partition->copy_blocks_auto = true;
1340 return 0;
1341 }
1342
de61a04b 1343 r = specifier_printf(rvalue, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &d);
5c08da58
LP
1344 if (r < 0) {
1345 log_syntax(unit, LOG_WARNING, filename, line, r,
1346 "Failed to expand specifiers in CopyBlocks= source path, ignoring: %s", rvalue);
1347 return 0;
1348 }
1349
1350 r = path_simplify_and_warn(d, PATH_CHECK_ABSOLUTE, unit, filename, line, lvalue);
1351 if (r < 0)
1352 return 0;
1353
1354 free_and_replace(partition->copy_blocks_path, d);
1355 partition->copy_blocks_auto = false;
1356 return 0;
1357}
1358
d83d8048
LP
1359static int config_parse_make_dirs(
1360 const char *unit,
1361 const char *filename,
1362 unsigned line,
1363 const char *section,
1364 unsigned section_line,
1365 const char *lvalue,
1366 int ltype,
1367 const char *rvalue,
1368 void *data,
1369 void *userdata) {
1370
99534007
DT
1371 Partition *partition = ASSERT_PTR(data);
1372 const char *p = ASSERT_PTR(rvalue);
d83d8048
LP
1373 int r;
1374
d83d8048
LP
1375 for (;;) {
1376 _cleanup_free_ char *word = NULL, *d = NULL;
1377
1378 r = extract_first_word(&p, &word, NULL, EXTRACT_UNQUOTE);
1379 if (r == -ENOMEM)
1380 return log_oom();
1381 if (r < 0) {
1382 log_syntax(unit, LOG_WARNING, filename, line, r, "Invalid syntax, ignoring: %s", rvalue);
1383 return 0;
1384 }
1385 if (r == 0)
1386 return 0;
1387
de61a04b 1388 r = specifier_printf(word, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &d);
d83d8048
LP
1389 if (r < 0) {
1390 log_syntax(unit, LOG_WARNING, filename, line, r,
1391 "Failed to expand specifiers in MakeDirectories= parameter, ignoring: %s", word);
1392 continue;
1393 }
1394
1395 r = path_simplify_and_warn(d, PATH_CHECK_ABSOLUTE, unit, filename, line, lvalue);
1396 if (r < 0)
1397 continue;
1398
1399 r = strv_consume(&partition->make_directories, TAKE_PTR(d));
1400 if (r < 0)
1401 return log_oom();
1402 }
1403}
1404
889914ef
LP
1405static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_encrypt, encrypt_mode, EncryptMode, ENCRYPT_OFF, "Invalid encryption mode");
1406
e73309c5
LP
1407static int config_parse_gpt_flags(
1408 const char *unit,
1409 const char *filename,
1410 unsigned line,
1411 const char *section,
1412 unsigned section_line,
1413 const char *lvalue,
1414 int ltype,
1415 const char *rvalue,
1416 void *data,
1417 void *userdata) {
1418
99534007 1419 uint64_t *gpt_flags = ASSERT_PTR(data);
e73309c5
LP
1420 int r;
1421
1422 assert(rvalue);
e73309c5
LP
1423
1424 r = safe_atou64(rvalue, gpt_flags);
1425 if (r < 0) {
1426 log_syntax(unit, LOG_WARNING, filename, line, r,
1427 "Failed to parse Flags= value, ignoring: %s", rvalue);
1428 return 0;
1429 }
1430
1431 return 0;
1432}
1433
11749b61
DDM
1434static int config_parse_uuid(
1435 const char *unit,
1436 const char *filename,
1437 unsigned line,
1438 const char *section,
1439 unsigned section_line,
1440 const char *lvalue,
1441 int ltype,
1442 const char *rvalue,
1443 void *data,
1444 void *userdata) {
1445
1446 Partition *partition = ASSERT_PTR(data);
1447 int r;
1448
1449 if (isempty(rvalue)) {
1450 partition->new_uuid = SD_ID128_NULL;
1451 partition->new_uuid_is_set = false;
1452 return 0;
1453 }
1454
1455 if (streq(rvalue, "null")) {
1456 partition->new_uuid = SD_ID128_NULL;
1457 partition->new_uuid_is_set = true;
1458 return 0;
1459 }
1460
1461 r = sd_id128_from_string(rvalue, &partition->new_uuid);
1462 if (r < 0) {
1463 log_syntax(unit, LOG_WARNING, filename, line, r, "Failed to parse 128bit ID/UUID, ignoring: %s", rvalue);
1464 return 0;
1465 }
1466
1467 partition->new_uuid_is_set = true;
1468
1469 return 0;
1470}
1471
b5b7879a
DDM
1472static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_verity, verity_mode, VerityMode, VERITY_OFF, "Invalid verity mode");
1473
39fc0174 1474static int partition_read_definition(Partition *p, const char *path, const char *const *conf_file_dirs) {
e594a3b1
LP
1475
1476 ConfigTableItem table[] = {
4cee8333
DDM
1477 { "Partition", "Type", config_parse_type, 0, &p->type_uuid },
1478 { "Partition", "Label", config_parse_label, 0, &p->new_label },
1479 { "Partition", "UUID", config_parse_uuid, 0, p },
1480 { "Partition", "Priority", config_parse_int32, 0, &p->priority },
1481 { "Partition", "Weight", config_parse_weight, 0, &p->weight },
1482 { "Partition", "PaddingWeight", config_parse_weight, 0, &p->padding_weight },
1483 { "Partition", "SizeMinBytes", config_parse_size4096, 1, &p->size_min },
1484 { "Partition", "SizeMaxBytes", config_parse_size4096, -1, &p->size_max },
1485 { "Partition", "PaddingMinBytes", config_parse_size4096, 1, &p->padding_min },
1486 { "Partition", "PaddingMaxBytes", config_parse_size4096, -1, &p->padding_max },
1487 { "Partition", "FactoryReset", config_parse_bool, 0, &p->factory_reset },
1488 { "Partition", "CopyBlocks", config_parse_copy_blocks, 0, p },
1489 { "Partition", "Format", config_parse_fstype, 0, &p->format },
1490 { "Partition", "CopyFiles", config_parse_copy_files, 0, p },
1491 { "Partition", "MakeDirectories", config_parse_make_dirs, 0, p },
1492 { "Partition", "Encrypt", config_parse_encrypt, 0, &p->encrypt },
1493 { "Partition", "Verity", config_parse_verity, 0, &p->verity },
1494 { "Partition", "VerityMatchKey", config_parse_string, 0, &p->verity_match_key },
1495 { "Partition", "Flags", config_parse_gpt_flags, 0, &p->gpt_flags },
1496 { "Partition", "ReadOnly", config_parse_tristate, 0, &p->read_only },
1497 { "Partition", "NoAuto", config_parse_tristate, 0, &p->no_auto },
1498 { "Partition", "GrowFileSystem", config_parse_tristate, 0, &p->growfs },
1499 { "Partition", "SplitName", config_parse_string, 0, &p->split_name_format },
e594a3b1
LP
1500 {}
1501 };
1502 int r;
39fc0174
RP
1503 _cleanup_free_ char *filename = NULL;
1504 const char* dropin_dirname;
e594a3b1 1505
39fc0174
RP
1506 r = path_extract_filename(path, &filename);
1507 if (r < 0)
1508 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);;
1509
1510 dropin_dirname = strjoina(filename, ".d");
1511
1512 r = config_parse_many(
1513 STRV_MAKE_CONST(path),
1514 conf_file_dirs,
1515 dropin_dirname,
1516 "Partition\0",
1517 config_item_table_lookup, table,
1518 CONFIG_PARSE_WARN,
1519 p,
1520 NULL,
1521 &p->drop_in_files);
e594a3b1
LP
1522 if (r < 0)
1523 return r;
1524
1525 if (p->size_min != UINT64_MAX && p->size_max != UINT64_MAX && p->size_min > p->size_max)
1526 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
1527 "SizeMinBytes= larger than SizeMaxBytes=, refusing.");
1528
1529 if (p->padding_min != UINT64_MAX && p->padding_max != UINT64_MAX && p->padding_min > p->padding_max)
1530 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
1531 "PaddingMinBytes= larger than PaddingMaxBytes=, refusing.");
1532
1533 if (sd_id128_is_null(p->type_uuid))
1534 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
1535 "Type= not defined, refusing.");
1536
5c08da58
LP
1537 if ((p->copy_blocks_path || p->copy_blocks_auto) &&
1538 (p->format || !strv_isempty(p->copy_files) || !strv_isempty(p->make_directories)))
53171c04 1539 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
5c08da58 1540 "Format=/CopyFiles=/MakeDirectories= and CopyBlocks= cannot be combined, refusing.");
53171c04 1541
d83d8048 1542 if ((!strv_isempty(p->copy_files) || !strv_isempty(p->make_directories)) && streq_ptr(p->format, "swap"))
8a794850
LP
1543 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
1544 "Format=swap and CopyFiles= cannot be combined, refusing.");
1545
5c08da58 1546 if (!p->format && (!strv_isempty(p->copy_files) || !strv_isempty(p->make_directories) || (p->encrypt != ENCRYPT_OFF && !(p->copy_blocks_path || p->copy_blocks_auto)))) {
b9df3536 1547 /* Pick "ext4" as file system if we are configured to copy files or encrypt the device */
8a794850
LP
1548 p->format = strdup("ext4");
1549 if (!p->format)
1550 return log_oom();
1551 }
1552
b5b7879a
DDM
1553 if (p->verity != VERITY_OFF || p->encrypt != ENCRYPT_OFF) {
1554 r = dlopen_cryptsetup();
1555 if (r < 0)
1556 return log_syntax(NULL, LOG_ERR, path, 1, r,
1557 "libcryptsetup not found, Verity=/Encrypt= are not supported: %m");
1558 }
1559
1560 if (p->verity != VERITY_OFF && !p->verity_match_key)
1561 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
1562 "VerityMatchKey= must be set if Verity=%s", verity_mode_to_string(p->verity));
1563
1564 if (p->verity == VERITY_OFF && p->verity_match_key)
1565 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
1566 "VerityMatchKey= can only be set if Verity= is not \"%s\"",
1567 verity_mode_to_string(p->verity));
1568
b456191d
DDM
1569 if (IN_SET(p->verity, VERITY_HASH, VERITY_SIG) &&
1570 (p->copy_files || p->copy_blocks_path || p->copy_blocks_auto || p->format || p->make_directories))
b5b7879a
DDM
1571 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
1572 "CopyBlocks=/CopyFiles=/Format=/MakeDirectories= cannot be used with Verity=%s",
1573 verity_mode_to_string(p->verity));
1574
1575 if (p->verity != VERITY_OFF && p->encrypt != ENCRYPT_OFF)
1576 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
1577 "Encrypting verity hash/data partitions is not supported");
1578
b456191d
DDM
1579 if (p->verity == VERITY_SIG && !arg_private_key)
1580 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
1581 "Verity signature partition requested but no private key provided (--private-key=)");
1582
1583 if (p->verity == VERITY_SIG && !arg_certificate)
1584 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
ba4a5eff 1585 "Verity signature partition requested but no PEM certificate provided (--certificate=)");
b456191d
DDM
1586
1587 if (p->verity == VERITY_SIG && (p->size_min != UINT64_MAX || p->size_max != UINT64_MAX))
1588 return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
1589 "SizeMinBytes=/SizeMaxBytes= cannot be used with Verity=%s",
1590 verity_mode_to_string(p->verity));
1591
e73309c5
LP
1592 /* Verity partitions are read only, let's imply the RO flag hence, unless explicitly configured otherwise. */
1593 if ((gpt_partition_type_is_root_verity(p->type_uuid) ||
1594 gpt_partition_type_is_usr_verity(p->type_uuid)) &&
1595 p->read_only < 0)
1596 p->read_only = true;
1597
1c41c1dc
LP
1598 /* Default to "growfs" on, unless read-only */
1599 if (gpt_partition_type_knows_growfs(p->type_uuid) &&
1600 p->read_only <= 0)
1601 p->growfs = true;
1602
4cee8333
DDM
1603 if (!p->split_name_format) {
1604 char *s = strdup("%t");
1605 if (!s)
1606 return log_oom();
1607
1608 p->split_name_format = s;
1609 } else if (streq(p->split_name_format, "-"))
1610 p->split_name_format = mfree(p->split_name_format);
1611
e594a3b1
LP
1612 return 0;
1613}
1614
b5b7879a
DDM
1615static int find_verity_sibling(Context *context, Partition *p, VerityMode mode, Partition **ret) {
1616 Partition *s = NULL;
1617
1618 assert(p);
1619 assert(p->verity != VERITY_OFF);
1620 assert(p->verity_match_key);
1621 assert(mode != VERITY_OFF);
1622 assert(p->verity != mode);
1623 assert(ret);
1624
1625 /* Try to find the matching sibling partition of the given type for a verity partition. For a data
af3d3873
YW
1626 * partition, this is the corresponding hash partition with the same verity name (and vice versa for
1627 * the hash partition). */
b5b7879a
DDM
1628
1629 LIST_FOREACH(partitions, q, context->partitions) {
1630 if (p == q)
1631 continue;
1632
1633 if (q->verity != mode)
1634 continue;
1635
1636 assert(q->verity_match_key);
1637
1638 if (!streq(p->verity_match_key, q->verity_match_key))
1639 continue;
1640
1641 if (s)
1642 return -ENOTUNIQ;
1643
1644 s = q;
1645 }
1646
1647 if (!s)
1648 return -ENXIO;
1649
1650 *ret = s;
1651
1652 return 0;
1653}
1654
e594a3b1
LP
1655static int context_read_definitions(
1656 Context *context,
224c853f 1657 char **directories,
e594a3b1
LP
1658 const char *root) {
1659
1660 _cleanup_strv_free_ char **files = NULL;
1661 Partition *last = NULL;
e594a3b1 1662 int r;
39fc0174 1663 const char *const *dirs;
e594a3b1
LP
1664
1665 assert(context);
1666
224c853f 1667 dirs = (const char* const*) (directories ?: CONF_PATHS_STRV("repart.d"));
39fc0174 1668
224c853f 1669 r = conf_files_list_strv(&files, ".conf", directories ? NULL : root, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, dirs);
e594a3b1
LP
1670 if (r < 0)
1671 return log_error_errno(r, "Failed to enumerate *.conf files: %m");
1672
1673 STRV_FOREACH(f, files) {
1674 _cleanup_(partition_freep) Partition *p = NULL;
1675
1676 p = partition_new();
1677 if (!p)
1678 return log_oom();
1679
1680 p->definition_path = strdup(*f);
1681 if (!p->definition_path)
1682 return log_oom();
1683
39fc0174 1684 r = partition_read_definition(p, *f, dirs);
e594a3b1
LP
1685 if (r < 0)
1686 return r;
1687
1688 LIST_INSERT_AFTER(partitions, context->partitions, last, p);
1689 last = TAKE_PTR(p);
1690 context->n_partitions++;
1691 }
1692
b5b7879a
DDM
1693 /* Check that each configured verity hash/data partition has a matching verity data/hash partition. */
1694
1695 LIST_FOREACH(partitions, p, context->partitions) {
1696 if (p->verity == VERITY_OFF)
1697 continue;
1698
1699 for (VerityMode mode = VERITY_OFF + 1; mode < _VERITY_MODE_MAX; mode++) {
b456191d 1700 Partition *q = NULL;
b5b7879a
DDM
1701
1702 if (p->verity == mode)
1703 continue;
1704
1705 if (p->siblings[mode])
1706 continue;
1707
1708 r = find_verity_sibling(context, p, mode, &q);
8e52ed02
DDM
1709 if (r == -ENXIO) {
1710 if (mode != VERITY_SIG)
1711 return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
1712 "Missing verity %s partition for verity %s partition with VerityMatchKey=%s",
1713 verity_mode_to_string(mode), verity_mode_to_string(p->verity), p->verity_match_key);
1714 } else if (r == -ENOTUNIQ)
b5b7879a
DDM
1715 return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
1716 "Multiple verity %s partitions found for verity %s partition with VerityMatchKey=%s",
1717 verity_mode_to_string(mode), verity_mode_to_string(p->verity), p->verity_match_key);
8e52ed02
DDM
1718 else if (r < 0)
1719 return log_syntax(NULL, LOG_ERR, p->definition_path, 1, r,
1720 "Failed to find verity %s partition for verity %s partition with VerityMatchKey=%s",
1721 verity_mode_to_string(mode), verity_mode_to_string(p->verity), p->verity_match_key);
b5b7879a 1722
b456191d
DDM
1723 if (q) {
1724 if (q->priority != p->priority)
1725 return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
1726 "Priority mismatch (%i != %i) for verity sibling partitions with VerityMatchKey=%s",
1727 p->priority, q->priority, p->verity_match_key);
b5b7879a 1728
b456191d
DDM
1729 p->siblings[mode] = q;
1730 }
b5b7879a
DDM
1731 }
1732 }
1733
e594a3b1
LP
1734 return 0;
1735}
1736
e594a3b1
LP
1737static int determine_current_padding(
1738 struct fdisk_context *c,
1739 struct fdisk_table *t,
1740 struct fdisk_partition *p,
994b3031
LP
1741 uint64_t secsz,
1742 uint64_t grainsz,
e594a3b1
LP
1743 uint64_t *ret) {
1744
1745 size_t n_partitions;
1746 uint64_t offset, next = UINT64_MAX;
1747
1748 assert(c);
1749 assert(t);
1750 assert(p);
1751
1752 if (!fdisk_partition_has_end(p))
1753 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition has no end!");
1754
1755 offset = fdisk_partition_get_end(p);
994b3031
LP
1756 assert(offset < UINT64_MAX / secsz);
1757 offset *= secsz;
e594a3b1
LP
1758
1759 n_partitions = fdisk_table_get_nents(t);
695cfd53 1760 for (size_t i = 0; i < n_partitions; i++) {
e594a3b1
LP
1761 struct fdisk_partition *q;
1762 uint64_t start;
1763
1764 q = fdisk_table_get_partition(t, i);
1765 if (!q)
1766 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read partition metadata: %m");
1767
1768 if (fdisk_partition_is_used(q) <= 0)
1769 continue;
1770
1771 if (!fdisk_partition_has_start(q))
1772 continue;
1773
1774 start = fdisk_partition_get_start(q);
994b3031
LP
1775 assert(start < UINT64_MAX / secsz);
1776 start *= secsz;
e594a3b1
LP
1777
1778 if (start >= offset && (next == UINT64_MAX || next > start))
1779 next = start;
1780 }
1781
1782 if (next == UINT64_MAX) {
1783 /* No later partition? In that case check the end of the usable area */
1784 next = fdisk_get_last_lba(c);
1785 assert(next < UINT64_MAX);
1786 next++; /* The last LBA is one sector before the end */
1787
994b3031
LP
1788 assert(next < UINT64_MAX / secsz);
1789 next *= secsz;
e594a3b1
LP
1790
1791 if (offset > next)
1792 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition end beyond disk end.");
1793 }
1794
1795 assert(next >= offset);
994b3031
LP
1796 offset = round_up_size(offset, grainsz);
1797 next = round_down_size(next, grainsz);
e594a3b1 1798
a6f44d61 1799 *ret = LESS_BY(next, offset); /* Saturated subtraction, rounding might have fucked things up */
e594a3b1
LP
1800 return 0;
1801}
1802
1803static int fdisk_ask_cb(struct fdisk_context *c, struct fdisk_ask *ask, void *data) {
1804 _cleanup_free_ char *ids = NULL;
1805 int r;
1806
1807 if (fdisk_ask_get_type(ask) != FDISK_ASKTYPE_STRING)
1808 return -EINVAL;
1809
b7416360 1810 ids = new(char, SD_ID128_UUID_STRING_MAX);
e594a3b1
LP
1811 if (!ids)
1812 return -ENOMEM;
1813
b7416360 1814 r = fdisk_ask_string_set_result(ask, sd_id128_to_uuid_string(*(sd_id128_t*) data, ids));
e594a3b1
LP
1815 if (r < 0)
1816 return r;
1817
1818 TAKE_PTR(ids);
1819 return 0;
1820}
1821
1822static int fdisk_set_disklabel_id_by_uuid(struct fdisk_context *c, sd_id128_t id) {
1823 int r;
1824
1825 r = fdisk_set_ask(c, fdisk_ask_cb, &id);
1826 if (r < 0)
1827 return r;
1828
1829 r = fdisk_set_disklabel_id(c);
1830 if (r < 0)
1831 return r;
1832
1833 return fdisk_set_ask(c, NULL, NULL);
1834}
1835
53171c04 1836static int derive_uuid(sd_id128_t base, const char *token, sd_id128_t *ret) {
e594a3b1 1837 union {
ade99252 1838 uint8_t md[SHA256_DIGEST_SIZE];
e594a3b1
LP
1839 sd_id128_t id;
1840 } result;
1841
53171c04 1842 assert(token);
e594a3b1
LP
1843 assert(ret);
1844
53171c04
LP
1845 /* Derive a new UUID from the specified UUID in a stable and reasonably safe way. Specifically, we
1846 * calculate the HMAC-SHA256 of the specified token string, keyed by the supplied base (typically the
1847 * machine ID). We use the machine ID as key (and not as cleartext!) of the HMAC operation since it's
1848 * the machine ID we don't want to leak. */
e594a3b1 1849
ade99252 1850 hmac_sha256(base.bytes, sizeof(base.bytes), token, strlen(token), result.md);
e594a3b1
LP
1851
1852 /* Take the first half, mark it as v4 UUID */
1853 assert_cc(sizeof(result.md) == sizeof(result.id) * 2);
1854 *ret = id128_make_v4_uuid(result.id);
1855 return 0;
1856}
1857
a26f4a49
LP
1858static int context_load_partition_table(
1859 Context *context,
1860 const char *node,
1861 int *backing_fd) {
1862
e594a3b1
LP
1863 _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
1864 _cleanup_(fdisk_unref_tablep) struct fdisk_table *t = NULL;
1865 uint64_t left_boundary = UINT64_MAX, first_lba, last_lba, nsectors;
1866 _cleanup_free_ char *disk_uuid_string = NULL;
1867 bool from_scratch = false;
1868 sd_id128_t disk_uuid;
1869 size_t n_partitions;
994b3031
LP
1870 unsigned long secsz;
1871 uint64_t grainsz;
e594a3b1
LP
1872 int r;
1873
1874 assert(context);
1875 assert(node);
a26f4a49 1876 assert(backing_fd);
170c9823
LP
1877 assert(!context->fdisk_context);
1878 assert(!context->free_areas);
1879 assert(context->start == UINT64_MAX);
1880 assert(context->end == UINT64_MAX);
1881 assert(context->total == UINT64_MAX);
e594a3b1
LP
1882
1883 c = fdisk_new_context();
1884 if (!c)
1885 return log_oom();
1886
a26f4a49
LP
1887 /* libfdisk doesn't have an API to operate on arbitrary fds, hence reopen the fd going via the
1888 * /proc/self/fd/ magic path if we have an existing fd. Open the original file otherwise. */
1889 if (*backing_fd < 0)
1890 r = fdisk_assign_device(c, node, arg_dry_run);
ddb6eeaf
LP
1891 else
1892 r = fdisk_assign_device(c, FORMAT_PROC_FD_PATH(*backing_fd), arg_dry_run);
170c9823
LP
1893 if (r == -EINVAL && arg_size_auto) {
1894 struct stat st;
1895
1896 /* libfdisk returns EINVAL if opening a file of size zero. Let's check for that, and accept
1897 * it if automatic sizing is requested. */
1898
1899 if (*backing_fd < 0)
1900 r = stat(node, &st);
1901 else
1902 r = fstat(*backing_fd, &st);
1903 if (r < 0)
1904 return log_error_errno(errno, "Failed to stat block device '%s': %m", node);
1905
994b3031
LP
1906 if (S_ISREG(st.st_mode) && st.st_size == 0) {
1907 /* User the fallback values if we have no better idea */
1908 context->sector_size = 512;
1909 context->grain_size = 4096;
170c9823 1910 return /* from_scratch = */ true;
994b3031 1911 }
170c9823
LP
1912
1913 r = -EINVAL;
1914 }
e594a3b1 1915 if (r < 0)
a26f4a49
LP
1916 return log_error_errno(r, "Failed to open device '%s': %m", node);
1917
1918 if (*backing_fd < 0) {
1919 /* If we have no fd referencing the device yet, make a copy of the fd now, so that we have one */
38f81e93 1920 *backing_fd = fd_reopen(fdisk_get_devfd(c), O_RDONLY|O_CLOEXEC);
a26f4a49 1921 if (*backing_fd < 0)
38f81e93 1922 return log_error_errno(*backing_fd, "Failed to duplicate fdisk fd: %m");
e594a3b1 1923
25baae50
DDM
1924 /* Tell udev not to interfere while we are processing the device */
1925 if (flock(*backing_fd, arg_dry_run ? LOCK_SH : LOCK_EX) < 0)
1926 return log_error_errno(errno, "Failed to lock block device: %m");
1927 }
e594a3b1 1928
994b3031
LP
1929 /* The offsets/sizes libfdisk returns to us will be in multiple of the sector size of the
1930 * device. This is typically 512, and sometimes 4096. Let's query libfdisk once for it, and then use
1931 * it for all our needs. Note that the values we use ourselves always are in bytes though, thus mean
1932 * the same thing universally. Also note that regardless what kind of sector size is in use we'll
1933 * place partitions at multiples of 4K. */
1934 secsz = fdisk_get_sector_size(c);
1935
1936 /* Insist on a power of two, and that it's a multiple of 512, i.e. the traditional sector size. */
983ce0b5
LP
1937 if (secsz < 512 || !ISPOWEROF2(secsz))
1938 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Sector size %lu is not a power of two larger than 512? Refusing.", secsz);
994b3031
LP
1939
1940 /* Use at least 4K, and ensure it's a multiple of the sector size, regardless if that is smaller or
1941 * larger */
1942 grainsz = secsz < 4096 ? 4096 : secsz;
1943
1944 log_debug("Sector size of device is %lu bytes. Using grain size of %" PRIu64 ".", secsz, grainsz);
1945
e594a3b1
LP
1946 switch (arg_empty) {
1947
1948 case EMPTY_REFUSE:
1949 /* Refuse empty disks, insist on an existing GPT partition table */
1950 if (!fdisk_is_labeltype(c, FDISK_DISKLABEL_GPT))
1951 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON), "Disk %s has no GPT disk label, not repartitioning.", node);
1952
1953 break;
1954
1955 case EMPTY_REQUIRE:
1956 /* Require an empty disk, refuse any existing partition table */
1957 r = fdisk_has_label(c);
1958 if (r < 0)
1959 return log_error_errno(r, "Failed to determine whether disk %s has a disk label: %m", node);
1960 if (r > 0)
1961 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON), "Disk %s already has a disk label, refusing.", node);
1962
1963 from_scratch = true;
1964 break;
1965
1966 case EMPTY_ALLOW:
1967 /* Allow both an empty disk and an existing partition table, but only GPT */
1968 r = fdisk_has_label(c);
1969 if (r < 0)
1970 return log_error_errno(r, "Failed to determine whether disk %s has a disk label: %m", node);
1971 if (r > 0) {
1972 if (!fdisk_is_labeltype(c, FDISK_DISKLABEL_GPT))
1973 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON), "Disk %s has non-GPT disk label, not repartitioning.", node);
1974 } else
1975 from_scratch = true;
1976
1977 break;
1978
1979 case EMPTY_FORCE:
a26f4a49 1980 case EMPTY_CREATE:
e594a3b1
LP
1981 /* Always reinitiaize the disk, don't consider what there was on the disk before */
1982 from_scratch = true;
1983 break;
1984 }
1985
1986 if (from_scratch) {
e594a3b1
LP
1987 r = fdisk_create_disklabel(c, "gpt");
1988 if (r < 0)
1989 return log_error_errno(r, "Failed to create GPT disk label: %m");
1990
53171c04 1991 r = derive_uuid(context->seed, "disk-uuid", &disk_uuid);
e594a3b1
LP
1992 if (r < 0)
1993 return log_error_errno(r, "Failed to acquire disk GPT uuid: %m");
1994
1995 r = fdisk_set_disklabel_id_by_uuid(c, disk_uuid);
1996 if (r < 0)
1997 return log_error_errno(r, "Failed to set GPT disk label: %m");
1998
1999 goto add_initial_free_area;
2000 }
2001
2002 r = fdisk_get_disklabel_id(c, &disk_uuid_string);
2003 if (r < 0)
2004 return log_error_errno(r, "Failed to get current GPT disk label UUID: %m");
2005
2006 r = sd_id128_from_string(disk_uuid_string, &disk_uuid);
2007 if (r < 0)
2008 return log_error_errno(r, "Failed to parse current GPT disk label UUID: %m");
2009
2010 if (sd_id128_is_null(disk_uuid)) {
53171c04 2011 r = derive_uuid(context->seed, "disk-uuid", &disk_uuid);
e594a3b1
LP
2012 if (r < 0)
2013 return log_error_errno(r, "Failed to acquire disk GPT uuid: %m");
2014
2015 r = fdisk_set_disklabel_id(c);
2016 if (r < 0)
2017 return log_error_errno(r, "Failed to set GPT disk label: %m");
2018 }
2019
2020 r = fdisk_get_partitions(c, &t);
2021 if (r < 0)
2022 return log_error_errno(r, "Failed to acquire partition table: %m");
2023
2024 n_partitions = fdisk_table_get_nents(t);
695cfd53 2025 for (size_t i = 0; i < n_partitions; i++) {
e594a3b1 2026 _cleanup_free_ char *label_copy = NULL;
03677889 2027 Partition *last = NULL;
e594a3b1
LP
2028 struct fdisk_partition *p;
2029 struct fdisk_parttype *pt;
2030 const char *pts, *ids, *label;
2031 uint64_t sz, start;
2032 bool found = false;
2033 sd_id128_t ptid, id;
2034 size_t partno;
2035
2036 p = fdisk_table_get_partition(t, i);
2037 if (!p)
2038 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read partition metadata: %m");
2039
2040 if (fdisk_partition_is_used(p) <= 0)
2041 continue;
2042
2043 if (fdisk_partition_has_start(p) <= 0 ||
2044 fdisk_partition_has_size(p) <= 0 ||
2045 fdisk_partition_has_partno(p) <= 0)
2046 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Found a partition without a position, size or number.");
2047
2048 pt = fdisk_partition_get_type(p);
2049 if (!pt)
2050 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to acquire type of partition: %m");
2051
2052 pts = fdisk_parttype_get_string(pt);
2053 if (!pts)
2054 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to acquire type of partition as string: %m");
2055
2056 r = sd_id128_from_string(pts, &ptid);
2057 if (r < 0)
2058 return log_error_errno(r, "Failed to parse partition type UUID %s: %m", pts);
2059
2060 ids = fdisk_partition_get_uuid(p);
2061 if (!ids)
2062 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Found a partition without a UUID.");
2063
2064 r = sd_id128_from_string(ids, &id);
2065 if (r < 0)
2066 return log_error_errno(r, "Failed to parse partition UUID %s: %m", ids);
2067
2068 label = fdisk_partition_get_name(p);
2069 if (!isempty(label)) {
2070 label_copy = strdup(label);
2071 if (!label_copy)
2072 return log_oom();
2073 }
2074
2075 sz = fdisk_partition_get_size(p);
ac33e147 2076 assert(sz <= UINT64_MAX/secsz);
994b3031 2077 sz *= secsz;
e594a3b1
LP
2078
2079 start = fdisk_partition_get_start(p);
ac33e147 2080 assert(start <= UINT64_MAX/secsz);
994b3031 2081 start *= secsz;
e594a3b1
LP
2082
2083 partno = fdisk_partition_get_partno(p);
2084
2085 if (left_boundary == UINT64_MAX || left_boundary > start)
2086 left_boundary = start;
2087
2088 /* Assign this existing partition to the first partition of the right type that doesn't have
2089 * an existing one assigned yet. */
2090 LIST_FOREACH(partitions, pp, context->partitions) {
2091 last = pp;
2092
2093 if (!sd_id128_equal(pp->type_uuid, ptid))
2094 continue;
2095
2096 if (!pp->current_partition) {
2097 pp->current_uuid = id;
2098 pp->current_size = sz;
2099 pp->offset = start;
2100 pp->partno = partno;
2101 pp->current_label = TAKE_PTR(label_copy);
2102
2103 pp->current_partition = p;
2104 fdisk_ref_partition(p);
2105
994b3031 2106 r = determine_current_padding(c, t, p, secsz, grainsz, &pp->current_padding);
e594a3b1
LP
2107 if (r < 0)
2108 return r;
2109
2110 if (pp->current_padding > 0) {
2111 r = context_add_free_area(context, pp->current_padding, pp);
2112 if (r < 0)
2113 return r;
2114 }
2115
2116 found = true;
2117 break;
2118 }
2119 }
2120
2121 /* If we have no matching definition, create a new one. */
2122 if (!found) {
2123 _cleanup_(partition_freep) Partition *np = NULL;
2124
2125 np = partition_new();
2126 if (!np)
2127 return log_oom();
2128
2129 np->current_uuid = id;
2130 np->type_uuid = ptid;
2131 np->current_size = sz;
2132 np->offset = start;
2133 np->partno = partno;
2134 np->current_label = TAKE_PTR(label_copy);
2135
2136 np->current_partition = p;
2137 fdisk_ref_partition(p);
2138
994b3031 2139 r = determine_current_padding(c, t, p, secsz, grainsz, &np->current_padding);
e594a3b1
LP
2140 if (r < 0)
2141 return r;
2142
2143 if (np->current_padding > 0) {
2144 r = context_add_free_area(context, np->current_padding, np);
2145 if (r < 0)
2146 return r;
2147 }
2148
2149 LIST_INSERT_AFTER(partitions, context->partitions, last, TAKE_PTR(np));
2150 context->n_partitions++;
2151 }
2152 }
2153
2154add_initial_free_area:
2155 nsectors = fdisk_get_nsectors(c);
994b3031
LP
2156 assert(nsectors <= UINT64_MAX/secsz);
2157 nsectors *= secsz;
e594a3b1
LP
2158
2159 first_lba = fdisk_get_first_lba(c);
994b3031
LP
2160 assert(first_lba <= UINT64_MAX/secsz);
2161 first_lba *= secsz;
e594a3b1
LP
2162
2163 last_lba = fdisk_get_last_lba(c);
2164 assert(last_lba < UINT64_MAX);
2165 last_lba++;
994b3031
LP
2166 assert(last_lba <= UINT64_MAX/secsz);
2167 last_lba *= secsz;
e594a3b1
LP
2168
2169 assert(last_lba >= first_lba);
2170
2171 if (left_boundary == UINT64_MAX) {
2172 /* No partitions at all? Then the whole disk is up for grabs. */
2173
994b3031
LP
2174 first_lba = round_up_size(first_lba, grainsz);
2175 last_lba = round_down_size(last_lba, grainsz);
e594a3b1
LP
2176
2177 if (last_lba > first_lba) {
2178 r = context_add_free_area(context, last_lba - first_lba, NULL);
2179 if (r < 0)
2180 return r;
2181 }
2182 } else {
2183 /* Add space left of first partition */
2184 assert(left_boundary >= first_lba);
2185
994b3031
LP
2186 first_lba = round_up_size(first_lba, grainsz);
2187 left_boundary = round_down_size(left_boundary, grainsz);
2188 last_lba = round_down_size(last_lba, grainsz);
e594a3b1
LP
2189
2190 if (left_boundary > first_lba) {
2191 r = context_add_free_area(context, left_boundary - first_lba, NULL);
2192 if (r < 0)
2193 return r;
2194 }
2195 }
2196
2197 context->start = first_lba;
2198 context->end = last_lba;
2199 context->total = nsectors;
994b3031
LP
2200 context->sector_size = secsz;
2201 context->grain_size = grainsz;
e594a3b1
LP
2202 context->fdisk_context = TAKE_PTR(c);
2203
2204 return from_scratch;
2205}
2206
2207static void context_unload_partition_table(Context *context) {
e594a3b1
LP
2208 assert(context);
2209
80a226b2 2210 LIST_FOREACH(partitions, p, context->partitions) {
e594a3b1
LP
2211
2212 /* Entirely remove partitions that have no configuration */
2213 if (PARTITION_IS_FOREIGN(p)) {
2214 partition_unlink_and_free(context, p);
2215 continue;
2216 }
2217
2218 /* Otherwise drop all data we read off the block device and everything we might have
2219 * calculated based on it */
2220
2221 p->dropped = false;
2222 p->current_size = UINT64_MAX;
2223 p->new_size = UINT64_MAX;
2224 p->current_padding = UINT64_MAX;
2225 p->new_padding = UINT64_MAX;
2226 p->partno = UINT64_MAX;
2227 p->offset = UINT64_MAX;
2228
2229 if (p->current_partition) {
2230 fdisk_unref_partition(p->current_partition);
2231 p->current_partition = NULL;
2232 }
2233
2234 if (p->new_partition) {
2235 fdisk_unref_partition(p->new_partition);
2236 p->new_partition = NULL;
2237 }
2238
2239 p->padding_area = NULL;
2240 p->allocated_to_area = NULL;
2241
15d43e30
LP
2242 p->current_uuid = SD_ID128_NULL;
2243 p->current_label = mfree(p->current_label);
e594a3b1
LP
2244 }
2245
2246 context->start = UINT64_MAX;
2247 context->end = UINT64_MAX;
2248 context->total = UINT64_MAX;
2249
2250 if (context->fdisk_context) {
2251 fdisk_unref_context(context->fdisk_context);
2252 context->fdisk_context = NULL;
2253 }
2254
2255 context_free_free_areas(context);
2256}
2257
2258static int format_size_change(uint64_t from, uint64_t to, char **ret) {
2b59bf51 2259 char *t;
e594a3b1
LP
2260
2261 if (from != UINT64_MAX) {
2262 if (from == to || to == UINT64_MAX)
2b59bf51 2263 t = strdup(FORMAT_BYTES(from));
e594a3b1 2264 else
fc03e80c 2265 t = strjoin(FORMAT_BYTES(from), " ", special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), " ", FORMAT_BYTES(to));
e594a3b1 2266 } else if (to != UINT64_MAX)
fc03e80c 2267 t = strjoin(special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), " ", FORMAT_BYTES(to));
e594a3b1
LP
2268 else {
2269 *ret = NULL;
2270 return 0;
2271 }
2272
2b59bf51 2273 if (!t)
e594a3b1
LP
2274 return log_oom();
2275
2b59bf51 2276 *ret = t;
e594a3b1
LP
2277 return 1;
2278}
2279
2280static const char *partition_label(const Partition *p) {
2281 assert(p);
2282
2283 if (p->new_label)
2284 return p->new_label;
2285
2286 if (p->current_label)
2287 return p->current_label;
2288
2289 return gpt_partition_type_uuid_to_string(p->type_uuid);
2290}
2291
2292static int context_dump_partitions(Context *context, const char *node) {
2293 _cleanup_(table_unrefp) Table *t = NULL;
2294 uint64_t sum_padding = 0, sum_size = 0;
e594a3b1 2295 int r;
b5b7879a
DDM
2296 const size_t roothash_col = 13, dropin_files_col = 14;
2297 bool has_roothash = false, has_dropin_files = false;
e594a3b1 2298
6a01ea4a 2299 if ((arg_json_format_flags & JSON_FORMAT_OFF) && context->n_partitions == 0) {
a015fbe7
TH
2300 log_info("Empty partition table.");
2301 return 0;
2302 }
2303
b5b7879a 2304 t = table_new("type", "label", "uuid", "file", "node", "offset", "old size", "raw size", "size", "old padding", "raw padding", "padding", "activity", "roothash", "drop-in files");
e594a3b1
LP
2305 if (!t)
2306 return log_oom();
2307
a015fbe7 2308 if (!DEBUG_LOGGING) {
6a01ea4a 2309 if (arg_json_format_flags & JSON_FORMAT_OFF)
a015fbe7 2310 (void) table_set_display(t, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4,
b5b7879a 2311 (size_t) 8, (size_t) 11, roothash_col, dropin_files_col);
a015fbe7
TH
2312 else
2313 (void) table_set_display(t, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4,
b5b7879a
DDM
2314 (size_t) 5, (size_t) 6, (size_t) 7, (size_t) 9, (size_t) 10,
2315 (size_t) 12, roothash_col, dropin_files_col);
a015fbe7 2316 }
e594a3b1 2317
e594a3b1 2318 (void) table_set_align_percent(t, table_get_cell(t, 0, 5), 100);
9c07c9ec
LP
2319 (void) table_set_align_percent(t, table_get_cell(t, 0, 6), 100);
2320 (void) table_set_align_percent(t, table_get_cell(t, 0, 7), 100);
2321 (void) table_set_align_percent(t, table_get_cell(t, 0, 8), 100);
2322 (void) table_set_align_percent(t, table_get_cell(t, 0, 9), 100);
2323 (void) table_set_align_percent(t, table_get_cell(t, 0, 10), 100);
2324 (void) table_set_align_percent(t, table_get_cell(t, 0, 11), 100);
e594a3b1
LP
2325
2326 LIST_FOREACH(partitions, p, context->partitions) {
b5b7879a 2327 _cleanup_free_ char *size_change = NULL, *padding_change = NULL, *partname = NULL, *rh = NULL;
b7416360 2328 char uuid_buffer[SD_ID128_UUID_STRING_MAX];
a015fbe7 2329 const char *label, *activity = NULL;
e594a3b1
LP
2330
2331 if (p->dropped)
2332 continue;
2333
a015fbe7
TH
2334 if (p->current_size == UINT64_MAX)
2335 activity = "create";
2336 else if (p->current_size != p->new_size)
2337 activity = "resize";
2338
e594a3b1
LP
2339 label = partition_label(p);
2340 partname = p->partno != UINT64_MAX ? fdisk_partname(node, p->partno+1) : NULL;
2341
2342 r = format_size_change(p->current_size, p->new_size, &size_change);
2343 if (r < 0)
2344 return r;
2345
2346 r = format_size_change(p->current_padding, p->new_padding, &padding_change);
2347 if (r < 0)
2348 return r;
2349
2350 if (p->new_size != UINT64_MAX)
2351 sum_size += p->new_size;
2352 if (p->new_padding != UINT64_MAX)
2353 sum_padding += p->new_padding;
2354
b5b7879a
DDM
2355 if (p->verity == VERITY_HASH) {
2356 rh = p->roothash ? hexmem(p->roothash, p->roothash_size) : strdup("TBD");
2357 if (!rh)
2358 return log_oom();
2359 }
2360
e594a3b1
LP
2361 r = table_add_many(
2362 t,
2363 TABLE_STRING, gpt_partition_type_uuid_to_string_harder(p->type_uuid, uuid_buffer),
be9ce018 2364 TABLE_STRING, empty_to_null(label) ?: "-", TABLE_SET_COLOR, empty_to_null(label) ? NULL : ansi_grey(),
11749b61 2365 TABLE_UUID, p->new_uuid_is_set ? p->new_uuid : p->current_uuid,
e594a3b1 2366 TABLE_STRING, p->definition_path ? basename(p->definition_path) : "-", TABLE_SET_COLOR, p->definition_path ? NULL : ansi_grey(),
a015fbe7 2367 TABLE_STRING, partname ?: "-", TABLE_SET_COLOR, partname ? NULL : ansi_highlight(),
e594a3b1 2368 TABLE_UINT64, p->offset,
a015fbe7 2369 TABLE_UINT64, p->current_size == UINT64_MAX ? 0 : p->current_size,
e594a3b1
LP
2370 TABLE_UINT64, p->new_size,
2371 TABLE_STRING, size_change, TABLE_SET_COLOR, !p->partitions_next && sum_size > 0 ? ansi_underline() : NULL,
a015fbe7 2372 TABLE_UINT64, p->current_padding == UINT64_MAX ? 0 : p->current_padding,
e594a3b1 2373 TABLE_UINT64, p->new_padding,
a015fbe7 2374 TABLE_STRING, padding_change, TABLE_SET_COLOR, !p->partitions_next && sum_padding > 0 ? ansi_underline() : NULL,
39fc0174 2375 TABLE_STRING, activity ?: "unchanged",
b5b7879a 2376 TABLE_STRING, rh,
39fc0174 2377 TABLE_STRV, p->drop_in_files);
e594a3b1 2378 if (r < 0)
f987a261 2379 return table_log_add_error(r);
39fc0174 2380
b5b7879a 2381 has_roothash = has_roothash || !isempty(rh);
3ab44dbd 2382 has_dropin_files = has_dropin_files || !strv_isempty(p->drop_in_files);
e594a3b1
LP
2383 }
2384
6a01ea4a 2385 if ((arg_json_format_flags & JSON_FORMAT_OFF) && (sum_padding > 0 || sum_size > 0)) {
e594a3b1
LP
2386 const char *a, *b;
2387
2b59bf51
ZJS
2388 a = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", FORMAT_BYTES(sum_size));
2389 b = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", FORMAT_BYTES(sum_padding));
e594a3b1
LP
2390
2391 r = table_add_many(
2392 t,
2393 TABLE_EMPTY,
2394 TABLE_EMPTY,
2395 TABLE_EMPTY,
2396 TABLE_EMPTY,
2397 TABLE_EMPTY,
2398 TABLE_EMPTY,
2399 TABLE_EMPTY,
a015fbe7 2400 TABLE_EMPTY,
e594a3b1
LP
2401 TABLE_STRING, a,
2402 TABLE_EMPTY,
a015fbe7
TH
2403 TABLE_EMPTY,
2404 TABLE_STRING, b,
39fc0174 2405 TABLE_EMPTY,
b5b7879a 2406 TABLE_EMPTY,
a015fbe7 2407 TABLE_EMPTY);
e594a3b1 2408 if (r < 0)
f987a261 2409 return table_log_add_error(r);
e594a3b1
LP
2410 }
2411
b5b7879a
DDM
2412 if (!has_roothash) {
2413 r = table_hide_column_from_display(t, roothash_col);
2414 if (r < 0)
2415 return log_error_errno(r, "Failed to set columns to display: %m");
2416 }
2417
3ab44dbd 2418 if (!has_dropin_files) {
39fc0174
RP
2419 r = table_hide_column_from_display(t, dropin_files_col);
2420 if (r < 0)
2421 return log_error_errno(r, "Failed to set columns to display: %m");
2422 }
2423
896e678b 2424 return table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
e594a3b1
LP
2425}
2426
2427static void context_bar_char_process_partition(
2428 Context *context,
2429 Partition *bar[],
2430 size_t n,
2431 Partition *p,
2432 size_t *ret_start) {
2433
2434 uint64_t from, to, total;
2435 size_t x, y;
2436
2437 assert(context);
2438 assert(bar);
2439 assert(n > 0);
2440 assert(p);
2441
2442 if (p->dropped)
2443 return;
2444
2445 assert(p->offset != UINT64_MAX);
2446 assert(p->new_size != UINT64_MAX);
2447
2448 from = p->offset;
2449 to = from + p->new_size;
2450
d8daed09
TY
2451 assert(context->total > 0);
2452 total = context->total;
e594a3b1 2453
d8daed09
TY
2454 assert(from <= total);
2455 x = from * n / total;
e594a3b1 2456
d8daed09
TY
2457 assert(to <= total);
2458 y = to * n / total;
e594a3b1
LP
2459
2460 assert(x <= y);
2461 assert(y <= n);
2462
2463 for (size_t i = x; i < y; i++)
2464 bar[i] = p;
2465
2466 *ret_start = x;
2467}
2468
2469static int partition_hint(const Partition *p, const char *node, char **ret) {
2470 _cleanup_free_ char *buf = NULL;
e594a3b1
LP
2471 const char *label;
2472 sd_id128_t id;
2473
2474 /* Tries really hard to find a suitable description for this partition */
2475
2476 if (p->definition_path) {
2477 buf = strdup(basename(p->definition_path));
2478 goto done;
2479 }
2480
2481 label = partition_label(p);
2482 if (!isempty(label)) {
2483 buf = strdup(label);
2484 goto done;
2485 }
2486
2487 if (p->partno != UINT64_MAX) {
2488 buf = fdisk_partname(node, p->partno+1);
2489 goto done;
2490 }
2491
11749b61 2492 if (p->new_uuid_is_set)
e594a3b1
LP
2493 id = p->new_uuid;
2494 else if (!sd_id128_is_null(p->current_uuid))
2495 id = p->current_uuid;
2496 else
2497 id = p->type_uuid;
2498
b7416360 2499 buf = strdup(SD_ID128_TO_UUID_STRING(id));
e594a3b1
LP
2500
2501done:
2502 if (!buf)
2503 return -ENOMEM;
2504
2505 *ret = TAKE_PTR(buf);
2506 return 0;
2507}
2508
2509static int context_dump_partition_bar(Context *context, const char *node) {
2510 _cleanup_free_ Partition **bar = NULL;
2511 _cleanup_free_ size_t *start_array = NULL;
03677889 2512 Partition *last = NULL;
e594a3b1
LP
2513 bool z = false;
2514 size_t c, j = 0;
2515
f391597c 2516 assert_se((c = columns()) >= 2);
e594a3b1
LP
2517 c -= 2; /* We do not use the leftmost and rightmost character cell */
2518
2519 bar = new0(Partition*, c);
2520 if (!bar)
2521 return log_oom();
2522
2523 start_array = new(size_t, context->n_partitions);
2524 if (!start_array)
2525 return log_oom();
2526
2527 LIST_FOREACH(partitions, p, context->partitions)
2528 context_bar_char_process_partition(context, bar, c, p, start_array + j++);
2529
2530 putc(' ', stdout);
2531
2532 for (size_t i = 0; i < c; i++) {
2533 if (bar[i]) {
2534 if (last != bar[i])
2535 z = !z;
2536
2537 fputs(z ? ansi_green() : ansi_yellow(), stdout);
2538 fputs(special_glyph(SPECIAL_GLYPH_DARK_SHADE), stdout);
2539 } else {
2540 fputs(ansi_normal(), stdout);
2541 fputs(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE), stdout);
2542 }
2543
2544 last = bar[i];
2545 }
2546
2547 fputs(ansi_normal(), stdout);
2548 putc('\n', stdout);
2549
2550 for (size_t i = 0; i < context->n_partitions; i++) {
2551 _cleanup_free_ char **line = NULL;
2552
2553 line = new0(char*, c);
2554 if (!line)
2555 return log_oom();
2556
2557 j = 0;
2558 LIST_FOREACH(partitions, p, context->partitions) {
2559 _cleanup_free_ char *d = NULL;
2560 j++;
2561
2562 if (i < context->n_partitions - j) {
2563
2564 if (line[start_array[j-1]]) {
2565 const char *e;
2566
2567 /* Upgrade final corner to the right with a branch to the right */
2568 e = startswith(line[start_array[j-1]], special_glyph(SPECIAL_GLYPH_TREE_RIGHT));
2569 if (e) {
2570 d = strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH), e);
2571 if (!d)
2572 return log_oom();
2573 }
2574 }
2575
2576 if (!d) {
2577 d = strdup(special_glyph(SPECIAL_GLYPH_TREE_VERTICAL));
2578 if (!d)
2579 return log_oom();
2580 }
2581
2582 } else if (i == context->n_partitions - j) {
2583 _cleanup_free_ char *hint = NULL;
2584
2585 (void) partition_hint(p, node, &hint);
2586
2587 if (streq_ptr(line[start_array[j-1]], special_glyph(SPECIAL_GLYPH_TREE_VERTICAL)))
2588 d = strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH), " ", strna(hint));
2589 else
2590 d = strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT), " ", strna(hint));
2591
2592 if (!d)
2593 return log_oom();
2594 }
2595
2596 if (d)
2597 free_and_replace(line[start_array[j-1]], d);
2598 }
2599
2600 putc(' ', stdout);
2601
2602 j = 0;
2603 while (j < c) {
2604 if (line[j]) {
2605 fputs(line[j], stdout);
2606 j += utf8_console_width(line[j]);
2607 } else {
2608 putc(' ', stdout);
2609 j++;
2610 }
2611 }
2612
2613 putc('\n', stdout);
2614
2615 for (j = 0; j < c; j++)
2616 free(line[j]);
2617 }
2618
2619 return 0;
2620}
2621
b5b7879a
DDM
2622static bool context_has_roothash(Context *context) {
2623 LIST_FOREACH(partitions, p, context->partitions)
2624 if (p->roothash)
2625 return true;
2626
2627 return false;
2628}
2629
2630static int context_dump(Context *context, const char *node, bool late) {
a26d463d
DDM
2631 int r;
2632
2633 assert(context);
2634 assert(node);
2635
2636 if (arg_pretty == 0 && FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF))
2637 return 0;
2638
b5b7879a
DDM
2639 /* If we're outputting JSON, only dump after doing all operations so we can include the roothashes
2640 * in the output. */
2641 if (!late && !FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF))
2642 return 0;
2643
2644 /* If we're not outputting JSON, only dump again after doing all operations if there are any
2645 * roothashes that we need to communicate to the user. */
2646 if (late && FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF) && !context_has_roothash(context))
2647 return 0;
2648
a26d463d
DDM
2649 r = context_dump_partitions(context, node);
2650 if (r < 0)
2651 return r;
2652
b5b7879a
DDM
2653 /* Make sure we only write the partition bar once, even if we're writing the partition table twice to
2654 * communicate roothashes. */
2655 if (FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF) && !late) {
a26d463d
DDM
2656 putc('\n', stdout);
2657
2658 r = context_dump_partition_bar(context, node);
2659 if (r < 0)
2660 return r;
2661
2662 putc('\n', stdout);
2663 }
2664
2665 fflush(stdout);
2666
2667 return 0;
2668}
2669
2670
e594a3b1 2671static bool context_changed(const Context *context) {
03677889 2672 assert(context);
e594a3b1
LP
2673
2674 LIST_FOREACH(partitions, p, context->partitions) {
2675 if (p->dropped)
2676 continue;
2677
2678 if (p->allocated_to_area)
2679 return true;
2680
2681 if (p->new_size != p->current_size)
2682 return true;
2683 }
2684
2685 return false;
2686}
2687
81873a6b 2688static int context_wipe_range(Context *context, uint64_t offset, uint64_t size) {
e594a3b1
LP
2689 _cleanup_(blkid_free_probep) blkid_probe probe = NULL;
2690 int r;
2691
2692 assert(context);
81873a6b
LP
2693 assert(offset != UINT64_MAX);
2694 assert(size != UINT64_MAX);
e594a3b1
LP
2695
2696 probe = blkid_new_probe();
2697 if (!probe)
2698 return log_oom();
2699
e594a3b1 2700 errno = 0;
81873a6b 2701 r = blkid_probe_set_device(probe, fdisk_get_devfd(context->fdisk_context), offset, size);
e594a3b1 2702 if (r < 0)
81873a6b 2703 return log_error_errno(errno ?: SYNTHETIC_ERRNO(EIO), "Failed to allocate device probe for wiping.");
e594a3b1
LP
2704
2705 errno = 0;
2706 if (blkid_probe_enable_superblocks(probe, true) < 0 ||
2707 blkid_probe_set_superblocks_flags(probe, BLKID_SUBLKS_MAGIC|BLKID_SUBLKS_BADCSUM) < 0 ||
2708 blkid_probe_enable_partitions(probe, true) < 0 ||
2709 blkid_probe_set_partitions_flags(probe, BLKID_PARTS_MAGIC) < 0)
81873a6b 2710 return log_error_errno(errno ?: SYNTHETIC_ERRNO(EIO), "Failed to enable superblock and partition probing.");
e594a3b1
LP
2711
2712 for (;;) {
2713 errno = 0;
2714 r = blkid_do_probe(probe);
2715 if (r < 0)
2716 return log_error_errno(errno ?: SYNTHETIC_ERRNO(EIO), "Failed to probe for file systems.");
2717 if (r > 0)
2718 break;
2719
2720 errno = 0;
2721 if (blkid_do_wipe(probe, false) < 0)
2722 return log_error_errno(errno ?: SYNTHETIC_ERRNO(EIO), "Failed to wipe file system signature.");
2723 }
2724
e594a3b1
LP
2725 return 0;
2726}
2727
81873a6b
LP
2728static int context_wipe_partition(Context *context, Partition *p) {
2729 int r;
2730
2731 assert(context);
2732 assert(p);
2733 assert(!PARTITION_EXISTS(p)); /* Safety check: never wipe existing partitions */
2734
2735 assert(p->offset != UINT64_MAX);
2736 assert(p->new_size != UINT64_MAX);
2737
2738 r = context_wipe_range(context, p->offset, p->new_size);
2739 if (r < 0)
2740 return r;
2741
2742 log_info("Successfully wiped file system signatures from future partition %" PRIu64 ".", p->partno);
2743 return 0;
2744}
2745
2746static int context_discard_range(
2747 Context *context,
2748 uint64_t offset,
2749 uint64_t size) {
2750
e594a3b1
LP
2751 struct stat st;
2752 int fd;
2753
2754 assert(context);
2755 assert(offset != UINT64_MAX);
2756 assert(size != UINT64_MAX);
2757
2758 if (size <= 0)
2759 return 0;
2760
a26f4a49 2761 assert_se((fd = fdisk_get_devfd(context->fdisk_context)) >= 0);
e594a3b1
LP
2762
2763 if (fstat(fd, &st) < 0)
2764 return -errno;
2765
2766 if (S_ISREG(st.st_mode)) {
2767 if (fallocate(fd, FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE, offset, size) < 0) {
2768 if (ERRNO_IS_NOT_SUPPORTED(errno))
2769 return -EOPNOTSUPP;
2770
2771 return -errno;
2772 }
2773
2774 return 1;
2775 }
2776
2777 if (S_ISBLK(st.st_mode)) {
2778 uint64_t range[2], end;
2779
994b3031 2780 range[0] = round_up_size(offset, context->sector_size);
e594a3b1 2781
55d38014
LP
2782 if (offset > UINT64_MAX - size)
2783 return -ERANGE;
2784
e594a3b1
LP
2785 end = offset + size;
2786 if (end <= range[0])
2787 return 0;
2788
994b3031 2789 range[1] = round_down_size(end - range[0], context->sector_size);
e594a3b1
LP
2790 if (range[1] <= 0)
2791 return 0;
2792
2793 if (ioctl(fd, BLKDISCARD, range) < 0) {
2794 if (ERRNO_IS_NOT_SUPPORTED(errno))
2795 return -EOPNOTSUPP;
2796
2797 return -errno;
2798 }
2799
2800 return 1;
2801 }
2802
2803 return -EOPNOTSUPP;
2804}
2805
2806static int context_discard_partition(Context *context, Partition *p) {
2807 int r;
2808
2809 assert(context);
2810 assert(p);
2811
2812 assert(p->offset != UINT64_MAX);
2813 assert(p->new_size != UINT64_MAX);
2814 assert(!PARTITION_EXISTS(p)); /* Safety check: never discard existing partitions */
2815
2816 if (!arg_discard)
2817 return 0;
2818
2819 r = context_discard_range(context, p->offset, p->new_size);
2820 if (r == -EOPNOTSUPP) {
5b5109e2 2821 log_info("Storage does not support discard, not discarding data in future partition %" PRIu64 ".", p->partno);
e594a3b1
LP
2822 return 0;
2823 }
22163eb5
LP
2824 if (r == -EBUSY) {
2825 /* Let's handle this gracefully: https://bugzilla.kernel.org/show_bug.cgi?id=211167 */
2826 log_info("Block device is busy, not discarding partition %" PRIu64 " because it probably is mounted.", p->partno);
2827 return 0;
2828 }
e594a3b1
LP
2829 if (r == 0) {
2830 log_info("Partition %" PRIu64 " too short for discard, skipping.", p->partno);
2831 return 0;
2832 }
2833 if (r < 0)
5b5109e2 2834 return log_error_errno(r, "Failed to discard data for future partition %" PRIu64 ".", p->partno);
e594a3b1 2835
5b5109e2 2836 log_info("Successfully discarded data from future partition %" PRIu64 ".", p->partno);
e594a3b1
LP
2837 return 1;
2838}
2839
2840static int context_discard_gap_after(Context *context, Partition *p) {
2841 uint64_t gap, next = UINT64_MAX;
e594a3b1
LP
2842 int r;
2843
2844 assert(context);
2845 assert(!p || (p->offset != UINT64_MAX && p->new_size != UINT64_MAX));
2846
5113436b
AF
2847 if (!arg_discard)
2848 return 0;
2849
e594a3b1
LP
2850 if (p)
2851 gap = p->offset + p->new_size;
2852 else
2853 gap = context->start;
2854
2855 LIST_FOREACH(partitions, q, context->partitions) {
2856 if (q->dropped)
2857 continue;
2858
2859 assert(q->offset != UINT64_MAX);
2860 assert(q->new_size != UINT64_MAX);
2861
2862 if (q->offset < gap)
2863 continue;
2864
2865 if (next == UINT64_MAX || q->offset < next)
2866 next = q->offset;
2867 }
2868
2869 if (next == UINT64_MAX) {
2870 next = context->end;
2871 if (gap > next)
2872 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition end beyond disk end.");
2873 }
2874
2875 assert(next >= gap);
2876 r = context_discard_range(context, gap, next - gap);
2877 if (r == -EOPNOTSUPP) {
2878 if (p)
5b5109e2 2879 log_info("Storage does not support discard, not discarding gap after partition %" PRIu64 ".", p->partno);
e594a3b1 2880 else
5b5109e2 2881 log_info("Storage does not support discard, not discarding gap at beginning of disk.");
e594a3b1
LP
2882 return 0;
2883 }
2884 if (r == 0) /* Too short */
2885 return 0;
2886 if (r < 0) {
2887 if (p)
2888 return log_error_errno(r, "Failed to discard gap after partition %" PRIu64 ".", p->partno);
2889 else
2890 return log_error_errno(r, "Failed to discard gap at beginning of disk.");
2891 }
2892
2893 if (p)
2894 log_info("Successfully discarded gap after partition %" PRIu64 ".", p->partno);
2895 else
2896 log_info("Successfully discarded gap at beginning of disk.");
2897
2898 return 0;
2899}
2900
2901static int context_wipe_and_discard(Context *context, bool from_scratch) {
e594a3b1
LP
2902 int r;
2903
2904 assert(context);
2905
2906 /* Wipe and discard the contents of all partitions we are about to create. We skip the discarding if
2907 * we were supposed to start from scratch anyway, as in that case we just discard the whole block
2908 * device in one go early on. */
2909
2910 LIST_FOREACH(partitions, p, context->partitions) {
2911
2912 if (!p->allocated_to_area)
2913 continue;
2914
e594a3b1
LP
2915 r = context_wipe_partition(context, p);
2916 if (r < 0)
2917 return r;
2918
2919 if (!from_scratch) {
f0cb1b95
LP
2920 r = context_discard_partition(context, p);
2921 if (r < 0)
2922 return r;
2923
e594a3b1
LP
2924 r = context_discard_gap_after(context, p);
2925 if (r < 0)
2926 return r;
2927 }
2928 }
2929
2930 if (!from_scratch) {
2931 r = context_discard_gap_after(context, NULL);
2932 if (r < 0)
2933 return r;
2934 }
2935
2936 return 0;
2937}
2938
b9df3536 2939static int partition_encrypt(
994b3031 2940 Context *context,
b9df3536
LP
2941 Partition *p,
2942 const char *node,
2943 struct crypt_device **ret_cd,
2944 char **ret_volume,
2945 int *ret_fd) {
3dd8ae5c 2946#if HAVE_LIBCRYPTSETUP
0d12936d 2947 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
b9df3536
LP
2948 _cleanup_(erase_and_freep) void *volume_key = NULL;
2949 _cleanup_free_ char *dm_name = NULL, *vol = NULL;
b9df3536
LP
2950 size_t volume_key_size = 256 / 8;
2951 sd_id128_t uuid;
2952 int r;
2953
994b3031 2954 assert(context);
b9df3536 2955 assert(p);
889914ef
LP
2956 assert(p->encrypt != ENCRYPT_OFF);
2957
2958 log_debug("Encryption mode for partition %" PRIu64 ": %s", p->partno, encrypt_mode_to_string(p->encrypt));
b9df3536 2959
0d12936d
LP
2960 r = dlopen_cryptsetup();
2961 if (r < 0)
2962 return log_error_errno(r, "libcryptsetup not found, cannot encrypt: %m");
2963
b9df3536
LP
2964 if (asprintf(&dm_name, "luks-repart-%08" PRIx64, random_u64()) < 0)
2965 return log_oom();
2966
2967 if (ret_volume) {
2968 vol = path_join("/dev/mapper/", dm_name);
2969 if (!vol)
2970 return log_oom();
2971 }
2972
2973 r = derive_uuid(p->new_uuid, "luks-uuid", &uuid);
2974 if (r < 0)
2975 return r;
2976
2977 log_info("Encrypting future partition %" PRIu64 "...", p->partno);
2978
2979 volume_key = malloc(volume_key_size);
2980 if (!volume_key)
2981 return log_oom();
2982
87cb1ab6 2983 r = crypto_random_bytes(volume_key, volume_key_size);
b9df3536
LP
2984 if (r < 0)
2985 return log_error_errno(r, "Failed to generate volume key: %m");
2986
0d12936d 2987 r = sym_crypt_init(&cd, node);
b9df3536
LP
2988 if (r < 0)
2989 return log_error_errno(r, "Failed to allocate libcryptsetup context: %m");
2990
2991 cryptsetup_enable_logging(cd);
2992
0d12936d 2993 r = sym_crypt_format(cd,
b9df3536
LP
2994 CRYPT_LUKS2,
2995 "aes",
2996 "xts-plain64",
b7416360 2997 SD_ID128_TO_UUID_STRING(uuid),
b9df3536
LP
2998 volume_key,
2999 volume_key_size,
3000 &(struct crypt_params_luks2) {
be9ce018 3001 .label = strempty(p->new_label),
994b3031 3002 .sector_size = context->sector_size,
b9df3536
LP
3003 });
3004 if (r < 0)
3005 return log_error_errno(r, "Failed to LUKS2 format future partition: %m");
3006
889914ef
LP
3007 if (IN_SET(p->encrypt, ENCRYPT_KEY_FILE, ENCRYPT_KEY_FILE_TPM2)) {
3008 r = sym_crypt_keyslot_add_by_volume_key(
3009 cd,
3010 CRYPT_ANY_SLOT,
3011 volume_key,
3012 volume_key_size,
3013 strempty(arg_key),
3014 arg_key_size);
3015 if (r < 0)
3016 return log_error_errno(r, "Failed to add LUKS2 key: %m");
3017 }
3018
3019 if (IN_SET(p->encrypt, ENCRYPT_TPM2, ENCRYPT_KEY_FILE_TPM2)) {
3020#if HAVE_TPM2
3021 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
3022 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
3023 _cleanup_(erase_and_freep) void *secret = NULL;
02ef97cd 3024 _cleanup_free_ void *pubkey = NULL;
889914ef 3025 _cleanup_free_ void *blob = NULL, *hash = NULL;
02ef97cd 3026 size_t secret_size, blob_size, hash_size, pubkey_size = 0;
2b92a672 3027 uint16_t pcr_bank, primary_alg;
889914ef
LP
3028 int keyslot;
3029
02ef97cd
LP
3030 if (arg_tpm2_public_key_pcr_mask != 0) {
3031 r = tpm2_load_pcr_public_key(arg_tpm2_public_key, &pubkey, &pubkey_size);
3032 if (r < 0) {
3033 if (arg_tpm2_public_key || r != -ENOENT)
3034 return log_error_errno(r, "Failed read TPM PCR public key: %m");
3035
3036 log_debug_errno(r, "Failed to read TPM2 PCR public key, proceeding without: %m");
3037 arg_tpm2_public_key_pcr_mask = 0;
3038 }
3039 }
3040
d9b5841d
LP
3041 r = tpm2_seal(arg_tpm2_device,
3042 arg_tpm2_pcr_mask,
02ef97cd
LP
3043 pubkey, pubkey_size,
3044 arg_tpm2_public_key_pcr_mask,
d9b5841d
LP
3045 /* pin= */ NULL,
3046 &secret, &secret_size,
3047 &blob, &blob_size,
3048 &hash, &hash_size,
3049 &pcr_bank,
3050 &primary_alg);
889914ef
LP
3051 if (r < 0)
3052 return log_error_errno(r, "Failed to seal to TPM2: %m");
3053
3054 r = base64mem(secret, secret_size, &base64_encoded);
3055 if (r < 0)
3056 return log_error_errno(r, "Failed to base64 encode secret key: %m");
3057
3058 r = cryptsetup_set_minimal_pbkdf(cd);
3059 if (r < 0)
3060 return log_error_errno(r, "Failed to set minimal PBKDF: %m");
3061
3062 keyslot = sym_crypt_keyslot_add_by_volume_key(
3063 cd,
3064 CRYPT_ANY_SLOT,
3065 volume_key,
3066 volume_key_size,
3067 base64_encoded,
3068 strlen(base64_encoded));
3069 if (keyslot < 0)
3070 return log_error_errno(keyslot, "Failed to add new TPM2 key to %s: %m", node);
3071
f0f4fcae
LP
3072 r = tpm2_make_luks2_json(
3073 keyslot,
3074 arg_tpm2_pcr_mask,
3075 pcr_bank,
02ef97cd
LP
3076 pubkey, pubkey_size,
3077 arg_tpm2_public_key_pcr_mask,
f0f4fcae
LP
3078 primary_alg,
3079 blob, blob_size,
3080 hash, hash_size,
3081 0,
3082 &v);
889914ef
LP
3083 if (r < 0)
3084 return log_error_errno(r, "Failed to prepare TPM2 JSON token object: %m");
3085
3086 r = cryptsetup_add_token_json(cd, v);
3087 if (r < 0)
3088 return log_error_errno(r, "Failed to add TPM2 JSON token to LUKS2 header: %m");
3089#else
3090 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3091 "Support for TPM2 enrollment not enabled.");
3092#endif
3093 }
b9df3536 3094
0d12936d 3095 r = sym_crypt_activate_by_volume_key(
b9df3536
LP
3096 cd,
3097 dm_name,
3098 volume_key,
3099 volume_key_size,
3100 arg_discard ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0);
3101 if (r < 0)
3102 return log_error_errno(r, "Failed to activate LUKS superblock: %m");
3103
3104 log_info("Successfully encrypted future partition %" PRIu64 ".", p->partno);
3105
3106 if (ret_fd) {
3107 _cleanup_close_ int dev_fd = -1;
3108
3109 dev_fd = open(vol, O_RDWR|O_CLOEXEC|O_NOCTTY);
3110 if (dev_fd < 0)
3111 return log_error_errno(errno, "Failed to open LUKS volume '%s': %m", vol);
3112
3113 *ret_fd = TAKE_FD(dev_fd);
3114 }
3115
3116 if (ret_cd)
3117 *ret_cd = TAKE_PTR(cd);
3118 if (ret_volume)
3119 *ret_volume = TAKE_PTR(vol);
3120
3121 return 0;
3dd8ae5c 3122#else
3123 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "libcryptsetup is not supported, cannot encrypt: %m");
3124#endif
b9df3536
LP
3125}
3126
3127static int deactivate_luks(struct crypt_device *cd, const char *node) {
3dd8ae5c 3128#if HAVE_LIBCRYPTSETUP
b9df3536
LP
3129 int r;
3130
3131 if (!cd)
3132 return 0;
3133
3134 assert(node);
3135
3136 /* udev or so might access out block device in the background while we are done. Let's hence force
3137 * detach the volume. We sync'ed before, hence this should be safe. */
3138
0d12936d 3139 r = sym_crypt_deactivate_by_name(cd, basename(node), CRYPT_DEACTIVATE_FORCE);
b9df3536
LP
3140 if (r < 0)
3141 return log_error_errno(r, "Failed to deactivate LUKS device: %m");
3142
3143 return 1;
3dd8ae5c 3144#else
3145 return 0;
3146#endif
b9df3536
LP
3147}
3148
757bc2e4 3149static int context_copy_blocks(Context *context) {
b9df3536 3150 int whole_fd = -1, r;
757bc2e4
LP
3151
3152 assert(context);
3153
3154 /* Copy in file systems on the block level */
3155
3156 LIST_FOREACH(partitions, p, context->partitions) {
0d12936d 3157 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
b9df3536
LP
3158 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
3159 _cleanup_free_ char *encrypted = NULL;
3160 _cleanup_close_ int encrypted_dev_fd = -1;
b9df3536 3161 int target_fd;
757bc2e4
LP
3162
3163 if (p->copy_blocks_fd < 0)
3164 continue;
3165
3166 if (p->dropped)
3167 continue;
3168
3169 if (PARTITION_EXISTS(p)) /* Never copy over existing partitions */
3170 continue;
3171
3172 assert(p->new_size != UINT64_MAX);
3173 assert(p->copy_blocks_size != UINT64_MAX);
3174 assert(p->new_size >= p->copy_blocks_size);
3175
b9df3536
LP
3176 if (whole_fd < 0)
3177 assert_se((whole_fd = fdisk_get_devfd(context->fdisk_context)) >= 0);
3178
889914ef 3179 if (p->encrypt != ENCRYPT_OFF) {
fd83c98e 3180 r = loop_device_make(whole_fd, O_RDWR, p->offset, p->new_size, 0, 0, LOCK_EX, &d);
b9df3536
LP
3181 if (r < 0)
3182 return log_error_errno(r, "Failed to make loopback device of future partition %" PRIu64 ": %m", p->partno);
3183
994b3031 3184 r = partition_encrypt(context, p, d->node, &cd, &encrypted, &encrypted_dev_fd);
b9df3536
LP
3185 if (r < 0)
3186 return log_error_errno(r, "Failed to encrypt device: %m");
757bc2e4 3187
b9df3536
LP
3188 if (flock(encrypted_dev_fd, LOCK_EX) < 0)
3189 return log_error_errno(errno, "Failed to lock LUKS device: %m");
3190
3191 target_fd = encrypted_dev_fd;
695cfd53 3192 } else {
b9df3536
LP
3193 if (lseek(whole_fd, p->offset, SEEK_SET) == (off_t) -1)
3194 return log_error_errno(errno, "Failed to seek to partition offset: %m");
3195
3196 target_fd = whole_fd;
3197 }
757bc2e4 3198
2b59bf51
ZJS
3199 log_info("Copying in '%s' (%s) on block level into future partition %" PRIu64 ".",
3200 p->copy_blocks_path, FORMAT_BYTES(p->copy_blocks_size), p->partno);
757bc2e4 3201
b9df3536 3202 r = copy_bytes_full(p->copy_blocks_fd, target_fd, p->copy_blocks_size, 0, NULL, NULL, NULL, NULL);
757bc2e4
LP
3203 if (r < 0)
3204 return log_error_errno(r, "Failed to copy in data from '%s': %m", p->copy_blocks_path);
3205
b9df3536 3206 if (fsync(target_fd) < 0)
8ac04a65 3207 return log_error_errno(errno, "Failed to synchronize copied data blocks: %m");
b9df3536 3208
889914ef 3209 if (p->encrypt != ENCRYPT_OFF) {
b9df3536
LP
3210 encrypted_dev_fd = safe_close(encrypted_dev_fd);
3211
3212 r = deactivate_luks(cd, encrypted);
3213 if (r < 0)
3214 return r;
3215
0d12936d 3216 sym_crypt_free(cd);
b9df3536
LP
3217 cd = NULL;
3218
3219 r = loop_device_sync(d);
3220 if (r < 0)
3221 return log_error_errno(r, "Failed to sync loopback device: %m");
3222 }
3223
757bc2e4
LP
3224 log_info("Copying in of '%s' on block level completed.", p->copy_blocks_path);
3225 }
3226
3227 return 0;
3228}
3229
92cd7e7c 3230static int do_copy_files(Partition *p, const char *root) {
8a794850
LP
3231 int r;
3232
3233 assert(p);
92cd7e7c 3234 assert(root);
8a794850
LP
3235
3236 STRV_FOREACH_PAIR(source, target, p->copy_files) {
3237 _cleanup_close_ int sfd = -1, pfd = -1, tfd = -1;
8a794850 3238
fd1ca01a 3239 sfd = chase_symlinks_and_open(*source, arg_root, CHASE_PREFIX_ROOT, O_CLOEXEC|O_NOCTTY, NULL);
8a794850
LP
3240 if (sfd < 0)
3241 return log_error_errno(sfd, "Failed to open source file '%s%s': %m", strempty(arg_root), *source);
3242
3243 r = fd_verify_regular(sfd);
3244 if (r < 0) {
3245 if (r != -EISDIR)
3246 return log_error_errno(r, "Failed to check type of source file '%s': %m", *source);
3247
3248 /* We are looking at a directory */
fd1ca01a 3249 tfd = chase_symlinks_and_open(*target, root, CHASE_PREFIX_ROOT, O_RDONLY|O_DIRECTORY|O_CLOEXEC, NULL);
8a794850 3250 if (tfd < 0) {
f21a3a82
LP
3251 _cleanup_free_ char *dn = NULL, *fn = NULL;
3252
8a794850
LP
3253 if (tfd != -ENOENT)
3254 return log_error_errno(tfd, "Failed to open target directory '%s': %m", *target);
3255
f21a3a82
LP
3256 r = path_extract_filename(*target, &fn);
3257 if (r < 0)
3258 return log_error_errno(r, "Failed to extract filename from '%s': %m", *target);
3259
3260 r = path_extract_directory(*target, &dn);
3261 if (r < 0)
3262 return log_error_errno(r, "Failed to extract directory from '%s': %m", *target);
3263
92cd7e7c 3264 r = mkdir_p_root(root, dn, UID_INVALID, GID_INVALID, 0755);
8a794850
LP
3265 if (r < 0)
3266 return log_error_errno(r, "Failed to create parent directory '%s': %m", dn);
3267
fd1ca01a 3268 pfd = chase_symlinks_and_open(dn, root, CHASE_PREFIX_ROOT, O_RDONLY|O_DIRECTORY|O_CLOEXEC, NULL);
8a794850
LP
3269 if (pfd < 0)
3270 return log_error_errno(pfd, "Failed to open parent directory of target: %m");
3271
652d9040
LP
3272 r = copy_tree_at(
3273 sfd, ".",
6020d00d 3274 pfd, fn,
652d9040 3275 UID_INVALID, GID_INVALID,
a424958a
DDM
3276 COPY_REFLINK|COPY_MERGE|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS|COPY_ALL_XATTRS,
3277 NULL);
8a794850 3278 } else
652d9040
LP
3279 r = copy_tree_at(
3280 sfd, ".",
3281 tfd, ".",
3282 UID_INVALID, GID_INVALID,
a424958a
DDM
3283 COPY_REFLINK|COPY_MERGE|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS|COPY_ALL_XATTRS,
3284 NULL);
8a794850 3285 if (r < 0)
554a2b64 3286 return log_error_errno(r, "Failed to copy '%s' to '%s%s': %m", *source, strempty(arg_root), *target);
8a794850 3287 } else {
f21a3a82
LP
3288 _cleanup_free_ char *dn = NULL, *fn = NULL;
3289
8a794850
LP
3290 /* We are looking at a regular file */
3291
f21a3a82
LP
3292 r = path_extract_filename(*target, &fn);
3293 if (r == -EADDRNOTAVAIL || r == O_DIRECTORY)
3294 return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
3295 "Target path '%s' refers to a directory, but source path '%s' refers to regular file, can't copy.", *target, *source);
3296 if (r < 0)
3297 return log_error_errno(r, "Failed to extract filename from '%s': %m", *target);
3298
3299 r = path_extract_directory(*target, &dn);
3300 if (r < 0)
3301 return log_error_errno(r, "Failed to extract directory from '%s': %m", *target);
3302
92cd7e7c 3303 r = mkdir_p_root(root, dn, UID_INVALID, GID_INVALID, 0755);
8a794850
LP
3304 if (r < 0)
3305 return log_error_errno(r, "Failed to create parent directory: %m");
3306
fd1ca01a 3307 pfd = chase_symlinks_and_open(dn, root, CHASE_PREFIX_ROOT, O_RDONLY|O_DIRECTORY|O_CLOEXEC, NULL);
8a794850 3308 if (pfd < 0)
a0ff9971 3309 return log_error_errno(pfd, "Failed to open parent directory of target: %m");
8a794850 3310
e2819067 3311 tfd = openat(pfd, fn, O_CREAT|O_EXCL|O_WRONLY|O_CLOEXEC, 0700);
8a794850
LP
3312 if (tfd < 0)
3313 return log_error_errno(errno, "Failed to create target file '%s': %m", *target);
3314
3315 r = copy_bytes(sfd, tfd, UINT64_MAX, COPY_REFLINK|COPY_SIGINT);
3316 if (r < 0)
554a2b64 3317 return log_error_errno(r, "Failed to copy '%s' to '%s%s': %m", *source, strempty(arg_root), *target);
8a794850 3318
23e026de 3319 (void) copy_xattr(sfd, tfd, COPY_ALL_XATTRS);
8a794850
LP
3320 (void) copy_access(sfd, tfd);
3321 (void) copy_times(sfd, tfd, 0);
3322 }
3323 }
3324
3325 return 0;
3326}
3327
92cd7e7c 3328static int do_make_directories(Partition *p, const char *root) {
d83d8048
LP
3329 int r;
3330
3331 assert(p);
92cd7e7c 3332 assert(root);
d83d8048
LP
3333
3334 STRV_FOREACH(d, p->make_directories) {
3335
92cd7e7c 3336 r = mkdir_p_root(root, *d, UID_INVALID, GID_INVALID, 0755);
d83d8048
LP
3337 if (r < 0)
3338 return log_error_errno(r, "Failed to create directory '%s' in file system: %m", *d);
3339 }
3340
3341 return 0;
3342}
3343
95bfd3cd
DDM
3344static int partition_populate_directory(Partition *p, char **ret_root, char **ret_tmp_root) {
3345 _cleanup_(rm_rf_physical_and_freep) char *root = NULL;
3346 int r;
3347
3348 assert(ret_root);
3349 assert(ret_tmp_root);
3350
eb43379c
DDM
3351 /* When generating read-only filesystems, we need the source tree to be available when we generate
3352 * the read-only filesystem. Because we might have multiple source trees, we build a temporary source
3353 * tree beforehand where we merge all our inputs. We then use this merged source tree to create the
3354 * read-only filesystem. */
95bfd3cd 3355
eb43379c 3356 if (!fstype_is_ro(p->format)) {
95bfd3cd
DDM
3357 *ret_root = NULL;
3358 *ret_tmp_root = NULL;
3359 return 0;
3360 }
3361
3362 /* If we only have a single directory that's meant to become the root directory of the filesystem,
3363 * we can shortcut this function and just use that directory as the root directory instead. If we
3364 * allocate a temporary directory, it's stored in "ret_tmp_root" to indicate it should be removed.
3365 * Otherwise, we return the directory to use in "root" to indicate it should not be removed. */
3366
3367 if (strv_length(p->copy_files) == 2 && strv_length(p->make_directories) == 0 && streq(p->copy_files[1], "/")) {
3368 _cleanup_free_ char *s = NULL;
3369
fd1ca01a 3370 r = chase_symlinks(p->copy_files[0], arg_root, CHASE_PREFIX_ROOT, &s, NULL);
898db9f3
DDM
3371 if (r < 0)
3372 return log_error_errno(r, "Failed to resolve source '%s%s': %m", strempty(arg_root), p->copy_files[0]);
95bfd3cd
DDM
3373
3374 *ret_root = TAKE_PTR(s);
3375 *ret_tmp_root = NULL;
3376 return 0;
3377 }
3378
3379 r = mkdtemp_malloc("/var/tmp/repart-XXXXXX", &root);
3380 if (r < 0)
3381 return log_error_errno(r, "Failed to create temporary directory: %m");
3382
3383 r = do_copy_files(p, root);
3384 if (r < 0)
3385 return r;
3386
3387 r = do_make_directories(p, root);
3388 if (r < 0)
3389 return r;
3390
3391 *ret_root = NULL;
3392 *ret_tmp_root = TAKE_PTR(root);
3393 return 0;
3394}
3395
3396static int partition_populate_filesystem(Partition *p, const char *node) {
8a794850
LP
3397 int r;
3398
3399 assert(p);
3400 assert(node);
3401
eb43379c 3402 if (fstype_is_ro(p->format))
95bfd3cd
DDM
3403 return 0;
3404
d83d8048 3405 if (strv_isempty(p->copy_files) && strv_isempty(p->make_directories))
8a794850
LP
3406 return 0;
3407
3408 log_info("Populating partition %" PRIu64 " with files.", p->partno);
3409
3410 /* We copy in a child process, since we have to mount the fs for that, and we don't want that fs to
3411 * appear in the host namespace. Hence we fork a child that has its own file system namespace and
3412 * detached mount propagation. */
3413
3414 r = safe_fork("(sd-copy)", FORK_DEATHSIG|FORK_LOG|FORK_WAIT|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, NULL);
3415 if (r < 0)
3416 return r;
3417 if (r == 0) {
3418 static const char fs[] = "/run/systemd/mount-root";
3419 /* This is a child process with its own mount namespace and propagation to host turned off */
3420
3421 r = mkdir_p(fs, 0700);
3422 if (r < 0) {
3423 log_error_errno(r, "Failed to create mount point: %m");
3424 _exit(EXIT_FAILURE);
3425 }
3426
511a8cfe 3427 if (mount_nofollow_verbose(LOG_ERR, node, fs, p->format, MS_NOATIME|MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL) < 0)
8a794850
LP
3428 _exit(EXIT_FAILURE);
3429
3430 if (do_copy_files(p, fs) < 0)
3431 _exit(EXIT_FAILURE);
3432
d83d8048
LP
3433 if (do_make_directories(p, fs) < 0)
3434 _exit(EXIT_FAILURE);
3435
8a794850
LP
3436 r = syncfs_path(AT_FDCWD, fs);
3437 if (r < 0) {
3438 log_error_errno(r, "Failed to synchronize written files: %m");
3439 _exit(EXIT_FAILURE);
3440 }
3441
3442 _exit(EXIT_SUCCESS);
3443 }
3444
3445 log_info("Successfully populated partition %" PRIu64 " with files.", p->partno);
3446 return 0;
3447}
3448
53171c04 3449static int context_mkfs(Context *context) {
53171c04
LP
3450 int fd = -1, r;
3451
3452 assert(context);
3453
3454 /* Make a file system */
3455
3456 LIST_FOREACH(partitions, p, context->partitions) {
0d12936d 3457 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
53171c04 3458 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
95bfd3cd
DDM
3459 _cleanup_(rm_rf_physical_and_freep) char *tmp_root = NULL;
3460 _cleanup_free_ char *encrypted = NULL, *root = NULL;
b9df3536
LP
3461 _cleanup_close_ int encrypted_dev_fd = -1;
3462 const char *fsdev;
53171c04
LP
3463 sd_id128_t fs_uuid;
3464
3465 if (p->dropped)
3466 continue;
3467
3468 if (PARTITION_EXISTS(p)) /* Never format existing partitions */
3469 continue;
3470
3471 if (!p->format)
3472 continue;
3473
3474 assert(p->offset != UINT64_MAX);
3475 assert(p->new_size != UINT64_MAX);
3476
3477 if (fd < 0)
3478 assert_se((fd = fdisk_get_devfd(context->fdisk_context)) >= 0);
3479
3480 /* Loopback block devices are not only useful to turn regular files into block devices, but
3481 * also to cut out sections of block devices into new block devices. */
3482
fd83c98e 3483 r = loop_device_make(fd, O_RDWR, p->offset, p->new_size, 0, 0, LOCK_EX, &d);
53171c04 3484 if (r < 0)
5b5109e2 3485 return log_error_errno(r, "Failed to make loopback device of future partition %" PRIu64 ": %m", p->partno);
53171c04 3486
889914ef 3487 if (p->encrypt != ENCRYPT_OFF) {
994b3031 3488 r = partition_encrypt(context, p, d->node, &cd, &encrypted, &encrypted_dev_fd);
b9df3536
LP
3489 if (r < 0)
3490 return log_error_errno(r, "Failed to encrypt device: %m");
3491
3492 if (flock(encrypted_dev_fd, LOCK_EX) < 0)
3493 return log_error_errno(errno, "Failed to lock LUKS device: %m");
3494
3495 fsdev = encrypted;
3496 } else
3497 fsdev = d->node;
3498
53171c04
LP
3499 log_info("Formatting future partition %" PRIu64 ".", p->partno);
3500
3501 /* Calculate the UUID for the file system as HMAC-SHA256 of the string "file-system-uuid",
3502 * keyed off the partition UUID. */
3503 r = derive_uuid(p->new_uuid, "file-system-uuid", &fs_uuid);
3504 if (r < 0)
3505 return r;
3506
95bfd3cd
DDM
3507 /* Ideally, we populate filesystems using our own code after creating the filesystem to
3508 * ensure consistent handling of chattrs, xattrs and other similar things. However, when
eb43379c
DDM
3509 * using read-only filesystems such as squashfs, we can't populate after creating the
3510 * filesystem because it's read-only, so instead we create a temporary root to use as the
3511 * source tree when generating the read-only filesystem. */
95bfd3cd
DDM
3512 r = partition_populate_directory(p, &root, &tmp_root);
3513 if (r < 0)
3514 return r;
3515
3516 r = make_filesystem(fsdev, p->format, strempty(p->new_label), root ?: tmp_root, fs_uuid, arg_discard);
b9df3536
LP
3517 if (r < 0) {
3518 encrypted_dev_fd = safe_close(encrypted_dev_fd);
3519 (void) deactivate_luks(cd, encrypted);
53171c04 3520 return r;
b9df3536 3521 }
53171c04
LP
3522
3523 log_info("Successfully formatted future partition %" PRIu64 ".", p->partno);
3524
b9df3536 3525 /* The file system is now created, no need to delay udev further */
889914ef 3526 if (p->encrypt != ENCRYPT_OFF)
b9df3536
LP
3527 if (flock(encrypted_dev_fd, LOCK_UN) < 0)
3528 return log_error_errno(errno, "Failed to unlock LUKS device: %m");
3529
eb43379c 3530 /* Now, we can populate all the other filesystems that aren't read-only. */
95bfd3cd 3531 r = partition_populate_filesystem(p, fsdev);
b9df3536
LP
3532 if (r < 0) {
3533 encrypted_dev_fd = safe_close(encrypted_dev_fd);
3534 (void) deactivate_luks(cd, encrypted);
8a794850 3535 return r;
b9df3536
LP
3536 }
3537
3538 /* Note that we always sync explicitly here, since mkfs.fat doesn't do that on its own, and
3539 * if we don't sync before detaching a block device the in-flight sectors possibly won't hit
3540 * the disk. */
3541
889914ef 3542 if (p->encrypt != ENCRYPT_OFF) {
b9df3536 3543 if (fsync(encrypted_dev_fd) < 0)
8ac04a65 3544 return log_error_errno(errno, "Failed to synchronize LUKS volume: %m");
b9df3536
LP
3545 encrypted_dev_fd = safe_close(encrypted_dev_fd);
3546
3547 r = deactivate_luks(cd, encrypted);
3548 if (r < 0)
3549 return r;
3550
0d12936d 3551 sym_crypt_free(cd);
b9df3536
LP
3552 cd = NULL;
3553 }
8a794850 3554
53171c04
LP
3555 r = loop_device_sync(d);
3556 if (r < 0)
3557 return log_error_errno(r, "Failed to sync loopback device: %m");
3558 }
3559
3560 return 0;
3561}
3562
b5b7879a
DDM
3563static int do_verity_format(
3564 LoopDevice *data_device,
3565 LoopDevice *hash_device,
3566 uint64_t sector_size,
3567 uint8_t **ret_roothash,
3568 size_t *ret_roothash_size) {
3569
3570#if HAVE_LIBCRYPTSETUP
3571 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
3572 _cleanup_free_ uint8_t *rh = NULL;
3573 size_t rhs;
3574 int r;
3575
3576 assert(data_device);
3577 assert(hash_device);
3578 assert(sector_size > 0);
3579 assert(ret_roothash);
3580 assert(ret_roothash_size);
3581
3582 r = dlopen_cryptsetup();
3583 if (r < 0)
3584 return log_error_errno(r, "libcryptsetup not found, cannot setup verity: %m");
3585
3586 r = sym_crypt_init(&cd, hash_device->node);
3587 if (r < 0)
3588 return log_error_errno(r, "Failed to allocate libcryptsetup context: %m");
3589
3590 r = sym_crypt_format(
3591 cd, CRYPT_VERITY, NULL, NULL, NULL, NULL, 0,
3592 &(struct crypt_params_verity){
3593 .data_device = data_device->node,
3594 .flags = CRYPT_VERITY_CREATE_HASH,
3595 .hash_name = "sha256",
3596 .hash_type = 1,
3597 .data_block_size = sector_size,
3598 .hash_block_size = sector_size,
3599 .salt_size = 32,
3600 });
3601 if (r < 0)
3602 return log_error_errno(r, "Failed to setup verity hash data: %m");
3603
3604 r = sym_crypt_get_volume_key_size(cd);
3605 if (r < 0)
3606 return log_error_errno(r, "Failed to determine verity root hash size: %m");
3607 rhs = (size_t) r;
3608
3609 rh = malloc(rhs);
3610 if (!rh)
3611 return log_oom();
3612
3613 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, (char *) rh, &rhs, NULL, 0);
3614 if (r < 0)
3615 return log_error_errno(r, "Failed to get verity root hash: %m");
3616
3617 *ret_roothash = TAKE_PTR(rh);
3618 *ret_roothash_size = rhs;
3619
3620 return 0;
3621#else
9c98e277 3622 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "libcryptsetup is not supported, cannot setup verity hashes: %m");
b5b7879a
DDM
3623#endif
3624}
3625
b6db96a2 3626static int context_verity_hash(Context *context) {
b5b7879a
DDM
3627 int fd = -1, r;
3628
3629 assert(context);
3630
3631 LIST_FOREACH(partitions, p, context->partitions) {
3632 Partition *dp;
3633 _cleanup_(loop_device_unrefp) LoopDevice *hash_device = NULL, *data_device = NULL;
3634 _cleanup_free_ uint8_t *rh = NULL;
3635 size_t rhs = 0; /* Initialize to work around for GCC false positive. */
3636
3637 if (p->dropped)
3638 continue;
3639
3640 if (PARTITION_EXISTS(p)) /* Never format existing partitions */
3641 continue;
3642
3643 if (p->verity != VERITY_HASH)
3644 continue;
3645
3646 assert_se(dp = p->siblings[VERITY_DATA]);
3647 assert(!dp->dropped);
3648
3649 if (fd < 0)
3650 assert_se((fd = fdisk_get_devfd(context->fdisk_context)) >= 0);
3651
fd83c98e 3652 r = loop_device_make(fd, O_RDONLY, dp->offset, dp->new_size, 0, 0, LOCK_EX, &data_device);
b5b7879a
DDM
3653 if (r < 0)
3654 return log_error_errno(r,
3655 "Failed to make loopback device of verity data partition %" PRIu64 ": %m",
3656 p->partno);
3657
fd83c98e 3658 r = loop_device_make(fd, O_RDWR, p->offset, p->new_size, 0, 0, LOCK_EX, &hash_device);
b5b7879a
DDM
3659 if (r < 0)
3660 return log_error_errno(r,
3661 "Failed to make loopback device of verity hash partition %" PRIu64 ": %m",
3662 p->partno);
3663
3664 r = do_verity_format(data_device, hash_device, context->sector_size, &rh, &rhs);
3665 if (r < 0)
3666 return r;
3667
3668 assert(rhs >= sizeof(sd_id128_t) * 2);
3669
3670 if (!dp->new_uuid_is_set) {
3671 memcpy_safe(dp->new_uuid.bytes, rh, sizeof(sd_id128_t));
3672 dp->new_uuid_is_set = true;
3673 }
3674
3675 if (!p->new_uuid_is_set) {
3676 memcpy_safe(p->new_uuid.bytes, rh + rhs - sizeof(sd_id128_t), sizeof(sd_id128_t));
3677 p->new_uuid_is_set = true;
3678 }
3679
3680 p->roothash = TAKE_PTR(rh);
3681 p->roothash_size = rhs;
3682 }
3683
3684 return 0;
3685}
3686
b456191d
DDM
3687static int parse_x509_certificate(const char *certificate, size_t certificate_size, X509 **ret) {
3688#if HAVE_OPENSSL
3689 _cleanup_(X509_freep) X509 *cert = NULL;
3690 _cleanup_(BIO_freep) BIO *cb = NULL;
3691
3692 assert(certificate);
3693 assert(certificate_size > 0);
3694 assert(ret);
3695
3696 cb = BIO_new_mem_buf(certificate, certificate_size);
3697 if (!cb)
3698 return log_oom();
3699
3700 cert = PEM_read_bio_X509(cb, NULL, NULL, NULL);
3701 if (!cert)
3702 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Failed to parse X.509 certificate: %s",
3703 ERR_error_string(ERR_get_error(), NULL));
3704
3705 if (ret)
3706 *ret = TAKE_PTR(cert);
3707
3708 return 0;
3709#else
3710 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "openssl is not supported, cannot parse X509 certificate.");
3711#endif
3712}
3713
3714static int parse_private_key(const char *key, size_t key_size, EVP_PKEY **ret) {
3715#if HAVE_OPENSSL
3716 _cleanup_(BIO_freep) BIO *kb = NULL;
3717 _cleanup_(EVP_PKEY_freep) EVP_PKEY *pk = NULL;
3718
3719 assert(key);
3720 assert(key_size > 0);
3721 assert(ret);
3722
3723 kb = BIO_new_mem_buf(key, key_size);
3724 if (!kb)
3725 return log_oom();
3726
3727 pk = PEM_read_bio_PrivateKey(kb, NULL, NULL, NULL);
3728 if (!pk)
3729 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to parse PEM private key: %s",
3730 ERR_error_string(ERR_get_error(), NULL));
3731
3732 if (ret)
3733 *ret = TAKE_PTR(pk);
3734
3735 return 0;
3736#else
3737 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "openssl is not supported, cannot parse private key.");
3738#endif
3739}
3740
3741static int sign_verity_roothash(
3742 const uint8_t *roothash,
3743 size_t roothash_size,
3744 uint8_t **ret_signature,
3745 size_t *ret_signature_size) {
3746
3747#if HAVE_OPENSSL
3748 _cleanup_(BIO_freep) BIO *rb = NULL;
3749 _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
3750 _cleanup_free_ char *hex = NULL;
3751 _cleanup_free_ uint8_t *sig = NULL;
3752 int sigsz;
3753
3754 assert(roothash);
3755 assert(roothash_size > 0);
3756 assert(ret_signature);
3757 assert(ret_signature_size);
3758
3759 hex = hexmem(roothash, roothash_size);
3760 if (!hex)
3761 return log_oom();
3762
3763 rb = BIO_new_mem_buf(hex, -1);
3764 if (!rb)
3765 return log_oom();
3766
3767 p7 = PKCS7_sign(arg_certificate, arg_private_key, NULL, rb, PKCS7_DETACHED|PKCS7_NOATTR|PKCS7_BINARY);
3768 if (!p7)
3769 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to calculate PKCS7 signature: %s",
3770 ERR_error_string(ERR_get_error(), NULL));
3771
3772 sigsz = i2d_PKCS7(p7, &sig);
3773 if (sigsz < 0)
3774 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert PKCS7 signature to DER: %s",
3775 ERR_error_string(ERR_get_error(), NULL));
3776
3777 *ret_signature = TAKE_PTR(sig);
3778 *ret_signature_size = sigsz;
3779
3780 return 0;
3781#else
3782 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "openssl is not supported, cannot setup verity signature: %m");
3783#endif
3784}
3785
3786static int context_verity_sig(Context *context) {
3787 int fd = -1, r;
3788
3789 assert(context);
3790
3791 LIST_FOREACH(partitions, p, context->partitions) {
3792 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
3793 _cleanup_free_ uint8_t *sig = NULL;
3794 _cleanup_free_ char *text = NULL;
3795 Partition *hp;
3796 uint8_t fp[X509_FINGERPRINT_SIZE];
419f2742 3797 size_t sigsz = 0, padsz; /* avoid false maybe-uninitialized warning */
b456191d
DDM
3798
3799 if (p->dropped)
3800 continue;
3801
3802 if (PARTITION_EXISTS(p))
3803 continue;
3804
3805 if (p->verity != VERITY_SIG)
3806 continue;
3807
3808 assert_se(hp = p->siblings[VERITY_HASH]);
3809 assert(!hp->dropped);
3810
3811 assert(arg_certificate);
3812
3813 if (fd < 0)
3814 assert_se((fd = fdisk_get_devfd(context->fdisk_context)) >= 0);
3815
3816 r = sign_verity_roothash(hp->roothash, hp->roothash_size, &sig, &sigsz);
3817 if (r < 0)
3818 return r;
3819
3820 r = x509_fingerprint(arg_certificate, fp);
3821 if (r < 0)
3822 return log_error_errno(r, "Unable to calculate X509 certificate fingerprint: %m");
3823
3824 r = json_build(&v,
3825 JSON_BUILD_OBJECT(
3826 JSON_BUILD_PAIR("rootHash", JSON_BUILD_HEX(hp->roothash, hp->roothash_size)),
3827 JSON_BUILD_PAIR(
3828 "certificateFingerprint",
3829 JSON_BUILD_HEX(fp, sizeof(fp))
3830 ),
3831 JSON_BUILD_PAIR("signature", JSON_BUILD_BASE64(sig, sigsz))
3832 )
3833 );
3834 if (r < 0)
3835 return log_error_errno(r, "Failed to build JSON object: %m");
3836
3837 r = json_variant_format(v, 0, &text);
3838 if (r < 0)
3839 return log_error_errno(r, "Failed to format JSON object: %m");
3840
3841 padsz = round_up_size(strlen(text), 4096);
3842 assert_se(padsz <= p->new_size);
3843
3844 r = strgrowpad0(&text, padsz);
3845 if (r < 0)
3846 return log_error_errno(r, "Failed to pad string to %s", FORMAT_BYTES(padsz));
3847
3848 if (lseek(fd, p->offset, SEEK_SET) == (off_t) -1)
3849 return log_error_errno(errno, "Failed to seek to partition offset: %m");
3850
3851 r = loop_write(fd, text, padsz, /*do_poll=*/ false);
3852 if (r < 0)
3853 return log_error_errno(r, "Failed to write verity signature to partition: %m");
3854
3855 if (fsync(fd) < 0)
3856 return log_error_errno(errno, "Failed to synchronize verity signature JSON: %m");
3857 }
3858
3859 return 0;
3860}
3861
e594a3b1
LP
3862static int partition_acquire_uuid(Context *context, Partition *p, sd_id128_t *ret) {
3863 struct {
3864 sd_id128_t type_uuid;
3865 uint64_t counter;
695cfd53 3866 } _packed_ plaintext = {};
e594a3b1 3867 union {
ade99252 3868 uint8_t md[SHA256_DIGEST_SIZE];
e594a3b1
LP
3869 sd_id128_t id;
3870 } result;
3871
3872 uint64_t k = 0;
e594a3b1
LP
3873 int r;
3874
3875 assert(context);
3876 assert(p);
3877 assert(ret);
3878
3879 /* Calculate a good UUID for the indicated partition. We want a certain degree of reproducibility,
3880 * hence we won't generate the UUIDs randomly. Instead we use a cryptographic hash (precisely:
3881 * HMAC-SHA256) to derive them from a single seed. The seed is generally the machine ID of the
3882 * installation we are processing, but if random behaviour is desired can be random, too. We use the
3883 * seed value as key for the HMAC (since the machine ID is something we generally don't want to leak)
3884 * and the partition type as plaintext. The partition type is suffixed with a counter (only for the
3885 * second and later partition of the same type) if we have more than one partition of the same
3886 * time. Or in other words:
3887 *
3888 * With:
3889 * SEED := /etc/machine-id
3890 *
3891 * If first partition instance of type TYPE_UUID:
3892 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
3893 *
3894 * For all later partition instances of type TYPE_UUID with INSTANCE being the LE64 encoded instance number:
3895 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID || INSTANCE)
3896 */
3897
3898 LIST_FOREACH(partitions, q, context->partitions) {
3899 if (p == q)
3900 break;
3901
3902 if (!sd_id128_equal(p->type_uuid, q->type_uuid))
3903 continue;
3904
3905 k++;
3906 }
3907
3908 plaintext.type_uuid = p->type_uuid;
3909 plaintext.counter = htole64(k);
3910
ade99252
KK
3911 hmac_sha256(context->seed.bytes, sizeof(context->seed.bytes),
3912 &plaintext,
3913 k == 0 ? sizeof(sd_id128_t) : sizeof(plaintext),
3914 result.md);
e594a3b1
LP
3915
3916 /* Take the first half, mark it as v4 UUID */
3917 assert_cc(sizeof(result.md) == sizeof(result.id) * 2);
3918 result.id = id128_make_v4_uuid(result.id);
3919
3920 /* Ensure this partition UUID is actually unique, and there's no remaining partition from an earlier run? */
3921 LIST_FOREACH(partitions, q, context->partitions) {
3922 if (p == q)
3923 continue;
3924
580f48cc 3925 if (sd_id128_in_set(result.id, q->current_uuid, q->new_uuid)) {
da1af43d 3926 log_warning("Partition UUID calculated from seed for partition %" PRIu64 " already used, reverting to randomized UUID.", p->partno);
e594a3b1
LP
3927
3928 r = sd_id128_randomize(&result.id);
3929 if (r < 0)
3930 return log_error_errno(r, "Failed to generate randomized UUID: %m");
3931
3932 break;
3933 }
3934 }
3935
3936 *ret = result.id;
3937 return 0;
3938}
3939
3940static int partition_acquire_label(Context *context, Partition *p, char **ret) {
3941 _cleanup_free_ char *label = NULL;
3942 const char *prefix;
3943 unsigned k = 1;
3944
3945 assert(context);
3946 assert(p);
3947 assert(ret);
3948
3949 prefix = gpt_partition_type_uuid_to_string(p->type_uuid);
3950 if (!prefix)
3951 prefix = "linux";
3952
3953 for (;;) {
3954 const char *ll = label ?: prefix;
3955 bool retry = false;
e594a3b1
LP
3956
3957 LIST_FOREACH(partitions, q, context->partitions) {
3958 if (p == q)
3959 break;
3960
3961 if (streq_ptr(ll, q->current_label) ||
3962 streq_ptr(ll, q->new_label)) {
3963 retry = true;
3964 break;
3965 }
3966 }
3967
3968 if (!retry)
3969 break;
3970
3971 label = mfree(label);
e594a3b1
LP
3972 if (asprintf(&label, "%s-%u", prefix, ++k) < 0)
3973 return log_oom();
3974 }
3975
3976 if (!label) {
3977 label = strdup(prefix);
3978 if (!label)
3979 return log_oom();
3980 }
3981
3982 *ret = TAKE_PTR(label);
3983 return 0;
3984}
3985
3986static int context_acquire_partition_uuids_and_labels(Context *context) {
e594a3b1
LP
3987 int r;
3988
3989 assert(context);
3990
3991 LIST_FOREACH(partitions, p, context->partitions) {
e594a3b1
LP
3992 /* Never touch foreign partitions */
3993 if (PARTITION_IS_FOREIGN(p)) {
3994 p->new_uuid = p->current_uuid;
3995
3996 if (p->current_label) {
78eee6ce
LP
3997 r = free_and_strdup_warn(&p->new_label, strempty(p->current_label));
3998 if (r < 0)
3999 return r;
e594a3b1
LP
4000 }
4001
4002 continue;
4003 }
4004
4005 if (!sd_id128_is_null(p->current_uuid))
4006 p->new_uuid = p->current_uuid; /* Never change initialized UUIDs */
b456191d 4007 else if (!p->new_uuid_is_set && !IN_SET(p->verity, VERITY_DATA, VERITY_HASH)) {
12963533 4008 /* Not explicitly set by user! */
e594a3b1
LP
4009 r = partition_acquire_uuid(context, p, &p->new_uuid);
4010 if (r < 0)
4011 return r;
11749b61
DDM
4012
4013 p->new_uuid_is_set = true;
e594a3b1
LP
4014 }
4015
4016 if (!isempty(p->current_label)) {
78eee6ce
LP
4017 /* never change initialized labels */
4018 r = free_and_strdup_warn(&p->new_label, p->current_label);
4019 if (r < 0)
4020 return r;
12963533
TH
4021 } else if (!p->new_label) {
4022 /* Not explicitly set by user! */
4023
e594a3b1
LP
4024 r = partition_acquire_label(context, p, &p->new_label);
4025 if (r < 0)
4026 return r;
4027 }
4028 }
4029
4030 return 0;
4031}
4032
e73309c5
LP
4033static int set_gpt_flags(struct fdisk_partition *q, uint64_t flags) {
4034 _cleanup_free_ char *a = NULL;
4035
4036 for (unsigned i = 0; i < sizeof(flags) * 8; i++) {
4037 uint64_t bit = UINT64_C(1) << i;
4038 char buf[DECIMAL_STR_MAX(unsigned)+1];
4039
4040 if (!FLAGS_SET(flags, bit))
4041 continue;
4042
4043 xsprintf(buf, "%u", i);
4044 if (!strextend_with_separator(&a, ",", buf))
4045 return -ENOMEM;
4046 }
4047
4048 return fdisk_partition_set_attrs(q, a);
4049}
4050
1c41c1dc
LP
4051static uint64_t partition_merge_flags(Partition *p) {
4052 uint64_t f;
4053
4054 assert(p);
4055
4056 f = p->gpt_flags;
4057
ff0771bf
LP
4058 if (p->no_auto >= 0) {
4059 if (gpt_partition_type_knows_no_auto(p->type_uuid))
92e72028 4060 SET_FLAG(f, SD_GPT_FLAG_NO_AUTO, p->no_auto);
ff0771bf 4061 else {
b7416360 4062 char buffer[SD_ID128_UUID_STRING_MAX];
ff0771bf
LP
4063 log_warning("Configured NoAuto=%s for partition type '%s' that doesn't support it, ignoring.",
4064 yes_no(p->no_auto),
4065 gpt_partition_type_uuid_to_string_harder(p->type_uuid, buffer));
4066 }
4067 }
4068
1c41c1dc
LP
4069 if (p->read_only >= 0) {
4070 if (gpt_partition_type_knows_read_only(p->type_uuid))
92e72028 4071 SET_FLAG(f, SD_GPT_FLAG_READ_ONLY, p->read_only);
1c41c1dc 4072 else {
b7416360 4073 char buffer[SD_ID128_UUID_STRING_MAX];
1c41c1dc
LP
4074 log_warning("Configured ReadOnly=%s for partition type '%s' that doesn't support it, ignoring.",
4075 yes_no(p->read_only),
4076 gpt_partition_type_uuid_to_string_harder(p->type_uuid, buffer));
4077 }
4078 }
4079
4080 if (p->growfs >= 0) {
4081 if (gpt_partition_type_knows_growfs(p->type_uuid))
92e72028 4082 SET_FLAG(f, SD_GPT_FLAG_GROWFS, p->growfs);
1c41c1dc 4083 else {
b7416360 4084 char buffer[SD_ID128_UUID_STRING_MAX];
1c41c1dc
LP
4085 log_warning("Configured GrowFileSystem=%s for partition type '%s' that doesn't support it, ignoring.",
4086 yes_no(p->growfs),
4087 gpt_partition_type_uuid_to_string_harder(p->type_uuid, buffer));
4088 }
4089 }
4090
4091 return f;
4092}
4093
f28d4f42 4094static int context_mangle_partitions(Context *context) {
f28d4f42 4095 int r;
e594a3b1
LP
4096
4097 assert(context);
4098
e594a3b1
LP
4099 LIST_FOREACH(partitions, p, context->partitions) {
4100 if (p->dropped)
4101 continue;
4102
4103 assert(p->new_size != UINT64_MAX);
4104 assert(p->offset != UINT64_MAX);
4105 assert(p->partno != UINT64_MAX);
4106
4107 if (PARTITION_EXISTS(p)) {
4108 bool changed = false;
4109
4110 assert(p->current_partition);
4111
4112 if (p->new_size != p->current_size) {
4113 assert(p->new_size >= p->current_size);
994b3031 4114 assert(p->new_size % context->sector_size == 0);
e594a3b1
LP
4115
4116 r = fdisk_partition_size_explicit(p->current_partition, true);
4117 if (r < 0)
4118 return log_error_errno(r, "Failed to enable explicit sizing: %m");
4119
994b3031 4120 r = fdisk_partition_set_size(p->current_partition, p->new_size / context->sector_size);
e594a3b1
LP
4121 if (r < 0)
4122 return log_error_errno(r, "Failed to grow partition: %m");
4123
4124 log_info("Growing existing partition %" PRIu64 ".", p->partno);
4125 changed = true;
4126 }
4127
4128 if (!sd_id128_equal(p->new_uuid, p->current_uuid)) {
b7416360 4129 r = fdisk_partition_set_uuid(p->current_partition, SD_ID128_TO_UUID_STRING(p->new_uuid));
e594a3b1
LP
4130 if (r < 0)
4131 return log_error_errno(r, "Failed to set partition UUID: %m");
4132
4133 log_info("Initializing UUID of existing partition %" PRIu64 ".", p->partno);
4134 changed = true;
4135 }
4136
4137 if (!streq_ptr(p->new_label, p->current_label)) {
be9ce018 4138 r = fdisk_partition_set_name(p->current_partition, strempty(p->new_label));
e594a3b1
LP
4139 if (r < 0)
4140 return log_error_errno(r, "Failed to set partition label: %m");
4141
4142 log_info("Setting partition label of existing partition %" PRIu64 ".", p->partno);
4143 changed = true;
4144 }
4145
4146 if (changed) {
4147 assert(!PARTITION_IS_FOREIGN(p)); /* never touch foreign partitions */
4148
4149 r = fdisk_set_partition(context->fdisk_context, p->partno, p->current_partition);
4150 if (r < 0)
4151 return log_error_errno(r, "Failed to update partition: %m");
4152 }
4153 } else {
4154 _cleanup_(fdisk_unref_partitionp) struct fdisk_partition *q = NULL;
4155 _cleanup_(fdisk_unref_parttypep) struct fdisk_parttype *t = NULL;
e594a3b1
LP
4156
4157 assert(!p->new_partition);
994b3031
LP
4158 assert(p->offset % context->sector_size == 0);
4159 assert(p->new_size % context->sector_size == 0);
be9ce018 4160 assert(p->new_label);
e594a3b1
LP
4161
4162 t = fdisk_new_parttype();
4163 if (!t)
4164 return log_oom();
4165
b7416360 4166 r = fdisk_parttype_set_typestr(t, SD_ID128_TO_UUID_STRING(p->type_uuid));
e594a3b1
LP
4167 if (r < 0)
4168 return log_error_errno(r, "Failed to initialize partition type: %m");
4169
4170 q = fdisk_new_partition();
4171 if (!q)
4172 return log_oom();
4173
4174 r = fdisk_partition_set_type(q, t);
4175 if (r < 0)
4176 return log_error_errno(r, "Failed to set partition type: %m");
4177
4178 r = fdisk_partition_size_explicit(q, true);
4179 if (r < 0)
4180 return log_error_errno(r, "Failed to enable explicit sizing: %m");
4181
994b3031 4182 r = fdisk_partition_set_start(q, p->offset / context->sector_size);
e594a3b1
LP
4183 if (r < 0)
4184 return log_error_errno(r, "Failed to position partition: %m");
4185
994b3031 4186 r = fdisk_partition_set_size(q, p->new_size / context->sector_size);
e594a3b1
LP
4187 if (r < 0)
4188 return log_error_errno(r, "Failed to grow partition: %m");
4189
4190 r = fdisk_partition_set_partno(q, p->partno);
4191 if (r < 0)
4192 return log_error_errno(r, "Failed to set partition number: %m");
4193
b7416360 4194 r = fdisk_partition_set_uuid(q, SD_ID128_TO_UUID_STRING(p->new_uuid));
e594a3b1
LP
4195 if (r < 0)
4196 return log_error_errno(r, "Failed to set partition UUID: %m");
4197
be9ce018 4198 r = fdisk_partition_set_name(q, strempty(p->new_label));
e594a3b1
LP
4199 if (r < 0)
4200 return log_error_errno(r, "Failed to set partition label: %m");
4201
ff0771bf 4202 /* Merge the no auto + read only + growfs setting with the literal flags, and set them for the partition */
1c41c1dc 4203 r = set_gpt_flags(q, partition_merge_flags(p));
e73309c5
LP
4204 if (r < 0)
4205 return log_error_errno(r, "Failed to set GPT partition flags: %m");
4206
5b5109e2 4207 log_info("Adding new partition %" PRIu64 " to partition table.", p->partno);
e594a3b1
LP
4208
4209 r = fdisk_add_partition(context->fdisk_context, q, NULL);
4210 if (r < 0)
4211 return log_error_errno(r, "Failed to add partition: %m");
4212
4213 assert(!p->new_partition);
4214 p->new_partition = TAKE_PTR(q);
4215 }
4216 }
4217
f28d4f42
LP
4218 return 0;
4219}
4220
4cee8333
DDM
4221static int split_name_printf(Partition *p) {
4222 assert(p);
4223
4224 const Specifier table[] = {
4225 { 't', specifier_string, GPT_PARTITION_TYPE_UUID_TO_STRING_HARDER(p->type_uuid) },
4226 { 'T', specifier_id128, &p->type_uuid },
4227 { 'U', specifier_id128, &p->new_uuid },
4228 { 'n', specifier_uint64, &p->partno },
4229
4230 COMMON_SYSTEM_SPECIFIERS,
4231 {}
4232 };
4233
4234 return specifier_printf(p->split_name_format, NAME_MAX, table, arg_root, p, &p->split_name_resolved);
4235}
4236
4237static int split_name_resolve(Context *context) {
4238 int r;
4239
4240 LIST_FOREACH(partitions, p, context->partitions) {
4241 if (p->dropped)
4242 continue;
4243
4244 if (!p->split_name_format)
4245 continue;
4246
4247 r = split_name_printf(p);
4248 if (r < 0)
4249 return log_error_errno(r, "Failed to resolve specifiers in %s: %m", p->split_name_format);
4250 }
4251
4252 LIST_FOREACH(partitions, p, context->partitions) {
4253 if (!p->split_name_resolved)
4254 continue;
4255
4256 LIST_FOREACH(partitions, q, context->partitions) {
4257 if (p == q)
4258 continue;
4259
4260 if (!q->split_name_resolved)
4261 continue;
4262
4263 if (!streq(p->split_name_resolved, q->split_name_resolved))
4264 continue;
4265
4266 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
4267 "%s and %s have the same resolved split name \"%s\", refusing",
4268 p->definition_path, q->definition_path, p->split_name_resolved);
4269 }
4270 }
4271
4272 return 0;
4273}
4274
4275static int split_node(const char *node, char **ret_base, char **ret_ext) {
4276 _cleanup_free_ char *base = NULL, *ext = NULL;
4277 char *e;
4278 int r;
4279
4280 assert(node);
4281 assert(ret_base);
4282 assert(ret_ext);
4283
4284 r = path_extract_filename(node, &base);
4285 if (r == O_DIRECTORY || r == -EADDRNOTAVAIL)
4286 return log_error_errno(r, "Device node %s cannot be a directory", arg_node);
4287 if (r < 0)
4288 return log_error_errno(r, "Failed to extract filename from %s: %m", arg_node);
4289
4290 e = endswith(base, ".raw");
4291 if (e) {
4292 ext = strdup(e);
4293 if (!ext)
4294 return log_oom();
4295
4296 *e = 0;
4297 }
4298
4299 *ret_base = TAKE_PTR(base);
4300 *ret_ext = TAKE_PTR(ext);
4301
4302 return 0;
4303}
4304
4305static int context_split(Context *context) {
4306 _cleanup_free_ char *base = NULL, *ext = NULL;
4307 _cleanup_close_ int dir_fd = -1;
4308 int fd = -1, r;
4309
4310 if (!arg_split)
4311 return 0;
4312
4313 assert(context);
4314 assert(arg_node);
4315
4316 /* We can't do resolution earlier because the partition UUIDs for verity partitions are only filled
4317 * in after they've been generated. */
4318
4319 r = split_name_resolve(context);
4320 if (r < 0)
4321 return r;
4322
4323 r = split_node(arg_node, &base, &ext);
4324 if (r < 0)
4325 return r;
4326
4327 dir_fd = r = open_parent(arg_node, O_PATH|O_CLOEXEC, 0);
4328 if (r == -EDESTADDRREQ)
4329 dir_fd = AT_FDCWD;
4330 else if (r < 0)
4331 return log_error_errno(r, "Failed to open parent directory of %s: %m", arg_node);
4332
4333 LIST_FOREACH(partitions, p, context->partitions) {
4334 _cleanup_free_ char *fname = NULL;
4335 _cleanup_close_ int fdt = -1;
4336
4337 if (p->dropped)
4338 continue;
4339
4340 if (!p->split_name_resolved)
4341 continue;
4342
4343 fname = strjoin(base, ".", p->split_name_resolved, ext);
4344 if (!fname)
4345 return log_oom();
4346
4347 fdt = openat(dir_fd, fname, O_WRONLY|O_NOCTTY|O_CLOEXEC|O_NOFOLLOW|O_CREAT|O_EXCL, 0666);
4348 if (fdt < 0)
4349 return log_error_errno(errno, "Failed to open %s: %m", fname);
4350
4351 if (fd < 0)
4352 assert_se((fd = fdisk_get_devfd(context->fdisk_context)) >= 0);
4353
4354 if (lseek(fd, p->offset, SEEK_SET) < 0)
4355 return log_error_errno(errno, "Failed to seek to partition offset: %m");
4356
4357 r = copy_bytes_full(fd, fdt, p->new_size, COPY_REFLINK|COPY_HOLES, NULL, NULL, NULL, NULL);
4358 if (r < 0)
4359 return log_error_errno(r, "Failed to copy to split partition %s: %m", fname);
4360 }
4361
4362 return 0;
4363}
4364
f28d4f42
LP
4365static int context_write_partition_table(
4366 Context *context,
4367 const char *node,
4368 bool from_scratch) {
4369
4370 _cleanup_(fdisk_unref_tablep) struct fdisk_table *original_table = NULL;
4371 int capable, r;
4372
4373 assert(context);
4374
f28d4f42
LP
4375 if (!from_scratch && !context_changed(context)) {
4376 log_info("No changes.");
4377 return 0;
4378 }
4379
4380 if (arg_dry_run) {
4381 log_notice("Refusing to repartition, please re-run with --dry-run=no.");
4382 return 0;
4383 }
4384
4385 log_info("Applying changes.");
4386
4387 if (from_scratch) {
81873a6b
LP
4388 r = context_wipe_range(context, 0, context->total);
4389 if (r < 0)
4390 return r;
4391
4392 log_info("Wiped block device.");
4393
f28d4f42
LP
4394 r = context_discard_range(context, 0, context->total);
4395 if (r == -EOPNOTSUPP)
5b5109e2 4396 log_info("Storage does not support discard, not discarding entire block device data.");
f28d4f42
LP
4397 else if (r < 0)
4398 return log_error_errno(r, "Failed to discard entire block device: %m");
4399 else if (r > 0)
4400 log_info("Discarded entire block device.");
4401 }
4402
4403 r = fdisk_get_partitions(context->fdisk_context, &original_table);
4404 if (r < 0)
4405 return log_error_errno(r, "Failed to acquire partition table: %m");
4406
4407 /* Wipe fs signatures and discard sectors where the new partitions are going to be placed and in the
4408 * gaps between partitions, just to be sure. */
4409 r = context_wipe_and_discard(context, from_scratch);
4410 if (r < 0)
4411 return r;
4412
4413 r = context_copy_blocks(context);
4414 if (r < 0)
4415 return r;
4416
4417 r = context_mkfs(context);
4418 if (r < 0)
4419 return r;
4420
b6db96a2 4421 r = context_verity_hash(context);
b5b7879a
DDM
4422 if (r < 0)
4423 return r;
4424
b456191d 4425 r = context_verity_sig(context);
b5b7879a
DDM
4426 if (r < 0)
4427 return r;
4428
f28d4f42
LP
4429 r = context_mangle_partitions(context);
4430 if (r < 0)
4431 return r;
4432
e594a3b1
LP
4433 log_info("Writing new partition table.");
4434
4435 r = fdisk_write_disklabel(context->fdisk_context);
4436 if (r < 0)
4437 return log_error_errno(r, "Failed to write partition table: %m");
4438
911ba624 4439 capable = blockdev_partscan_enabled(fdisk_get_devfd(context->fdisk_context));
9a1deb85
LP
4440 if (capable == -ENOTBLK)
4441 log_debug("Not telling kernel to reread partition table, since we are not operating on a block device.");
4442 else if (capable < 0)
911ba624 4443 return log_error_errno(capable, "Failed to check if block device supports partition scanning: %m");
9a1deb85 4444 else if (capable > 0) {
e594a3b1
LP
4445 log_info("Telling kernel to reread partition table.");
4446
4447 if (from_scratch)
4448 r = fdisk_reread_partition_table(context->fdisk_context);
4449 else
4450 r = fdisk_reread_changes(context->fdisk_context, original_table);
4451 if (r < 0)
4452 return log_error_errno(r, "Failed to reread partition table: %m");
4453 } else
4454 log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
4455
4456 log_info("All done.");
4457
4458 return 0;
4459}
4460
4461static int context_read_seed(Context *context, const char *root) {
4462 int r;
4463
4464 assert(context);
4465
4466 if (!sd_id128_is_null(context->seed))
4467 return 0;
4468
4469 if (!arg_randomize) {
4470 _cleanup_close_ int fd = -1;
4471
4472 fd = chase_symlinks_and_open("/etc/machine-id", root, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC, NULL);
4473 if (fd == -ENOENT)
4474 log_info("No machine ID set, using randomized partition UUIDs.");
4475 else if (fd < 0)
4476 return log_error_errno(fd, "Failed to determine machine ID of image: %m");
4477 else {
448b782c 4478 r = id128_read_fd(fd, ID128_PLAIN_OR_UNINIT, &context->seed);
e594a3b1
LP
4479 if (r == -ENOMEDIUM)
4480 log_info("No machine ID set, using randomized partition UUIDs.");
4481 else if (r < 0)
4482 return log_error_errno(r, "Failed to parse machine ID of image: %m");
4483
4484 return 0;
4485 }
4486 }
4487
4488 r = sd_id128_randomize(&context->seed);
4489 if (r < 0)
4490 return log_error_errno(r, "Failed to generate randomized seed: %m");
4491
4492 return 0;
4493}
4494
4495static int context_factory_reset(Context *context, bool from_scratch) {
e594a3b1
LP
4496 size_t n = 0;
4497 int r;
4498
4499 assert(context);
4500
4501 if (arg_factory_reset <= 0)
4502 return 0;
4503
4504 if (from_scratch) /* Nothing to reset if we start from scratch */
4505 return 0;
4506
4507 if (arg_dry_run) {
4508 log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
4509 return 0;
4510 }
4511
4512 log_info("Applying factory reset.");
4513
4514 LIST_FOREACH(partitions, p, context->partitions) {
4515
4516 if (!p->factory_reset || !PARTITION_EXISTS(p))
4517 continue;
4518
4519 assert(p->partno != UINT64_MAX);
4520
4521 log_info("Removing partition %" PRIu64 " for factory reset.", p->partno);
4522
4523 r = fdisk_delete_partition(context->fdisk_context, p->partno);
4524 if (r < 0)
4525 return log_error_errno(r, "Failed to remove partition %" PRIu64 ": %m", p->partno);
4526
4527 n++;
4528 }
4529
4530 if (n == 0) {
4531 log_info("Factory reset requested, but no partitions to delete found.");
4532 return 0;
4533 }
4534
4535 r = fdisk_write_disklabel(context->fdisk_context);
4536 if (r < 0)
4537 return log_error_errno(r, "Failed to write disk label: %m");
4538
4539 log_info("Successfully deleted %zu partitions.", n);
4540 return 1;
4541}
4542
4543static int context_can_factory_reset(Context *context) {
e594a3b1
LP
4544 assert(context);
4545
4546 LIST_FOREACH(partitions, p, context->partitions)
4547 if (p->factory_reset && PARTITION_EXISTS(p))
4548 return true;
4549
4550 return false;
4551}
4552
5c08da58
LP
4553static int resolve_copy_blocks_auto_candidate(
4554 dev_t partition_devno,
4555 sd_id128_t partition_type_uuid,
4556 dev_t restrict_devno,
4557 sd_id128_t *ret_uuid) {
4558
4559 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
5c08da58 4560 _cleanup_close_ int fd = -1;
ca822829
YW
4561 _cleanup_free_ char *p = NULL;
4562 const char *pttype, *t;
5c08da58
LP
4563 sd_id128_t pt_parsed, u;
4564 blkid_partition pp;
4565 dev_t whole_devno;
4566 blkid_partlist pl;
5c08da58
LP
4567 int r;
4568
4569 /* Checks if the specified partition has the specified GPT type UUID, and is located on the specified
4570 * 'restrict_devno' device. The type check is particularly relevant if we have Verity volume which is
4571 * backed by two separate partitions: the data and the hash partitions, and we need to find the right
4572 * one of the two. */
4573
4574 r = block_get_whole_disk(partition_devno, &whole_devno);
4575 if (r < 0)
4576 return log_error_errno(
4577 r,
4578 "Unable to determine containing block device of partition %u:%u: %m",
4579 major(partition_devno), minor(partition_devno));
4580
4581 if (restrict_devno != (dev_t) -1 &&
4582 restrict_devno != whole_devno)
4583 return log_error_errno(
4584 SYNTHETIC_ERRNO(EPERM),
4585 "Partition %u:%u is located outside of block device %u:%u, refusing.",
4586 major(partition_devno), minor(partition_devno),
4587 major(restrict_devno), minor(restrict_devno));
4588
ca822829 4589 fd = r = device_open_from_devnum(S_IFBLK, whole_devno, O_RDONLY|O_CLOEXEC|O_NONBLOCK, &p);
5c08da58 4590 if (r < 0)
ca822829
YW
4591 return log_error_errno(r, "Failed to open block device " DEVNUM_FORMAT_STR ": %m",
4592 DEVNUM_FORMAT_VAL(whole_devno));
5c08da58
LP
4593
4594 b = blkid_new_probe();
4595 if (!b)
4596 return log_oom();
4597
4598 errno = 0;
4599 r = blkid_probe_set_device(b, fd, 0, 0);
4600 if (r != 0)
4601 return log_error_errno(errno_or_else(ENOMEM), "Failed to open block device '%s': %m", p);
4602
4603 (void) blkid_probe_enable_partitions(b, 1);
4604 (void) blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
4605
4606 errno = 0;
4607 r = blkid_do_safeprobe(b);
4608 if (IN_SET(r, -2, 1)) { /* nothing found or ambiguous result */
4609 log_debug("Didn't find partition table on block device '%s'.", p);
4610 return false;
4611 }
4612 if (r != 0)
4613 return log_error_errno(errno_or_else(EIO), "Unable to probe for partition table of '%s': %m", p);
4614
4615 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
4616 if (!streq_ptr(pttype, "gpt")) {
4617 log_debug("Didn't find a GPT partition table on '%s'.", p);
4618 return false;
4619 }
4620
4621 errno = 0;
4622 pl = blkid_probe_get_partitions(b);
4623 if (!pl)
4624 return log_error_errno(errno_or_else(EIO), "Unable read partition table of '%s': %m", p);
4625 errno = 0;
4626
4627 pp = blkid_partlist_devno_to_partition(pl, partition_devno);
4628 if (!pp) {
4629 log_debug("Partition %u:%u has no matching partition table entry on '%s'.",
4630 major(partition_devno), minor(partition_devno), p);
4631 return false;
4632 }
4633
4634 t = blkid_partition_get_type_string(pp);
4635 if (isempty(t)) {
4636 log_debug("Partition %u:%u has no type on '%s'.",
4637 major(partition_devno), minor(partition_devno), p);
4638 return false;
4639 }
4640
4641 r = sd_id128_from_string(t, &pt_parsed);
4642 if (r < 0) {
4643 log_debug_errno(r, "Failed to parse partition type \"%s\": %m", t);
4644 return false;
4645 }
4646
4647 if (!sd_id128_equal(pt_parsed, partition_type_uuid)) {
4648 log_debug("Partition %u:%u has non-matching partition type " SD_ID128_FORMAT_STR " (needed: " SD_ID128_FORMAT_STR "), ignoring.",
4649 major(partition_devno), minor(partition_devno),
4650 SD_ID128_FORMAT_VAL(pt_parsed), SD_ID128_FORMAT_VAL(partition_type_uuid));
4651 return false;
4652 }
4653
4654 t = blkid_partition_get_uuid(pp);
4655 if (isempty(t)) {
4656 log_debug("Partition %u:%u has no UUID.",
4657 major(partition_devno), minor(partition_devno));
4658 return false;
4659 }
4660
4661 r = sd_id128_from_string(t, &u);
4662 if (r < 0) {
4663 log_debug_errno(r, "Failed to parse partition UUID \"%s\": %m", t);
4664 return false;
4665 }
4666
4667 log_debug("Automatically found partition %u:%u of right type " SD_ID128_FORMAT_STR ".",
4668 major(partition_devno), minor(partition_devno),
4669 SD_ID128_FORMAT_VAL(pt_parsed));
4670
4671 if (ret_uuid)
4672 *ret_uuid = u;
4673
4674 return true;
4675}
4676
4677static int find_backing_devno(
4678 const char *path,
4679 const char *root,
4680 dev_t *ret) {
4681
4682 _cleanup_free_ char *resolved = NULL;
4683 int r;
4684
4685 assert(path);
4686
4687 r = chase_symlinks(path, root, CHASE_PREFIX_ROOT, &resolved, NULL);
4688 if (r < 0)
4689 return r;
4690
4691 r = path_is_mount_point(resolved, NULL, 0);
4692 if (r < 0)
4693 return r;
4694 if (r == 0) /* Not a mount point, then it's not a partition of its own, let's not automatically use it. */
4695 return -ENOENT;
4696
4697 r = get_block_device(resolved, ret);
4698 if (r < 0)
4699 return r;
4700 if (r == 0) /* Not backed by physical file system, we can't use this */
4701 return -ENOENT;
4702
4703 return 0;
4704}
4705
4706static int resolve_copy_blocks_auto(
4707 sd_id128_t type_uuid,
4708 const char *root,
4709 dev_t restrict_devno,
1a037ba2 4710 dev_t *ret_devno,
5c08da58
LP
4711 sd_id128_t *ret_uuid) {
4712
4713 const char *try1 = NULL, *try2 = NULL;
4714 char p[SYS_BLOCK_PATH_MAX("/slaves")];
4715 _cleanup_(closedirp) DIR *d = NULL;
4716 sd_id128_t found_uuid = SD_ID128_NULL;
4717 dev_t devno, found = 0;
4718 int r;
4719
5c08da58
LP
4720 /* Enforce some security restrictions: CopyBlocks=auto should not be an avenue to get outside of the
4721 * --root=/--image= confinement. Specifically, refuse CopyBlocks= in combination with --root= at all,
4722 * and restrict block device references in the --image= case to loopback block device we set up.
4723 *
4724 * restrict_devno contain the dev_t of the loop back device we operate on in case of --image=, and
4725 * thus declares which device (and its partition subdevices) we shall limit access to. If
4726 * restrict_devno is zero no device probing access shall be allowed at all (used for --root=) and if
4727 * it is (dev_t) -1 then free access shall be allowed (if neither switch is used). */
4728
4729 if (restrict_devno == 0)
4730 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
4731 "Automatic discovery of backing block devices not permitted in --root= mode, refusing.");
4732
4733 /* Handles CopyBlocks=auto, and finds the right source partition to copy from. We look for matching
4734 * partitions in the host, using the appropriate directory as key and ensuring that the partition
4735 * type matches. */
4736
4737 if (gpt_partition_type_is_root(type_uuid))
4738 try1 = "/";
4739 else if (gpt_partition_type_is_usr(type_uuid))
4740 try1 = "/usr/";
4741 else if (gpt_partition_type_is_root_verity(type_uuid))
4742 try1 = "/";
4743 else if (gpt_partition_type_is_usr_verity(type_uuid))
4744 try1 = "/usr/";
92e72028 4745 else if (sd_id128_equal(type_uuid, SD_GPT_ESP)) {
5c08da58
LP
4746 try1 = "/efi/";
4747 try2 = "/boot/";
92e72028 4748 } else if (sd_id128_equal(type_uuid, SD_GPT_XBOOTLDR))
5c08da58
LP
4749 try1 = "/boot/";
4750 else
4751 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
4752 "Partition type " SD_ID128_FORMAT_STR " not supported from automatic source block device discovery.",
4753 SD_ID128_FORMAT_VAL(type_uuid));
4754
4755 r = find_backing_devno(try1, root, &devno);
4756 if (r == -ENOENT && try2)
4757 r = find_backing_devno(try2, root, &devno);
4758 if (r < 0)
4759 return log_error_errno(r, "Failed to resolve automatic CopyBlocks= path for partition type " SD_ID128_FORMAT_STR ", sorry: %m",
4760 SD_ID128_FORMAT_VAL(type_uuid));
4761
4762 xsprintf_sys_block_path(p, "/slaves", devno);
4763 d = opendir(p);
4764 if (d) {
4765 struct dirent *de;
4766
4767 for (;;) {
4768 _cleanup_free_ char *q = NULL, *t = NULL;
4769 sd_id128_t u;
4770 dev_t sl;
4771
4772 errno = 0;
4773 de = readdir_no_dot(d);
4774 if (!de) {
4775 if (errno != 0)
4776 return log_error_errno(errno, "Failed to read directory '%s': %m", p);
4777
4778 break;
4779 }
4780
4781 if (!IN_SET(de->d_type, DT_LNK, DT_UNKNOWN))
4782 continue;
4783
4784 q = path_join(p, de->d_name, "/dev");
4785 if (!q)
4786 return log_oom();
4787
4788 r = read_one_line_file(q, &t);
4789 if (r < 0)
4790 return log_error_errno(r, "Failed to read %s: %m", q);
4791
7176f06c 4792 r = parse_devnum(t, &sl);
5c08da58
LP
4793 if (r < 0) {
4794 log_debug_errno(r, "Failed to parse %s, ignoring: %m", q);
4795 continue;
4796 }
4797 if (major(sl) == 0) {
4798 log_debug_errno(r, "Device backing %s is special, ignoring: %m", q);
4799 continue;
4800 }
4801
4802 r = resolve_copy_blocks_auto_candidate(sl, type_uuid, restrict_devno, &u);
4803 if (r < 0)
4804 return r;
4805 if (r > 0) {
4806 /* We found a matching one! */
4807 if (found != 0)
4808 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
4809 "Multiple matching partitions found, refusing.");
4810
4811 found = sl;
4812 found_uuid = u;
4813 }
4814 }
4815 } else if (errno != ENOENT)
4816 return log_error_errno(errno, "Failed open %s: %m", p);
4817 else {
4818 r = resolve_copy_blocks_auto_candidate(devno, type_uuid, restrict_devno, &found_uuid);
4819 if (r < 0)
4820 return r;
4821 if (r > 0)
4822 found = devno;
4823 }
4824
4825 if (found == 0)
4826 return log_error_errno(SYNTHETIC_ERRNO(ENXIO),
4827 "Unable to automatically discover suitable partition to copy blocks from.");
4828
1a037ba2
YW
4829 if (ret_devno)
4830 *ret_devno = found;
5c08da58
LP
4831
4832 if (ret_uuid)
4833 *ret_uuid = found_uuid;
4834
4835 return 0;
4836}
4837
4838static int context_open_copy_block_paths(
4839 Context *context,
4840 const char *root,
4841 dev_t restrict_devno) {
4842
757bc2e4
LP
4843 int r;
4844
4845 assert(context);
4846
4847 LIST_FOREACH(partitions, p, context->partitions) {
4848 _cleanup_close_ int source_fd = -1;
5c08da58
LP
4849 _cleanup_free_ char *opened = NULL;
4850 sd_id128_t uuid = SD_ID128_NULL;
757bc2e4
LP
4851 uint64_t size;
4852 struct stat st;
4853
4854 assert(p->copy_blocks_fd < 0);
4855 assert(p->copy_blocks_size == UINT64_MAX);
4856
4857 if (PARTITION_EXISTS(p)) /* Never copy over partitions that already exist! */
4858 continue;
4859
5c08da58 4860 if (p->copy_blocks_path) {
757bc2e4 4861
5c08da58
LP
4862 source_fd = chase_symlinks_and_open(p->copy_blocks_path, root, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NONBLOCK, &opened);
4863 if (source_fd < 0)
4864 return log_error_errno(source_fd, "Failed to open '%s': %m", p->copy_blocks_path);
757bc2e4 4865
5c08da58
LP
4866 if (fstat(source_fd, &st) < 0)
4867 return log_error_errno(errno, "Failed to stat block copy file '%s': %m", opened);
4868
4869 if (!S_ISREG(st.st_mode) && restrict_devno != (dev_t) -1)
4870 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
4871 "Copying from block device node is not permitted in --image=/--root= mode, refusing.");
4872
4873 } else if (p->copy_blocks_auto) {
1a037ba2 4874 dev_t devno;
5c08da58 4875
1a037ba2 4876 r = resolve_copy_blocks_auto(p->type_uuid, root, restrict_devno, &devno, &uuid);
5c08da58
LP
4877 if (r < 0)
4878 return r;
4879
ca822829 4880 source_fd = r = device_open_from_devnum(S_IFBLK, devno, O_RDONLY|O_CLOEXEC|O_NONBLOCK, &opened);
1a037ba2 4881 if (r < 0)
ca822829
YW
4882 return log_error_errno(r, "Failed to open automatically determined source block copy device " DEVNUM_FORMAT_STR ": %m",
4883 DEVNUM_FORMAT_VAL(devno));
5c08da58
LP
4884
4885 if (fstat(source_fd, &st) < 0)
4886 return log_error_errno(errno, "Failed to stat block copy file '%s': %m", opened);
1a037ba2 4887 } else
5c08da58 4888 continue;
757bc2e4
LP
4889
4890 if (S_ISDIR(st.st_mode)) {
ca822829
YW
4891 _cleanup_free_ char *bdev = NULL;
4892 dev_t devt;
757bc2e4
LP
4893
4894 /* If the file is a directory, automatically find the backing block device */
4895
4896 if (major(st.st_dev) != 0)
ca822829 4897 devt = st.st_dev;
757bc2e4 4898 else {
757bc2e4 4899 /* Special support for btrfs */
757bc2e4 4900 r = btrfs_get_block_device_fd(source_fd, &devt);
67f0ac8c 4901 if (r == -EUCLEAN)
5c08da58 4902 return btrfs_log_dev_root(LOG_ERR, r, opened);
757bc2e4 4903 if (r < 0)
5c08da58 4904 return log_error_errno(r, "Unable to determine backing block device of '%s': %m", opened);
757bc2e4 4905 }
757bc2e4
LP
4906
4907 safe_close(source_fd);
4908
ca822829
YW
4909 source_fd = r = device_open_from_devnum(S_IFBLK, devt, O_RDONLY|O_CLOEXEC|O_NONBLOCK, &bdev);
4910 if (r < 0)
4911 return log_error_errno(r, "Failed to open block device backing '%s': %m", opened);
757bc2e4
LP
4912
4913 if (fstat(source_fd, &st) < 0)
4914 return log_error_errno(errno, "Failed to stat block device '%s': %m", bdev);
757bc2e4
LP
4915 }
4916
4917 if (S_ISREG(st.st_mode))
4918 size = st.st_size;
4919 else if (S_ISBLK(st.st_mode)) {
4920 if (ioctl(source_fd, BLKGETSIZE64, &size) != 0)
4921 return log_error_errno(errno, "Failed to determine size of block device to copy from: %m");
4922 } else
5c08da58 4923 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Specified path to copy blocks from '%s' is not a regular file, block device or directory, refusing: %m", opened);
757bc2e4
LP
4924
4925 if (size <= 0)
5c08da58 4926 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "File to copy bytes from '%s' has zero size, refusing.", opened);
757bc2e4 4927 if (size % 512 != 0)
5c08da58 4928 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "File to copy bytes from '%s' has size that is not multiple of 512, refusing.", opened);
757bc2e4
LP
4929
4930 p->copy_blocks_fd = TAKE_FD(source_fd);
4931 p->copy_blocks_size = size;
5c08da58
LP
4932
4933 free_and_replace(p->copy_blocks_path, opened);
4934
4935 /* When copying from an existing partition copy that partitions UUID if none is configured explicitly */
11749b61 4936 if (!p->new_uuid_is_set && !sd_id128_is_null(uuid)) {
5c08da58 4937 p->new_uuid = uuid;
11749b61
DDM
4938 p->new_uuid_is_set = true;
4939 }
757bc2e4
LP
4940 }
4941
4942 return 0;
4943}
4944
e594a3b1
LP
4945static int help(void) {
4946 _cleanup_free_ char *link = NULL;
4947 int r;
4948
4949 r = terminal_urlify_man("systemd-repart", "1", &link);
4950 if (r < 0)
4951 return log_oom();
4952
4953 printf("%s [OPTIONS...] [DEVICE]\n"
4954 "\n%sGrow and add partitions to partition table.%s\n\n"
4955 " -h --help Show this help\n"
4956 " --version Show package version\n"
896e678b
LP
4957 " --no-pager Do not pipe output into a pager\n"
4958 " --no-legend Do not show the headers and footers\n"
e594a3b1 4959 " --dry-run=BOOL Whether to run dry-run operation\n"
a26f4a49
LP
4960 " --empty=MODE One of refuse, allow, require, force, create; controls\n"
4961 " how to handle empty disks lacking partition tables\n"
e594a3b1 4962 " --discard=BOOL Whether to discard backing blocks for new partitions\n"
2d2d0a57 4963 " --pretty=BOOL Whether to show pretty summary before doing changes\n"
e594a3b1
LP
4964 " --factory-reset=BOOL Whether to remove data partitions before recreating\n"
4965 " them\n"
4966 " --can-factory-reset Test whether factory reset is defined\n"
4967 " --root=PATH Operate relative to root path\n"
252d6267 4968 " --image=PATH Operate relative to image file\n"
9d252fbb 4969 " --definitions=DIR Find partition definitions in specified directory\n"
b9df3536 4970 " --key-file=PATH Key to use when encrypting partitions\n"
b456191d
DDM
4971 " --private-key=PATH Private key to use when generating verity roothash\n"
4972 " signatures\n"
4973 " --certificate=PATH PEM certificate to use when generating verity\n"
4974 " roothash signatures\n"
889914ef 4975 " --tpm2-device=PATH Path to TPM2 device node to use\n"
a1788a69 4976 " --tpm2-pcrs=PCR1+PCR2+PCR3+…\n"
889914ef 4977 " TPM2 PCR indexes to use for TPM2 enrollment\n"
02ef97cd
LP
4978 " --tpm2-public-key=PATH\n"
4979 " Enroll signed TPM2 PCR policy against PEM public key\n"
4980 " --tpm2-public-key-pcrs=PCR1+PCR2+PCR3+…\n"
4981 " Enroll signed TPM2 PCR policy for specified TPM2 PCRs\n"
e594a3b1 4982 " --seed=UUID 128bit seed UUID to derive all UUIDs from\n"
a26f4a49 4983 " --size=BYTES Grow loopback file to specified size\n"
2d2d0a57 4984 " --json=pretty|short|off\n"
de8231b0 4985 " Generate JSON output\n"
4cee8333 4986 " --split=BOOL Whether to generate split artifacts\n"
bc556335
DDM
4987 "\nSee the %s for details.\n",
4988 program_invocation_short_name,
4989 ansi_highlight(),
4990 ansi_normal(),
4991 link);
e594a3b1
LP
4992
4993 return 0;
4994}
4995
4996static int parse_argv(int argc, char *argv[]) {
4997
4998 enum {
4999 ARG_VERSION = 0x100,
896e678b
LP
5000 ARG_NO_PAGER,
5001 ARG_NO_LEGEND,
e594a3b1
LP
5002 ARG_DRY_RUN,
5003 ARG_EMPTY,
5004 ARG_DISCARD,
5005 ARG_FACTORY_RESET,
5006 ARG_CAN_FACTORY_RESET,
5007 ARG_ROOT,
252d6267 5008 ARG_IMAGE,
e594a3b1
LP
5009 ARG_SEED,
5010 ARG_PRETTY,
5011 ARG_DEFINITIONS,
a26f4a49 5012 ARG_SIZE,
a015fbe7 5013 ARG_JSON,
b9df3536 5014 ARG_KEY_FILE,
b456191d
DDM
5015 ARG_PRIVATE_KEY,
5016 ARG_CERTIFICATE,
889914ef
LP
5017 ARG_TPM2_DEVICE,
5018 ARG_TPM2_PCRS,
02ef97cd
LP
5019 ARG_TPM2_PUBLIC_KEY,
5020 ARG_TPM2_PUBLIC_KEY_PCRS,
4cee8333 5021 ARG_SPLIT,
e594a3b1
LP
5022 };
5023
5024 static const struct option options[] = {
02ef97cd
LP
5025 { "help", no_argument, NULL, 'h' },
5026 { "version", no_argument, NULL, ARG_VERSION },
5027 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
5028 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
5029 { "dry-run", required_argument, NULL, ARG_DRY_RUN },
5030 { "empty", required_argument, NULL, ARG_EMPTY },
5031 { "discard", required_argument, NULL, ARG_DISCARD },
5032 { "factory-reset", required_argument, NULL, ARG_FACTORY_RESET },
5033 { "can-factory-reset", no_argument, NULL, ARG_CAN_FACTORY_RESET },
5034 { "root", required_argument, NULL, ARG_ROOT },
5035 { "image", required_argument, NULL, ARG_IMAGE },
5036 { "seed", required_argument, NULL, ARG_SEED },
5037 { "pretty", required_argument, NULL, ARG_PRETTY },
5038 { "definitions", required_argument, NULL, ARG_DEFINITIONS },
5039 { "size", required_argument, NULL, ARG_SIZE },
5040 { "json", required_argument, NULL, ARG_JSON },
5041 { "key-file", required_argument, NULL, ARG_KEY_FILE },
b456191d
DDM
5042 { "private-key", required_argument, NULL, ARG_PRIVATE_KEY },
5043 { "certificate", required_argument, NULL, ARG_CERTIFICATE },
02ef97cd
LP
5044 { "tpm2-device", required_argument, NULL, ARG_TPM2_DEVICE },
5045 { "tpm2-pcrs", required_argument, NULL, ARG_TPM2_PCRS },
5046 { "tpm2-public-key", required_argument, NULL, ARG_TPM2_PUBLIC_KEY },
5047 { "tpm2-public-key-pcrs", required_argument, NULL, ARG_TPM2_PUBLIC_KEY_PCRS },
4cee8333 5048 { "split", required_argument, NULL, ARG_SPLIT },
e594a3b1
LP
5049 {}
5050 };
5051
a26f4a49 5052 int c, r, dry_run = -1;
e594a3b1
LP
5053
5054 assert(argc >= 0);
5055 assert(argv);
5056
5057 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
5058
5059 switch (c) {
5060
5061 case 'h':
5062 return help();
5063
5064 case ARG_VERSION:
5065 return version();
5066
896e678b
LP
5067 case ARG_NO_PAGER:
5068 arg_pager_flags |= PAGER_DISABLE;
5069 break;
5070
5071 case ARG_NO_LEGEND:
5072 arg_legend = false;
5073 break;
5074
e594a3b1 5075 case ARG_DRY_RUN:
599c7c54 5076 r = parse_boolean_argument("--dry-run=", optarg, &arg_dry_run);
e594a3b1 5077 if (r < 0)
599c7c54 5078 return r;
e594a3b1
LP
5079 break;
5080
5081 case ARG_EMPTY:
5082 if (isempty(optarg) || streq(optarg, "refuse"))
5083 arg_empty = EMPTY_REFUSE;
5084 else if (streq(optarg, "allow"))
5085 arg_empty = EMPTY_ALLOW;
5086 else if (streq(optarg, "require"))
5087 arg_empty = EMPTY_REQUIRE;
5088 else if (streq(optarg, "force"))
5089 arg_empty = EMPTY_FORCE;
a26f4a49
LP
5090 else if (streq(optarg, "create")) {
5091 arg_empty = EMPTY_CREATE;
5092
5093 if (dry_run < 0)
5094 dry_run = false; /* Imply --dry-run=no if we create the loopback file
5095 * anew. After all we cannot really break anyone's
5096 * partition tables that way. */
5097 } else
e594a3b1
LP
5098 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5099 "Failed to parse --empty= parameter: %s", optarg);
5100 break;
5101
5102 case ARG_DISCARD:
599c7c54 5103 r = parse_boolean_argument("--discard=", optarg, &arg_discard);
e594a3b1 5104 if (r < 0)
599c7c54 5105 return r;
e594a3b1
LP
5106 break;
5107
5108 case ARG_FACTORY_RESET:
c3470872 5109 r = parse_boolean_argument("--factory-reset=", optarg, NULL);
e594a3b1 5110 if (r < 0)
c3470872 5111 return r;
e594a3b1
LP
5112 arg_factory_reset = r;
5113 break;
5114
5115 case ARG_CAN_FACTORY_RESET:
5116 arg_can_factory_reset = true;
5117 break;
5118
5119 case ARG_ROOT:
252d6267
LP
5120 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
5121 if (r < 0)
5122 return r;
5123 break;
5124
5125 case ARG_IMAGE:
5126 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
e594a3b1
LP
5127 if (r < 0)
5128 return r;
5129 break;
5130
5131 case ARG_SEED:
5132 if (isempty(optarg)) {
5133 arg_seed = SD_ID128_NULL;
5134 arg_randomize = false;
5135 } else if (streq(optarg, "random"))
5136 arg_randomize = true;
5137 else {
5138 r = sd_id128_from_string(optarg, &arg_seed);
5139 if (r < 0)
5140 return log_error_errno(r, "Failed to parse seed: %s", optarg);
5141
5142 arg_randomize = false;
5143 }
5144
5145 break;
5146
5147 case ARG_PRETTY:
c3470872 5148 r = parse_boolean_argument("--pretty=", optarg, NULL);
e594a3b1 5149 if (r < 0)
c3470872 5150 return r;
e594a3b1
LP
5151 arg_pretty = r;
5152 break;
5153
224c853f
RP
5154 case ARG_DEFINITIONS: {
5155 _cleanup_free_ char *path = NULL;
5156 r = parse_path_argument(optarg, false, &path);
e594a3b1
LP
5157 if (r < 0)
5158 return r;
224c853f
RP
5159 if (strv_consume(&arg_definitions, TAKE_PTR(path)) < 0)
5160 return log_oom();
e594a3b1 5161 break;
224c853f 5162 }
e594a3b1 5163
a26f4a49
LP
5164 case ARG_SIZE: {
5165 uint64_t parsed, rounded;
5166
170c9823
LP
5167 if (streq(optarg, "auto")) {
5168 arg_size = UINT64_MAX;
5169 arg_size_auto = true;
5170 break;
5171 }
5172
a26f4a49
LP
5173 r = parse_size(optarg, 1024, &parsed);
5174 if (r < 0)
5175 return log_error_errno(r, "Failed to parse --size= parameter: %s", optarg);
5176
5177 rounded = round_up_size(parsed, 4096);
5178 if (rounded == 0)
5179 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Specified image size too small, refusing.");
5180 if (rounded == UINT64_MAX)
5181 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Specified image size too large, refusing.");
5182
5183 if (rounded != parsed)
e2341b6b
DT
5184 log_warning("Specified size is not a multiple of 4096, rounding up automatically. (%" PRIu64 " %s %" PRIu64 ")",
5185 parsed, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), rounded);
a26f4a49
LP
5186
5187 arg_size = rounded;
170c9823 5188 arg_size_auto = false;
a26f4a49
LP
5189 break;
5190 }
b9df3536 5191
a015fbe7 5192 case ARG_JSON:
b1e8f46c 5193 r = parse_json_argument(optarg, &arg_json_format_flags);
6a01ea4a
LP
5194 if (r <= 0)
5195 return r;
a015fbe7
TH
5196
5197 break;
5198
b9df3536
LP
5199 case ARG_KEY_FILE: {
5200 _cleanup_(erase_and_freep) char *k = NULL;
5201 size_t n = 0;
5202
8b3c3a49 5203 r = read_full_file_full(
986311c2 5204 AT_FDCWD, optarg, UINT64_MAX, SIZE_MAX,
8b3c3a49
LP
5205 READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
5206 NULL,
5207 &k, &n);
b9df3536
LP
5208 if (r < 0)
5209 return log_error_errno(r, "Failed to read key file '%s': %m", optarg);
5210
5211 erase_and_free(arg_key);
5212 arg_key = TAKE_PTR(k);
5213 arg_key_size = n;
5214 break;
5215 }
a26f4a49 5216
b456191d
DDM
5217 case ARG_PRIVATE_KEY: {
5218 _cleanup_(erase_and_freep) char *k = NULL;
5219 size_t n = 0;
5220
5221 r = read_full_file_full(
5222 AT_FDCWD, optarg, UINT64_MAX, SIZE_MAX,
5223 READ_FULL_FILE_SECURE|READ_FULL_FILE_WARN_WORLD_READABLE|READ_FULL_FILE_CONNECT_SOCKET,
5224 NULL,
5225 &k, &n);
5226 if (r < 0)
5227 return log_error_errno(r, "Failed to read key file '%s': %m", optarg);
5228
5229 EVP_PKEY_free(arg_private_key);
5230 arg_private_key = NULL;
5231 r = parse_private_key(k, n, &arg_private_key);
5232 if (r < 0)
5233 return r;
5234 break;
5235 }
5236
5237 case ARG_CERTIFICATE: {
5238 _cleanup_free_ char *cert = NULL;
5239 size_t n = 0;
5240
5241 r = read_full_file_full(
5242 AT_FDCWD, optarg, UINT64_MAX, SIZE_MAX,
5243 READ_FULL_FILE_CONNECT_SOCKET,
5244 NULL,
5245 &cert, &n);
5246 if (r < 0)
5247 return log_error_errno(r, "Failed to read certificate file '%s': %m", optarg);
5248
5249 X509_free(arg_certificate);
5250 arg_certificate = NULL;
5251 r = parse_x509_certificate(cert, n, &arg_certificate);
5252 if (r < 0)
5253 return r;
5254 break;
5255 }
5256
889914ef
LP
5257 case ARG_TPM2_DEVICE: {
5258 _cleanup_free_ char *device = NULL;
5259
5260 if (streq(optarg, "list"))
5261 return tpm2_list_devices();
5262
5263 if (!streq(optarg, "auto")) {
5264 device = strdup(optarg);
5265 if (!device)
5266 return log_oom();
5267 }
5268
5269 free(arg_tpm2_device);
5270 arg_tpm2_device = TAKE_PTR(device);
5271 break;
5272 }
5273
222a951f
LP
5274 case ARG_TPM2_PCRS:
5275 r = tpm2_parse_pcr_argument(optarg, &arg_tpm2_pcr_mask);
889914ef
LP
5276 if (r < 0)
5277 return r;
5278
889914ef 5279 break;
889914ef 5280
02ef97cd
LP
5281 case ARG_TPM2_PUBLIC_KEY:
5282 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_tpm2_public_key);
5283 if (r < 0)
5284 return r;
5285
5286 break;
5287
5288 case ARG_TPM2_PUBLIC_KEY_PCRS:
5289 r = tpm2_parse_pcr_argument(optarg, &arg_tpm2_public_key_pcr_mask);
5290 if (r < 0)
5291 return r;
5292
5293 break;
5294
4cee8333
DDM
5295 case ARG_SPLIT:
5296 r = parse_boolean_argument("--split=", optarg, NULL);
5297 if (r < 0)
5298 return r;
5299
5300 arg_split = r;
5301 break;
5302
e594a3b1
LP
5303 case '?':
5304 return -EINVAL;
5305
5306 default:
04499a70 5307 assert_not_reached();
e594a3b1
LP
5308 }
5309
5310 if (argc - optind > 1)
5311 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5312 "Expected at most one argument, the path to the block device.");
5313
a26f4a49 5314 if (arg_factory_reset > 0 && IN_SET(arg_empty, EMPTY_FORCE, EMPTY_REQUIRE, EMPTY_CREATE))
e594a3b1 5315 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
a26f4a49 5316 "Combination of --factory-reset=yes and --empty=force/--empty=require/--empty=create is invalid.");
e594a3b1
LP
5317
5318 if (arg_can_factory_reset)
a26f4a49
LP
5319 arg_dry_run = true; /* When --can-factory-reset is specified we don't make changes, hence
5320 * non-dry-run mode makes no sense. Thus, imply dry run mode so that we
5321 * open things strictly read-only. */
5322 else if (dry_run >= 0)
5323 arg_dry_run = dry_run;
5324
170c9823 5325 if (arg_empty == EMPTY_CREATE && (arg_size == UINT64_MAX && !arg_size_auto))
a26f4a49
LP
5326 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5327 "If --empty=create is specified, --size= must be specified, too.");
e594a3b1 5328
252d6267
LP
5329 if (arg_image && arg_root)
5330 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root= or --image=, the combination of both is not supported.");
5331 else if (!arg_image && !arg_root && in_initrd()) {
8f47e32a
LP
5332
5333 /* By default operate on /sysusr/ or /sysroot/ when invoked in the initrd. We prefer the
5334 * former, if it is mounted, so that we have deterministic behaviour on systems where /usr/
5335 * is vendor-supplied but the root fs formatted on first boot. */
5336 r = path_is_mount_point("/sysusr/usr", NULL, 0);
5337 if (r <= 0) {
5338 if (r < 0 && r != -ENOENT)
5339 log_debug_errno(r, "Unable to determine whether /sysusr/usr is a mount point, assuming it is not: %m");
5340
5341 arg_root = strdup("/sysroot");
5342 } else
5343 arg_root = strdup("/sysusr");
252d6267
LP
5344 if (!arg_root)
5345 return log_oom();
5346 }
5347
e594a3b1 5348 arg_node = argc > optind ? argv[optind] : NULL;
a26f4a49 5349
252d6267 5350 if (IN_SET(arg_empty, EMPTY_FORCE, EMPTY_REQUIRE, EMPTY_CREATE) && !arg_node && !arg_image)
a26f4a49
LP
5351 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5352 "A path to a device node or loopback file must be specified when --empty=force, --empty=require or --empty=create are used.");
5353
4cee8333
DDM
5354 if (arg_split && !arg_node)
5355 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5356 "A path to a loopback file must be specified when --split is used.");
5357
889914ef
LP
5358 if (arg_tpm2_pcr_mask == UINT32_MAX)
5359 arg_tpm2_pcr_mask = TPM2_PCR_MASK_DEFAULT;
02ef97cd
LP
5360 if (arg_tpm2_public_key_pcr_mask == UINT32_MAX)
5361 arg_tpm2_public_key_pcr_mask = UINT32_C(1) << TPM_PCR_INDEX_KERNEL_IMAGE;
889914ef 5362
a26d463d
DDM
5363 if (arg_pretty < 0 && isatty(STDOUT_FILENO))
5364 arg_pretty = true;
5365
e594a3b1
LP
5366 return 1;
5367}
5368
5369static int parse_proc_cmdline_factory_reset(void) {
5370 bool b;
5371 int r;
5372
5373 if (arg_factory_reset >= 0) /* Never override what is specified on the process command line */
5374 return 0;
5375
5376 if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
5377 return 0;
5378
5379 r = proc_cmdline_get_bool("systemd.factory_reset", &b);
5380 if (r < 0)
5381 return log_error_errno(r, "Failed to parse systemd.factory_reset kernel command line argument: %m");
5382 if (r > 0) {
5383 arg_factory_reset = b;
5384
5385 if (b)
5386 log_notice("Honouring factory reset requested via kernel command line.");
5387 }
5388
5389 return 0;
5390}
5391
5392static int parse_efi_variable_factory_reset(void) {
5393 _cleanup_free_ char *value = NULL;
5394 int r;
5395
5396 if (arg_factory_reset >= 0) /* Never override what is specified on the process command line */
5397 return 0;
5398
5399 if (!in_initrd()) /* Never honour EFI variable factory reset request outside of the initrd */
5400 return 0;
5401
e6f055cb 5402 r = efi_get_variable_string(EFI_SYSTEMD_VARIABLE(FactoryReset), &value);
e594a3b1
LP
5403 if (r == -ENOENT || ERRNO_IS_NOT_SUPPORTED(r))
5404 return 0;
5405 if (r < 0)
5406 return log_error_errno(r, "Failed to read EFI variable FactoryReset: %m");
5407
5408 r = parse_boolean(value);
5409 if (r < 0)
5410 return log_error_errno(r, "Failed to parse EFI variable FactoryReset: %m");
5411
5412 arg_factory_reset = r;
5413 if (r)
111a3aae 5414 log_notice("Factory reset requested via EFI variable FactoryReset.");
e594a3b1
LP
5415
5416 return 0;
5417}
5418
5419static int remove_efi_variable_factory_reset(void) {
5420 int r;
5421
e6f055cb 5422 r = efi_set_variable(EFI_SYSTEMD_VARIABLE(FactoryReset), NULL, 0);
e594a3b1
LP
5423 if (r == -ENOENT || ERRNO_IS_NOT_SUPPORTED(r))
5424 return 0;
5425 if (r < 0)
5426 return log_error_errno(r, "Failed to remove EFI variable FactoryReset: %m");
5427
5428 log_info("Successfully unset EFI variable FactoryReset.");
5429 return 0;
5430}
5431
252d6267
LP
5432static int acquire_root_devno(
5433 const char *p,
5434 const char *root,
5435 int mode,
5436 char **ret,
5437 int *ret_fd) {
5438
5439 _cleanup_free_ char *found_path = NULL;
5440 dev_t devno, fd_devno = MODE_INVALID;
e594a3b1
LP
5441 _cleanup_close_ int fd = -1;
5442 struct stat st;
e594a3b1
LP
5443 int r;
5444
a26f4a49
LP
5445 assert(p);
5446 assert(ret);
5447 assert(ret_fd);
5448
252d6267 5449 fd = chase_symlinks_and_open(p, root, CHASE_PREFIX_ROOT, mode, &found_path);
e594a3b1 5450 if (fd < 0)
252d6267 5451 return fd;
e594a3b1
LP
5452
5453 if (fstat(fd, &st) < 0)
5454 return -errno;
5455
5456 if (S_ISREG(st.st_mode)) {
252d6267 5457 *ret = TAKE_PTR(found_path);
a26f4a49 5458 *ret_fd = TAKE_FD(fd);
e594a3b1
LP
5459 return 0;
5460 }
5461
252d6267
LP
5462 if (S_ISBLK(st.st_mode)) {
5463 /* Refuse referencing explicit block devices if a root dir is specified, after all we should
5c08da58 5464 * not be able to leave the image the root path constrains us to. */
252d6267
LP
5465 if (root)
5466 return -EPERM;
5467
a26f4a49 5468 fd_devno = devno = st.st_rdev;
252d6267 5469 } else if (S_ISDIR(st.st_mode)) {
e594a3b1
LP
5470
5471 devno = st.st_dev;
a26f4a49 5472 if (major(devno) == 0) {
e594a3b1
LP
5473 r = btrfs_get_block_device_fd(fd, &devno);
5474 if (r == -ENOTTY) /* not btrfs */
5475 return -ENODEV;
5476 if (r < 0)
5477 return r;
5478 }
e594a3b1
LP
5479 } else
5480 return -ENOTBLK;
5481
5482 /* From dm-crypt to backing partition */
5483 r = block_get_originating(devno, &devno);
8e5f3cec
LP
5484 if (r == -ENOENT)
5485 log_debug_errno(r, "Device '%s' has no dm-crypt/dm-verity device, no need to look for underlying block device.", p);
5486 else if (r < 0)
e594a3b1
LP
5487 log_debug_errno(r, "Failed to find underlying block device for '%s', ignoring: %m", p);
5488
5489 /* From partition to whole disk containing it */
5490 r = block_get_whole_disk(devno, &devno);
5491 if (r < 0)
162392b7 5492 log_debug_errno(r, "Failed to find whole disk block device for '%s', ignoring: %m", p);
e594a3b1 5493
4fe46c34 5494 r = devname_from_devnum(S_IFBLK, devno, ret);
a26f4a49
LP
5495 if (r < 0)
5496 return log_debug_errno(r, "Failed to determine canonical path for '%s': %m", p);
5497
6bbae9f8 5498 /* Only if we still look at the same block device we can reuse the fd. Otherwise return an
a26f4a49 5499 * invalidated fd. */
f5fbe71d 5500 *ret_fd = fd_devno != MODE_INVALID && fd_devno == devno ? TAKE_FD(fd) : -1;
a26f4a49 5501 return 0;
e594a3b1
LP
5502}
5503
a26f4a49 5504static int find_root(char **ret, int *ret_fd) {
54632d2e 5505 _cleanup_free_ char *device = NULL;
5980d463 5506 int r;
e594a3b1 5507
a26f4a49
LP
5508 assert(ret);
5509 assert(ret_fd);
5510
e594a3b1 5511 if (arg_node) {
a26f4a49
LP
5512 if (arg_empty == EMPTY_CREATE) {
5513 _cleanup_close_ int fd = -1;
5514 _cleanup_free_ char *s = NULL;
5515
5516 s = strdup(arg_node);
5517 if (!s)
5518 return log_oom();
5519
5332d7c6 5520 fd = open(arg_node, O_RDONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOFOLLOW, 0666);
a26f4a49
LP
5521 if (fd < 0)
5522 return log_error_errno(errno, "Failed to create '%s': %m", arg_node);
5523
5524 *ret = TAKE_PTR(s);
5525 *ret_fd = TAKE_FD(fd);
5526 return 0;
5527 }
5528
252d6267
LP
5529 /* Note that we don't specify a root argument here: if the user explicitly configured a node
5530 * we'll take it relative to the host, not the image */
5531 r = acquire_root_devno(arg_node, NULL, O_RDONLY|O_CLOEXEC, ret, ret_fd);
67f0ac8c
LP
5532 if (r == -EUCLEAN)
5533 return btrfs_log_dev_root(LOG_ERR, r, arg_node);
e594a3b1 5534 if (r < 0)
aa2a74ad 5535 return log_error_errno(r, "Failed to open file or determine backing device of %s: %m", arg_node);
e594a3b1
LP
5536
5537 return 0;
5538 }
5539
a26f4a49
LP
5540 assert(IN_SET(arg_empty, EMPTY_REFUSE, EMPTY_ALLOW));
5541
54632d2e
KK
5542 /* If the root mount has been replaced by some form of volatile file system (overlayfs), the
5543 * original root block device node is symlinked in /run/systemd/volatile-root. Let's read that
5544 * here. */
5545 r = readlink_malloc("/run/systemd/volatile-root", &device);
5546 if (r == -ENOENT) { /* volatile-root not found */
5547 /* Let's search for the root device. We look for two cases here: first in /, and then in /usr. The
5548 * latter we check for cases where / is a tmpfs and only /usr is an actual persistent block device
5549 * (think: volatile setups) */
e594a3b1 5550
54632d2e 5551 FOREACH_STRING(p, "/", "/usr") {
e594a3b1 5552
54632d2e
KK
5553 r = acquire_root_devno(p, arg_root, O_RDONLY|O_DIRECTORY|O_CLOEXEC, ret, ret_fd);
5554 if (r < 0) {
5555 if (r == -EUCLEAN)
5556 return btrfs_log_dev_root(LOG_ERR, r, p);
5557 if (r != -ENODEV)
5558 return log_error_errno(r, "Failed to determine backing device of %s: %m", p);
5559 } else
5560 return 0;
5561 }
5562 } else if (r < 0)
5563 return log_error_errno(r, "Failed to read symlink /run/systemd/volatile-root: %m");
5564 else {
5565 r = acquire_root_devno(device, NULL, O_RDONLY|O_CLOEXEC, ret, ret_fd);
5566 if (r == -EUCLEAN)
5567 return btrfs_log_dev_root(LOG_ERR, r, device);
5568 if (r < 0)
5569 return log_error_errno(r, "Failed to open file or determine backing device of %s: %m", device);
5570
5571 return 0;
e594a3b1
LP
5572 }
5573
5574 return log_error_errno(SYNTHETIC_ERRNO(ENODEV), "Failed to discover root block device.");
5575}
5576
f9b3afae 5577static int resize_pt(int fd) {
f9b3afae
LP
5578 _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
5579 int r;
5580
5581 /* After resizing the backing file we need to resize the partition table itself too, so that it takes
5582 * possession of the enlarged backing file. For this it suffices to open the device with libfdisk and
5583 * immediately write it again, with no changes. */
5584
5585 c = fdisk_new_context();
5586 if (!c)
5587 return log_oom();
5588
ddb6eeaf 5589 r = fdisk_assign_device(c, FORMAT_PROC_FD_PATH(fd), 0);
f9b3afae 5590 if (r < 0)
ddb6eeaf 5591 return log_error_errno(r, "Failed to open device '%s': %m", FORMAT_PROC_FD_PATH(fd));
f9b3afae
LP
5592
5593 r = fdisk_has_label(c);
5594 if (r < 0)
ddb6eeaf 5595 return log_error_errno(r, "Failed to determine whether disk '%s' has a disk label: %m", FORMAT_PROC_FD_PATH(fd));
f9b3afae
LP
5596 if (r == 0) {
5597 log_debug("Not resizing partition table, as there currently is none.");
5598 return 0;
5599 }
5600
5601 r = fdisk_write_disklabel(c);
5602 if (r < 0)
5603 return log_error_errno(r, "Failed to write resized partition table: %m");
5604
5605 log_info("Resized partition table.");
5606 return 1;
5607}
5608
252d6267
LP
5609static int resize_backing_fd(
5610 const char *node, /* The primary way we access the disk image to operate on */
5611 int *fd, /* An O_RDONLY fd referring to that inode */
5612 const char *backing_file, /* If the above refers to a loopback device, the backing regular file for that, which we can grow */
5613 LoopDevice *loop_device) {
5614
a26f4a49 5615 _cleanup_close_ int writable_fd = -1;
252d6267 5616 uint64_t current_size;
a26f4a49
LP
5617 struct stat st;
5618 int r;
5619
5620 assert(node);
5621 assert(fd);
5622
5623 if (arg_size == UINT64_MAX) /* Nothing to do */
5624 return 0;
5625
5626 if (*fd < 0) {
5627 /* Open the file if we haven't opened it yet. Note that we open it read-only here, just to
5628 * keep a reference to the file we can pass around. */
5629 *fd = open(node, O_RDONLY|O_CLOEXEC);
5630 if (*fd < 0)
5631 return log_error_errno(errno, "Failed to open '%s' in order to adjust size: %m", node);
5632 }
5633
5634 if (fstat(*fd, &st) < 0)
5635 return log_error_errno(errno, "Failed to stat '%s': %m", node);
5636
252d6267
LP
5637 if (S_ISBLK(st.st_mode)) {
5638 if (!backing_file)
5639 return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Cannot resize block device '%s'.", node);
5640
5641 assert(loop_device);
a26f4a49 5642
252d6267
LP
5643 if (ioctl(*fd, BLKGETSIZE64, &current_size) < 0)
5644 return log_error_errno(errno, "Failed to determine size of block device %s: %m", node);
5645 } else {
5646 r = stat_verify_regular(&st);
5647 if (r < 0)
5648 return log_error_errno(r, "Specified path '%s' is not a regular file or loopback block device, cannot resize: %m", node);
5649
5650 assert(!backing_file);
5651 assert(!loop_device);
5652 current_size = st.st_size;
5653 }
5654
252d6267 5655 if (current_size >= arg_size) {
2b59bf51
ZJS
5656 log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)",
5657 node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
a26f4a49
LP
5658 return 0;
5659 }
5660
252d6267
LP
5661 if (S_ISBLK(st.st_mode)) {
5662 assert(backing_file);
5663
5664 /* This is a loopback device. We can't really grow those directly, but we can grow the
5665 * backing file, hence let's do that. */
5666
5667 writable_fd = open(backing_file, O_WRONLY|O_CLOEXEC|O_NONBLOCK);
5668 if (writable_fd < 0)
5669 return log_error_errno(errno, "Failed to open backing file '%s': %m", backing_file);
5670
5671 if (fstat(writable_fd, &st) < 0)
5672 return log_error_errno(errno, "Failed to stat() backing file '%s': %m", backing_file);
5673
5674 r = stat_verify_regular(&st);
5675 if (r < 0)
5676 return log_error_errno(r, "Backing file '%s' of block device is not a regular file: %m", backing_file);
5677
5678 if ((uint64_t) st.st_size != current_size)
5679 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2b59bf51
ZJS
5680 "Size of backing file '%s' of loopback block device '%s' don't match, refusing.",
5681 node, backing_file);
252d6267
LP
5682 } else {
5683 assert(S_ISREG(st.st_mode));
5684 assert(!backing_file);
a26f4a49 5685
252d6267
LP
5686 /* The file descriptor is read-only. In order to grow the file we need to have a writable fd. We
5687 * reopen the file for that temporarily. We keep the writable fd only open for this operation though,
5688 * as fdisk can't accept it anyway. */
5689
5690 writable_fd = fd_reopen(*fd, O_WRONLY|O_CLOEXEC);
5691 if (writable_fd < 0)
5692 return log_error_errno(writable_fd, "Failed to reopen backing file '%s' writable: %m", node);
5693 }
a26f4a49
LP
5694
5695 if (!arg_discard) {
5696 if (fallocate(writable_fd, 0, 0, arg_size) < 0) {
5697 if (!ERRNO_IS_NOT_SUPPORTED(errno))
5698 return log_error_errno(errno, "Failed to grow '%s' from %s to %s by allocation: %m",
2b59bf51 5699 node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
a26f4a49
LP
5700
5701 /* Fallback to truncation, if fallocate() is not supported. */
5702 log_debug("Backing file system does not support fallocate(), falling back to ftruncate().");
5703 } else {
252d6267 5704 if (current_size == 0) /* Likely regular file just created by us */
2b59bf51 5705 log_info("Allocated %s for '%s'.", FORMAT_BYTES(arg_size), node);
a26f4a49 5706 else
2b59bf51
ZJS
5707 log_info("File '%s' grown from %s to %s by allocation.",
5708 node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
a26f4a49 5709
252d6267 5710 goto done;
a26f4a49
LP
5711 }
5712 }
5713
5714 if (ftruncate(writable_fd, arg_size) < 0)
5715 return log_error_errno(errno, "Failed to grow '%s' from %s to %s by truncation: %m",
2b59bf51 5716 node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
a26f4a49 5717
252d6267 5718 if (current_size == 0) /* Likely regular file just created by us */
2b59bf51 5719 log_info("Sized '%s' to %s.", node, FORMAT_BYTES(arg_size));
252d6267 5720 else
2b59bf51
ZJS
5721 log_info("File '%s' grown from %s to %s by truncation.",
5722 node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
252d6267
LP
5723
5724done:
f9b3afae
LP
5725 r = resize_pt(writable_fd);
5726 if (r < 0)
5727 return r;
5728
252d6267
LP
5729 if (loop_device) {
5730 r = loop_device_refresh_size(loop_device, UINT64_MAX, arg_size);
5731 if (r < 0)
5732 return log_error_errno(r, "Failed to update loop device size: %m");
5733 }
a26f4a49
LP
5734
5735 return 1;
5736}
5737
170c9823 5738static int determine_auto_size(Context *c) {
994b3031 5739 uint64_t sum;
170c9823 5740
ac33e147 5741 assert(c);
170c9823 5742
994b3031
LP
5743 sum = round_up_size(GPT_METADATA_SIZE, 4096);
5744
170c9823
LP
5745 LIST_FOREACH(partitions, p, c->partitions) {
5746 uint64_t m;
5747
5748 if (p->dropped)
5749 continue;
5750
994b3031 5751 m = partition_min_size_with_padding(c, p);
170c9823
LP
5752 if (m > UINT64_MAX - sum)
5753 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Image would grow too large, refusing.");
5754
5755 sum += m;
5756 }
5757
2b59bf51
ZJS
5758 if (c->total != UINT64_MAX)
5759 /* Image already allocated? Then show its size. */
5760 log_info("Automatically determined minimal disk image size as %s, current image size is %s.",
5761 FORMAT_BYTES(sum), FORMAT_BYTES(c->total));
5762 else
5763 /* If the image is being created right now, then it has no previous size, suppress any comment about it hence. */
5764 log_info("Automatically determined minimal disk image size as %s.",
5765 FORMAT_BYTES(sum));
170c9823
LP
5766
5767 arg_size = sum;
5768 return 0;
5769}
5770
e594a3b1 5771static int run(int argc, char *argv[]) {
252d6267 5772 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
252d6267 5773 _cleanup_(umount_and_rmdir_and_freep) char *mounted_dir = NULL;
e594a3b1
LP
5774 _cleanup_(context_freep) Context* context = NULL;
5775 _cleanup_free_ char *node = NULL;
a26f4a49 5776 _cleanup_close_ int backing_fd = -1;
252d6267 5777 bool from_scratch, node_is_our_loop = false;
e594a3b1
LP
5778 int r;
5779
5780 log_show_color(true);
5781 log_parse_environment();
5782 log_open();
5783
e594a3b1
LP
5784 r = parse_argv(argc, argv);
5785 if (r <= 0)
5786 return r;
5787
5788 r = parse_proc_cmdline_factory_reset();
5789 if (r < 0)
5790 return r;
5791
5792 r = parse_efi_variable_factory_reset();
5793 if (r < 0)
5794 return r;
5795
30f19400
LP
5796#if HAVE_LIBCRYPTSETUP
5797 cryptsetup_enable_logging(NULL);
5798#endif
5799
252d6267
LP
5800 if (arg_image) {
5801 assert(!arg_root);
5802
5803 /* Mount this strictly read-only: we shall modify the partition table, not the file
5804 * systems */
5805 r = mount_image_privately_interactively(
5806 arg_image,
5807 DISSECT_IMAGE_MOUNT_READ_ONLY |
5808 (arg_node ? DISSECT_IMAGE_DEVICE_READ_ONLY : 0) | /* If a different node to make changes to is specified let's open the device in read-only mode) */
5809 DISSECT_IMAGE_GPT_ONLY |
5810 DISSECT_IMAGE_RELAX_VAR_CHECK |
5811 DISSECT_IMAGE_USR_NO_ROOT |
5812 DISSECT_IMAGE_REQUIRE_ROOT,
5813 &mounted_dir,
e330f97a 5814 &loop_device);
252d6267
LP
5815 if (r < 0)
5816 return r;
5817
5818 arg_root = strdup(mounted_dir);
5819 if (!arg_root)
5820 return log_oom();
5821
5822 if (!arg_node) {
5823 arg_node = strdup(loop_device->node);
5824 if (!arg_node)
5825 return log_oom();
5826
3d62af7d 5827 /* Remember that the device we are about to manipulate is actually the one we
252d6267
LP
5828 * allocated here, and thus to increase its backing file we know what to do */
5829 node_is_our_loop = true;
5830 }
5831 }
5832
e594a3b1
LP
5833 context = context_new(arg_seed);
5834 if (!context)
5835 return log_oom();
5836
224c853f
RP
5837 strv_uniq(arg_definitions);
5838
e594a3b1
LP
5839 r = context_read_definitions(context, arg_definitions, arg_root);
5840 if (r < 0)
5841 return r;
5842
a26f4a49 5843 if (context->n_partitions <= 0 && arg_empty == EMPTY_REFUSE) {
e2d65cd2 5844 log_info("Didn't find any partition definition files, nothing to do.");
0ae5ffe0 5845 return 0;
e2d65cd2 5846 }
0ae5ffe0 5847
a26f4a49 5848 r = find_root(&node, &backing_fd);
0ae5ffe0
YW
5849 if (r < 0)
5850 return r;
5851
a26f4a49 5852 if (arg_size != UINT64_MAX) {
252d6267
LP
5853 r = resize_backing_fd(
5854 node,
5855 &backing_fd,
5856 node_is_our_loop ? arg_image : NULL,
5857 node_is_our_loop ? loop_device : NULL);
a26f4a49
LP
5858 if (r < 0)
5859 return r;
5860 }
5861
5862 r = context_load_partition_table(context, node, &backing_fd);
e594a3b1
LP
5863 if (r == -EHWPOISON)
5864 return 77; /* Special return value which means "Not GPT, so not doing anything". This isn't
5865 * really an error when called at boot. */
5866 if (r < 0)
5867 return r;
5868 from_scratch = r > 0; /* Starting from scratch */
5869
5870 if (arg_can_factory_reset) {
5871 r = context_can_factory_reset(context);
5872 if (r < 0)
5873 return r;
5874 if (r == 0)
5875 return EXIT_FAILURE;
5876
5877 return 0;
5878 }
5879
5880 r = context_factory_reset(context, from_scratch);
5881 if (r < 0)
5882 return r;
5883 if (r > 0) {
5884 /* We actually did a factory reset! */
5885 r = remove_efi_variable_factory_reset();
5886 if (r < 0)
5887 return r;
5888
5889 /* Reload the reduced partition table */
5890 context_unload_partition_table(context);
a26f4a49 5891 r = context_load_partition_table(context, node, &backing_fd);
e594a3b1
LP
5892 if (r < 0)
5893 return r;
5894 }
5895
5896#if 0
5897 (void) context_dump_partitions(context, node);
5898 putchar('\n');
5899#endif
5900
5901 r = context_read_seed(context, arg_root);
5902 if (r < 0)
5903 return r;
5904
757bc2e4 5905 /* Open all files to copy blocks from now, since we want to take their size into consideration */
5c08da58
LP
5906 r = context_open_copy_block_paths(
5907 context,
5908 arg_root,
7802194a 5909 loop_device ? loop_device->devno : /* if --image= is specified, only allow partitions on the loopback device */
5c08da58
LP
5910 arg_root && !arg_image ? 0 : /* if --root= is specified, don't accept any block device */
5911 (dev_t) -1); /* if neither is specified, make no restrictions */
757bc2e4
LP
5912 if (r < 0)
5913 return r;
5914
170c9823
LP
5915 if (arg_size_auto) {
5916 r = determine_auto_size(context);
5917 if (r < 0)
5918 return r;
5919
5920 /* Flush out everything again, and let's grow the file first, then start fresh */
5921 context_unload_partition_table(context);
5922
ac33e147 5923 assert(arg_size != UINT64_MAX);
252d6267
LP
5924 r = resize_backing_fd(
5925 node,
5926 &backing_fd,
5927 node_is_our_loop ? arg_image : NULL,
5928 node_is_our_loop ? loop_device : NULL);
170c9823
LP
5929 if (r < 0)
5930 return r;
5931
5932 r = context_load_partition_table(context, node, &backing_fd);
5933 if (r < 0)
5934 return r;
5935 }
5936
e594a3b1
LP
5937 /* First try to fit new partitions in, dropping by priority until it fits */
5938 for (;;) {
14a4c4ed
LP
5939 uint64_t largest_free_area;
5940
5941 if (context_allocate_partitions(context, &largest_free_area))
e594a3b1
LP
5942 break; /* Success! */
5943
9ccceb9d 5944 if (!context_drop_or_foreignize_one_priority(context)) {
d17db7b2 5945 r = log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
14a4c4ed 5946 "Can't fit requested partitions into available free space (%s), refusing.",
2b59bf51 5947 FORMAT_BYTES(largest_free_area));
d17db7b2
LP
5948 determine_auto_size(context);
5949 return r;
5950 }
e594a3b1
LP
5951 }
5952
5953 /* Now assign free space according to the weight logic */
5954 r = context_grow_partitions(context);
5955 if (r < 0)
5956 return r;
5957
0b7f574f 5958 /* Now calculate where each new partition gets placed */
e594a3b1
LP
5959 context_place_partitions(context);
5960
5961 /* Make sure each partition has a unique UUID and unique label */
5962 r = context_acquire_partition_uuids_and_labels(context);
5963 if (r < 0)
5964 return r;
5965
b5b7879a 5966 (void) context_dump(context, node, /*late=*/ false);
a26d463d 5967
e594a3b1
LP
5968 r = context_write_partition_table(context, node, from_scratch);
5969 if (r < 0)
5970 return r;
5971
4cee8333
DDM
5972 r = context_split(context);
5973 if (r < 0)
5974 return r;
5975
b5b7879a
DDM
5976 (void) context_dump(context, node, /*late=*/ true);
5977
e594a3b1
LP
5978 return 0;
5979}
5980
5981DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);