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