1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #if HAVE_VALGRIND_MEMCHECK_H
4 #include <valgrind/memcheck.h>
10 #include <linux/loop.h>
12 #include <sys/ioctl.h>
15 #include "sd-device.h"
18 #include "alloc-util.h"
19 #include "blkid-util.h"
20 #include "blockdev-util.h"
21 #include "btrfs-util.h"
24 #include "conf-files.h"
25 #include "conf-parser.h"
26 #include "constants.h"
27 #include "cryptsetup-util.h"
28 #include "device-util.h"
29 #include "devnum-util.h"
30 #include "dirent-util.h"
32 #include "errno-util.h"
34 #include "fdisk-util.h"
36 #include "format-table.h"
37 #include "format-util.h"
39 #include "glyph-util.h"
41 #include "hexdecoct.h"
43 #include "id128-util.h"
44 #include "initrd-util.h"
48 #include "loop-util.h"
49 #include "main-func.h"
51 #include "mkfs-util.h"
52 #include "mount-util.h"
53 #include "mountpoint-util.h"
54 #include "nulstr-util.h"
55 #include "openssl-util.h"
56 #include "parse-argument.h"
57 #include "parse-helpers.h"
58 #include "pretty-print.h"
59 #include "proc-cmdline.h"
60 #include "process-util.h"
61 #include "random-util.h"
62 #include "resize-fs.h"
64 #include "sort-util.h"
65 #include "specifier.h"
66 #include "stdio-util.h"
67 #include "string-table.h"
68 #include "string-util.h"
70 #include "sync-util.h"
71 #include "terminal-util.h"
72 #include "tmpfile-util.h"
74 #include "tpm2-util.h"
75 #include "user-util.h"
78 /* If not configured otherwise use a minimal partition size of 10M */
79 #define DEFAULT_MIN_SIZE (10ULL*1024ULL*1024ULL)
81 /* Hard lower limit for new partition sizes */
82 #define HARD_MIN_SIZE 4096ULL
84 /* We know up front we're never going to put more than this in a verity sig partition. */
85 #define VERITY_SIG_SIZE (HARD_MIN_SIZE*4ULL)
87 /* libfdisk takes off slightly more than 1M of the disk size when creating a GPT disk label */
88 #define GPT_METADATA_SIZE (1044ULL*1024ULL)
90 /* LUKS2 takes off 16M of the partition size with its metadata by default */
91 #define LUKS2_METADATA_SIZE (16ULL*1024ULL*1024ULL)
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)
96 /* LUKS2 volume key size. */
97 #define VOLUME_KEY_SIZE (512ULL/8ULL)
99 /* Use 4K as the default filesystem sector size because as long as the partitions are aligned to 4K, the
100 * filesystems will then also be compatible with sector sizes 512, 1024 and 2048. */
101 #define DEFAULT_FILESYSTEM_SECTOR_SIZE 4096ULL
103 #define APIVFS_TMP_DIRS_NULSTR "proc\0sys\0dev\0tmp\0run\0var/tmp\0"
105 /* Note: When growing and placing new partitions we always align to 4K sector size. It's how newer hard disks
106 * are designed, and if everything is aligned to that performance is best. And for older hard disks with 512B
107 * sector size devices were generally assumed to have an even number of sectors, hence at the worst we'll
108 * waste 3K per partition, which is probably fine. */
110 typedef enum EmptyMode
{
111 EMPTY_UNSET
, /* no choice has been made yet */
112 EMPTY_REFUSE
, /* refuse empty disks, never create a partition table */
113 EMPTY_ALLOW
, /* allow empty disks, create partition table if necessary */
114 EMPTY_REQUIRE
, /* require an empty disk, create a partition table */
115 EMPTY_FORCE
, /* make disk empty, erase everything, create a partition table always */
116 EMPTY_CREATE
, /* create disk as loopback file, create a partition table always */
118 _EMPTY_MODE_INVALID
= -EINVAL
,
121 typedef enum FilterPartitionType
{
122 FILTER_PARTITIONS_NONE
,
123 FILTER_PARTITIONS_EXCLUDE
,
124 FILTER_PARTITIONS_INCLUDE
,
125 _FILTER_PARTITIONS_MAX
,
126 _FILTER_PARTITIONS_INVALID
= -EINVAL
,
127 } FilterPartitionsType
;
129 static EmptyMode arg_empty
= EMPTY_UNSET
;
130 static bool arg_dry_run
= true;
131 static const char *arg_node
= NULL
;
132 static char *arg_root
= NULL
;
133 static char *arg_image
= NULL
;
134 static char **arg_definitions
= NULL
;
135 static bool arg_discard
= true;
136 static bool arg_can_factory_reset
= false;
137 static int arg_factory_reset
= -1;
138 static sd_id128_t arg_seed
= SD_ID128_NULL
;
139 static bool arg_randomize
= false;
140 static int arg_pretty
= -1;
141 static uint64_t arg_size
= UINT64_MAX
;
142 static bool arg_size_auto
= false;
143 static JsonFormatFlags arg_json_format_flags
= JSON_FORMAT_OFF
;
144 static PagerFlags arg_pager_flags
= 0;
145 static bool arg_legend
= true;
146 static void *arg_key
= NULL
;
147 static size_t arg_key_size
= 0;
148 static EVP_PKEY
*arg_private_key
= NULL
;
149 static X509
*arg_certificate
= NULL
;
150 static char *arg_tpm2_device
= NULL
;
151 static uint32_t arg_tpm2_seal_key_handle
= 0;
152 static char *arg_tpm2_device_key
= NULL
;
153 static Tpm2PCRValue
*arg_tpm2_hash_pcr_values
= NULL
;
154 static size_t arg_tpm2_n_hash_pcr_values
= 0;
155 static char *arg_tpm2_public_key
= NULL
;
156 static uint32_t arg_tpm2_public_key_pcr_mask
= 0;
157 static char *arg_tpm2_pcrlock
= NULL
;
158 static bool arg_split
= false;
159 static GptPartitionType
*arg_filter_partitions
= NULL
;
160 static size_t arg_n_filter_partitions
= 0;
161 static FilterPartitionsType arg_filter_partitions_type
= FILTER_PARTITIONS_NONE
;
162 static GptPartitionType
*arg_defer_partitions
= NULL
;
163 static size_t arg_n_defer_partitions
= 0;
164 static uint64_t arg_sector_size
= 0;
165 static ImagePolicy
*arg_image_policy
= NULL
;
166 static Architecture arg_architecture
= _ARCHITECTURE_INVALID
;
167 static int arg_offline
= -1;
168 static char **arg_copy_from
= NULL
;
169 static char *arg_copy_source
= NULL
;
170 static char *arg_make_ddi
= NULL
;
172 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
173 STATIC_DESTRUCTOR_REGISTER(arg_image
, freep
);
174 STATIC_DESTRUCTOR_REGISTER(arg_definitions
, strv_freep
);
175 STATIC_DESTRUCTOR_REGISTER(arg_key
, erase_and_freep
);
176 STATIC_DESTRUCTOR_REGISTER(arg_private_key
, EVP_PKEY_freep
);
177 STATIC_DESTRUCTOR_REGISTER(arg_certificate
, X509_freep
);
178 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device
, freep
);
179 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device_key
, freep
);
180 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_hash_pcr_values
, freep
);
181 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_public_key
, freep
);
182 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_pcrlock
, freep
);
183 STATIC_DESTRUCTOR_REGISTER(arg_filter_partitions
, freep
);
184 STATIC_DESTRUCTOR_REGISTER(arg_image_policy
, image_policy_freep
);
185 STATIC_DESTRUCTOR_REGISTER(arg_copy_from
, strv_freep
);
186 STATIC_DESTRUCTOR_REGISTER(arg_copy_source
, freep
);
187 STATIC_DESTRUCTOR_REGISTER(arg_make_ddi
, freep
);
189 typedef struct FreeArea FreeArea
;
191 typedef enum EncryptMode
{
195 ENCRYPT_KEY_FILE_TPM2
,
197 _ENCRYPT_MODE_INVALID
= -EINVAL
,
200 typedef enum VerityMode
{
206 _VERITY_MODE_INVALID
= -EINVAL
,
209 typedef enum MinimizeMode
{
214 _MINIMIZE_MODE_INVALID
= -EINVAL
,
217 typedef struct Partition
{
218 char *definition_path
;
219 char **drop_in_files
;
221 GptPartitionType type
;
222 sd_id128_t current_uuid
, new_uuid
;
223 bool new_uuid_is_set
;
224 char *current_label
, *new_label
;
225 sd_id128_t fs_uuid
, luks_uuid
, verity_uuid
;
226 uint8_t verity_salt
[SHA256_DIGEST_SIZE
];
232 uint32_t weight
, padding_weight
;
234 uint64_t current_size
, new_size
;
235 uint64_t size_min
, size_max
;
237 uint64_t current_padding
, new_padding
;
238 uint64_t padding_min
, padding_max
;
243 struct fdisk_partition
*current_partition
;
244 struct fdisk_partition
*new_partition
;
245 FreeArea
*padding_area
;
246 FreeArea
*allocated_to_area
;
248 char *copy_blocks_path
;
249 bool copy_blocks_path_is_our_file
;
250 bool copy_blocks_auto
;
251 const char *copy_blocks_root
;
253 uint64_t copy_blocks_offset
;
254 uint64_t copy_blocks_size
;
258 char **exclude_files_source
;
259 char **exclude_files_target
;
260 char **make_directories
;
264 char *verity_match_key
;
265 MinimizeMode minimize
;
266 uint64_t verity_data_block_size
;
267 uint64_t verity_hash_block_size
;
274 struct iovec roothash
;
276 char *split_name_format
;
279 struct Partition
*siblings
[_VERITY_MODE_MAX
];
281 LIST_FIELDS(struct Partition
, partitions
);
284 #define PARTITION_IS_FOREIGN(p) (!(p)->definition_path)
285 #define PARTITION_EXISTS(p) (!!(p)->current_partition)
293 typedef struct Context
{
294 LIST_HEAD(Partition
, partitions
);
297 FreeArea
**free_areas
;
300 uint64_t start
, end
, total
;
302 struct fdisk_context
*fdisk_context
;
303 uint64_t sector_size
, grain_size
, fs_sector_size
;
308 bool node_is_our_file
;
314 static const char *empty_mode_table
[_EMPTY_MODE_MAX
] = {
315 [EMPTY_UNSET
] = "unset",
316 [EMPTY_REFUSE
] = "refuse",
317 [EMPTY_ALLOW
] = "allow",
318 [EMPTY_REQUIRE
] = "require",
319 [EMPTY_FORCE
] = "force",
320 [EMPTY_CREATE
] = "create",
323 static const char *encrypt_mode_table
[_ENCRYPT_MODE_MAX
] = {
324 [ENCRYPT_OFF
] = "off",
325 [ENCRYPT_KEY_FILE
] = "key-file",
326 [ENCRYPT_TPM2
] = "tpm2",
327 [ENCRYPT_KEY_FILE_TPM2
] = "key-file+tpm2",
330 static const char *verity_mode_table
[_VERITY_MODE_MAX
] = {
331 [VERITY_OFF
] = "off",
332 [VERITY_DATA
] = "data",
333 [VERITY_HASH
] = "hash",
334 [VERITY_SIG
] = "signature",
337 static const char *minimize_mode_table
[_MINIMIZE_MODE_MAX
] = {
338 [MINIMIZE_OFF
] = "off",
339 [MINIMIZE_BEST
] = "best",
340 [MINIMIZE_GUESS
] = "guess",
343 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(empty_mode
, EmptyMode
);
344 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(encrypt_mode
, EncryptMode
, ENCRYPT_KEY_FILE
);
345 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(verity_mode
, VerityMode
);
346 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(minimize_mode
, MinimizeMode
, MINIMIZE_BEST
);
348 static uint64_t round_down_size(uint64_t v
, uint64_t p
) {
352 static uint64_t round_up_size(uint64_t v
, uint64_t p
) {
354 v
= DIV_ROUND_UP(v
, p
);
356 if (v
> UINT64_MAX
/ p
)
357 return UINT64_MAX
; /* overflow */
362 static Partition
*partition_new(void) {
365 p
= new(Partition
, 1);
372 .current_size
= UINT64_MAX
,
373 .new_size
= UINT64_MAX
,
374 .size_min
= UINT64_MAX
,
375 .size_max
= UINT64_MAX
,
376 .current_padding
= UINT64_MAX
,
377 .new_padding
= UINT64_MAX
,
378 .padding_min
= UINT64_MAX
,
379 .padding_max
= UINT64_MAX
,
380 .partno
= UINT64_MAX
,
381 .offset
= UINT64_MAX
,
382 .copy_blocks_fd
= -EBADF
,
383 .copy_blocks_offset
= UINT64_MAX
,
384 .copy_blocks_size
= UINT64_MAX
,
388 .verity_data_block_size
= UINT64_MAX
,
389 .verity_hash_block_size
= UINT64_MAX
,
395 static Partition
* partition_free(Partition
*p
) {
399 free(p
->current_label
);
401 free(p
->definition_path
);
402 strv_free(p
->drop_in_files
);
404 if (p
->current_partition
)
405 fdisk_unref_partition(p
->current_partition
);
406 if (p
->new_partition
)
407 fdisk_unref_partition(p
->new_partition
);
409 if (p
->copy_blocks_path_is_our_file
)
410 unlink_and_free(p
->copy_blocks_path
);
412 free(p
->copy_blocks_path
);
413 safe_close(p
->copy_blocks_fd
);
416 strv_free(p
->copy_files
);
417 strv_free(p
->exclude_files_source
);
418 strv_free(p
->exclude_files_target
);
419 strv_free(p
->make_directories
);
420 strv_free(p
->subvolumes
);
421 free(p
->verity_match_key
);
423 iovec_done(&p
->roothash
);
425 free(p
->split_name_format
);
426 unlink_and_free(p
->split_path
);
431 static void partition_foreignize(Partition
*p
) {
433 assert(PARTITION_EXISTS(p
));
435 /* Reset several parameters set through definition file to make the partition foreign. */
437 p
->definition_path
= mfree(p
->definition_path
);
438 p
->drop_in_files
= strv_free(p
->drop_in_files
);
440 p
->copy_blocks_path
= mfree(p
->copy_blocks_path
);
441 p
->copy_blocks_fd
= safe_close(p
->copy_blocks_fd
);
442 p
->copy_blocks_root
= NULL
;
444 p
->format
= mfree(p
->format
);
445 p
->copy_files
= strv_free(p
->copy_files
);
446 p
->exclude_files_source
= strv_free(p
->exclude_files_source
);
447 p
->exclude_files_target
= strv_free(p
->exclude_files_target
);
448 p
->make_directories
= strv_free(p
->make_directories
);
449 p
->subvolumes
= strv_free(p
->subvolumes
);
450 p
->verity_match_key
= mfree(p
->verity_match_key
);
454 p
->padding_weight
= 0;
455 p
->size_min
= UINT64_MAX
;
456 p
->size_max
= UINT64_MAX
;
457 p
->padding_min
= UINT64_MAX
;
458 p
->padding_max
= UINT64_MAX
;
462 p
->verity
= VERITY_OFF
;
465 static bool partition_type_exclude(const GptPartitionType
*type
) {
466 if (arg_filter_partitions_type
== FILTER_PARTITIONS_NONE
)
469 for (size_t i
= 0; i
< arg_n_filter_partitions
; i
++)
470 if (sd_id128_equal(type
->uuid
, arg_filter_partitions
[i
].uuid
))
471 return arg_filter_partitions_type
== FILTER_PARTITIONS_EXCLUDE
;
473 return arg_filter_partitions_type
== FILTER_PARTITIONS_INCLUDE
;
476 static bool partition_type_defer(const GptPartitionType
*type
) {
477 for (size_t i
= 0; i
< arg_n_defer_partitions
; i
++)
478 if (sd_id128_equal(type
->uuid
, arg_defer_partitions
[i
].uuid
))
484 static Partition
* partition_unlink_and_free(Context
*context
, Partition
*p
) {
488 LIST_REMOVE(partitions
, context
->partitions
, p
);
490 assert(context
->n_partitions
> 0);
491 context
->n_partitions
--;
493 return partition_free(p
);
496 DEFINE_TRIVIAL_CLEANUP_FUNC(Partition
*, partition_free
);
498 static Context
*context_new(sd_id128_t seed
) {
501 context
= new(Context
, 1);
505 *context
= (Context
) {
515 static void context_free_free_areas(Context
*context
) {
518 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
519 free(context
->free_areas
[i
]);
521 context
->free_areas
= mfree(context
->free_areas
);
522 context
->n_free_areas
= 0;
525 static Context
*context_free(Context
*context
) {
529 while (context
->partitions
)
530 partition_unlink_and_free(context
, context
->partitions
);
531 assert(context
->n_partitions
== 0);
533 context_free_free_areas(context
);
535 if (context
->fdisk_context
)
536 fdisk_unref_context(context
->fdisk_context
);
538 safe_close(context
->backing_fd
);
539 if (context
->node_is_our_file
)
540 unlink_and_free(context
->node
);
544 return mfree(context
);
547 DEFINE_TRIVIAL_CLEANUP_FUNC(Context
*, context_free
);
549 static int context_add_free_area(
557 assert(!after
|| !after
->padding_area
);
559 if (!GREEDY_REALLOC(context
->free_areas
, context
->n_free_areas
+ 1))
562 a
= new(FreeArea
, 1);
571 context
->free_areas
[context
->n_free_areas
++] = a
;
574 after
->padding_area
= a
;
579 static void partition_drop_or_foreignize(Partition
*p
) {
580 if (!p
|| p
->dropped
|| PARTITION_IS_FOREIGN(p
))
583 if (PARTITION_EXISTS(p
)) {
584 log_info("Can't grow existing partition %s of priority %" PRIi32
", ignoring.",
585 strna(p
->current_label
?: p
->new_label
), p
->priority
);
587 /* Handle the partition as foreign. Do not set dropped flag. */
588 partition_foreignize(p
);
590 log_info("Can't fit partition %s of priority %" PRIi32
", dropping.",
591 p
->definition_path
, p
->priority
);
594 p
->allocated_to_area
= NULL
;
598 static bool context_drop_or_foreignize_one_priority(Context
*context
) {
599 int32_t priority
= 0;
601 LIST_FOREACH(partitions
, p
, context
->partitions
) {
605 priority
= MAX(priority
, p
->priority
);
608 /* Refuse to drop partitions with 0 or negative priorities or partitions of priorities that have at
609 * least one existing priority */
613 LIST_FOREACH(partitions
, p
, context
->partitions
) {
614 if (p
->priority
< priority
)
617 partition_drop_or_foreignize(p
);
619 /* We ensure that all verity sibling partitions have the same priority, so it's safe
620 * to drop all siblings here as well. */
622 for (VerityMode mode
= VERITY_OFF
+ 1; mode
< _VERITY_MODE_MAX
; mode
++)
623 partition_drop_or_foreignize(p
->siblings
[mode
]);
629 static uint64_t partition_min_size(const Context
*context
, const Partition
*p
) {
635 /* Calculate the disk space we really need at minimum for this partition. If the partition already
636 * exists the current size is what we really need. If it doesn't exist yet refuse to allocate less
639 * DEFAULT_MIN_SIZE is the default SizeMin= we configure if nothing else is specified. */
641 if (PARTITION_IS_FOREIGN(p
)) {
642 /* Don't allow changing size of partitions not managed by us */
643 assert(p
->current_size
!= UINT64_MAX
);
644 return p
->current_size
;
647 if (p
->verity
== VERITY_SIG
)
648 return VERITY_SIG_SIZE
;
650 sz
= p
->current_size
!= UINT64_MAX
? p
->current_size
: HARD_MIN_SIZE
;
652 if (!PARTITION_EXISTS(p
)) {
655 if (p
->encrypt
!= ENCRYPT_OFF
)
656 d
+= round_up_size(LUKS2_METADATA_KEEP_FREE
, context
->grain_size
);
658 if (p
->copy_blocks_size
!= UINT64_MAX
)
659 d
+= round_up_size(p
->copy_blocks_size
, context
->grain_size
);
660 else if (p
->format
|| p
->encrypt
!= ENCRYPT_OFF
) {
663 /* If we shall synthesize a file system, take minimal fs size into account (assumed to be 4K if not known) */
664 f
= p
->format
? round_up_size(minimal_size_by_fs_name(p
->format
), context
->grain_size
) : UINT64_MAX
;
665 d
+= f
== UINT64_MAX
? context
->grain_size
: f
;
672 return MAX(round_up_size(p
->size_min
!= UINT64_MAX
? p
->size_min
: DEFAULT_MIN_SIZE
, context
->grain_size
), sz
);
675 static uint64_t partition_max_size(const Context
*context
, const Partition
*p
) {
678 /* Calculate how large the partition may become at max. This is generally the configured maximum
679 * size, except when it already exists and is larger than that. In that case it's the existing size,
680 * since we never want to shrink partitions. */
685 if (PARTITION_IS_FOREIGN(p
)) {
686 /* Don't allow changing size of partitions not managed by us */
687 assert(p
->current_size
!= UINT64_MAX
);
688 return p
->current_size
;
691 if (p
->verity
== VERITY_SIG
)
692 return VERITY_SIG_SIZE
;
694 if (p
->size_max
== UINT64_MAX
)
697 sm
= round_down_size(p
->size_max
, context
->grain_size
);
699 if (p
->current_size
!= UINT64_MAX
)
700 sm
= MAX(p
->current_size
, sm
);
702 return MAX(partition_min_size(context
, p
), sm
);
705 static uint64_t partition_min_padding(const Partition
*p
) {
707 return p
->padding_min
!= UINT64_MAX
? p
->padding_min
: 0;
710 static uint64_t partition_max_padding(const Partition
*p
) {
712 return p
->padding_max
;
715 static uint64_t partition_min_size_with_padding(Context
*context
, const Partition
*p
) {
718 /* Calculate the disk space we need for this partition plus any free space coming after it. This
719 * takes user configured padding into account as well as any additional whitespace needed to align
720 * the next partition to 4K again. */
725 sz
= partition_min_size(context
, p
) + partition_min_padding(p
);
727 if (PARTITION_EXISTS(p
)) {
728 /* If the partition wasn't aligned, add extra space so that any we might add will be aligned */
729 assert(p
->offset
!= UINT64_MAX
);
730 return round_up_size(p
->offset
+ sz
, context
->grain_size
) - p
->offset
;
733 /* If this is a new partition we'll place it aligned, hence we just need to round up the required size here */
734 return round_up_size(sz
, context
->grain_size
);
737 static uint64_t free_area_available(const FreeArea
*a
) {
740 /* Determines how much of this free area is not allocated yet */
742 assert(a
->size
>= a
->allocated
);
743 return a
->size
- a
->allocated
;
746 static uint64_t free_area_current_end(Context
*context
, const FreeArea
*a
) {
751 return free_area_available(a
);
753 assert(a
->after
->offset
!= UINT64_MAX
);
754 assert(a
->after
->current_size
!= UINT64_MAX
);
756 /* Calculate where the free area ends, based on the offset of the partition preceding it. */
757 return round_up_size(a
->after
->offset
+ a
->after
->current_size
, context
->grain_size
) + free_area_available(a
);
760 static uint64_t free_area_min_end(Context
*context
, const FreeArea
*a
) {
767 assert(a
->after
->offset
!= UINT64_MAX
);
768 assert(a
->after
->current_size
!= UINT64_MAX
);
770 /* Calculate where the partition would end when we give it as much as it needs. */
771 return round_up_size(a
->after
->offset
+ partition_min_size_with_padding(context
, a
->after
), context
->grain_size
);
774 static uint64_t free_area_available_for_new_partitions(Context
*context
, const FreeArea
*a
) {
778 /* Similar to free_area_available(), but takes into account that the required size and padding of the
779 * preceding partition is honoured. */
781 return LESS_BY(free_area_current_end(context
, a
), free_area_min_end(context
, a
));
784 static int free_area_compare(FreeArea
*const *a
, FreeArea
*const*b
, Context
*context
) {
787 return CMP(free_area_available_for_new_partitions(context
, *a
),
788 free_area_available_for_new_partitions(context
, *b
));
791 static uint64_t charge_size(Context
*context
, uint64_t total
, uint64_t amount
) {
793 /* Subtract the specified amount from total, rounding up to multiple of 4K if there's room */
794 assert(amount
<= total
);
795 return LESS_BY(total
, round_up_size(amount
, context
->grain_size
));
798 static uint64_t charge_weight(uint64_t total
, uint64_t amount
) {
799 assert(amount
<= total
);
800 return total
- amount
;
803 static bool context_allocate_partitions(Context
*context
, uint64_t *ret_largest_free_area
) {
806 /* This may be called multiple times. Reset previous assignments. */
807 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
808 context
->free_areas
[i
]->allocated
= 0;
810 /* Sort free areas by size, putting smallest first */
811 typesafe_qsort_r(context
->free_areas
, context
->n_free_areas
, free_area_compare
, context
);
813 /* In any case return size of the largest free area (i.e. not the size of all free areas
815 if (ret_largest_free_area
)
816 *ret_largest_free_area
=
817 context
->n_free_areas
== 0 ? 0 :
818 free_area_available_for_new_partitions(context
, context
->free_areas
[context
->n_free_areas
-1]);
820 /* Check that each existing partition can fit its area. */
821 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
822 if (free_area_current_end(context
, context
->free_areas
[i
]) <
823 free_area_min_end(context
, context
->free_areas
[i
]))
826 /* A simple first-fit algorithm. We return true if we can fit the partitions in, otherwise false. */
827 LIST_FOREACH(partitions
, p
, context
->partitions
) {
832 /* Skip partitions we already dropped or that already exist */
833 if (p
->dropped
|| PARTITION_EXISTS(p
))
836 /* How much do we need to fit? */
837 required
= partition_min_size_with_padding(context
, p
);
838 assert(required
% context
->grain_size
== 0);
840 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
841 a
= context
->free_areas
[i
];
843 if (free_area_available_for_new_partitions(context
, a
) >= required
) {
850 return false; /* 😢 Oh no! We can't fit this partition into any free area! */
852 /* Assign the partition to this free area */
853 p
->allocated_to_area
= a
;
855 /* Budget the minimal partition size */
856 a
->allocated
+= required
;
862 static int context_sum_weights(Context
*context
, FreeArea
*a
, uint64_t *ret
) {
863 uint64_t weight_sum
= 0;
869 /* Determine the sum of the weights of all partitions placed in or before the specified free area */
871 LIST_FOREACH(partitions
, p
, context
->partitions
) {
872 if (p
->padding_area
!= a
&& p
->allocated_to_area
!= a
)
875 if (p
->weight
> UINT64_MAX
- weight_sum
)
877 weight_sum
+= p
->weight
;
879 if (p
->padding_weight
> UINT64_MAX
- weight_sum
)
881 weight_sum
+= p
->padding_weight
;
888 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Combined weight of partition exceeds unsigned 64-bit range, refusing.");
891 static uint64_t scale_by_weight(uint64_t value
, uint64_t weight
, uint64_t weight_sum
) {
892 assert(weight_sum
>= weight
);
897 if (weight
== weight_sum
)
899 if (value
<= UINT64_MAX
/ weight
)
900 return value
* weight
/ weight_sum
;
902 /* Rescale weight and weight_sum to make not the calculation overflow. To satisfy the
903 * following conditions, 'weight_sum' is rounded up but 'weight' is rounded down:
904 * - the sum of scale_by_weight() for all weights must not be larger than the input value,
905 * - scale_by_weight() must not be larger than the ideal value (i.e. calculated with uint128_t). */
906 weight_sum
= DIV_ROUND_UP(weight_sum
, 2);
911 typedef enum GrowPartitionPhase
{
912 /* The zeroth phase: do not touch foreign partitions (i.e. those we don't manage). */
915 /* The first phase: we charge partitions which need more (according to constraints) than their weight-based share. */
918 /* The second phase: we charge partitions which need less (according to constraints) than their weight-based share. */
921 /* The third phase: we distribute what remains among the remaining partitions, according to the weights */
924 _GROW_PARTITION_PHASE_MAX
,
925 } GrowPartitionPhase
;
927 static bool context_grow_partitions_phase(
930 GrowPartitionPhase phase
,
932 uint64_t *weight_sum
) {
934 bool try_again
= false;
941 /* Now let's look at the intended weights and adjust them taking the minimum space assignments into
942 * account. i.e. if a partition has a small weight but a high minimum space value set it should not
943 * get any additional room from the left-overs. Similar, if two partitions have the same weight they
944 * should get the same space if possible, even if one has a smaller minimum size than the other. */
945 LIST_FOREACH(partitions
, p
, context
->partitions
) {
947 /* Look only at partitions associated with this free area, i.e. immediately
948 * preceding it, or allocated into it */
949 if (p
->allocated_to_area
!= a
&& p
->padding_area
!= a
)
952 if (p
->new_size
== UINT64_MAX
) {
953 uint64_t share
, rsz
, xsz
;
956 /* Calculate how much this space this partition needs if everyone would get
957 * the weight based share */
958 share
= scale_by_weight(*span
, p
->weight
, *weight_sum
);
960 rsz
= partition_min_size(context
, p
);
961 xsz
= partition_max_size(context
, p
);
963 if (phase
== PHASE_FOREIGN
&& PARTITION_IS_FOREIGN(p
)) {
964 /* Never change of foreign partitions (i.e. those we don't manage) */
966 p
->new_size
= p
->current_size
;
969 } else if (phase
== PHASE_OVERCHARGE
&& rsz
> share
) {
970 /* This partition needs more than its calculated share. Let's assign
971 * it that, and take this partition out of all calculations and start
975 charge
= try_again
= true;
977 } else if (phase
== PHASE_UNDERCHARGE
&& xsz
< share
) {
978 /* This partition accepts less than its calculated
979 * share. Let's assign it that, and take this partition out
980 * of all calculations and start again. */
983 charge
= try_again
= true;
985 } else if (phase
== PHASE_DISTRIBUTE
) {
986 /* This partition can accept its calculated share. Let's
987 * assign it. There's no need to restart things here since
988 * assigning this shouldn't impact the shares of the other
991 assert(share
>= rsz
);
992 p
->new_size
= CLAMP(round_down_size(share
, context
->grain_size
), rsz
, xsz
);
997 *span
= charge_size(context
, *span
, p
->new_size
);
998 *weight_sum
= charge_weight(*weight_sum
, p
->weight
);
1002 if (p
->new_padding
== UINT64_MAX
) {
1003 uint64_t share
, rsz
, xsz
;
1004 bool charge
= false;
1006 share
= scale_by_weight(*span
, p
->padding_weight
, *weight_sum
);
1008 rsz
= partition_min_padding(p
);
1009 xsz
= partition_max_padding(p
);
1011 if (phase
== PHASE_OVERCHARGE
&& rsz
> share
) {
1012 p
->new_padding
= rsz
;
1013 charge
= try_again
= true;
1014 } else if (phase
== PHASE_UNDERCHARGE
&& xsz
< share
) {
1015 p
->new_padding
= xsz
;
1016 charge
= try_again
= true;
1017 } else if (phase
== PHASE_DISTRIBUTE
) {
1018 assert(share
>= rsz
);
1019 p
->new_padding
= CLAMP(round_down_size(share
, context
->grain_size
), rsz
, xsz
);
1024 *span
= charge_size(context
, *span
, p
->new_padding
);
1025 *weight_sum
= charge_weight(*weight_sum
, p
->padding_weight
);
1033 static void context_grow_partition_one(Context
*context
, FreeArea
*a
, Partition
*p
, uint64_t *span
) {
1044 if (p
->allocated_to_area
!= a
)
1047 if (PARTITION_IS_FOREIGN(p
))
1050 assert(p
->new_size
!= UINT64_MAX
);
1052 /* Calculate new size and align. */
1053 m
= round_down_size(p
->new_size
+ *span
, context
->grain_size
);
1054 /* But ensure this doesn't shrink the size. */
1055 m
= MAX(m
, p
->new_size
);
1056 /* And ensure this doesn't exceed the maximum size. */
1057 m
= MIN(m
, partition_max_size(context
, p
));
1059 assert(m
>= p
->new_size
);
1061 *span
= charge_size(context
, *span
, m
- p
->new_size
);
1065 static int context_grow_partitions_on_free_area(Context
*context
, FreeArea
*a
) {
1066 uint64_t weight_sum
= 0, span
;
1072 r
= context_sum_weights(context
, a
, &weight_sum
);
1076 /* Let's calculate the total area covered by this free area and the partition before it */
1079 assert(a
->after
->offset
!= UINT64_MAX
);
1080 assert(a
->after
->current_size
!= UINT64_MAX
);
1082 span
+= round_up_size(a
->after
->offset
+ a
->after
->current_size
, context
->grain_size
) - a
->after
->offset
;
1085 for (GrowPartitionPhase phase
= 0; phase
< _GROW_PARTITION_PHASE_MAX
;)
1086 if (context_grow_partitions_phase(context
, a
, phase
, &span
, &weight_sum
))
1087 phase
++; /* go to the next phase */
1089 /* We still have space left over? Donate to preceding partition if we have one */
1090 if (span
> 0 && a
->after
)
1091 context_grow_partition_one(context
, a
, a
->after
, &span
);
1093 /* What? Even still some space left (maybe because there was no preceding partition, or it had a
1094 * size limit), then let's donate it to whoever wants it. */
1096 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1097 context_grow_partition_one(context
, a
, p
, &span
);
1102 /* Yuck, still no one? Then make it padding */
1103 if (span
> 0 && a
->after
) {
1104 assert(a
->after
->new_padding
!= UINT64_MAX
);
1105 a
->after
->new_padding
+= span
;
1111 static int context_grow_partitions(Context
*context
) {
1116 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
1117 r
= context_grow_partitions_on_free_area(context
, context
->free_areas
[i
]);
1122 /* All existing partitions that have no free space after them can't change size */
1123 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1127 if (!PARTITION_EXISTS(p
) || p
->padding_area
) {
1128 /* The algorithm above must have initialized this already */
1129 assert(p
->new_size
!= UINT64_MAX
);
1133 assert(p
->new_size
== UINT64_MAX
);
1134 p
->new_size
= p
->current_size
;
1136 assert(p
->new_padding
== UINT64_MAX
);
1137 p
->new_padding
= p
->current_padding
;
1143 static uint64_t find_first_unused_partno(Context
*context
) {
1144 uint64_t partno
= 0;
1148 for (partno
= 0;; partno
++) {
1150 LIST_FOREACH(partitions
, p
, context
->partitions
)
1151 if (p
->partno
!= UINT64_MAX
&& p
->partno
== partno
)
1160 static void context_place_partitions(Context
*context
) {
1164 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
1165 FreeArea
*a
= context
->free_areas
[i
];
1166 _unused_
uint64_t left
;
1170 assert(a
->after
->offset
!= UINT64_MAX
);
1171 assert(a
->after
->new_size
!= UINT64_MAX
);
1172 assert(a
->after
->new_padding
!= UINT64_MAX
);
1174 start
= a
->after
->offset
+ a
->after
->new_size
+ a
->after
->new_padding
;
1176 start
= context
->start
;
1178 start
= round_up_size(start
, context
->grain_size
);
1181 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1182 if (p
->allocated_to_area
!= a
)
1186 p
->partno
= find_first_unused_partno(context
);
1188 assert(left
>= p
->new_size
);
1189 start
+= p
->new_size
;
1190 left
-= p
->new_size
;
1192 assert(left
>= p
->new_padding
);
1193 start
+= p
->new_padding
;
1194 left
-= p
->new_padding
;
1199 static int config_parse_type(
1201 const char *filename
,
1203 const char *section
,
1204 unsigned section_line
,
1211 GptPartitionType
*type
= ASSERT_PTR(data
);
1216 r
= gpt_partition_type_from_string(rvalue
, type
);
1218 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to parse partition type: %s", rvalue
);
1220 if (arg_architecture
>= 0)
1221 *type
= gpt_partition_type_override_architecture(*type
, arg_architecture
);
1226 static int config_parse_label(
1228 const char *filename
,
1230 const char *section
,
1231 unsigned section_line
,
1238 _cleanup_free_
char *resolved
= NULL
;
1239 char **label
= ASSERT_PTR(data
);
1244 /* Nota bene: the empty label is a totally valid one. Let's hence not follow our usual rule of
1245 * assigning the empty string to reset to default here, but really accept it as label to set. */
1247 r
= specifier_printf(rvalue
, GPT_LABEL_MAX
, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved
);
1249 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1250 "Failed to expand specifiers in Label=, ignoring: %s", rvalue
);
1254 if (!utf8_is_valid(resolved
)) {
1255 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1256 "Partition label not valid UTF-8, ignoring: %s", rvalue
);
1260 r
= gpt_partition_label_valid(resolved
);
1262 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1263 "Failed to check if string is valid as GPT partition label, ignoring: \"%s\" (from \"%s\")",
1268 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1269 "Partition label too long for GPT table, ignoring: \"%s\" (from \"%s\")",
1274 free_and_replace(*label
, resolved
);
1278 static int config_parse_weight(
1280 const char *filename
,
1282 const char *section
,
1283 unsigned section_line
,
1290 uint32_t *w
= ASSERT_PTR(data
), v
;
1295 r
= safe_atou32(rvalue
, &v
);
1297 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1298 "Failed to parse weight value, ignoring: %s", rvalue
);
1302 if (v
> 1000U*1000U) {
1303 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1304 "Weight needs to be in range 0…10000000, ignoring: %" PRIu32
, v
);
1312 static int config_parse_size4096(
1314 const char *filename
,
1316 const char *section
,
1317 unsigned section_line
,
1324 uint64_t *sz
= data
, parsed
;
1330 r
= parse_size(rvalue
, 1024, &parsed
);
1332 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
,
1333 "Failed to parse size value: %s", rvalue
);
1336 *sz
= round_up_size(parsed
, 4096);
1338 *sz
= round_down_size(parsed
, 4096);
1343 log_syntax(unit
, LOG_NOTICE
, filename
, line
, r
, "Rounded %s= size %" PRIu64
" %s %" PRIu64
", a multiple of 4096.",
1344 lvalue
, parsed
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), *sz
);
1349 static int config_parse_block_size(
1351 const char *filename
,
1353 const char *section
,
1354 unsigned section_line
,
1361 uint64_t *blksz
= ASSERT_PTR(data
), parsed
;
1366 r
= parse_size(rvalue
, 1024, &parsed
);
1368 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
,
1369 "Failed to parse size value: %s", rvalue
);
1371 if (parsed
< 512 || parsed
> 4096)
1372 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1373 "Value not between 512 and 4096: %s", rvalue
);
1375 if (!ISPOWEROF2(parsed
))
1376 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1377 "Value not a power of 2: %s", rvalue
);
1383 static int config_parse_fstype(
1385 const char *filename
,
1387 const char *section
,
1388 unsigned section_line
,
1395 char **fstype
= ASSERT_PTR(data
);
1400 /* Let's provide an easy way to override the chosen fstype for file system partitions */
1401 e
= secure_getenv("SYSTEMD_REPART_OVERRIDE_FSTYPE");
1402 if (e
&& !streq(rvalue
, e
)) {
1403 log_syntax(unit
, LOG_NOTICE
, filename
, line
, 0,
1404 "Overriding defined file system type '%s' with '%s'.", rvalue
, e
);
1408 if (!filename_is_valid(rvalue
))
1409 return log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1410 "File system type is not valid, refusing: %s", rvalue
);
1412 return free_and_strdup_warn(fstype
, rvalue
);
1415 static int config_parse_copy_files(
1417 const char *filename
,
1419 const char *section
,
1420 unsigned section_line
,
1427 _cleanup_free_
char *source
= NULL
, *buffer
= NULL
, *resolved_source
= NULL
, *resolved_target
= NULL
;
1428 const char *p
= rvalue
, *target
;
1429 char ***copy_files
= ASSERT_PTR(data
);
1434 r
= extract_first_word(&p
, &source
, ":", EXTRACT_CUNESCAPE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
1436 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to extract source path: %s", rvalue
);
1438 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0, "No argument specified: %s", rvalue
);
1442 r
= extract_first_word(&p
, &buffer
, ":", EXTRACT_CUNESCAPE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
1444 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to extract target path: %s", rvalue
);
1446 target
= source
; /* No target, then it's the same as the source */
1451 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
), "Too many arguments: %s", rvalue
);
1453 r
= specifier_printf(source
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_source
);
1455 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1456 "Failed to expand specifiers in CopyFiles= source, ignoring: %s", rvalue
);
1460 r
= path_simplify_and_warn(resolved_source
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1464 r
= specifier_printf(target
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_target
);
1466 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1467 "Failed to expand specifiers in CopyFiles= target, ignoring: %s", resolved_target
);
1471 r
= path_simplify_and_warn(resolved_target
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1475 r
= strv_consume_pair(copy_files
, TAKE_PTR(resolved_source
), TAKE_PTR(resolved_target
));
1482 static int config_parse_exclude_files(
1484 const char *filename
,
1486 const char *section
,
1487 unsigned section_line
,
1493 _cleanup_free_
char *resolved
= NULL
;
1494 char ***exclude_files
= ASSERT_PTR(data
);
1497 if (isempty(rvalue
)) {
1498 *exclude_files
= strv_free(*exclude_files
);
1502 r
= specifier_printf(rvalue
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved
);
1504 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1505 "Failed to expand specifiers in ExcludeFiles= path, ignoring: %s", rvalue
);
1509 r
= path_simplify_and_warn(resolved
, PATH_CHECK_ABSOLUTE
|PATH_KEEP_TRAILING_SLASH
, unit
, filename
, line
, lvalue
);
1513 if (strv_consume(exclude_files
, TAKE_PTR(resolved
)) < 0)
1519 static int config_parse_copy_blocks(
1521 const char *filename
,
1523 const char *section
,
1524 unsigned section_line
,
1531 _cleanup_free_
char *d
= NULL
;
1532 Partition
*partition
= ASSERT_PTR(data
);
1537 if (isempty(rvalue
)) {
1538 partition
->copy_blocks_path
= mfree(partition
->copy_blocks_path
);
1539 partition
->copy_blocks_auto
= false;
1543 if (streq(rvalue
, "auto")) {
1544 partition
->copy_blocks_path
= mfree(partition
->copy_blocks_path
);
1545 partition
->copy_blocks_auto
= true;
1546 partition
->copy_blocks_root
= arg_root
;
1550 r
= specifier_printf(rvalue
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &d
);
1552 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1553 "Failed to expand specifiers in CopyBlocks= source path, ignoring: %s", rvalue
);
1557 r
= path_simplify_and_warn(d
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1561 free_and_replace(partition
->copy_blocks_path
, d
);
1562 partition
->copy_blocks_auto
= false;
1563 partition
->copy_blocks_root
= arg_root
;
1567 static int config_parse_make_dirs(
1569 const char *filename
,
1571 const char *section
,
1572 unsigned section_line
,
1579 char ***sv
= ASSERT_PTR(data
);
1580 const char *p
= ASSERT_PTR(rvalue
);
1584 _cleanup_free_
char *word
= NULL
, *d
= NULL
;
1586 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_UNQUOTE
);
1590 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Invalid syntax, ignoring: %s", rvalue
);
1596 r
= specifier_printf(word
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &d
);
1598 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1599 "Failed to expand specifiers in MakeDirectories= parameter, ignoring: %s", word
);
1603 r
= path_simplify_and_warn(d
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1607 r
= strv_consume(sv
, TAKE_PTR(d
));
1613 static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_encrypt
, encrypt_mode
, EncryptMode
, ENCRYPT_OFF
, "Invalid encryption mode");
1615 static int config_parse_gpt_flags(
1617 const char *filename
,
1619 const char *section
,
1620 unsigned section_line
,
1627 uint64_t *gpt_flags
= ASSERT_PTR(data
);
1632 r
= safe_atou64(rvalue
, gpt_flags
);
1634 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1635 "Failed to parse Flags= value, ignoring: %s", rvalue
);
1642 static int config_parse_uuid(
1644 const char *filename
,
1646 const char *section
,
1647 unsigned section_line
,
1654 Partition
*partition
= ASSERT_PTR(data
);
1657 if (isempty(rvalue
)) {
1658 partition
->new_uuid
= SD_ID128_NULL
;
1659 partition
->new_uuid_is_set
= false;
1663 if (streq(rvalue
, "null")) {
1664 partition
->new_uuid
= SD_ID128_NULL
;
1665 partition
->new_uuid_is_set
= true;
1669 r
= sd_id128_from_string(rvalue
, &partition
->new_uuid
);
1671 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse 128-bit ID/UUID, ignoring: %s", rvalue
);
1675 partition
->new_uuid_is_set
= true;
1680 static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_verity
, verity_mode
, VerityMode
, VERITY_OFF
, "Invalid verity mode");
1681 static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_minimize
, minimize_mode
, MinimizeMode
, MINIMIZE_OFF
, "Invalid minimize mode");
1683 static int partition_read_definition(Partition
*p
, const char *path
, const char *const *conf_file_dirs
) {
1685 ConfigTableItem table
[] = {
1686 { "Partition", "Type", config_parse_type
, 0, &p
->type
},
1687 { "Partition", "Label", config_parse_label
, 0, &p
->new_label
},
1688 { "Partition", "UUID", config_parse_uuid
, 0, p
},
1689 { "Partition", "Priority", config_parse_int32
, 0, &p
->priority
},
1690 { "Partition", "Weight", config_parse_weight
, 0, &p
->weight
},
1691 { "Partition", "PaddingWeight", config_parse_weight
, 0, &p
->padding_weight
},
1692 { "Partition", "SizeMinBytes", config_parse_size4096
, -1, &p
->size_min
},
1693 { "Partition", "SizeMaxBytes", config_parse_size4096
, 1, &p
->size_max
},
1694 { "Partition", "PaddingMinBytes", config_parse_size4096
, -1, &p
->padding_min
},
1695 { "Partition", "PaddingMaxBytes", config_parse_size4096
, 1, &p
->padding_max
},
1696 { "Partition", "FactoryReset", config_parse_bool
, 0, &p
->factory_reset
},
1697 { "Partition", "CopyBlocks", config_parse_copy_blocks
, 0, p
},
1698 { "Partition", "Format", config_parse_fstype
, 0, &p
->format
},
1699 { "Partition", "CopyFiles", config_parse_copy_files
, 0, &p
->copy_files
},
1700 { "Partition", "ExcludeFiles", config_parse_exclude_files
, 0, &p
->exclude_files_source
},
1701 { "Partition", "ExcludeFilesTarget", config_parse_exclude_files
, 0, &p
->exclude_files_target
},
1702 { "Partition", "MakeDirectories", config_parse_make_dirs
, 0, &p
->make_directories
},
1703 { "Partition", "Encrypt", config_parse_encrypt
, 0, &p
->encrypt
},
1704 { "Partition", "Verity", config_parse_verity
, 0, &p
->verity
},
1705 { "Partition", "VerityMatchKey", config_parse_string
, 0, &p
->verity_match_key
},
1706 { "Partition", "Flags", config_parse_gpt_flags
, 0, &p
->gpt_flags
},
1707 { "Partition", "ReadOnly", config_parse_tristate
, 0, &p
->read_only
},
1708 { "Partition", "NoAuto", config_parse_tristate
, 0, &p
->no_auto
},
1709 { "Partition", "GrowFileSystem", config_parse_tristate
, 0, &p
->growfs
},
1710 { "Partition", "SplitName", config_parse_string
, 0, &p
->split_name_format
},
1711 { "Partition", "Minimize", config_parse_minimize
, 0, &p
->minimize
},
1712 { "Partition", "Subvolumes", config_parse_make_dirs
, 0, &p
->subvolumes
},
1713 { "Partition", "VerityDataBlockSizeBytes", config_parse_block_size
, 0, &p
->verity_data_block_size
},
1714 { "Partition", "VerityHashBlockSizeBytes", config_parse_block_size
, 0, &p
->verity_hash_block_size
},
1718 _cleanup_free_
char *filename
= NULL
;
1719 const char* dropin_dirname
;
1721 r
= path_extract_filename(path
, &filename
);
1723 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1725 dropin_dirname
= strjoina(filename
, ".d");
1727 r
= config_parse_many(
1728 STRV_MAKE_CONST(path
),
1731 arg_definitions
? NULL
: arg_root
,
1733 config_item_table_lookup
, table
,
1741 if (partition_type_exclude(&p
->type
))
1744 if (p
->size_min
!= UINT64_MAX
&& p
->size_max
!= UINT64_MAX
&& p
->size_min
> p
->size_max
)
1745 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1746 "SizeMinBytes= larger than SizeMaxBytes=, refusing.");
1748 if (p
->padding_min
!= UINT64_MAX
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_min
> p
->padding_max
)
1749 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1750 "PaddingMinBytes= larger than PaddingMaxBytes=, refusing.");
1752 if (sd_id128_is_null(p
->type
.uuid
))
1753 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1754 "Type= not defined, refusing.");
1756 if ((p
->copy_blocks_path
|| p
->copy_blocks_auto
) &&
1757 (p
->format
|| !strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
)))
1758 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1759 "Format=/CopyFiles=/MakeDirectories= and CopyBlocks= cannot be combined, refusing.");
1761 if ((!strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
)) && streq_ptr(p
->format
, "swap"))
1762 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1763 "Format=swap and CopyFiles= cannot be combined, refusing.");
1766 const char *format
= NULL
;
1768 if (!strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
) || (p
->encrypt
!= ENCRYPT_OFF
&& !(p
->copy_blocks_path
|| p
->copy_blocks_auto
)))
1769 /* Pick "vfat" as file system for esp and xbootldr partitions, otherwise default to "ext4". */
1770 format
= IN_SET(p
->type
.designator
, PARTITION_ESP
, PARTITION_XBOOTLDR
) ? "vfat" : "ext4";
1771 else if (p
->type
.designator
== PARTITION_SWAP
)
1775 p
->format
= strdup(format
);
1781 if (p
->minimize
!= MINIMIZE_OFF
&& !p
->format
&& p
->verity
!= VERITY_HASH
)
1782 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1783 "Minimize= can only be enabled if Format= or Verity=hash are set");
1785 if (p
->minimize
== MINIMIZE_BEST
&& (p
->format
&& !fstype_is_ro(p
->format
)) && p
->verity
!= VERITY_HASH
)
1786 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1787 "Minimize=best can only be used with read-only filesystems or Verity=hash");
1789 if ((!strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
)) && !mkfs_supports_root_option(p
->format
) && geteuid() != 0)
1790 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EPERM
),
1791 "Need to be root to populate %s filesystems with CopyFiles=/MakeDirectories=",
1794 if (p
->format
&& fstype_is_ro(p
->format
) && strv_isempty(p
->copy_files
) && strv_isempty(p
->make_directories
))
1795 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1796 "Cannot format %s filesystem without source files, refusing", p
->format
);
1798 if (p
->verity
!= VERITY_OFF
|| p
->encrypt
!= ENCRYPT_OFF
) {
1799 r
= dlopen_cryptsetup();
1801 return log_syntax(NULL
, LOG_ERR
, path
, 1, r
,
1802 "libcryptsetup not found, Verity=/Encrypt= are not supported: %m");
1805 if (p
->verity
!= VERITY_OFF
&& !p
->verity_match_key
)
1806 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1807 "VerityMatchKey= must be set if Verity=%s", verity_mode_to_string(p
->verity
));
1809 if (p
->verity
== VERITY_OFF
&& p
->verity_match_key
)
1810 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1811 "VerityMatchKey= can only be set if Verity= is not \"%s\"",
1812 verity_mode_to_string(p
->verity
));
1814 if (IN_SET(p
->verity
, VERITY_HASH
, VERITY_SIG
) &&
1815 (p
->copy_files
|| p
->copy_blocks_path
|| p
->copy_blocks_auto
|| p
->format
|| p
->make_directories
))
1816 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1817 "CopyBlocks=/CopyFiles=/Format=/MakeDirectories= cannot be used with Verity=%s",
1818 verity_mode_to_string(p
->verity
));
1820 if (p
->verity
!= VERITY_OFF
&& p
->encrypt
!= ENCRYPT_OFF
)
1821 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1822 "Encrypting verity hash/data partitions is not supported");
1824 if (p
->verity
== VERITY_SIG
&& !arg_private_key
)
1825 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1826 "Verity signature partition requested but no private key provided (--private-key=)");
1828 if (p
->verity
== VERITY_SIG
&& !arg_certificate
)
1829 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1830 "Verity signature partition requested but no PEM certificate provided (--certificate=)");
1832 if (p
->verity
== VERITY_SIG
&& (p
->size_min
!= UINT64_MAX
|| p
->size_max
!= UINT64_MAX
))
1833 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1834 "SizeMinBytes=/SizeMaxBytes= cannot be used with Verity=%s",
1835 verity_mode_to_string(p
->verity
));
1837 if (!strv_isempty(p
->subvolumes
) && arg_offline
> 0)
1838 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EOPNOTSUPP
),
1839 "Subvolumes= cannot be used with --offline=yes");
1841 /* Verity partitions are read only, let's imply the RO flag hence, unless explicitly configured otherwise. */
1842 if ((IN_SET(p
->type
.designator
,
1843 PARTITION_ROOT_VERITY
,
1844 PARTITION_USR_VERITY
) || p
->verity
== VERITY_DATA
) && p
->read_only
< 0)
1845 p
->read_only
= true;
1847 /* Default to "growfs" on, unless read-only */
1848 if (gpt_partition_type_knows_growfs(p
->type
) &&
1852 if (!p
->split_name_format
) {
1853 char *s
= strdup("%t");
1857 p
->split_name_format
= s
;
1858 } else if (streq(p
->split_name_format
, "-"))
1859 p
->split_name_format
= mfree(p
->split_name_format
);
1864 static int find_verity_sibling(Context
*context
, Partition
*p
, VerityMode mode
, Partition
**ret
) {
1865 Partition
*s
= NULL
;
1868 assert(p
->verity
!= VERITY_OFF
);
1869 assert(p
->verity_match_key
);
1870 assert(mode
!= VERITY_OFF
);
1871 assert(p
->verity
!= mode
);
1874 /* Try to find the matching sibling partition of the given type for a verity partition. For a data
1875 * partition, this is the corresponding hash partition with the same verity name (and vice versa for
1876 * the hash partition). */
1878 LIST_FOREACH(partitions
, q
, context
->partitions
) {
1882 if (q
->verity
!= mode
)
1885 assert(q
->verity_match_key
);
1887 if (!streq(p
->verity_match_key
, q
->verity_match_key
))
1904 static int context_open_and_lock_backing_fd(const char *node
, int operation
, int *backing_fd
) {
1905 _cleanup_close_
int fd
= -EBADF
;
1910 if (*backing_fd
>= 0)
1913 fd
= open(node
, O_RDONLY
|O_CLOEXEC
);
1915 return log_error_errno(errno
, "Failed to open device '%s': %m", node
);
1917 /* Tell udev not to interfere while we are processing the device */
1918 if (flock(fd
, operation
) < 0)
1919 return log_error_errno(errno
, "Failed to lock device '%s': %m", node
);
1921 log_debug("Device %s opened and locked.", node
);
1922 *backing_fd
= TAKE_FD(fd
);
1926 static int determine_current_padding(
1927 struct fdisk_context
*c
,
1928 struct fdisk_table
*t
,
1929 struct fdisk_partition
*p
,
1934 size_t n_partitions
;
1935 uint64_t offset
, next
= UINT64_MAX
;
1942 if (!fdisk_partition_has_end(p
))
1943 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition has no end!");
1945 offset
= fdisk_partition_get_end(p
);
1946 assert(offset
< UINT64_MAX
);
1947 offset
++; /* The end is one sector before the next partition or padding. */
1948 assert(offset
< UINT64_MAX
/ secsz
);
1951 n_partitions
= fdisk_table_get_nents(t
);
1952 for (size_t i
= 0; i
< n_partitions
; i
++) {
1953 struct fdisk_partition
*q
;
1956 q
= fdisk_table_get_partition(t
, i
);
1958 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1960 if (fdisk_partition_is_used(q
) <= 0)
1963 if (!fdisk_partition_has_start(q
))
1966 start
= fdisk_partition_get_start(q
);
1967 assert(start
< UINT64_MAX
/ secsz
);
1970 if (start
>= offset
&& (next
== UINT64_MAX
|| next
> start
))
1974 if (next
== UINT64_MAX
) {
1975 /* No later partition? In that case check the end of the usable area */
1976 next
= fdisk_get_last_lba(c
);
1977 assert(next
< UINT64_MAX
);
1978 next
++; /* The last LBA is one sector before the end */
1980 assert(next
< UINT64_MAX
/ secsz
);
1984 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
1987 assert(next
>= offset
);
1988 offset
= round_up_size(offset
, grainsz
);
1989 next
= round_down_size(next
, grainsz
);
1991 *ret
= LESS_BY(next
, offset
); /* Saturated subtraction, rounding might have fucked things up */
1995 static int context_copy_from_one(Context
*context
, const char *src
) {
1996 _cleanup_close_
int fd
= -EBADF
;
1997 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
1998 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
1999 Partition
*last
= NULL
;
2000 unsigned long secsz
, grainsz
;
2001 size_t n_partitions
;
2006 r
= context_open_and_lock_backing_fd(src
, LOCK_SH
, &fd
);
2010 r
= fd_verify_regular(fd
);
2012 return log_error_errno(r
, "%s is not a file: %m", src
);
2014 r
= fdisk_new_context_at(fd
, /* path = */ NULL
, /* read_only = */ true, /* sector_size = */ UINT32_MAX
, &c
);
2016 return log_error_errno(r
, "Failed to create fdisk context: %m");
2018 secsz
= fdisk_get_sector_size(c
);
2019 grainsz
= fdisk_get_grain_size(c
);
2021 /* Insist on a power of two, and that it's a multiple of 512, i.e. the traditional sector size. */
2022 if (secsz
< 512 || !ISPOWEROF2(secsz
))
2023 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Sector size %lu is not a power of two larger than 512? Refusing.", secsz
);
2025 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2026 return log_error_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Cannot copy from disk %s with no GPT disk label.", src
);
2028 r
= fdisk_get_partitions(c
, &t
);
2030 return log_error_errno(r
, "Failed to acquire partition table: %m");
2032 n_partitions
= fdisk_table_get_nents(t
);
2033 for (size_t i
= 0; i
< n_partitions
; i
++) {
2034 _cleanup_(partition_freep
) Partition
*np
= NULL
;
2035 _cleanup_free_
char *label_copy
= NULL
;
2036 struct fdisk_partition
*p
;
2038 uint64_t sz
, start
, padding
;
2039 sd_id128_t ptid
, id
;
2040 GptPartitionType type
;
2042 p
= fdisk_table_get_partition(t
, i
);
2044 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
2046 if (fdisk_partition_is_used(p
) <= 0)
2049 if (fdisk_partition_has_start(p
) <= 0 ||
2050 fdisk_partition_has_size(p
) <= 0 ||
2051 fdisk_partition_has_partno(p
) <= 0)
2052 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a position, size or number.");
2054 r
= fdisk_partition_get_type_as_id128(p
, &ptid
);
2056 return log_error_errno(r
, "Failed to query partition type UUID: %m");
2058 type
= gpt_partition_type_from_uuid(ptid
);
2060 r
= fdisk_partition_get_uuid_as_id128(p
, &id
);
2062 return log_error_errno(r
, "Failed to query partition UUID: %m");
2064 label
= fdisk_partition_get_name(p
);
2065 if (!isempty(label
)) {
2066 label_copy
= strdup(label
);
2071 sz
= fdisk_partition_get_size(p
);
2072 assert(sz
<= UINT64_MAX
/secsz
);
2075 start
= fdisk_partition_get_start(p
);
2076 assert(start
<= UINT64_MAX
/secsz
);
2079 if (partition_type_exclude(&type
))
2082 np
= partition_new();
2088 np
->new_uuid_is_set
= true;
2089 np
->size_min
= np
->size_max
= sz
;
2090 np
->new_label
= TAKE_PTR(label_copy
);
2092 np
->definition_path
= strdup(src
);
2093 if (!np
->definition_path
)
2096 r
= determine_current_padding(c
, t
, p
, secsz
, grainsz
, &padding
);
2100 np
->padding_min
= np
->padding_max
= padding
;
2102 np
->copy_blocks_path
= strdup(src
);
2103 if (!np
->copy_blocks_path
)
2106 np
->copy_blocks_fd
= fcntl(fd
, F_DUPFD_CLOEXEC
, 3);
2107 if (np
->copy_blocks_fd
< 0)
2108 return log_error_errno(r
, "Failed to duplicate file descriptor of %s: %m", src
);
2110 np
->copy_blocks_offset
= start
;
2111 np
->copy_blocks_size
= sz
;
2113 r
= fdisk_partition_get_attrs_as_uint64(p
, &np
->gpt_flags
);
2115 return log_error_errno(r
, "Failed to get partition flags: %m");
2117 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, np
);
2118 last
= TAKE_PTR(np
);
2119 context
->n_partitions
++;
2125 static int context_copy_from(Context
*context
) {
2130 STRV_FOREACH(src
, arg_copy_from
) {
2131 r
= context_copy_from_one(context
, *src
);
2139 static int context_read_definitions(Context
*context
) {
2140 _cleanup_strv_free_
char **files
= NULL
;
2141 Partition
*last
= LIST_FIND_TAIL(partitions
, context
->partitions
);
2142 const char *const *dirs
;
2147 dirs
= (const char* const*) (arg_definitions
?: CONF_PATHS_STRV("repart.d"));
2149 r
= conf_files_list_strv(&files
, ".conf", arg_definitions
? NULL
: arg_root
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, dirs
);
2151 return log_error_errno(r
, "Failed to enumerate *.conf files: %m");
2153 STRV_FOREACH(f
, files
) {
2154 _cleanup_(partition_freep
) Partition
*p
= NULL
;
2156 p
= partition_new();
2160 p
->definition_path
= strdup(*f
);
2161 if (!p
->definition_path
)
2164 r
= partition_read_definition(p
, *f
, dirs
);
2170 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, p
);
2172 context
->n_partitions
++;
2175 /* Check that each configured verity hash/data partition has a matching verity data/hash partition. */
2177 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2178 if (p
->verity
== VERITY_OFF
)
2181 for (VerityMode mode
= VERITY_OFF
+ 1; mode
< _VERITY_MODE_MAX
; mode
++) {
2182 Partition
*q
= NULL
;
2184 if (p
->verity
== mode
)
2187 if (p
->siblings
[mode
])
2190 r
= find_verity_sibling(context
, p
, mode
, &q
);
2192 if (mode
!= VERITY_SIG
)
2193 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, SYNTHETIC_ERRNO(EINVAL
),
2194 "Missing verity %s partition for verity %s partition with VerityMatchKey=%s",
2195 verity_mode_to_string(mode
), verity_mode_to_string(p
->verity
), p
->verity_match_key
);
2196 } else if (r
== -ENOTUNIQ
)
2197 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, SYNTHETIC_ERRNO(EINVAL
),
2198 "Multiple verity %s partitions found for verity %s partition with VerityMatchKey=%s",
2199 verity_mode_to_string(mode
), verity_mode_to_string(p
->verity
), p
->verity_match_key
);
2201 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, r
,
2202 "Failed to find verity %s partition for verity %s partition with VerityMatchKey=%s",
2203 verity_mode_to_string(mode
), verity_mode_to_string(p
->verity
), p
->verity_match_key
);
2206 if (q
->priority
!= p
->priority
)
2207 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, SYNTHETIC_ERRNO(EINVAL
),
2208 "Priority mismatch (%i != %i) for verity sibling partitions with VerityMatchKey=%s",
2209 p
->priority
, q
->priority
, p
->verity_match_key
);
2211 p
->siblings
[mode
] = q
;
2216 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2219 if (p
->verity
!= VERITY_HASH
)
2222 if (p
->minimize
== MINIMIZE_OFF
)
2225 assert_se(dp
= p
->siblings
[VERITY_DATA
]);
2227 if (dp
->minimize
== MINIMIZE_OFF
&& !(dp
->copy_blocks_path
|| dp
->copy_blocks_auto
))
2228 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, SYNTHETIC_ERRNO(EINVAL
),
2229 "Minimize= set for verity hash partition but data partition does "
2230 "not set CopyBlocks= or Minimize=");
2237 static int fdisk_ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *data
) {
2238 _cleanup_free_
char *ids
= NULL
;
2241 if (fdisk_ask_get_type(ask
) != FDISK_ASKTYPE_STRING
)
2244 ids
= new(char, SD_ID128_UUID_STRING_MAX
);
2248 r
= fdisk_ask_string_set_result(ask
, sd_id128_to_uuid_string(*(sd_id128_t
*) data
, ids
));
2256 static int fdisk_set_disklabel_id_by_uuid(struct fdisk_context
*c
, sd_id128_t id
) {
2259 r
= fdisk_set_ask(c
, fdisk_ask_cb
, &id
);
2263 r
= fdisk_set_disklabel_id(c
);
2267 return fdisk_set_ask(c
, NULL
, NULL
);
2270 static int derive_uuid(sd_id128_t base
, const char *token
, sd_id128_t
*ret
) {
2272 uint8_t md
[SHA256_DIGEST_SIZE
];
2279 /* Derive a new UUID from the specified UUID in a stable and reasonably safe way. Specifically, we
2280 * calculate the HMAC-SHA256 of the specified token string, keyed by the supplied base (typically the
2281 * machine ID). We use the machine ID as key (and not as cleartext!) of the HMAC operation since it's
2282 * the machine ID we don't want to leak. */
2284 hmac_sha256(base
.bytes
, sizeof(base
.bytes
), token
, strlen(token
), result
.md
);
2286 /* Take the first half, mark it as v4 UUID */
2287 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
2288 *ret
= id128_make_v4_uuid(result
.id
);
2292 static void derive_salt(sd_id128_t base
, const char *token
, uint8_t ret
[static SHA256_DIGEST_SIZE
]) {
2295 hmac_sha256(base
.bytes
, sizeof(base
.bytes
), token
, strlen(token
), ret
);
2298 static int context_load_partition_table(Context
*context
) {
2299 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2300 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
2301 uint64_t left_boundary
= UINT64_MAX
, first_lba
, last_lba
, nsectors
;
2302 _cleanup_free_
char *disk_uuid_string
= NULL
;
2303 bool from_scratch
= false;
2304 sd_id128_t disk_uuid
;
2305 size_t n_partitions
;
2306 unsigned long secsz
;
2307 uint64_t grainsz
, fs_secsz
= DEFAULT_FILESYSTEM_SECTOR_SIZE
;
2311 assert(!context
->fdisk_context
);
2312 assert(!context
->free_areas
);
2313 assert(context
->start
== UINT64_MAX
);
2314 assert(context
->end
== UINT64_MAX
);
2315 assert(context
->total
== UINT64_MAX
);
2317 c
= fdisk_new_context();
2321 if (arg_sector_size
> 0) {
2322 fs_secsz
= arg_sector_size
;
2323 r
= fdisk_save_user_sector_size(c
, /* phy= */ 0, arg_sector_size
);
2328 r
= context_open_and_lock_backing_fd(context
->node
, arg_dry_run
? LOCK_SH
: LOCK_EX
,
2329 &context
->backing_fd
);
2333 if (fstat(context
->backing_fd
, &st
) < 0)
2334 return log_error_errno(r
, "Failed to stat %s: %m", context
->node
);
2336 /* Auto-detect sector size if not specified. */
2337 r
= probe_sector_size_prefer_ioctl(context
->backing_fd
, &ssz
);
2339 return log_error_errno(r
, "Failed to probe sector size of '%s': %m", context
->node
);
2341 /* If we found the sector size and we're operating on a block device, use it as the file
2342 * system sector size as well, as we know its the sector size of the actual block device and
2343 * not just the offset at which we found the GPT header. */
2344 if (r
> 0 && S_ISBLK(st
.st_mode
))
2347 r
= fdisk_save_user_sector_size(c
, /* phy= */ 0, ssz
);
2350 return log_error_errno(r
, "Failed to set sector size: %m");
2352 /* libfdisk doesn't have an API to operate on arbitrary fds, hence reopen the fd going via the
2353 * /proc/self/fd/ magic path if we have an existing fd. Open the original file otherwise. */
2354 r
= fdisk_assign_device(
2356 context
->backing_fd
>= 0 ? FORMAT_PROC_FD_PATH(context
->backing_fd
) : context
->node
,
2358 if (r
== -EINVAL
&& arg_size_auto
) {
2361 /* libfdisk returns EINVAL if opening a file of size zero. Let's check for that, and accept
2362 * it if automatic sizing is requested. */
2364 if (context
->backing_fd
< 0)
2365 r
= stat(context
->node
, &st
);
2367 r
= fstat(context
->backing_fd
, &st
);
2369 return log_error_errno(errno
, "Failed to stat block device '%s': %m", context
->node
);
2371 if (S_ISREG(st
.st_mode
) && st
.st_size
== 0) {
2372 /* Use the fallback values if we have no better idea */
2373 context
->sector_size
= fdisk_get_sector_size(c
);
2374 context
->fs_sector_size
= fs_secsz
;
2375 context
->grain_size
= 4096;
2376 return /* from_scratch = */ true;
2382 return log_error_errno(r
, "Failed to open device '%s': %m", context
->node
);
2384 if (context
->backing_fd
< 0) {
2385 /* If we have no fd referencing the device yet, make a copy of the fd now, so that we have one */
2386 r
= context_open_and_lock_backing_fd(FORMAT_PROC_FD_PATH(fdisk_get_devfd(c
)),
2387 arg_dry_run
? LOCK_SH
: LOCK_EX
,
2388 &context
->backing_fd
);
2393 /* The offsets/sizes libfdisk returns to us will be in multiple of the sector size of the
2394 * device. This is typically 512, and sometimes 4096. Let's query libfdisk once for it, and then use
2395 * it for all our needs. Note that the values we use ourselves always are in bytes though, thus mean
2396 * the same thing universally. Also note that regardless what kind of sector size is in use we'll
2397 * place partitions at multiples of 4K. */
2398 secsz
= fdisk_get_sector_size(c
);
2400 /* Insist on a power of two, and that it's a multiple of 512, i.e. the traditional sector size. */
2401 if (secsz
< 512 || !ISPOWEROF2(secsz
))
2402 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Sector size %lu is not a power of two larger than 512? Refusing.", secsz
);
2404 /* Use at least 4K, and ensure it's a multiple of the sector size, regardless if that is smaller or
2406 grainsz
= secsz
< 4096 ? 4096 : secsz
;
2408 log_debug("Sector size of device is %lu bytes. Using grain size of %" PRIu64
".", secsz
, grainsz
);
2410 switch (arg_empty
) {
2413 /* Refuse empty disks, insist on an existing GPT partition table */
2414 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2415 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has no GPT disk label, not repartitioning.", context
->node
);
2420 /* Require an empty disk, refuse any existing partition table */
2421 r
= fdisk_has_label(c
);
2423 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", context
->node
);
2425 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s already has a disk label, refusing.", context
->node
);
2427 from_scratch
= true;
2431 /* Allow both an empty disk and an existing partition table, but only GPT */
2432 r
= fdisk_has_label(c
);
2434 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", context
->node
);
2436 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2437 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has non-GPT disk label, not repartitioning.", context
->node
);
2439 from_scratch
= true;
2445 /* Always reinitiaize the disk, don't consider what there was on the disk before */
2446 from_scratch
= true;
2450 assert_not_reached();
2454 r
= fdisk_create_disklabel(c
, "gpt");
2456 return log_error_errno(r
, "Failed to create GPT disk label: %m");
2458 r
= derive_uuid(context
->seed
, "disk-uuid", &disk_uuid
);
2460 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
2462 r
= fdisk_set_disklabel_id_by_uuid(c
, disk_uuid
);
2464 return log_error_errno(r
, "Failed to set GPT disk label: %m");
2466 goto add_initial_free_area
;
2469 r
= fdisk_get_disklabel_id(c
, &disk_uuid_string
);
2471 return log_error_errno(r
, "Failed to get current GPT disk label UUID: %m");
2473 r
= id128_from_string_nonzero(disk_uuid_string
, &disk_uuid
);
2475 r
= derive_uuid(context
->seed
, "disk-uuid", &disk_uuid
);
2477 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
2479 r
= fdisk_set_disklabel_id(c
);
2481 return log_error_errno(r
, "Failed to set GPT disk label: %m");
2483 return log_error_errno(r
, "Failed to parse current GPT disk label UUID: %m");
2485 r
= fdisk_get_partitions(c
, &t
);
2487 return log_error_errno(r
, "Failed to acquire partition table: %m");
2489 n_partitions
= fdisk_table_get_nents(t
);
2490 for (size_t i
= 0; i
< n_partitions
; i
++) {
2491 _cleanup_free_
char *label_copy
= NULL
;
2492 Partition
*last
= NULL
;
2493 struct fdisk_partition
*p
;
2497 sd_id128_t ptid
, id
;
2500 p
= fdisk_table_get_partition(t
, i
);
2502 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
2504 if (fdisk_partition_is_used(p
) <= 0)
2507 if (fdisk_partition_has_start(p
) <= 0 ||
2508 fdisk_partition_has_size(p
) <= 0 ||
2509 fdisk_partition_has_partno(p
) <= 0)
2510 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a position, size or number.");
2512 r
= fdisk_partition_get_type_as_id128(p
, &ptid
);
2514 return log_error_errno(r
, "Failed to query partition type UUID: %m");
2516 r
= fdisk_partition_get_uuid_as_id128(p
, &id
);
2518 return log_error_errno(r
, "Failed to query partition UUID: %m");
2520 label
= fdisk_partition_get_name(p
);
2521 if (!isempty(label
)) {
2522 label_copy
= strdup(label
);
2527 sz
= fdisk_partition_get_size(p
);
2528 assert(sz
<= UINT64_MAX
/secsz
);
2531 start
= fdisk_partition_get_start(p
);
2532 assert(start
<= UINT64_MAX
/secsz
);
2535 partno
= fdisk_partition_get_partno(p
);
2537 if (left_boundary
== UINT64_MAX
|| left_boundary
> start
)
2538 left_boundary
= start
;
2540 /* Assign this existing partition to the first partition of the right type that doesn't have
2541 * an existing one assigned yet. */
2542 LIST_FOREACH(partitions
, pp
, context
->partitions
) {
2545 if (!sd_id128_equal(pp
->type
.uuid
, ptid
))
2548 if (!pp
->current_partition
) {
2549 pp
->current_uuid
= id
;
2550 pp
->current_size
= sz
;
2552 pp
->partno
= partno
;
2553 pp
->current_label
= TAKE_PTR(label_copy
);
2555 pp
->current_partition
= p
;
2556 fdisk_ref_partition(p
);
2558 r
= determine_current_padding(c
, t
, p
, secsz
, grainsz
, &pp
->current_padding
);
2562 if (pp
->current_padding
> 0) {
2563 r
= context_add_free_area(context
, pp
->current_padding
, pp
);
2573 /* If we have no matching definition, create a new one. */
2575 _cleanup_(partition_freep
) Partition
*np
= NULL
;
2577 np
= partition_new();
2581 np
->current_uuid
= id
;
2582 np
->type
= gpt_partition_type_from_uuid(ptid
);
2583 np
->current_size
= sz
;
2585 np
->partno
= partno
;
2586 np
->current_label
= TAKE_PTR(label_copy
);
2588 np
->current_partition
= p
;
2589 fdisk_ref_partition(p
);
2591 r
= determine_current_padding(c
, t
, p
, secsz
, grainsz
, &np
->current_padding
);
2595 if (np
->current_padding
> 0) {
2596 r
= context_add_free_area(context
, np
->current_padding
, np
);
2601 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, TAKE_PTR(np
));
2602 context
->n_partitions
++;
2606 add_initial_free_area
:
2607 nsectors
= fdisk_get_nsectors(c
);
2608 assert(nsectors
<= UINT64_MAX
/secsz
);
2611 first_lba
= fdisk_get_first_lba(c
);
2612 assert(first_lba
<= UINT64_MAX
/secsz
);
2615 last_lba
= fdisk_get_last_lba(c
);
2616 assert(last_lba
< UINT64_MAX
);
2618 assert(last_lba
<= UINT64_MAX
/secsz
);
2621 assert(last_lba
>= first_lba
);
2623 if (left_boundary
== UINT64_MAX
) {
2624 /* No partitions at all? Then the whole disk is up for grabs. */
2626 first_lba
= round_up_size(first_lba
, grainsz
);
2627 last_lba
= round_down_size(last_lba
, grainsz
);
2629 if (last_lba
> first_lba
) {
2630 r
= context_add_free_area(context
, last_lba
- first_lba
, NULL
);
2635 /* Add space left of first partition */
2636 assert(left_boundary
>= first_lba
);
2638 first_lba
= round_up_size(first_lba
, grainsz
);
2639 left_boundary
= round_down_size(left_boundary
, grainsz
);
2640 last_lba
= round_down_size(last_lba
, grainsz
);
2642 if (left_boundary
> first_lba
) {
2643 r
= context_add_free_area(context
, left_boundary
- first_lba
, NULL
);
2649 context
->start
= first_lba
;
2650 context
->end
= last_lba
;
2651 context
->total
= nsectors
;
2652 context
->sector_size
= secsz
;
2653 context
->fs_sector_size
= fs_secsz
;
2654 context
->grain_size
= grainsz
;
2655 context
->fdisk_context
= TAKE_PTR(c
);
2657 return from_scratch
;
2660 static void context_unload_partition_table(Context
*context
) {
2663 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2665 /* Entirely remove partitions that have no configuration */
2666 if (PARTITION_IS_FOREIGN(p
)) {
2667 partition_unlink_and_free(context
, p
);
2671 /* Otherwise drop all data we read off the block device and everything we might have
2672 * calculated based on it */
2675 p
->current_size
= UINT64_MAX
;
2676 p
->new_size
= UINT64_MAX
;
2677 p
->current_padding
= UINT64_MAX
;
2678 p
->new_padding
= UINT64_MAX
;
2679 p
->partno
= UINT64_MAX
;
2680 p
->offset
= UINT64_MAX
;
2682 if (p
->current_partition
) {
2683 fdisk_unref_partition(p
->current_partition
);
2684 p
->current_partition
= NULL
;
2687 if (p
->new_partition
) {
2688 fdisk_unref_partition(p
->new_partition
);
2689 p
->new_partition
= NULL
;
2692 p
->padding_area
= NULL
;
2693 p
->allocated_to_area
= NULL
;
2695 p
->current_uuid
= SD_ID128_NULL
;
2696 p
->current_label
= mfree(p
->current_label
);
2699 context
->start
= UINT64_MAX
;
2700 context
->end
= UINT64_MAX
;
2701 context
->total
= UINT64_MAX
;
2703 if (context
->fdisk_context
) {
2704 fdisk_unref_context(context
->fdisk_context
);
2705 context
->fdisk_context
= NULL
;
2708 context_free_free_areas(context
);
2711 static int format_size_change(uint64_t from
, uint64_t to
, char **ret
) {
2714 if (from
!= UINT64_MAX
) {
2715 if (from
== to
|| to
== UINT64_MAX
)
2716 t
= strdup(FORMAT_BYTES(from
));
2718 t
= strjoin(FORMAT_BYTES(from
), " ", special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), " ", FORMAT_BYTES(to
));
2719 } else if (to
!= UINT64_MAX
)
2720 t
= strjoin(special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), " ", FORMAT_BYTES(to
));
2733 static const char *partition_label(const Partition
*p
) {
2737 return p
->new_label
;
2739 if (p
->current_label
)
2740 return p
->current_label
;
2742 return gpt_partition_type_uuid_to_string(p
->type
.uuid
);
2745 static int context_dump_partitions(Context
*context
) {
2746 _cleanup_(table_unrefp
) Table
*t
= NULL
;
2747 uint64_t sum_padding
= 0, sum_size
= 0;
2749 const size_t roothash_col
= 14, dropin_files_col
= 15, split_path_col
= 16;
2750 bool has_roothash
= false, has_dropin_files
= false, has_split_path
= false;
2752 if ((arg_json_format_flags
& JSON_FORMAT_OFF
) && context
->n_partitions
== 0) {
2753 log_info("Empty partition table.");
2757 t
= table_new("type",
2777 if (!DEBUG_LOGGING
) {
2778 if (arg_json_format_flags
& JSON_FORMAT_OFF
)
2779 (void) table_set_display(t
, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4,
2780 (size_t) 8, (size_t) 9, (size_t) 12, roothash_col
, dropin_files_col
,
2783 (void) table_set_display(t
, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4,
2784 (size_t) 5, (size_t) 6, (size_t) 7, (size_t) 8, (size_t) 10,
2785 (size_t) 11, (size_t) 13, roothash_col
, dropin_files_col
,
2789 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 5), 100);
2790 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 6), 100);
2791 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 7), 100);
2792 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 8), 100);
2793 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 9), 100);
2794 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 10), 100);
2795 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 11), 100);
2797 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2798 _cleanup_free_
char *size_change
= NULL
, *padding_change
= NULL
, *partname
= NULL
, *rh
= NULL
;
2799 char uuid_buffer
[SD_ID128_UUID_STRING_MAX
];
2800 const char *label
, *activity
= NULL
;
2805 if (p
->current_size
== UINT64_MAX
)
2806 activity
= "create";
2807 else if (p
->current_size
!= p
->new_size
)
2808 activity
= "resize";
2810 label
= partition_label(p
);
2811 partname
= p
->partno
!= UINT64_MAX
? fdisk_partname(context
->node
, p
->partno
+1) : NULL
;
2813 r
= format_size_change(p
->current_size
, p
->new_size
, &size_change
);
2817 r
= format_size_change(p
->current_padding
, p
->new_padding
, &padding_change
);
2821 if (p
->new_size
!= UINT64_MAX
)
2822 sum_size
+= p
->new_size
;
2823 if (p
->new_padding
!= UINT64_MAX
)
2824 sum_padding
+= p
->new_padding
;
2826 if (p
->verity
!= VERITY_OFF
) {
2827 Partition
*hp
= p
->verity
== VERITY_HASH
? p
: p
->siblings
[VERITY_HASH
];
2829 rh
= iovec_is_set(&hp
->roothash
) ? hexmem(hp
->roothash
.iov_base
, hp
->roothash
.iov_len
) : strdup("TBD");
2836 TABLE_STRING
, gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, uuid_buffer
),
2837 TABLE_STRING
, empty_to_null(label
) ?: "-", TABLE_SET_COLOR
, empty_to_null(label
) ? NULL
: ansi_grey(),
2838 TABLE_UUID
, p
->new_uuid_is_set
? p
->new_uuid
: p
->current_uuid
,
2839 TABLE_UINT64
, p
->partno
,
2840 TABLE_PATH_BASENAME
, p
->definition_path
, TABLE_SET_COLOR
, p
->definition_path
? NULL
: ansi_grey(),
2841 TABLE_STRING
, partname
?: "-", TABLE_SET_COLOR
, partname
? NULL
: ansi_highlight(),
2842 TABLE_UINT64
, p
->offset
,
2843 TABLE_UINT64
, p
->current_size
== UINT64_MAX
? 0 : p
->current_size
,
2844 TABLE_UINT64
, p
->new_size
,
2845 TABLE_STRING
, size_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_size
> 0 ? ansi_underline() : NULL
,
2846 TABLE_UINT64
, p
->current_padding
== UINT64_MAX
? 0 : p
->current_padding
,
2847 TABLE_UINT64
, p
->new_padding
,
2848 TABLE_STRING
, padding_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_padding
> 0 ? ansi_underline() : NULL
,
2849 TABLE_STRING
, activity
?: "unchanged",
2851 TABLE_STRV
, p
->drop_in_files
,
2852 TABLE_STRING
, empty_to_null(p
->split_path
) ?: "-");
2854 return table_log_add_error(r
);
2856 has_roothash
= has_roothash
|| !isempty(rh
);
2857 has_dropin_files
= has_dropin_files
|| !strv_isempty(p
->drop_in_files
);
2858 has_split_path
= has_split_path
|| !isempty(p
->split_path
);
2861 if ((arg_json_format_flags
& JSON_FORMAT_OFF
) && (sum_padding
> 0 || sum_size
> 0)) {
2864 a
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", FORMAT_BYTES(sum_size
));
2865 b
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", FORMAT_BYTES(sum_padding
));
2887 return table_log_add_error(r
);
2890 if (!has_roothash
) {
2891 r
= table_hide_column_from_display(t
, roothash_col
);
2893 return log_error_errno(r
, "Failed to set columns to display: %m");
2896 if (!has_dropin_files
) {
2897 r
= table_hide_column_from_display(t
, dropin_files_col
);
2899 return log_error_errno(r
, "Failed to set columns to display: %m");
2902 if (!has_split_path
) {
2903 r
= table_hide_column_from_display(t
, split_path_col
);
2905 return log_error_errno(r
, "Failed to set columns to display: %m");
2908 return table_print_with_pager(t
, arg_json_format_flags
, arg_pager_flags
, arg_legend
);
2911 static void context_bar_char_process_partition(
2916 size_t *ret_start
) {
2918 uint64_t from
, to
, total
;
2929 assert(p
->offset
!= UINT64_MAX
);
2930 assert(p
->new_size
!= UINT64_MAX
);
2933 to
= from
+ p
->new_size
;
2935 assert(context
->total
> 0);
2936 total
= context
->total
;
2938 assert(from
<= total
);
2939 x
= from
* n
/ total
;
2941 assert(to
<= total
);
2947 for (size_t i
= x
; i
< y
; i
++)
2953 static int partition_hint(const Partition
*p
, const char *node
, char **ret
) {
2954 _cleanup_free_
char *buf
= NULL
;
2958 /* Tries really hard to find a suitable description for this partition */
2960 if (p
->definition_path
)
2961 return path_extract_filename(p
->definition_path
, ret
);
2963 label
= partition_label(p
);
2964 if (!isempty(label
)) {
2965 buf
= strdup(label
);
2969 if (p
->partno
!= UINT64_MAX
) {
2970 buf
= fdisk_partname(node
, p
->partno
+1);
2974 if (p
->new_uuid_is_set
)
2976 else if (!sd_id128_is_null(p
->current_uuid
))
2977 id
= p
->current_uuid
;
2981 buf
= strdup(SD_ID128_TO_UUID_STRING(id
));
2987 *ret
= TAKE_PTR(buf
);
2991 static int context_dump_partition_bar(Context
*context
) {
2992 _cleanup_free_ Partition
**bar
= NULL
;
2993 _cleanup_free_
size_t *start_array
= NULL
;
2994 Partition
*last
= NULL
;
2998 assert_se((c
= columns()) >= 2);
2999 c
-= 2; /* We do not use the leftmost and rightmost character cell */
3001 bar
= new0(Partition
*, c
);
3005 start_array
= new(size_t, context
->n_partitions
);
3009 LIST_FOREACH(partitions
, p
, context
->partitions
)
3010 context_bar_char_process_partition(context
, bar
, c
, p
, start_array
+ j
++);
3014 for (size_t i
= 0; i
< c
; i
++) {
3019 fputs(z
? ansi_green() : ansi_yellow(), stdout
);
3020 fputs(special_glyph(SPECIAL_GLYPH_DARK_SHADE
), stdout
);
3022 fputs(ansi_normal(), stdout
);
3023 fputs(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE
), stdout
);
3029 fputs(ansi_normal(), stdout
);
3032 for (size_t i
= 0; i
< context
->n_partitions
; i
++) {
3033 _cleanup_free_
char **line
= NULL
;
3035 line
= new0(char*, c
);
3040 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3041 _cleanup_free_
char *d
= NULL
;
3044 if (i
< context
->n_partitions
- j
) {
3046 if (line
[start_array
[j
-1]]) {
3049 /* Upgrade final corner to the right with a branch to the right */
3050 e
= startswith(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
3052 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), e
);
3059 d
= strdup(special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
));
3064 } else if (i
== context
->n_partitions
- j
) {
3065 _cleanup_free_
char *hint
= NULL
;
3067 (void) partition_hint(p
, context
->node
, &hint
);
3069 if (streq_ptr(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
)))
3070 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), " ", strna(hint
));
3072 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), " ", strna(hint
));
3079 free_and_replace(line
[start_array
[j
-1]], d
);
3087 fputs(line
[j
], stdout
);
3088 j
+= utf8_console_width(line
[j
]);
3097 for (j
= 0; j
< c
; j
++)
3104 static bool context_has_roothash(Context
*context
) {
3105 LIST_FOREACH(partitions
, p
, context
->partitions
)
3106 if (iovec_is_set(&p
->roothash
))
3112 static int context_dump(Context
*context
, bool late
) {
3117 if (arg_pretty
== 0 && FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
))
3120 /* If we're outputting JSON, only dump after doing all operations so we can include the roothashes
3122 if (!late
&& !FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
))
3125 /* If we're not outputting JSON, only dump again after doing all operations if there are any
3126 * roothashes that we need to communicate to the user. */
3127 if (late
&& FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
) && !context_has_roothash(context
))
3130 r
= context_dump_partitions(context
);
3134 /* Make sure we only write the partition bar once, even if we're writing the partition table twice to
3135 * communicate roothashes. */
3136 if (FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
) && !late
) {
3139 r
= context_dump_partition_bar(context
);
3152 static bool context_changed(const Context
*context
) {
3155 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3159 if (p
->allocated_to_area
)
3162 if (p
->new_size
!= p
->current_size
)
3169 static int context_wipe_range(Context
*context
, uint64_t offset
, uint64_t size
) {
3170 _cleanup_(blkid_free_probep
) blkid_probe probe
= NULL
;
3174 assert(offset
!= UINT64_MAX
);
3175 assert(size
!= UINT64_MAX
);
3177 probe
= blkid_new_probe();
3182 r
= blkid_probe_set_device(probe
, fdisk_get_devfd(context
->fdisk_context
), offset
, size
);
3184 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to allocate device probe for wiping.");
3187 if (blkid_probe_enable_superblocks(probe
, true) < 0 ||
3188 blkid_probe_set_superblocks_flags(probe
, BLKID_SUBLKS_MAGIC
|BLKID_SUBLKS_BADCSUM
) < 0 ||
3189 blkid_probe_enable_partitions(probe
, true) < 0 ||
3190 blkid_probe_set_partitions_flags(probe
, BLKID_PARTS_MAGIC
) < 0)
3191 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to enable superblock and partition probing.");
3195 r
= blkid_do_probe(probe
);
3197 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to probe for file systems.");
3202 if (blkid_do_wipe(probe
, false) < 0)
3203 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to wipe file system signature.");
3209 static int context_wipe_partition(Context
*context
, Partition
*p
) {
3214 assert(!PARTITION_EXISTS(p
)); /* Safety check: never wipe existing partitions */
3216 assert(p
->offset
!= UINT64_MAX
);
3217 assert(p
->new_size
!= UINT64_MAX
);
3219 r
= context_wipe_range(context
, p
->offset
, p
->new_size
);
3223 log_info("Successfully wiped file system signatures from future partition %" PRIu64
".", p
->partno
);
3227 static int context_discard_range(
3236 assert(offset
!= UINT64_MAX
);
3237 assert(size
!= UINT64_MAX
);
3242 assert_se((fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
3244 if (fstat(fd
, &st
) < 0)
3247 if (S_ISREG(st
.st_mode
)) {
3248 if (fallocate(fd
, FALLOC_FL_PUNCH_HOLE
|FALLOC_FL_KEEP_SIZE
, offset
, size
) < 0) {
3249 if (ERRNO_IS_NOT_SUPPORTED(errno
))
3258 if (S_ISBLK(st
.st_mode
)) {
3259 uint64_t range
[2], end
;
3261 range
[0] = round_up_size(offset
, context
->sector_size
);
3263 if (offset
> UINT64_MAX
- size
)
3266 end
= offset
+ size
;
3267 if (end
<= range
[0])
3270 range
[1] = round_down_size(end
- range
[0], context
->sector_size
);
3274 if (ioctl(fd
, BLKDISCARD
, range
) < 0) {
3275 if (ERRNO_IS_NOT_SUPPORTED(errno
))
3287 static int context_discard_partition(Context
*context
, Partition
*p
) {
3293 assert(p
->offset
!= UINT64_MAX
);
3294 assert(p
->new_size
!= UINT64_MAX
);
3295 assert(!PARTITION_EXISTS(p
)); /* Safety check: never discard existing partitions */
3300 r
= context_discard_range(context
, p
->offset
, p
->new_size
);
3301 if (r
== -EOPNOTSUPP
) {
3302 log_info("Storage does not support discard, not discarding data in future partition %" PRIu64
".", p
->partno
);
3306 /* Let's handle this gracefully: https://bugzilla.kernel.org/show_bug.cgi?id=211167 */
3307 log_info("Block device is busy, not discarding partition %" PRIu64
" because it probably is mounted.", p
->partno
);
3311 log_info("Partition %" PRIu64
" too short for discard, skipping.", p
->partno
);
3315 return log_error_errno(r
, "Failed to discard data for future partition %" PRIu64
".", p
->partno
);
3317 log_info("Successfully discarded data from future partition %" PRIu64
".", p
->partno
);
3321 static int context_discard_gap_after(Context
*context
, Partition
*p
) {
3322 uint64_t gap
, next
= UINT64_MAX
;
3326 assert(!p
|| (p
->offset
!= UINT64_MAX
&& p
->new_size
!= UINT64_MAX
));
3332 gap
= p
->offset
+ p
->new_size
;
3334 /* The context start gets rounded up to grain_size, however
3335 * existing partitions may be before that so ensure the gap
3336 * starts at the first actually usable lba
3338 gap
= fdisk_get_first_lba(context
->fdisk_context
) * context
->sector_size
;
3340 LIST_FOREACH(partitions
, q
, context
->partitions
) {
3344 assert(q
->offset
!= UINT64_MAX
);
3345 assert(q
->new_size
!= UINT64_MAX
);
3347 if (q
->offset
< gap
)
3350 if (next
== UINT64_MAX
|| q
->offset
< next
)
3354 if (next
== UINT64_MAX
) {
3355 next
= (fdisk_get_last_lba(context
->fdisk_context
) + 1) * context
->sector_size
;
3357 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
3360 assert(next
>= gap
);
3361 r
= context_discard_range(context
, gap
, next
- gap
);
3362 if (r
== -EOPNOTSUPP
) {
3364 log_info("Storage does not support discard, not discarding gap after partition %" PRIu64
".", p
->partno
);
3366 log_info("Storage does not support discard, not discarding gap at beginning of disk.");
3369 if (r
== 0) /* Too short */
3373 return log_error_errno(r
, "Failed to discard gap after partition %" PRIu64
".", p
->partno
);
3375 return log_error_errno(r
, "Failed to discard gap at beginning of disk.");
3379 log_info("Successfully discarded gap after partition %" PRIu64
".", p
->partno
);
3381 log_info("Successfully discarded gap at beginning of disk.");
3386 static int context_wipe_and_discard(Context
*context
) {
3391 if (arg_empty
== EMPTY_CREATE
) /* If we just created the image, no need to wipe */
3394 /* Wipe and discard the contents of all partitions we are about to create. We skip the discarding if
3395 * we were supposed to start from scratch anyway, as in that case we just discard the whole block
3396 * device in one go early on. */
3398 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3400 if (!p
->allocated_to_area
)
3403 if (partition_type_defer(&p
->type
))
3406 r
= context_wipe_partition(context
, p
);
3410 if (!context
->from_scratch
) {
3411 r
= context_discard_partition(context
, p
);
3415 r
= context_discard_gap_after(context
, p
);
3421 if (!context
->from_scratch
) {
3422 r
= context_discard_gap_after(context
, NULL
);
3430 typedef struct DecryptedPartitionTarget
{
3434 struct crypt_device
*device
;
3435 } DecryptedPartitionTarget
;
3437 static DecryptedPartitionTarget
* decrypted_partition_target_free(DecryptedPartitionTarget
*t
) {
3438 #if HAVE_LIBCRYPTSETUP
3446 /* udev or so might access out block device in the background while we are done. Let's hence
3447 * force detach the volume. We sync'ed before, hence this should be safe. */
3448 r
= sym_crypt_deactivate_by_name(t
->device
, t
->dm_name
, CRYPT_DEACTIVATE_FORCE
);
3450 log_warning_errno(r
, "Failed to deactivate LUKS device, ignoring: %m");
3452 sym_crypt_free(t
->device
);
3465 DecryptedPartitionTarget
*decrypted
;
3468 static int partition_target_fd(PartitionTarget
*t
) {
3470 assert(t
->loop
|| t
->fd
>= 0 || t
->whole_fd
>= 0);
3473 return t
->decrypted
->fd
;
3484 static const char* partition_target_path(PartitionTarget
*t
) {
3486 assert(t
->loop
|| t
->path
);
3489 return t
->decrypted
->volume
;
3492 return t
->loop
->node
;
3497 static PartitionTarget
*partition_target_free(PartitionTarget
*t
) {
3501 decrypted_partition_target_free(t
->decrypted
);
3502 loop_device_unref(t
->loop
);
3504 unlink_and_free(t
->path
);
3509 DEFINE_TRIVIAL_CLEANUP_FUNC(PartitionTarget
*, partition_target_free
);
3511 static int prepare_temporary_file(PartitionTarget
*t
, uint64_t size
) {
3512 _cleanup_(unlink_and_freep
) char *temp
= NULL
;
3513 _cleanup_close_
int fd
= -EBADF
;
3519 r
= var_tmp_dir(&vt
);
3521 return log_error_errno(r
, "Could not determine temporary directory: %m");
3523 temp
= path_join(vt
, "repart-XXXXXX");
3527 fd
= mkostemp_safe(temp
);
3529 return log_error_errno(fd
, "Failed to create temporary file: %m");
3531 if (ftruncate(fd
, size
) < 0)
3532 return log_error_errno(errno
, "Failed to truncate temporary file to %s: %m",
3533 FORMAT_BYTES(size
));
3535 t
->fd
= TAKE_FD(fd
);
3536 t
->path
= TAKE_PTR(temp
);
3541 static int partition_target_prepare(
3546 PartitionTarget
**ret
) {
3548 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
3549 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
3556 assert_se((whole_fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
3558 t
= new(PartitionTarget
, 1);
3561 *t
= (PartitionTarget
) {
3567 if (lseek(whole_fd
, p
->offset
, SEEK_SET
) < 0)
3568 return log_error_errno(errno
, "Failed to seek to partition offset: %m");
3570 t
->whole_fd
= whole_fd
;
3575 /* Loopback block devices are not only useful to turn regular files into block devices, but
3576 * also to cut out sections of block devices into new block devices. */
3578 if (arg_offline
<= 0) {
3579 r
= loop_device_make(whole_fd
, O_RDWR
, p
->offset
, size
, context
->sector_size
, 0, LOCK_EX
, &d
);
3580 if (r
< 0 && (arg_offline
== 0 || (r
!= -ENOENT
&& !ERRNO_IS_PRIVILEGE(r
)) || !strv_isempty(p
->subvolumes
)))
3581 return log_error_errno(r
, "Failed to make loopback device of future partition %" PRIu64
": %m", p
->partno
);
3583 t
->loop
= TAKE_PTR(d
);
3588 log_debug_errno(r
, "No access to loop devices, falling back to a regular file");
3591 /* If we can't allocate a loop device, let's write to a regular file that we copy into the final
3592 * image so we can run in containers and without needing root privileges. On filesystems with
3593 * reflinking support, we can take advantage of this and just reflink the result into the image.
3596 r
= prepare_temporary_file(t
, size
);
3605 static int partition_target_grow(PartitionTarget
*t
, uint64_t size
) {
3609 assert(!t
->decrypted
);
3612 r
= loop_device_refresh_size(t
->loop
, UINT64_MAX
, size
);
3614 return log_error_errno(r
, "Failed to refresh loopback device size: %m");
3615 } else if (t
->fd
>= 0) {
3616 if (ftruncate(t
->fd
, size
) < 0)
3617 return log_error_errno(errno
, "Failed to grow '%s' to %s by truncation: %m",
3618 t
->path
, FORMAT_BYTES(size
));
3624 static int partition_target_sync(Context
*context
, Partition
*p
, PartitionTarget
*t
) {
3631 assert_se((whole_fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
3633 if (t
->decrypted
&& fsync(t
->decrypted
->fd
) < 0)
3634 return log_error_errno(errno
, "Failed to sync changes to '%s': %m", t
->decrypted
->volume
);
3637 r
= loop_device_sync(t
->loop
);
3639 return log_error_errno(r
, "Failed to sync loopback device: %m");
3640 } else if (t
->fd
>= 0) {
3643 if (lseek(whole_fd
, p
->offset
, SEEK_SET
) < 0)
3644 return log_error_errno(errno
, "Failed to seek to partition offset: %m");
3646 if (lseek(t
->fd
, 0, SEEK_SET
) < 0)
3647 return log_error_errno(errno
, "Failed to seek to start of temporary file: %m");
3649 if (fstat(t
->fd
, &st
) < 0)
3650 return log_error_errno(errno
, "Failed to stat temporary file: %m");
3652 if (st
.st_size
> (off_t
) p
->new_size
)
3653 return log_error_errno(SYNTHETIC_ERRNO(ENOSPC
),
3654 "Partition %" PRIu64
"'s contents (%s) don't fit in the partition (%s)",
3655 p
->partno
, FORMAT_BYTES(st
.st_size
), FORMAT_BYTES(p
->new_size
));
3657 r
= copy_bytes(t
->fd
, whole_fd
, UINT64_MAX
, COPY_REFLINK
|COPY_HOLES
|COPY_FSYNC
);
3659 return log_error_errno(r
, "Failed to copy bytes to partition: %m");
3661 if (fsync(t
->whole_fd
) < 0)
3662 return log_error_errno(errno
, "Failed to sync changes: %m");
3668 static int partition_encrypt(Context
*context
, Partition
*p
, PartitionTarget
*target
, bool offline
) {
3669 #if HAVE_LIBCRYPTSETUP && HAVE_CRYPT_SET_DATA_OFFSET && HAVE_CRYPT_REENCRYPT_INIT_BY_PASSPHRASE && HAVE_CRYPT_REENCRYPT
3670 const char *node
= partition_target_path(target
);
3671 struct crypt_params_luks2 luks_params
= {
3672 .label
= strempty(ASSERT_PTR(p
)->new_label
),
3673 .sector_size
= ASSERT_PTR(context
)->fs_sector_size
,
3674 .data_device
= offline
? node
: NULL
,
3676 struct crypt_params_reencrypt reencrypt_params
= {
3677 .mode
= CRYPT_REENCRYPT_ENCRYPT
,
3678 .direction
= CRYPT_REENCRYPT_BACKWARD
,
3679 .resilience
= "datashift",
3680 .data_shift
= LUKS2_METADATA_SIZE
/ 512,
3681 .luks2
= &luks_params
,
3682 .flags
= CRYPT_REENCRYPT_INITIALIZE_ONLY
|CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT
,
3684 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
3685 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
3686 _cleanup_fclose_
FILE *h
= NULL
;
3687 _cleanup_free_
char *hp
= NULL
, *vol
= NULL
, *dm_name
= NULL
;
3688 const char *passphrase
= NULL
;
3689 size_t passphrase_size
= 0;
3690 TPM2Flags flags
= 0;
3696 assert(p
->encrypt
!= ENCRYPT_OFF
);
3698 r
= dlopen_cryptsetup();
3700 return log_error_errno(r
, "libcryptsetup not found, cannot encrypt: %m");
3702 log_info("Encrypting future partition %" PRIu64
"...", p
->partno
);
3705 r
= var_tmp_dir(&vt
);
3707 return log_error_errno(r
, "Failed to determine temporary files directory: %m");
3709 r
= fopen_temporary_child(vt
, &h
, &hp
);
3711 return log_error_errno(r
, "Failed to create temporary LUKS header file: %m");
3713 /* Weird cryptsetup requirement which requires the header file to be the size of at least one
3715 r
= ftruncate(fileno(h
), luks_params
.sector_size
);
3717 return log_error_errno(r
, "Failed to grow temporary LUKS header file: %m");
3719 if (asprintf(&dm_name
, "luks-repart-%08" PRIx64
, random_u64()) < 0)
3722 vol
= path_join("/dev/mapper/", dm_name
);
3727 r
= sym_crypt_init(&cd
, offline
? hp
: node
);
3729 return log_error_errno(r
, "Failed to allocate libcryptsetup context for %s: %m", hp
);
3731 cryptsetup_enable_logging(cd
);
3734 /* Disable kernel keyring usage by libcryptsetup as a workaround for
3735 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/273. This makes sure that we can
3736 * do offline encryption even when repart is running in a container. */
3737 r
= sym_crypt_volume_key_keyring(cd
, false);
3739 return log_error_errno(r
, "Failed to disable kernel keyring: %m");
3741 r
= sym_crypt_metadata_locking(cd
, false);
3743 return log_error_errno(r
, "Failed to disable metadata locking: %m");
3745 r
= sym_crypt_set_data_offset(cd
, LUKS2_METADATA_SIZE
/ 512);
3747 return log_error_errno(r
, "Failed to set data offset: %m");
3750 r
= sym_crypt_format(cd
,
3754 SD_ID128_TO_UUID_STRING(p
->luks_uuid
),
3759 return log_error_errno(r
, "Failed to LUKS2 format future partition: %m");
3761 if (IN_SET(p
->encrypt
, ENCRYPT_KEY_FILE
, ENCRYPT_KEY_FILE_TPM2
)) {
3762 r
= sym_crypt_keyslot_add_by_volume_key(
3770 return log_error_errno(r
, "Failed to add LUKS2 key: %m");
3772 passphrase
= strempty(arg_key
);
3773 passphrase_size
= arg_key_size
;
3776 if (IN_SET(p
->encrypt
, ENCRYPT_TPM2
, ENCRYPT_KEY_FILE_TPM2
)) {
3778 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
3779 _cleanup_(erase_and_freep
) void *secret
= NULL
;
3780 _cleanup_free_
void *pubkey
= NULL
;
3781 _cleanup_free_
void *blob
= NULL
, *srk_buf
= NULL
;
3782 size_t secret_size
, blob_size
, pubkey_size
= 0, srk_buf_size
= 0;
3783 ssize_t base64_encoded_size
;
3786 if (arg_tpm2_public_key_pcr_mask
!= 0) {
3787 r
= tpm2_load_pcr_public_key(arg_tpm2_public_key
, &pubkey
, &pubkey_size
);
3789 if (arg_tpm2_public_key
|| r
!= -ENOENT
)
3790 return log_error_errno(r
, "Failed to read TPM PCR public key: %m");
3792 log_debug_errno(r
, "Failed to read TPM2 PCR public key, proceeding without: %m");
3793 arg_tpm2_public_key_pcr_mask
= 0;
3797 TPM2B_PUBLIC
public;
3799 r
= tpm2_tpm2b_public_from_pem(pubkey
, pubkey_size
, &public);
3801 return log_error_errno(r
, "Could not convert public key to TPM2B_PUBLIC: %m");
3804 _cleanup_(tpm2_pcrlock_policy_done
) Tpm2PCRLockPolicy pcrlock_policy
= {};
3805 if (arg_tpm2_pcrlock
) {
3806 r
= tpm2_pcrlock_policy_load(arg_tpm2_pcrlock
, &pcrlock_policy
);
3810 flags
|= TPM2_FLAGS_USE_PCRLOCK
;
3813 _cleanup_(tpm2_context_unrefp
) Tpm2Context
*tpm2_context
= NULL
;
3814 TPM2B_PUBLIC device_key_public
= {};
3815 if (arg_tpm2_device_key
) {
3816 r
= tpm2_load_public_key_file(arg_tpm2_device_key
, &device_key_public
);
3820 if (!tpm2_pcr_values_has_all_values(arg_tpm2_hash_pcr_values
, arg_tpm2_n_hash_pcr_values
))
3821 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3822 "Must provide all PCR values when using TPM2 device key.");
3824 r
= tpm2_context_new(arg_tpm2_device
, &tpm2_context
);
3826 return log_error_errno(r
, "Failed to create TPM2 context: %m");
3828 if (!tpm2_pcr_values_has_all_values(arg_tpm2_hash_pcr_values
, arg_tpm2_n_hash_pcr_values
)) {
3829 r
= tpm2_pcr_read_missing_values(tpm2_context
, arg_tpm2_hash_pcr_values
, arg_tpm2_n_hash_pcr_values
);
3831 return log_error_errno(r
, "Could not read pcr values: %m");
3835 uint16_t hash_pcr_bank
= 0;
3836 uint32_t hash_pcr_mask
= 0;
3837 if (arg_tpm2_n_hash_pcr_values
> 0) {
3839 r
= tpm2_pcr_values_hash_count(arg_tpm2_hash_pcr_values
, arg_tpm2_n_hash_pcr_values
, &hash_count
);
3841 return log_error_errno(r
, "Could not get hash count: %m");
3844 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Multiple PCR banks selected.");
3846 hash_pcr_bank
= arg_tpm2_hash_pcr_values
[0].hash
;
3847 r
= tpm2_pcr_values_to_mask(arg_tpm2_hash_pcr_values
, arg_tpm2_n_hash_pcr_values
, hash_pcr_bank
, &hash_pcr_mask
);
3849 return log_error_errno(r
, "Could not get hash mask: %m");
3852 TPM2B_DIGEST policy
= TPM2B_DIGEST_MAKE(NULL
, TPM2_SHA256_DIGEST_SIZE
);
3853 r
= tpm2_calculate_sealing_policy(
3854 arg_tpm2_hash_pcr_values
,
3855 arg_tpm2_n_hash_pcr_values
,
3856 pubkey
? &public : NULL
,
3857 /* use_pin= */ false,
3858 arg_tpm2_pcrlock
? &pcrlock_policy
: NULL
,
3861 return log_error_errno(r
, "Could not calculate sealing policy digest: %m");
3863 if (arg_tpm2_device_key
)
3864 r
= tpm2_calculate_seal(
3865 arg_tpm2_seal_key_handle
,
3867 /* attributes= */ NULL
,
3868 /* secret= */ NULL
, /* secret_size= */ 0,
3871 &secret
, &secret_size
,
3873 &srk_buf
, &srk_buf_size
);
3875 r
= tpm2_seal(tpm2_context
,
3876 arg_tpm2_seal_key_handle
,
3879 &secret
, &secret_size
,
3881 /* ret_primary_alg= */ NULL
,
3882 &srk_buf
, &srk_buf_size
);
3884 return log_error_errno(r
, "Failed to seal to TPM2: %m");
3886 base64_encoded_size
= base64mem(secret
, secret_size
, &base64_encoded
);
3887 if (base64_encoded_size
< 0)
3888 return log_error_errno(base64_encoded_size
, "Failed to base64 encode secret key: %m");
3890 r
= cryptsetup_set_minimal_pbkdf(cd
);
3892 return log_error_errno(r
, "Failed to set minimal PBKDF: %m");
3894 keyslot
= sym_crypt_keyslot_add_by_volume_key(
3897 /* volume_key= */ NULL
,
3898 /* volume_key_size= */ VOLUME_KEY_SIZE
,
3900 base64_encoded_size
);
3902 return log_error_errno(keyslot
, "Failed to add new TPM2 key: %m");
3904 r
= tpm2_make_luks2_json(
3908 pubkey
, pubkey_size
,
3909 arg_tpm2_public_key_pcr_mask
,
3910 /* primary_alg= */ 0,
3912 policy
.buffer
, policy
.size
,
3913 NULL
, 0, /* no salt because tpm2_seal has no pin */
3914 srk_buf
, srk_buf_size
,
3918 return log_error_errno(r
, "Failed to prepare TPM2 JSON token object: %m");
3920 r
= cryptsetup_add_token_json(cd
, v
);
3922 return log_error_errno(r
, "Failed to add TPM2 JSON token to LUKS2 header: %m");
3924 passphrase
= base64_encoded
;
3925 passphrase_size
= strlen(base64_encoded
);
3927 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3928 "Support for TPM2 enrollment not enabled.");
3933 r
= sym_crypt_reencrypt_init_by_passphrase(
3940 sym_crypt_get_cipher(cd
),
3941 sym_crypt_get_cipher_mode(cd
),
3944 return log_error_errno(r
, "Failed to prepare for reencryption: %m");
3946 /* crypt_reencrypt_init_by_passphrase() doesn't actually put the LUKS header at the front, we
3947 * have to do that ourselves. */
3952 r
= sym_crypt_init(&cd
, node
);
3954 return log_error_errno(r
, "Failed to allocate libcryptsetup context for %s: %m", node
);
3956 r
= sym_crypt_header_restore(cd
, CRYPT_LUKS2
, hp
);
3958 return log_error_errno(r
, "Failed to place new LUKS header at head of %s: %m", node
);
3960 reencrypt_params
.flags
&= ~CRYPT_REENCRYPT_INITIALIZE_ONLY
;
3962 r
= sym_crypt_reencrypt_init_by_passphrase(
3973 return log_error_errno(r
, "Failed to load reencryption context: %m");
3975 r
= sym_crypt_reencrypt(cd
, NULL
);
3977 return log_error_errno(r
, "Failed to encrypt %s: %m", node
);
3979 _cleanup_free_ DecryptedPartitionTarget
*t
= NULL
;
3980 _cleanup_close_
int dev_fd
= -1;
3982 r
= sym_crypt_activate_by_volume_key(
3987 arg_discard
? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0);
3989 return log_error_errno(r
, "Failed to activate LUKS superblock: %m");
3991 dev_fd
= open(vol
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
);
3993 return log_error_errno(errno
, "Failed to open LUKS volume '%s': %m", vol
);
3995 if (flock(dev_fd
, LOCK_EX
) < 0)
3996 return log_error_errno(errno
, "Failed to lock '%s': %m", vol
);
3998 t
= new(DecryptedPartitionTarget
, 1);
4002 *t
= (DecryptedPartitionTarget
) {
4003 .fd
= TAKE_FD(dev_fd
),
4004 .dm_name
= TAKE_PTR(dm_name
),
4005 .volume
= TAKE_PTR(vol
),
4006 .device
= TAKE_PTR(cd
),
4009 target
->decrypted
= TAKE_PTR(t
);
4012 log_info("Successfully encrypted future partition %" PRIu64
".", p
->partno
);
4016 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
4017 "libcryptsetup is not supported or is missing required symbols, cannot encrypt: %m");
4021 static int partition_format_verity_hash(
4025 const char *data_node
) {
4027 #if HAVE_LIBCRYPTSETUP
4029 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
4030 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
4031 _cleanup_free_
char *hint
= NULL
;
4036 assert(p
->verity
== VERITY_HASH
);
4042 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
4045 /* Minimized partitions will use the copy blocks logic so let's make sure to skip those here. */
4046 if (p
->copy_blocks_fd
>= 0)
4049 assert_se(dp
= p
->siblings
[VERITY_DATA
]);
4050 assert(!dp
->dropped
);
4052 (void) partition_hint(p
, node
, &hint
);
4054 r
= dlopen_cryptsetup();
4056 return log_error_errno(r
, "libcryptsetup not found, cannot setup verity: %m");
4059 r
= partition_target_prepare(context
, p
, p
->new_size
, /*need_path=*/ true, &t
);
4063 node
= partition_target_path(t
);
4066 if (p
->verity_data_block_size
== UINT64_MAX
)
4067 p
->verity_data_block_size
= context
->fs_sector_size
;
4068 if (p
->verity_hash_block_size
== UINT64_MAX
)
4069 p
->verity_hash_block_size
= context
->fs_sector_size
;
4071 r
= sym_crypt_init(&cd
, node
);
4073 return log_error_errno(r
, "Failed to allocate libcryptsetup context for %s: %m", node
);
4075 cryptsetup_enable_logging(cd
);
4077 r
= sym_crypt_format(
4078 cd
, CRYPT_VERITY
, NULL
, NULL
, SD_ID128_TO_UUID_STRING(p
->verity_uuid
), NULL
, 0,
4079 &(struct crypt_params_verity
){
4080 .data_device
= data_node
,
4081 .flags
= CRYPT_VERITY_CREATE_HASH
,
4082 .hash_name
= "sha256",
4084 .data_block_size
= p
->verity_data_block_size
,
4085 .hash_block_size
= p
->verity_hash_block_size
,
4086 .salt_size
= sizeof(p
->verity_salt
),
4087 .salt
= (const char*)p
->verity_salt
,
4090 /* libcryptsetup reports non-descriptive EIO errors for every I/O failure. Luckily, it
4091 * doesn't clobber errno so let's check for ENOSPC so we can report a better error if the
4092 * partition is too small. */
4093 if (r
== -EIO
&& errno
== ENOSPC
)
4094 return log_error_errno(errno
,
4095 "Verity hash data does not fit in partition %s with size %s",
4096 strna(hint
), FORMAT_BYTES(p
->new_size
));
4098 return log_error_errno(r
, "Failed to setup verity hash data of partition %s: %m", strna(hint
));
4102 r
= partition_target_sync(context
, p
, t
);
4107 r
= sym_crypt_get_volume_key_size(cd
);
4109 return log_error_errno(r
, "Failed to determine verity root hash size of partition %s: %m", strna(hint
));
4111 _cleanup_(iovec_done
) struct iovec rh
= {
4112 .iov_base
= malloc(r
),
4118 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, (char *) rh
.iov_base
, &rh
.iov_len
, NULL
, 0);
4120 return log_error_errno(r
, "Failed to get verity root hash of partition %s: %m", strna(hint
));
4122 assert(rh
.iov_len
>= sizeof(sd_id128_t
) * 2);
4124 if (!dp
->new_uuid_is_set
) {
4125 memcpy_safe(dp
->new_uuid
.bytes
, rh
.iov_base
, sizeof(sd_id128_t
));
4126 dp
->new_uuid_is_set
= true;
4129 if (!p
->new_uuid_is_set
) {
4130 memcpy_safe(p
->new_uuid
.bytes
, (uint8_t*) rh
.iov_base
+ (rh
.iov_len
- sizeof(sd_id128_t
)), sizeof(sd_id128_t
));
4131 p
->new_uuid_is_set
= true;
4134 p
->roothash
= TAKE_STRUCT(rh
);
4138 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "libcryptsetup is not supported, cannot setup verity hashes: %m");
4142 static int sign_verity_roothash(
4143 const struct iovec
*roothash
,
4144 struct iovec
*ret_signature
) {
4147 _cleanup_(BIO_freep
) BIO
*rb
= NULL
;
4148 _cleanup_(PKCS7_freep
) PKCS7
*p7
= NULL
;
4149 _cleanup_free_
char *hex
= NULL
;
4150 _cleanup_free_
uint8_t *sig
= NULL
;
4154 assert(iovec_is_set(roothash
));
4155 assert(ret_signature
);
4157 hex
= hexmem(roothash
->iov_base
, roothash
->iov_len
);
4161 rb
= BIO_new_mem_buf(hex
, -1);
4165 p7
= PKCS7_sign(arg_certificate
, arg_private_key
, NULL
, rb
, PKCS7_DETACHED
|PKCS7_NOATTR
|PKCS7_BINARY
);
4167 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to calculate PKCS7 signature: %s",
4168 ERR_error_string(ERR_get_error(), NULL
));
4170 sigsz
= i2d_PKCS7(p7
, &sig
);
4172 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to convert PKCS7 signature to DER: %s",
4173 ERR_error_string(ERR_get_error(), NULL
));
4175 ret_signature
->iov_base
= TAKE_PTR(sig
);
4176 ret_signature
->iov_len
= sigsz
;
4180 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "openssl is not supported, cannot setup verity signature: %m");
4184 static int partition_format_verity_sig(Context
*context
, Partition
*p
) {
4185 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
4186 _cleanup_(iovec_done
) struct iovec sig
= {};
4187 _cleanup_free_
char *text
= NULL
, *hint
= NULL
;
4189 uint8_t fp
[X509_FINGERPRINT_SIZE
];
4192 assert(p
->verity
== VERITY_SIG
);
4197 if (PARTITION_EXISTS(p
))
4200 (void) partition_hint(p
, context
->node
, &hint
);
4202 assert_se(hp
= p
->siblings
[VERITY_HASH
]);
4203 assert(!hp
->dropped
);
4205 assert(arg_certificate
);
4207 assert_se((whole_fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
4209 r
= sign_verity_roothash(&hp
->roothash
, &sig
);
4213 r
= x509_fingerprint(arg_certificate
, fp
);
4215 return log_error_errno(r
, "Unable to calculate X509 certificate fingerprint: %m");
4219 JSON_BUILD_PAIR("rootHash", JSON_BUILD_HEX(hp
->roothash
.iov_base
, hp
->roothash
.iov_len
)),
4221 "certificateFingerprint",
4222 JSON_BUILD_HEX(fp
, sizeof(fp
))
4224 JSON_BUILD_PAIR("signature", JSON_BUILD_IOVEC_BASE64(&sig
))
4228 return log_error_errno(r
, "Failed to build verity signature JSON object: %m");
4230 r
= json_variant_format(v
, 0, &text
);
4232 return log_error_errno(r
, "Failed to format verity signature JSON object: %m");
4234 if (strlen(text
)+1 > p
->new_size
)
4235 return log_error_errno(SYNTHETIC_ERRNO(E2BIG
), "Verity signature too long for partition: %m");
4237 r
= strgrowpad0(&text
, p
->new_size
);
4239 return log_error_errno(r
, "Failed to pad string to %s", FORMAT_BYTES(p
->new_size
));
4241 if (lseek(whole_fd
, p
->offset
, SEEK_SET
) < 0)
4242 return log_error_errno(errno
, "Failed to seek to partition %s offset: %m", strna(hint
));
4244 r
= loop_write(whole_fd
, text
, p
->new_size
);
4246 return log_error_errno(r
, "Failed to write verity signature to partition %s: %m", strna(hint
));
4248 if (fsync(whole_fd
) < 0)
4249 return log_error_errno(errno
, "Failed to synchronize partition %s: %m", strna(hint
));
4254 static int context_copy_blocks(Context
*context
) {
4259 /* Copy in file systems on the block level */
4261 LIST_FOREACH(partitions
, p
, context
->partitions
) {
4262 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
4264 if (p
->copy_blocks_fd
< 0)
4270 if (PARTITION_EXISTS(p
)) /* Never copy over existing partitions */
4273 if (partition_type_defer(&p
->type
))
4276 assert(p
->new_size
!= UINT64_MAX
);
4277 assert(p
->copy_blocks_size
!= UINT64_MAX
);
4278 assert(p
->new_size
>= p
->copy_blocks_size
+ (p
->encrypt
!= ENCRYPT_OFF
? LUKS2_METADATA_KEEP_FREE
: 0));
4280 usec_t start_timestamp
= now(CLOCK_MONOTONIC
);
4282 r
= partition_target_prepare(context
, p
, p
->new_size
,
4283 /*need_path=*/ p
->encrypt
!= ENCRYPT_OFF
|| p
->siblings
[VERITY_HASH
],
4288 if (p
->encrypt
!= ENCRYPT_OFF
&& t
->loop
) {
4289 r
= partition_encrypt(context
, p
, t
, /* offline = */ false);
4294 if (p
->copy_blocks_offset
== UINT64_MAX
)
4295 log_info("Copying in '%s' (%s) on block level into future partition %" PRIu64
".",
4296 p
->copy_blocks_path
, FORMAT_BYTES(p
->copy_blocks_size
), p
->partno
);
4298 log_info("Copying in '%s' @ %" PRIu64
" (%s) on block level into future partition %" PRIu64
".",
4299 p
->copy_blocks_path
, p
->copy_blocks_offset
, FORMAT_BYTES(p
->copy_blocks_size
), p
->partno
);
4301 if (lseek(p
->copy_blocks_fd
, p
->copy_blocks_offset
, SEEK_SET
) < 0)
4302 return log_error_errno(errno
, "Failed to seek to copy blocks offset in %s: %m", p
->copy_blocks_path
);
4305 r
= copy_bytes(p
->copy_blocks_fd
, partition_target_fd(t
), p
->copy_blocks_size
, COPY_REFLINK
);
4307 return log_error_errno(r
, "Failed to copy in data from '%s': %m", p
->copy_blocks_path
);
4309 log_info("Copying in of '%s' on block level completed.", p
->copy_blocks_path
);
4311 if (p
->encrypt
!= ENCRYPT_OFF
&& !t
->loop
) {
4312 r
= partition_encrypt(context
, p
, t
, /* offline = */ true);
4317 r
= partition_target_sync(context
, p
, t
);
4321 usec_t time_spent
= usec_sub_unsigned(now(CLOCK_MONOTONIC
), start_timestamp
);
4322 if (time_spent
> 250 * USEC_PER_MSEC
) /* Show throughput, but not if we spent too little time on it, since it's just noise then */
4323 log_info("Block level copying and synchronization of partition %" PRIu64
" complete in %s (%s/s).",
4324 p
->partno
, FORMAT_TIMESPAN(time_spent
, 0), FORMAT_BYTES((uint64_t) ((double) p
->copy_blocks_size
/ time_spent
* USEC_PER_SEC
)));
4326 log_info("Block level copying and synchronization of partition %" PRIu64
" complete in %s.",
4327 p
->partno
, FORMAT_TIMESPAN(time_spent
, 0));
4329 if (p
->siblings
[VERITY_HASH
] && !partition_type_defer(&p
->siblings
[VERITY_HASH
]->type
)) {
4330 r
= partition_format_verity_hash(context
, p
->siblings
[VERITY_HASH
],
4331 /* node = */ NULL
, partition_target_path(t
));
4336 if (p
->siblings
[VERITY_SIG
] && !partition_type_defer(&p
->siblings
[VERITY_SIG
]->type
)) {
4337 r
= partition_format_verity_sig(context
, p
->siblings
[VERITY_SIG
]);
4346 static int add_exclude_path(const char *path
, Hashmap
**denylist
, DenyType type
) {
4347 _cleanup_free_
struct stat
*st
= NULL
;
4353 st
= new(struct stat
, 1);
4357 r
= chase_and_stat(path
, arg_copy_source
, CHASE_PREFIX_ROOT
, NULL
, st
);
4361 return log_error_errno(r
, "Failed to stat source file '%s/%s': %m", strempty(arg_copy_source
), path
);
4363 r
= hashmap_ensure_put(denylist
, &inode_hash_ops
, st
, INT_TO_PTR(type
));
4374 static int make_copy_files_denylist(
4381 _cleanup_hashmap_free_ Hashmap
*denylist
= NULL
;
4390 /* Always exclude the top level APIVFS and temporary directories since the contents of these
4391 * directories are almost certainly not intended to end up in an image. */
4393 NULSTR_FOREACH(s
, APIVFS_TMP_DIRS_NULSTR
) {
4394 r
= add_exclude_path(s
, &denylist
, DENY_CONTENTS
);
4399 /* Add the user configured excludes. */
4401 STRV_FOREACH(e
, p
->exclude_files_source
) {
4402 r
= add_exclude_path(*e
, &denylist
, endswith(*e
, "/") ? DENY_CONTENTS
: DENY_INODE
);
4407 STRV_FOREACH(e
, p
->exclude_files_target
) {
4408 _cleanup_free_
char *path
= NULL
;
4410 const char *s
= path_startswith(*e
, target
);
4414 path
= path_join(source
, s
);
4418 r
= add_exclude_path(path
, &denylist
, endswith(*e
, "/") ? DENY_CONTENTS
: DENY_INODE
);
4423 /* If we're populating a root partition, we don't want any files to end up under the APIVFS mount
4424 * points. While we already exclude <source>/proc, users could still do something such as
4425 * "CopyFiles=/abc:/". Now, if /abc has a proc subdirectory with files in it, those will end up in
4426 * the top level proc directory in the root partition, which we want to avoid. To deal with these
4427 * cases, whenever we're populating a root partition and the target of CopyFiles= is the root
4428 * directory of the root partition, we exclude all directories under the source that are named after
4429 * APIVFS directories or named after mount points of other partitions that are also going to be part
4432 if (p
->type
.designator
== PARTITION_ROOT
&& empty_or_root(target
)) {
4433 LIST_FOREACH(partitions
, q
, context
->partitions
) {
4434 if (q
->type
.designator
== PARTITION_ROOT
)
4437 const char *sources
= gpt_partition_type_mountpoint_nulstr(q
->type
);
4441 NULSTR_FOREACH(s
, sources
) {
4442 _cleanup_free_
char *path
= NULL
;
4444 /* Exclude only the children of partition mount points so that the nested
4445 * partition mount point itself still ends up in the upper partition. */
4447 path
= path_join(source
, s
);
4451 r
= add_exclude_path(path
, &denylist
, DENY_CONTENTS
);
4457 NULSTR_FOREACH(s
, APIVFS_TMP_DIRS_NULSTR
) {
4458 _cleanup_free_
char *path
= NULL
;
4460 path
= path_join(source
, s
);
4464 r
= add_exclude_path(path
, &denylist
, DENY_CONTENTS
);
4470 *ret
= TAKE_PTR(denylist
);
4474 static int add_subvolume_path(const char *path
, Set
**subvolumes
) {
4475 _cleanup_free_
struct stat
*st
= NULL
;
4481 st
= new(struct stat
, 1);
4485 r
= chase_and_stat(path
, arg_copy_source
, CHASE_PREFIX_ROOT
, NULL
, st
);
4489 return log_error_errno(r
, "Failed to stat source file '%s/%s': %m", strempty(arg_copy_source
), path
);
4491 r
= set_ensure_consume(subvolumes
, &inode_hash_ops
, TAKE_PTR(st
));
4498 static int make_subvolumes_set(
4504 _cleanup_set_free_ Set
*subvolumes
= NULL
;
4512 STRV_FOREACH(subvolume
, p
->subvolumes
) {
4513 _cleanup_free_
char *path
= NULL
;
4515 const char *s
= path_startswith(*subvolume
, target
);
4519 path
= path_join(source
, s
);
4523 r
= add_subvolume_path(path
, &subvolumes
);
4528 *ret
= TAKE_PTR(subvolumes
);
4532 static int do_copy_files(Context
*context
, Partition
*p
, const char *root
) {
4538 /* copy_tree_at() automatically copies the permissions of source directories to target directories if
4539 * it created them. However, the root directory is created by us, so we have to manually take care
4540 * that it is initialized. We use the first source directory targeting "/" as the metadata source for
4541 * the root directory. */
4542 STRV_FOREACH_PAIR(source
, target
, p
->copy_files
) {
4543 _cleanup_close_
int rfd
= -EBADF
, sfd
= -EBADF
;
4545 if (!path_equal(*target
, "/"))
4548 rfd
= open(root
, O_DIRECTORY
|O_CLOEXEC
|O_NOFOLLOW
);
4552 sfd
= chase_and_open(*source
, arg_copy_source
, CHASE_PREFIX_ROOT
, O_PATH
|O_DIRECTORY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
4554 return log_error_errno(sfd
, "Failed to open source file '%s%s': %m", strempty(arg_copy_source
), *source
);
4556 (void) copy_xattr(sfd
, NULL
, rfd
, NULL
, COPY_ALL_XATTRS
);
4557 (void) copy_access(sfd
, rfd
);
4558 (void) copy_times(sfd
, rfd
, 0);
4563 STRV_FOREACH_PAIR(source
, target
, p
->copy_files
) {
4564 _cleanup_hashmap_free_ Hashmap
*denylist
= NULL
;
4565 _cleanup_set_free_ Set
*subvolumes_by_source_inode
= NULL
;
4566 _cleanup_close_
int sfd
= -EBADF
, pfd
= -EBADF
, tfd
= -EBADF
;
4568 r
= make_copy_files_denylist(context
, p
, *source
, *target
, &denylist
);
4572 r
= make_subvolumes_set(context
, p
, *source
, *target
, &subvolumes_by_source_inode
);
4576 sfd
= chase_and_open(*source
, arg_copy_source
, CHASE_PREFIX_ROOT
, O_CLOEXEC
|O_NOCTTY
, NULL
);
4577 if (sfd
== -ENOENT
) {
4578 log_notice_errno(sfd
, "Failed to open source file '%s%s', skipping: %m", strempty(arg_copy_source
), *source
);
4582 return log_error_errno(sfd
, "Failed to open source file '%s%s': %m", strempty(arg_copy_source
), *source
);
4584 r
= fd_verify_regular(sfd
);
4587 return log_error_errno(r
, "Failed to check type of source file '%s': %m", *source
);
4589 /* We are looking at a directory */
4590 tfd
= chase_and_open(*target
, root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
4592 _cleanup_free_
char *dn
= NULL
, *fn
= NULL
;
4595 return log_error_errno(tfd
, "Failed to open target directory '%s': %m", *target
);
4597 r
= path_extract_filename(*target
, &fn
);
4599 return log_error_errno(r
, "Failed to extract filename from '%s': %m", *target
);
4601 r
= path_extract_directory(*target
, &dn
);
4603 return log_error_errno(r
, "Failed to extract directory from '%s': %m", *target
);
4605 r
= mkdir_p_root(root
, dn
, UID_INVALID
, GID_INVALID
, 0755, p
->subvolumes
);
4607 return log_error_errno(r
, "Failed to create parent directory '%s': %m", dn
);
4609 pfd
= chase_and_open(dn
, root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
4611 return log_error_errno(pfd
, "Failed to open parent directory of target: %m");
4616 UID_INVALID
, GID_INVALID
,
4617 COPY_REFLINK
|COPY_HOLES
|COPY_MERGE
|COPY_REPLACE
|COPY_SIGINT
|COPY_HARDLINKS
|COPY_ALL_XATTRS
|COPY_GRACEFUL_WARN
|COPY_TRUNCATE
,
4618 denylist
, subvolumes_by_source_inode
);
4623 UID_INVALID
, GID_INVALID
,
4624 COPY_REFLINK
|COPY_HOLES
|COPY_MERGE
|COPY_REPLACE
|COPY_SIGINT
|COPY_HARDLINKS
|COPY_ALL_XATTRS
|COPY_GRACEFUL_WARN
|COPY_TRUNCATE
,
4625 denylist
, subvolumes_by_source_inode
);
4627 return log_error_errno(r
, "Failed to copy '%s%s' to '%s%s': %m",
4628 strempty(arg_copy_source
), *source
, strempty(root
), *target
);
4630 _cleanup_free_
char *dn
= NULL
, *fn
= NULL
;
4632 /* We are looking at a regular file */
4634 r
= path_extract_filename(*target
, &fn
);
4635 if (r
== -EADDRNOTAVAIL
|| r
== O_DIRECTORY
)
4636 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
),
4637 "Target path '%s' refers to a directory, but source path '%s' refers to regular file, can't copy.", *target
, *source
);
4639 return log_error_errno(r
, "Failed to extract filename from '%s': %m", *target
);
4641 r
= path_extract_directory(*target
, &dn
);
4643 return log_error_errno(r
, "Failed to extract directory from '%s': %m", *target
);
4645 r
= mkdir_p_root(root
, dn
, UID_INVALID
, GID_INVALID
, 0755, p
->subvolumes
);
4647 return log_error_errno(r
, "Failed to create parent directory: %m");
4649 pfd
= chase_and_open(dn
, root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
4651 return log_error_errno(pfd
, "Failed to open parent directory of target: %m");
4653 tfd
= openat(pfd
, fn
, O_CREAT
|O_EXCL
|O_WRONLY
|O_CLOEXEC
, 0700);
4655 return log_error_errno(errno
, "Failed to create target file '%s': %m", *target
);
4657 r
= copy_bytes(sfd
, tfd
, UINT64_MAX
, COPY_REFLINK
|COPY_HOLES
|COPY_SIGINT
|COPY_TRUNCATE
);
4659 return log_error_errno(r
, "Failed to copy '%s' to '%s%s': %m", *source
, strempty(arg_copy_source
), *target
);
4661 (void) copy_xattr(sfd
, NULL
, tfd
, NULL
, COPY_ALL_XATTRS
);
4662 (void) copy_access(sfd
, tfd
);
4663 (void) copy_times(sfd
, tfd
, 0);
4670 static int do_make_directories(Partition
*p
, const char *root
) {
4676 STRV_FOREACH(d
, p
->make_directories
) {
4677 r
= mkdir_p_root(root
, *d
, UID_INVALID
, GID_INVALID
, 0755, p
->subvolumes
);
4679 return log_error_errno(r
, "Failed to create directory '%s' in file system: %m", *d
);
4685 static bool partition_needs_populate(Partition
*p
) {
4687 return !strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
);
4690 static int partition_populate_directory(Context
*context
, Partition
*p
, char **ret
) {
4691 _cleanup_(rm_rf_physical_and_freep
) char *root
= NULL
;
4697 log_info("Populating %s filesystem.", p
->format
);
4699 r
= var_tmp_dir(&vt
);
4701 return log_error_errno(r
, "Could not determine temporary directory: %m");
4703 r
= tempfn_random_child(vt
, "repart", &root
);
4705 return log_error_errno(r
, "Failed to generate temporary directory: %m");
4707 r
= mkdir(root
, 0755);
4709 return log_error_errno(errno
, "Failed to create temporary directory: %m");
4711 r
= do_copy_files(context
, p
, root
);
4715 r
= do_make_directories(p
, root
);
4719 log_info("Successfully populated %s filesystem.", p
->format
);
4721 *ret
= TAKE_PTR(root
);
4725 static int partition_populate_filesystem(Context
*context
, Partition
*p
, const char *node
) {
4731 log_info("Populating %s filesystem.", p
->format
);
4733 /* We copy in a child process, since we have to mount the fs for that, and we don't want that fs to
4734 * appear in the host namespace. Hence we fork a child that has its own file system namespace and
4735 * detached mount propagation. */
4737 r
= safe_fork("(sd-copy)", FORK_DEATHSIG_SIGTERM
|FORK_LOG
|FORK_WAIT
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, NULL
);
4741 static const char fs
[] = "/run/systemd/mount-root";
4742 /* This is a child process with its own mount namespace and propagation to host turned off */
4744 r
= mkdir_p(fs
, 0700);
4746 log_error_errno(r
, "Failed to create mount point: %m");
4747 _exit(EXIT_FAILURE
);
4750 if (mount_nofollow_verbose(LOG_ERR
, node
, fs
, p
->format
, MS_NOATIME
|MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
) < 0)
4751 _exit(EXIT_FAILURE
);
4753 if (do_copy_files(context
, p
, fs
) < 0)
4754 _exit(EXIT_FAILURE
);
4756 if (do_make_directories(p
, fs
) < 0)
4757 _exit(EXIT_FAILURE
);
4759 r
= syncfs_path(AT_FDCWD
, fs
);
4761 log_error_errno(r
, "Failed to synchronize written files: %m");
4762 _exit(EXIT_FAILURE
);
4765 _exit(EXIT_SUCCESS
);
4768 log_info("Successfully populated %s filesystem.", p
->format
);
4772 static int context_mkfs(Context
*context
) {
4777 /* Make a file system */
4779 LIST_FOREACH(partitions
, p
, context
->partitions
) {
4780 _cleanup_(rm_rf_physical_and_freep
) char *root
= NULL
;
4781 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
4782 _cleanup_strv_free_
char **extra_mkfs_options
= NULL
;
4787 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
4793 /* Minimized partitions will use the copy blocks logic so let's make sure to skip those here. */
4794 if (p
->copy_blocks_fd
>= 0)
4797 if (partition_type_defer(&p
->type
))
4800 assert(p
->offset
!= UINT64_MAX
);
4801 assert(p
->new_size
!= UINT64_MAX
);
4802 assert(p
->new_size
>= (p
->encrypt
!= ENCRYPT_OFF
? LUKS2_METADATA_KEEP_FREE
: 0));
4804 /* If we're doing encryption, we make sure we keep free space at the end which is required
4805 * for cryptsetup's offline encryption. */
4806 r
= partition_target_prepare(context
, p
,
4807 p
->new_size
- (p
->encrypt
!= ENCRYPT_OFF
? LUKS2_METADATA_KEEP_FREE
: 0),
4808 /*need_path=*/ true,
4813 if (p
->encrypt
!= ENCRYPT_OFF
&& t
->loop
) {
4814 r
= partition_target_grow(t
, p
->new_size
);
4818 r
= partition_encrypt(context
, p
, t
, /* offline = */ false);
4820 return log_error_errno(r
, "Failed to encrypt device: %m");
4823 log_info("Formatting future partition %" PRIu64
".", p
->partno
);
4825 /* If we're not writing to a loop device or if we're populating a read-only filesystem, we
4826 * have to populate using the filesystem's mkfs's --root (or equivalent) option. To do that,
4827 * we need to set up the final directory tree beforehand. */
4829 if (partition_needs_populate(p
) && (!t
->loop
|| fstype_is_ro(p
->format
))) {
4830 if (!mkfs_supports_root_option(p
->format
))
4831 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
),
4832 "Loop device access is required to populate %s filesystems.",
4835 r
= partition_populate_directory(context
, p
, &root
);
4840 r
= mkfs_options_from_env("REPART", p
->format
, &extra_mkfs_options
);
4842 return log_error_errno(r
,
4843 "Failed to determine mkfs command line options for '%s': %m",
4846 r
= make_filesystem(partition_target_path(t
), p
->format
, strempty(p
->new_label
), root
,
4847 p
->fs_uuid
, arg_discard
, /* quiet = */ false,
4848 context
->fs_sector_size
, extra_mkfs_options
);
4852 log_info("Successfully formatted future partition %" PRIu64
".", p
->partno
);
4854 /* If we're writing to a loop device, we can now mount the empty filesystem and populate it. */
4855 if (partition_needs_populate(p
) && !root
) {
4858 r
= partition_populate_filesystem(context
, p
, partition_target_path(t
));
4863 if (p
->encrypt
!= ENCRYPT_OFF
&& !t
->loop
) {
4864 r
= partition_target_grow(t
, p
->new_size
);
4868 r
= partition_encrypt(context
, p
, t
, /* offline = */ true);
4870 return log_error_errno(r
, "Failed to encrypt device: %m");
4873 /* Note that we always sync explicitly here, since mkfs.fat doesn't do that on its own, and
4874 * if we don't sync before detaching a block device the in-flight sectors possibly won't hit
4877 r
= partition_target_sync(context
, p
, t
);
4881 if (p
->siblings
[VERITY_HASH
] && !partition_type_defer(&p
->siblings
[VERITY_HASH
]->type
)) {
4882 r
= partition_format_verity_hash(context
, p
->siblings
[VERITY_HASH
],
4883 /* node = */ NULL
, partition_target_path(t
));
4888 if (p
->siblings
[VERITY_SIG
] && !partition_type_defer(&p
->siblings
[VERITY_SIG
]->type
)) {
4889 r
= partition_format_verity_sig(context
, p
->siblings
[VERITY_SIG
]);
4898 static int parse_x509_certificate(const char *certificate
, size_t certificate_size
, X509
**ret
) {
4900 _cleanup_(X509_freep
) X509
*cert
= NULL
;
4901 _cleanup_(BIO_freep
) BIO
*cb
= NULL
;
4903 assert(certificate
);
4904 assert(certificate_size
> 0);
4907 cb
= BIO_new_mem_buf(certificate
, certificate_size
);
4911 cert
= PEM_read_bio_X509(cb
, NULL
, NULL
, NULL
);
4913 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Failed to parse X.509 certificate: %s",
4914 ERR_error_string(ERR_get_error(), NULL
));
4917 *ret
= TAKE_PTR(cert
);
4921 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "openssl is not supported, cannot parse X509 certificate.");
4925 static int parse_private_key(const char *key
, size_t key_size
, EVP_PKEY
**ret
) {
4927 _cleanup_(BIO_freep
) BIO
*kb
= NULL
;
4928 _cleanup_(EVP_PKEY_freep
) EVP_PKEY
*pk
= NULL
;
4931 assert(key_size
> 0);
4934 kb
= BIO_new_mem_buf(key
, key_size
);
4938 pk
= PEM_read_bio_PrivateKey(kb
, NULL
, NULL
, NULL
);
4940 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse PEM private key: %s",
4941 ERR_error_string(ERR_get_error(), NULL
));
4944 *ret
= TAKE_PTR(pk
);
4948 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "openssl is not supported, cannot parse private key.");
4952 static int partition_acquire_uuid(Context
*context
, Partition
*p
, sd_id128_t
*ret
) {
4954 sd_id128_t type_uuid
;
4956 } _packed_ plaintext
= {};
4958 uint8_t md
[SHA256_DIGEST_SIZE
];
4969 /* Calculate a good UUID for the indicated partition. We want a certain degree of reproducibility,
4970 * hence we won't generate the UUIDs randomly. Instead we use a cryptographic hash (precisely:
4971 * HMAC-SHA256) to derive them from a single seed. The seed is generally the machine ID of the
4972 * installation we are processing, but if random behaviour is desired can be random, too. We use the
4973 * seed value as key for the HMAC (since the machine ID is something we generally don't want to leak)
4974 * and the partition type as plaintext. The partition type is suffixed with a counter (only for the
4975 * second and later partition of the same type) if we have more than one partition of the same
4976 * time. Or in other words:
4979 * SEED := /etc/machine-id
4981 * If first partition instance of type TYPE_UUID:
4982 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
4984 * For all later partition instances of type TYPE_UUID with INSTANCE being the LE64 encoded instance number:
4985 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID || INSTANCE)
4988 LIST_FOREACH(partitions
, q
, context
->partitions
) {
4992 if (!sd_id128_equal(p
->type
.uuid
, q
->type
.uuid
))
4998 plaintext
.type_uuid
= p
->type
.uuid
;
4999 plaintext
.counter
= htole64(k
);
5001 hmac_sha256(context
->seed
.bytes
, sizeof(context
->seed
.bytes
),
5003 k
== 0 ? sizeof(sd_id128_t
) : sizeof(plaintext
),
5006 /* Take the first half, mark it as v4 UUID */
5007 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
5008 result
.id
= id128_make_v4_uuid(result
.id
);
5010 /* Ensure this partition UUID is actually unique, and there's no remaining partition from an earlier run? */
5011 LIST_FOREACH(partitions
, q
, context
->partitions
) {
5015 if (sd_id128_in_set(result
.id
, q
->current_uuid
, q
->new_uuid
)) {
5016 log_warning("Partition UUID calculated from seed for partition %" PRIu64
" already used, reverting to randomized UUID.", p
->partno
);
5018 r
= sd_id128_randomize(&result
.id
);
5020 return log_error_errno(r
, "Failed to generate randomized UUID: %m");
5030 static int partition_acquire_label(Context
*context
, Partition
*p
, char **ret
) {
5031 _cleanup_free_
char *label
= NULL
;
5039 prefix
= gpt_partition_type_uuid_to_string(p
->type
.uuid
);
5044 const char *ll
= label
?: prefix
;
5047 LIST_FOREACH(partitions
, q
, context
->partitions
) {
5051 if (streq_ptr(ll
, q
->current_label
) ||
5052 streq_ptr(ll
, q
->new_label
)) {
5061 label
= mfree(label
);
5062 if (asprintf(&label
, "%s-%u", prefix
, ++k
) < 0)
5067 label
= strdup(prefix
);
5072 *ret
= TAKE_PTR(label
);
5076 static int context_acquire_partition_uuids_and_labels(Context
*context
) {
5081 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5084 /* Never touch foreign partitions */
5085 if (PARTITION_IS_FOREIGN(p
)) {
5086 p
->new_uuid
= p
->current_uuid
;
5088 if (p
->current_label
) {
5089 r
= free_and_strdup_warn(&p
->new_label
, strempty(p
->current_label
));
5097 if (!sd_id128_is_null(p
->current_uuid
))
5098 p
->new_uuid
= uuid
= p
->current_uuid
; /* Never change initialized UUIDs */
5099 else if (p
->new_uuid_is_set
)
5102 /* Not explicitly set by user! */
5103 r
= partition_acquire_uuid(context
, p
, &uuid
);
5107 /* The final verity hash/data UUIDs can only be determined after formatting the
5108 * verity hash partition. However, we still want to use the generated partition UUID
5109 * to derive other UUIDs to keep things unique and reproducible, so we always
5110 * generate a UUID if none is set, but we only use it as the actual partition UUID if
5111 * verity is not configured. */
5112 if (!IN_SET(p
->verity
, VERITY_DATA
, VERITY_HASH
)) {
5114 p
->new_uuid_is_set
= true;
5118 /* Calculate the UUID for the file system as HMAC-SHA256 of the string "file-system-uuid",
5119 * keyed off the partition UUID. */
5120 r
= derive_uuid(uuid
, "file-system-uuid", &p
->fs_uuid
);
5124 if (p
->encrypt
!= ENCRYPT_OFF
) {
5125 r
= derive_uuid(uuid
, "luks-uuid", &p
->luks_uuid
);
5130 /* Derive the verity salt and verity superblock UUID from the seed to keep them reproducible */
5131 if (p
->verity
== VERITY_HASH
) {
5132 derive_salt(context
->seed
, "verity-salt", p
->verity_salt
);
5134 r
= derive_uuid(context
->seed
, "verity-uuid", &p
->verity_uuid
);
5136 return log_error_errno(r
, "Failed to acquire verity uuid: %m");
5139 if (!isempty(p
->current_label
)) {
5140 /* never change initialized labels */
5141 r
= free_and_strdup_warn(&p
->new_label
, p
->current_label
);
5144 } else if (!p
->new_label
) {
5145 /* Not explicitly set by user! */
5147 r
= partition_acquire_label(context
, p
, &p
->new_label
);
5156 static int set_gpt_flags(struct fdisk_partition
*q
, uint64_t flags
) {
5157 _cleanup_free_
char *a
= NULL
;
5159 for (unsigned i
= 0; i
< sizeof(flags
) * 8; i
++) {
5160 uint64_t bit
= UINT64_C(1) << i
;
5161 char buf
[DECIMAL_STR_MAX(unsigned)+1];
5163 if (!FLAGS_SET(flags
, bit
))
5166 xsprintf(buf
, "%u", i
);
5167 if (!strextend_with_separator(&a
, ",", buf
))
5171 return fdisk_partition_set_attrs(q
, a
);
5174 static uint64_t partition_merge_flags(Partition
*p
) {
5181 if (p
->no_auto
>= 0) {
5182 if (gpt_partition_type_knows_no_auto(p
->type
))
5183 SET_FLAG(f
, SD_GPT_FLAG_NO_AUTO
, p
->no_auto
);
5185 char buffer
[SD_ID128_UUID_STRING_MAX
];
5186 log_warning("Configured NoAuto=%s for partition type '%s' that doesn't support it, ignoring.",
5188 gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, buffer
));
5192 if (p
->read_only
>= 0) {
5193 if (gpt_partition_type_knows_read_only(p
->type
))
5194 SET_FLAG(f
, SD_GPT_FLAG_READ_ONLY
, p
->read_only
);
5196 char buffer
[SD_ID128_UUID_STRING_MAX
];
5197 log_warning("Configured ReadOnly=%s for partition type '%s' that doesn't support it, ignoring.",
5198 yes_no(p
->read_only
),
5199 gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, buffer
));
5203 if (p
->growfs
>= 0) {
5204 if (gpt_partition_type_knows_growfs(p
->type
))
5205 SET_FLAG(f
, SD_GPT_FLAG_GROWFS
, p
->growfs
);
5207 char buffer
[SD_ID128_UUID_STRING_MAX
];
5208 log_warning("Configured GrowFileSystem=%s for partition type '%s' that doesn't support it, ignoring.",
5210 gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, buffer
));
5217 static int context_mangle_partitions(Context
*context
) {
5222 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5226 if (partition_type_defer(&p
->type
))
5229 assert(p
->new_size
!= UINT64_MAX
);
5230 assert(p
->offset
!= UINT64_MAX
);
5231 assert(p
->partno
!= UINT64_MAX
);
5233 if (PARTITION_EXISTS(p
)) {
5234 bool changed
= false;
5236 assert(p
->current_partition
);
5238 if (p
->new_size
!= p
->current_size
) {
5239 assert(p
->new_size
>= p
->current_size
);
5240 assert(p
->new_size
% context
->sector_size
== 0);
5242 r
= fdisk_partition_size_explicit(p
->current_partition
, true);
5244 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
5246 r
= fdisk_partition_set_size(p
->current_partition
, p
->new_size
/ context
->sector_size
);
5248 return log_error_errno(r
, "Failed to grow partition: %m");
5250 log_info("Growing existing partition %" PRIu64
".", p
->partno
);
5254 if (!sd_id128_equal(p
->new_uuid
, p
->current_uuid
)) {
5255 r
= fdisk_partition_set_uuid(p
->current_partition
, SD_ID128_TO_UUID_STRING(p
->new_uuid
));
5257 return log_error_errno(r
, "Failed to set partition UUID: %m");
5259 log_info("Initializing UUID of existing partition %" PRIu64
".", p
->partno
);
5263 if (!streq_ptr(p
->new_label
, p
->current_label
)) {
5264 r
= fdisk_partition_set_name(p
->current_partition
, strempty(p
->new_label
));
5266 return log_error_errno(r
, "Failed to set partition label: %m");
5268 log_info("Setting partition label of existing partition %" PRIu64
".", p
->partno
);
5273 assert(!PARTITION_IS_FOREIGN(p
)); /* never touch foreign partitions */
5275 r
= fdisk_set_partition(context
->fdisk_context
, p
->partno
, p
->current_partition
);
5277 return log_error_errno(r
, "Failed to update partition: %m");
5280 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*q
= NULL
;
5281 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
5283 assert(!p
->new_partition
);
5284 assert(p
->offset
% context
->sector_size
== 0);
5285 assert(p
->new_size
% context
->sector_size
== 0);
5286 assert(p
->new_label
);
5288 t
= fdisk_new_parttype();
5292 r
= fdisk_parttype_set_typestr(t
, SD_ID128_TO_UUID_STRING(p
->type
.uuid
));
5294 return log_error_errno(r
, "Failed to initialize partition type: %m");
5296 q
= fdisk_new_partition();
5300 r
= fdisk_partition_set_type(q
, t
);
5302 return log_error_errno(r
, "Failed to set partition type: %m");
5304 r
= fdisk_partition_size_explicit(q
, true);
5306 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
5308 r
= fdisk_partition_set_start(q
, p
->offset
/ context
->sector_size
);
5310 return log_error_errno(r
, "Failed to position partition: %m");
5312 r
= fdisk_partition_set_size(q
, p
->new_size
/ context
->sector_size
);
5314 return log_error_errno(r
, "Failed to grow partition: %m");
5316 r
= fdisk_partition_set_partno(q
, p
->partno
);
5318 return log_error_errno(r
, "Failed to set partition number: %m");
5320 r
= fdisk_partition_set_uuid(q
, SD_ID128_TO_UUID_STRING(p
->new_uuid
));
5322 return log_error_errno(r
, "Failed to set partition UUID: %m");
5324 r
= fdisk_partition_set_name(q
, strempty(p
->new_label
));
5326 return log_error_errno(r
, "Failed to set partition label: %m");
5328 /* Merge the no auto + read only + growfs setting with the literal flags, and set them for the partition */
5329 r
= set_gpt_flags(q
, partition_merge_flags(p
));
5331 return log_error_errno(r
, "Failed to set GPT partition flags: %m");
5333 log_info("Adding new partition %" PRIu64
" to partition table.", p
->partno
);
5335 r
= fdisk_add_partition(context
->fdisk_context
, q
, NULL
);
5337 return log_error_errno(r
, "Failed to add partition: %m");
5339 assert(!p
->new_partition
);
5340 p
->new_partition
= TAKE_PTR(q
);
5347 static int split_name_printf(Partition
*p
, char **ret
) {
5350 const Specifier table
[] = {
5351 { 't', specifier_string
, GPT_PARTITION_TYPE_UUID_TO_STRING_HARDER(p
->type
.uuid
) },
5352 { 'T', specifier_id128
, &p
->type
.uuid
},
5353 { 'U', specifier_id128
, &p
->new_uuid
},
5354 { 'n', specifier_uint64
, &p
->partno
},
5356 COMMON_SYSTEM_SPECIFIERS
,
5360 return specifier_printf(p
->split_name_format
, NAME_MAX
, table
, arg_root
, p
, ret
);
5363 static int split_node(const char *node
, char **ret_base
, char **ret_ext
) {
5364 _cleanup_free_
char *base
= NULL
, *ext
= NULL
;
5372 r
= path_extract_filename(node
, &base
);
5373 if (r
== O_DIRECTORY
|| r
== -EADDRNOTAVAIL
)
5374 return log_error_errno(r
, "Device node %s cannot be a directory", node
);
5376 return log_error_errno(r
, "Failed to extract filename from %s: %m", node
);
5378 e
= endswith(base
, ".raw");
5387 *ret_base
= TAKE_PTR(base
);
5388 *ret_ext
= TAKE_PTR(ext
);
5393 static int split_name_resolve(Context
*context
) {
5394 _cleanup_free_
char *parent
= NULL
, *base
= NULL
, *ext
= NULL
;
5399 r
= path_extract_directory(context
->node
, &parent
);
5400 if (r
< 0 && r
!= -EDESTADDRREQ
)
5401 return log_error_errno(r
, "Failed to extract directory from %s: %m", context
->node
);
5403 r
= split_node(context
->node
, &base
, &ext
);
5407 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5408 _cleanup_free_
char *resolved
= NULL
;
5413 if (!p
->split_name_format
)
5416 r
= split_name_printf(p
, &resolved
);
5418 return log_error_errno(r
, "Failed to resolve specifiers in %s: %m", p
->split_name_format
);
5421 p
->split_path
= strjoin(parent
, "/", base
, ".", resolved
, ext
);
5423 p
->split_path
= strjoin(base
, ".", resolved
, ext
);
5428 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5432 LIST_FOREACH(partitions
, q
, context
->partitions
) {
5439 if (!streq(p
->split_path
, q
->split_path
))
5442 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
5443 "%s and %s have the same resolved split name \"%s\", refusing",
5444 p
->definition_path
, q
->definition_path
, p
->split_path
);
5451 static int context_split(Context
*context
) {
5459 /* We can't do resolution earlier because the partition UUIDs for verity partitions are only filled
5460 * in after they've been generated. */
5462 r
= split_name_resolve(context
);
5466 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5467 _cleanup_close_
int fdt
= -EBADF
;
5475 if (partition_type_defer(&p
->type
))
5478 fdt
= open(p
->split_path
, O_WRONLY
|O_NOCTTY
|O_CLOEXEC
|O_NOFOLLOW
|O_CREAT
|O_EXCL
, 0666);
5480 return log_error_errno(fdt
, "Failed to open split partition file %s: %m", p
->split_path
);
5483 assert_se((fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
5485 if (lseek(fd
, p
->offset
, SEEK_SET
) < 0)
5486 return log_error_errno(errno
, "Failed to seek to partition offset: %m");
5488 r
= copy_bytes(fd
, fdt
, p
->new_size
, COPY_REFLINK
|COPY_HOLES
|COPY_TRUNCATE
);
5490 return log_error_errno(r
, "Failed to copy to split partition %s: %m", p
->split_path
);
5496 static int context_write_partition_table(Context
*context
) {
5497 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*original_table
= NULL
;
5502 if (!context
->from_scratch
&& !context_changed(context
)) {
5503 log_info("No changes.");
5508 log_notice("Refusing to repartition, please re-run with --dry-run=no.");
5512 log_info("Applying changes to %s.", context
->node
);
5514 if (context
->from_scratch
&& arg_empty
!= EMPTY_CREATE
) {
5515 /* Erase everything if we operate from scratch, except if the image was just created anyway, and thus is definitely empty. */
5516 r
= context_wipe_range(context
, 0, context
->total
);
5520 log_info("Wiped block device.");
5523 r
= context_discard_range(context
, 0, context
->total
);
5524 if (r
== -EOPNOTSUPP
)
5525 log_info("Storage does not support discard, not discarding entire block device data.");
5527 return log_error_errno(r
, "Failed to discard entire block device: %m");
5529 log_info("Discarded entire block device.");
5533 r
= fdisk_get_partitions(context
->fdisk_context
, &original_table
);
5535 return log_error_errno(r
, "Failed to acquire partition table: %m");
5537 /* Wipe fs signatures and discard sectors where the new partitions are going to be placed and in the
5538 * gaps between partitions, just to be sure. */
5539 r
= context_wipe_and_discard(context
);
5543 r
= context_copy_blocks(context
);
5547 r
= context_mkfs(context
);
5551 r
= context_mangle_partitions(context
);
5555 log_info("Writing new partition table.");
5557 r
= fdisk_write_disklabel(context
->fdisk_context
);
5559 return log_error_errno(r
, "Failed to write partition table: %m");
5561 capable
= blockdev_partscan_enabled(fdisk_get_devfd(context
->fdisk_context
));
5562 if (capable
== -ENOTBLK
)
5563 log_debug("Not telling kernel to reread partition table, since we are not operating on a block device.");
5564 else if (capable
< 0)
5565 return log_error_errno(capable
, "Failed to check if block device supports partition scanning: %m");
5566 else if (capable
> 0) {
5567 log_info("Telling kernel to reread partition table.");
5569 if (context
->from_scratch
)
5570 r
= fdisk_reread_partition_table(context
->fdisk_context
);
5572 r
= fdisk_reread_changes(context
->fdisk_context
, original_table
);
5574 return log_error_errno(r
, "Failed to reread partition table: %m");
5576 log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
5578 log_info("All done.");
5583 static int context_read_seed(Context
*context
, const char *root
) {
5588 if (!sd_id128_is_null(context
->seed
))
5591 if (!arg_randomize
) {
5592 r
= id128_get_machine(root
, &context
->seed
);
5596 if (!ERRNO_IS_MACHINE_ID_UNSET(r
))
5597 return log_error_errno(r
, "Failed to parse machine ID of image: %m");
5599 log_info("No machine ID set, using randomized partition UUIDs.");
5602 r
= sd_id128_randomize(&context
->seed
);
5604 return log_error_errno(r
, "Failed to generate randomized seed: %m");
5609 static int context_factory_reset(Context
*context
) {
5615 if (arg_factory_reset
<= 0)
5618 if (context
->from_scratch
) /* Nothing to reset if we start from scratch */
5622 log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
5626 log_info("Applying factory reset.");
5628 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5630 if (!p
->factory_reset
|| !PARTITION_EXISTS(p
))
5633 assert(p
->partno
!= UINT64_MAX
);
5635 log_info("Removing partition %" PRIu64
" for factory reset.", p
->partno
);
5637 r
= fdisk_delete_partition(context
->fdisk_context
, p
->partno
);
5639 return log_error_errno(r
, "Failed to remove partition %" PRIu64
": %m", p
->partno
);
5645 log_info("Factory reset requested, but no partitions to delete found.");
5649 r
= fdisk_write_disklabel(context
->fdisk_context
);
5651 return log_error_errno(r
, "Failed to write disk label: %m");
5653 log_info("Successfully deleted %zu partitions.", n
);
5657 static int context_can_factory_reset(Context
*context
) {
5660 LIST_FOREACH(partitions
, p
, context
->partitions
)
5661 if (p
->factory_reset
&& PARTITION_EXISTS(p
))
5667 static int resolve_copy_blocks_auto_candidate(
5668 dev_t partition_devno
,
5669 GptPartitionType partition_type
,
5670 dev_t restrict_devno
,
5671 sd_id128_t
*ret_uuid
) {
5673 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
5674 _cleanup_close_
int fd
= -EBADF
;
5675 _cleanup_free_
char *p
= NULL
;
5676 const char *pttype
, *t
;
5677 sd_id128_t pt_parsed
, u
;
5683 /* Checks if the specified partition has the specified GPT type UUID, and is located on the specified
5684 * 'restrict_devno' device. The type check is particularly relevant if we have Verity volume which is
5685 * backed by two separate partitions: the data and the hash partitions, and we need to find the right
5686 * one of the two. */
5688 r
= block_get_whole_disk(partition_devno
, &whole_devno
);
5690 return log_error_errno(
5692 "Unable to determine containing block device of partition %u:%u: %m",
5693 major(partition_devno
), minor(partition_devno
));
5695 if (restrict_devno
!= (dev_t
) -1 &&
5696 restrict_devno
!= whole_devno
)
5697 return log_error_errno(
5698 SYNTHETIC_ERRNO(EPERM
),
5699 "Partition %u:%u is located outside of block device %u:%u, refusing.",
5700 major(partition_devno
), minor(partition_devno
),
5701 major(restrict_devno
), minor(restrict_devno
));
5703 fd
= r
= device_open_from_devnum(S_IFBLK
, whole_devno
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &p
);
5705 return log_error_errno(r
, "Failed to open block device " DEVNUM_FORMAT_STR
": %m",
5706 DEVNUM_FORMAT_VAL(whole_devno
));
5708 b
= blkid_new_probe();
5713 r
= blkid_probe_set_device(b
, fd
, 0, 0);
5715 return log_error_errno(errno_or_else(ENOMEM
), "Failed to open block device '%s': %m", p
);
5717 (void) blkid_probe_enable_partitions(b
, 1);
5718 (void) blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
5721 r
= blkid_do_safeprobe(b
);
5722 if (r
== _BLKID_SAFEPROBE_ERROR
)
5723 return log_error_errno(errno_or_else(EIO
), "Unable to probe for partition table of '%s': %m", p
);
5724 if (IN_SET(r
, _BLKID_SAFEPROBE_AMBIGUOUS
, _BLKID_SAFEPROBE_NOT_FOUND
)) {
5725 log_debug("Didn't find partition table on block device '%s'.", p
);
5729 assert(r
== _BLKID_SAFEPROBE_FOUND
);
5731 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
5732 if (!streq_ptr(pttype
, "gpt")) {
5733 log_debug("Didn't find a GPT partition table on '%s'.", p
);
5738 pl
= blkid_probe_get_partitions(b
);
5740 return log_error_errno(errno_or_else(EIO
), "Unable read partition table of '%s': %m", p
);
5742 pp
= blkid_partlist_devno_to_partition(pl
, partition_devno
);
5744 log_debug("Partition %u:%u has no matching partition table entry on '%s'.",
5745 major(partition_devno
), minor(partition_devno
), p
);
5749 t
= blkid_partition_get_type_string(pp
);
5751 log_debug("Partition %u:%u has no type on '%s'.",
5752 major(partition_devno
), minor(partition_devno
), p
);
5756 r
= sd_id128_from_string(t
, &pt_parsed
);
5758 log_debug_errno(r
, "Failed to parse partition type \"%s\": %m", t
);
5762 if (!sd_id128_equal(pt_parsed
, partition_type
.uuid
)) {
5763 log_debug("Partition %u:%u has non-matching partition type " SD_ID128_FORMAT_STR
" (needed: " SD_ID128_FORMAT_STR
"), ignoring.",
5764 major(partition_devno
), minor(partition_devno
),
5765 SD_ID128_FORMAT_VAL(pt_parsed
), SD_ID128_FORMAT_VAL(partition_type
.uuid
));
5769 r
= blkid_partition_get_uuid_id128(pp
, &u
);
5771 log_debug_errno(r
, "Partition " DEVNUM_FORMAT_STR
" has no UUID.", DEVNUM_FORMAT_VAL(partition_devno
));
5775 log_debug_errno(r
, "Failed to read partition UUID of " DEVNUM_FORMAT_STR
": %m", DEVNUM_FORMAT_VAL(partition_devno
));
5779 log_debug("Automatically found partition " DEVNUM_FORMAT_STR
" of right type " SD_ID128_FORMAT_STR
".",
5780 DEVNUM_FORMAT_VAL(partition_devno
),
5781 SD_ID128_FORMAT_VAL(pt_parsed
));
5789 static int find_backing_devno(
5794 _cleanup_free_
char *resolved
= NULL
;
5799 r
= chase(path
, root
, CHASE_PREFIX_ROOT
, &resolved
, NULL
);
5803 r
= path_is_mount_point(resolved
, NULL
, 0);
5806 if (r
== 0) /* Not a mount point, then it's not a partition of its own, let's not automatically use it. */
5809 r
= get_block_device(resolved
, ret
);
5812 if (r
== 0) /* Not backed by physical file system, we can't use this */
5818 static int resolve_copy_blocks_auto(
5819 GptPartitionType type
,
5821 dev_t restrict_devno
,
5823 sd_id128_t
*ret_uuid
) {
5825 const char *try1
= NULL
, *try2
= NULL
;
5826 char p
[SYS_BLOCK_PATH_MAX("/slaves")];
5827 _cleanup_closedir_
DIR *d
= NULL
;
5828 sd_id128_t found_uuid
= SD_ID128_NULL
;
5829 dev_t devno
, found
= 0;
5832 /* Enforce some security restrictions: CopyBlocks=auto should not be an avenue to get outside of the
5833 * --root=/--image= confinement. Specifically, refuse CopyBlocks= in combination with --root= at all,
5834 * and restrict block device references in the --image= case to loopback block device we set up.
5836 * restrict_devno contain the dev_t of the loop back device we operate on in case of --image=, and
5837 * thus declares which device (and its partition subdevices) we shall limit access to. If
5838 * restrict_devno is zero no device probing access shall be allowed at all (used for --root=) and if
5839 * it is (dev_t) -1 then free access shall be allowed (if neither switch is used). */
5841 if (restrict_devno
== 0)
5842 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
5843 "Automatic discovery of backing block devices not permitted in --root= mode, refusing.");
5845 /* Handles CopyBlocks=auto, and finds the right source partition to copy from. We look for matching
5846 * partitions in the host, using the appropriate directory as key and ensuring that the partition
5849 if (type
.designator
== PARTITION_ROOT
)
5851 else if (type
.designator
== PARTITION_USR
)
5853 else if (type
.designator
== PARTITION_ROOT_VERITY
)
5855 else if (type
.designator
== PARTITION_USR_VERITY
)
5857 else if (type
.designator
== PARTITION_ESP
) {
5860 } else if (type
.designator
== PARTITION_XBOOTLDR
)
5863 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
5864 "Partition type " SD_ID128_FORMAT_STR
" not supported from automatic source block device discovery.",
5865 SD_ID128_FORMAT_VAL(type
.uuid
));
5867 r
= find_backing_devno(try1
, root
, &devno
);
5868 if (r
== -ENOENT
&& try2
)
5869 r
= find_backing_devno(try2
, root
, &devno
);
5871 return log_error_errno(r
, "Failed to resolve automatic CopyBlocks= path for partition type " SD_ID128_FORMAT_STR
", sorry: %m",
5872 SD_ID128_FORMAT_VAL(type
.uuid
));
5874 xsprintf_sys_block_path(p
, "/slaves", devno
);
5880 _cleanup_free_
char *q
= NULL
, *t
= NULL
;
5885 de
= readdir_no_dot(d
);
5888 return log_error_errno(errno
, "Failed to read directory '%s': %m", p
);
5893 if (!IN_SET(de
->d_type
, DT_LNK
, DT_UNKNOWN
))
5896 q
= path_join(p
, de
->d_name
, "/dev");
5900 r
= read_one_line_file(q
, &t
);
5902 return log_error_errno(r
, "Failed to read %s: %m", q
);
5904 r
= parse_devnum(t
, &sl
);
5906 log_debug_errno(r
, "Failed to parse %s, ignoring: %m", q
);
5909 if (major(sl
) == 0) {
5910 log_debug("Device backing %s is special, ignoring.", q
);
5914 r
= resolve_copy_blocks_auto_candidate(sl
, type
, restrict_devno
, &u
);
5918 /* We found a matching one! */
5920 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
5921 "Multiple matching partitions found, refusing.");
5927 } else if (errno
!= ENOENT
)
5928 return log_error_errno(errno
, "Failed open %s: %m", p
);
5930 r
= resolve_copy_blocks_auto_candidate(devno
, type
, restrict_devno
, &found_uuid
);
5938 return log_error_errno(SYNTHETIC_ERRNO(ENXIO
),
5939 "Unable to automatically discover suitable partition to copy blocks from.");
5945 *ret_uuid
= found_uuid
;
5950 static int context_open_copy_block_paths(
5952 dev_t restrict_devno
) {
5958 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5959 _cleanup_close_
int source_fd
= -EBADF
;
5960 _cleanup_free_
char *opened
= NULL
;
5961 sd_id128_t uuid
= SD_ID128_NULL
;
5965 if (p
->copy_blocks_fd
>= 0)
5968 assert(p
->copy_blocks_size
== UINT64_MAX
);
5970 if (PARTITION_EXISTS(p
)) /* Never copy over partitions that already exist! */
5973 if (p
->copy_blocks_path
) {
5975 source_fd
= chase_and_open(p
->copy_blocks_path
, p
->copy_blocks_root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &opened
);
5977 return log_error_errno(source_fd
, "Failed to open '%s': %m", p
->copy_blocks_path
);
5979 if (fstat(source_fd
, &st
) < 0)
5980 return log_error_errno(errno
, "Failed to stat block copy file '%s': %m", opened
);
5982 if (!S_ISREG(st
.st_mode
) && restrict_devno
!= (dev_t
) -1)
5983 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
5984 "Copying from block device node is not permitted in --image=/--root= mode, refusing.");
5986 } else if (p
->copy_blocks_auto
) {
5987 dev_t devno
= 0; /* Fake initialization to appease gcc. */
5989 r
= resolve_copy_blocks_auto(p
->type
, p
->copy_blocks_root
, restrict_devno
, &devno
, &uuid
);
5994 source_fd
= r
= device_open_from_devnum(S_IFBLK
, devno
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &opened
);
5996 return log_error_errno(r
, "Failed to open automatically determined source block copy device " DEVNUM_FORMAT_STR
": %m",
5997 DEVNUM_FORMAT_VAL(devno
));
5999 if (fstat(source_fd
, &st
) < 0)
6000 return log_error_errno(errno
, "Failed to stat block copy file '%s': %m", opened
);
6004 if (S_ISDIR(st
.st_mode
)) {
6005 _cleanup_free_
char *bdev
= NULL
;
6008 /* If the file is a directory, automatically find the backing block device */
6010 if (major(st
.st_dev
) != 0)
6013 /* Special support for btrfs */
6014 r
= btrfs_get_block_device_fd(source_fd
, &devt
);
6016 return btrfs_log_dev_root(LOG_ERR
, r
, opened
);
6018 return log_error_errno(r
, "Unable to determine backing block device of '%s': %m", opened
);
6021 safe_close(source_fd
);
6023 source_fd
= r
= device_open_from_devnum(S_IFBLK
, devt
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &bdev
);
6025 return log_error_errno(r
, "Failed to open block device backing '%s': %m", opened
);
6027 if (fstat(source_fd
, &st
) < 0)
6028 return log_error_errno(errno
, "Failed to stat block device '%s': %m", bdev
);
6031 if (S_ISREG(st
.st_mode
))
6033 else if (S_ISBLK(st
.st_mode
)) {
6034 if (ioctl(source_fd
, BLKGETSIZE64
, &size
) != 0)
6035 return log_error_errno(errno
, "Failed to determine size of block device to copy from: %m");
6037 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
);
6040 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "File to copy bytes from '%s' has zero size, refusing.", opened
);
6041 if (size
% 512 != 0)
6042 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "File to copy bytes from '%s' has size that is not multiple of 512, refusing.", opened
);
6044 p
->copy_blocks_fd
= TAKE_FD(source_fd
);
6045 p
->copy_blocks_size
= size
;
6047 free_and_replace(p
->copy_blocks_path
, opened
);
6049 /* When copying from an existing partition copy that partitions UUID if none is configured explicitly */
6050 if (!p
->new_uuid_is_set
&& !sd_id128_is_null(uuid
)) {
6052 p
->new_uuid_is_set
= true;
6059 static int fd_apparent_size(int fd
, uint64_t *ret
) {
6066 initial
= lseek(fd
, 0, SEEK_CUR
);
6068 return log_error_errno(errno
, "Failed to get file offset: %m");
6070 for (off_t off
= 0;;) {
6073 r
= lseek(fd
, off
, SEEK_DATA
);
6074 if (r
< 0 && errno
== ENXIO
)
6075 /* If errno == ENXIO, that means we've reached the final hole of the file and
6076 * that hole isn't followed by more data. */
6079 return log_error_errno(errno
, "Failed to seek data in file from offset %"PRIi64
": %m", off
);
6081 off
= r
; /* Set the offset to the start of the data segment. */
6083 /* After copying a potential hole, find the end of the data segment by looking for
6084 * the next hole. If we get ENXIO, we're at EOF. */
6085 r
= lseek(fd
, off
, SEEK_HOLE
);
6089 return log_error_errno(errno
, "Failed to seek hole in file from offset %"PRIi64
": %m", off
);
6096 if (lseek(fd
, initial
, SEEK_SET
) < 0)
6097 return log_error_errno(errno
, "Failed to reset file offset: %m");
6104 static int context_minimize(Context
*context
) {
6105 const char *vt
= NULL
;
6110 LIST_FOREACH(partitions
, p
, context
->partitions
) {
6111 _cleanup_(rm_rf_physical_and_freep
) char *root
= NULL
;
6112 _cleanup_(unlink_and_freep
) char *temp
= NULL
;
6113 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
6114 _cleanup_strv_free_
char **extra_mkfs_options
= NULL
;
6115 _cleanup_close_
int fd
= -EBADF
;
6116 _cleanup_free_
char *hint
= NULL
;
6124 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
6130 if (p
->copy_blocks_fd
>= 0)
6133 if (p
->minimize
== MINIMIZE_OFF
)
6136 if (!partition_needs_populate(p
))
6139 assert(!p
->copy_blocks_path
);
6141 (void) partition_hint(p
, context
->node
, &hint
);
6143 log_info("Pre-populating %s filesystem of partition %s twice to calculate minimal partition size",
6144 p
->format
, strna(hint
));
6147 r
= var_tmp_dir(&vt
);
6149 return log_error_errno(r
, "Could not determine temporary directory: %m");
6152 r
= tempfn_random_child(vt
, "repart", &temp
);
6154 return log_error_errno(r
, "Failed to generate temporary file path: %m");
6156 if (fstype_is_ro(p
->format
))
6157 fs_uuid
= p
->fs_uuid
;
6159 fd
= open(temp
, O_CREAT
|O_EXCL
|O_CLOEXEC
|O_RDWR
|O_NOCTTY
, 0600);
6161 return log_error_errno(errno
, "Failed to open temporary file %s: %m", temp
);
6163 /* This may seem huge but it will be created sparse so it doesn't take up any space
6164 * on disk until written to. */
6165 if (ftruncate(fd
, 1024ULL * 1024ULL * 1024ULL * 1024ULL) < 0)
6166 return log_error_errno(errno
, "Failed to truncate temporary file to %s: %m",
6167 FORMAT_BYTES(1024ULL * 1024ULL * 1024ULL * 1024ULL));
6169 if (arg_offline
<= 0) {
6170 r
= loop_device_make(fd
, O_RDWR
, 0, UINT64_MAX
, context
->sector_size
, 0, LOCK_EX
, &d
);
6171 if (r
< 0 && (arg_offline
== 0 || (r
!= -ENOENT
&& !ERRNO_IS_PRIVILEGE(r
)) || !strv_isempty(p
->subvolumes
)))
6172 return log_error_errno(r
, "Failed to make loopback device of %s: %m", temp
);
6175 /* We're going to populate this filesystem twice so use a random UUID the first time
6176 * to avoid UUID conflicts. */
6177 r
= sd_id128_randomize(&fs_uuid
);
6182 if (!d
|| fstype_is_ro(p
->format
)) {
6183 if (!mkfs_supports_root_option(p
->format
))
6184 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
),
6185 "Loop device access is required to populate %s filesystems",
6188 r
= partition_populate_directory(context
, p
, &root
);
6193 r
= mkfs_options_from_env("REPART", p
->format
, &extra_mkfs_options
);
6195 return log_error_errno(r
,
6196 "Failed to determine mkfs command line options for '%s': %m",
6199 r
= make_filesystem(d
? d
->node
: temp
,
6201 strempty(p
->new_label
),
6204 arg_discard
, /* quiet = */ false,
6205 context
->fs_sector_size
,
6206 extra_mkfs_options
);
6210 /* Read-only filesystems are minimal from the first try because they create and size the
6211 * loopback file for us. */
6212 if (fstype_is_ro(p
->format
)) {
6215 fd
= open(temp
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
);
6217 return log_error_errno(errno
, "Failed to open temporary file %s: %m", temp
);
6219 if (fstat(fd
, &st
) < 0)
6220 return log_error_errno(errno
, "Failed to stat temporary file: %m");
6222 log_info("Minimal partition size of %s filesystem of partition %s is %s",
6223 p
->format
, strna(hint
), FORMAT_BYTES(st
.st_size
));
6225 p
->copy_blocks_path
= TAKE_PTR(temp
);
6226 p
->copy_blocks_path_is_our_file
= true;
6227 p
->copy_blocks_fd
= TAKE_FD(fd
);
6228 p
->copy_blocks_size
= st
.st_size
;
6235 r
= partition_populate_filesystem(context
, p
, d
->node
);
6240 /* Other filesystems need to be provided with a pre-sized loopback file and will adapt to
6241 * fully occupy it. Because we gave the filesystem a 1T sparse file, we need to shrink the
6242 * filesystem down to a reasonable size again to fit it in the disk image. While there are
6243 * some filesystems that support shrinking, it doesn't always work properly (e.g. shrinking
6244 * btrfs gives us a 2.0G filesystem regardless of what we put in it). Instead, let's populate
6245 * the filesystem again, but this time, instead of providing the filesystem with a 1T sparse
6246 * loopback file, let's size the loopback file based on the actual data used by the
6247 * filesystem in the sparse file after the first attempt. This should be a good guess of the
6248 * minimal amount of space needed in the filesystem to fit all the required data.
6250 r
= fd_apparent_size(fd
, &fsz
);
6254 /* Massage the size a bit because just going by actual data used in the sparse file isn't
6256 uint64_t heuristic
= streq(p
->format
, "xfs") ? fsz
: fsz
/ 2;
6257 fsz
= round_up_size(fsz
+ heuristic
, context
->grain_size
);
6258 if (minimal_size_by_fs_name(p
->format
) != UINT64_MAX
)
6259 fsz
= MAX(minimal_size_by_fs_name(p
->format
), fsz
);
6261 log_info("Minimal partition size of %s filesystem of partition %s is %s",
6262 p
->format
, strna(hint
), FORMAT_BYTES(fsz
));
6264 d
= loop_device_unref(d
);
6266 /* Erase the previous filesystem first. */
6267 if (ftruncate(fd
, 0))
6268 return log_error_errno(errno
, "Failed to erase temporary file: %m");
6270 if (ftruncate(fd
, fsz
))
6271 return log_error_errno(errno
, "Failed to truncate temporary file to %s: %m", FORMAT_BYTES(fsz
));
6273 if (arg_offline
<= 0) {
6274 r
= loop_device_make(fd
, O_RDWR
, 0, UINT64_MAX
, context
->sector_size
, 0, LOCK_EX
, &d
);
6275 if (r
< 0 && (arg_offline
== 0 || (r
!= -ENOENT
&& !ERRNO_IS_PRIVILEGE(r
)) || !strv_isempty(p
->subvolumes
)))
6276 return log_error_errno(r
, "Failed to make loopback device of %s: %m", temp
);
6279 r
= make_filesystem(d
? d
->node
: temp
,
6281 strempty(p
->new_label
),
6285 /* quiet = */ false,
6286 context
->fs_sector_size
,
6287 extra_mkfs_options
);
6294 r
= partition_populate_filesystem(context
, p
, d
->node
);
6299 if (fstat(fd
, &st
) < 0)
6300 return log_error_errno(errno
, "Failed to stat temporary file: %m");
6302 p
->copy_blocks_path
= TAKE_PTR(temp
);
6303 p
->copy_blocks_path_is_our_file
= true;
6304 p
->copy_blocks_fd
= TAKE_FD(fd
);
6305 p
->copy_blocks_size
= st
.st_size
;
6308 /* Now that we've done the data partitions, do the verity hash partitions. We do these in a separate
6309 * step because they might depend on data generated in the previous step. */
6311 LIST_FOREACH(partitions
, p
, context
->partitions
) {
6312 _cleanup_(unlink_and_freep
) char *temp
= NULL
;
6313 _cleanup_free_
char *hint
= NULL
;
6314 _cleanup_close_
int fd
= -EBADF
;
6321 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
6324 if (p
->minimize
== MINIMIZE_OFF
)
6327 if (p
->verity
!= VERITY_HASH
)
6330 assert_se(dp
= p
->siblings
[VERITY_DATA
]);
6331 assert(!dp
->dropped
);
6332 assert(dp
->copy_blocks_path
);
6334 (void) partition_hint(p
, context
->node
, &hint
);
6336 log_info("Pre-populating verity hash data of partition %s to calculate minimal partition size",
6340 r
= var_tmp_dir(&vt
);
6342 return log_error_errno(r
, "Could not determine temporary directory: %m");
6345 r
= tempfn_random_child(vt
, "repart", &temp
);
6347 return log_error_errno(r
, "Failed to generate temporary file path: %m");
6351 return log_error_errno(r
, "Failed to create temporary file: %m");
6353 r
= partition_format_verity_hash(context
, p
, temp
, dp
->copy_blocks_path
);
6357 fd
= open(temp
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
);
6359 return log_error_errno(errno
, "Failed to open temporary file %s: %m", temp
);
6361 if (fstat(fd
, &st
) < 0)
6362 return log_error_errno(r
, "Failed to stat temporary file: %m");
6364 log_info("Minimal partition size of verity hash partition %s is %s",
6365 strna(hint
), FORMAT_BYTES(st
.st_size
));
6367 p
->copy_blocks_path
= TAKE_PTR(temp
);
6368 p
->copy_blocks_path_is_our_file
= true;
6369 p
->copy_blocks_fd
= TAKE_FD(fd
);
6370 p
->copy_blocks_size
= st
.st_size
;
6376 static int parse_partition_types(const char *p
, GptPartitionType
**partitions
, size_t *n_partitions
) {
6380 assert(n_partitions
);
6383 _cleanup_free_
char *name
= NULL
;
6384 GptPartitionType type
;
6386 r
= extract_first_word(&p
, &name
, ",", EXTRACT_CUNESCAPE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
6390 return log_error_errno(r
, "Failed to extract partition type identifier or GUID: %s", p
);
6392 r
= gpt_partition_type_from_string(name
, &type
);
6394 return log_error_errno(r
, "'%s' is not a valid partition type identifier or GUID", name
);
6396 if (!GREEDY_REALLOC(*partitions
, *n_partitions
+ 1))
6399 (*partitions
)[(*n_partitions
)++] = type
;
6405 static int help(void) {
6406 _cleanup_free_
char *link
= NULL
;
6409 r
= terminal_urlify_man("systemd-repart", "8", &link
);
6413 printf("%s [OPTIONS...] [DEVICE]\n"
6414 "\n%sGrow and add partitions to partition table.%s\n\n"
6415 " -h --help Show this help\n"
6416 " --version Show package version\n"
6417 " --no-pager Do not pipe output into a pager\n"
6418 " --no-legend Do not show the headers and footers\n"
6419 " --dry-run=BOOL Whether to run dry-run operation\n"
6420 " --empty=MODE One of refuse, allow, require, force, create; controls\n"
6421 " how to handle empty disks lacking partition tables\n"
6422 " --discard=BOOL Whether to discard backing blocks for new partitions\n"
6423 " --pretty=BOOL Whether to show pretty summary before doing changes\n"
6424 " --factory-reset=BOOL Whether to remove data partitions before recreating\n"
6426 " --can-factory-reset Test whether factory reset is defined\n"
6427 " --root=PATH Operate relative to root path\n"
6428 " --image=PATH Operate relative to image file\n"
6429 " --image-policy=POLICY\n"
6430 " Specify disk image dissection policy\n"
6431 " --definitions=DIR Find partition definitions in specified directory\n"
6432 " --key-file=PATH Key to use when encrypting partitions\n"
6433 " --private-key=PATH Private key to use when generating verity roothash\n"
6435 " --certificate=PATH PEM certificate to use when generating verity\n"
6436 " roothash signatures\n"
6437 " --tpm2-device=PATH Path to TPM2 device node to use\n"
6438 " --tpm2-device-key=PATH\n"
6439 " Enroll a TPM2 device using its public key\n"
6440 " --tpm2-seal-key-handle=HANDLE\n"
6441 " Specify handle of key to use for sealing\n"
6442 " --tpm2-pcrs=PCR1+PCR2+PCR3+…\n"
6443 " TPM2 PCR indexes to use for TPM2 enrollment\n"
6444 " --tpm2-public-key=PATH\n"
6445 " Enroll signed TPM2 PCR policy against PEM public key\n"
6446 " --tpm2-public-key-pcrs=PCR1+PCR2+PCR3+…\n"
6447 " Enroll signed TPM2 PCR policy for specified TPM2 PCRs\n"
6448 " --tpm2-pcrlock=PATH\n"
6449 " Specify pcrlock policy to lock against\n"
6450 " --seed=UUID 128-bit seed UUID to derive all UUIDs from\n"
6451 " --size=BYTES Grow loopback file to specified size\n"
6452 " --json=pretty|short|off\n"
6453 " Generate JSON output\n"
6454 " --split=BOOL Whether to generate split artifacts\n"
6455 " --include-partitions=PARTITION1,PARTITION2,PARTITION3,…\n"
6456 " Ignore partitions not of the specified types\n"
6457 " --exclude-partitions=PARTITION1,PARTITION2,PARTITION3,…\n"
6458 " Ignore partitions of the specified types\n"
6459 " --defer-partitions=PARTITION1,PARTITION2,PARTITION3,…\n"
6460 " Take partitions of the specified types into account\n"
6461 " but don't populate them yet\n"
6462 " --sector-size=SIZE Set the logical sector size for the image\n"
6463 " --architecture=ARCH Set the generic architecture for the image\n"
6464 " --offline=BOOL Whether to build the image offline\n"
6465 " -s --copy-source=PATH Specify the primary source tree to copy files from\n"
6466 " --copy-from=IMAGE Copy partitions from the given image(s)\n"
6467 " -S --make-ddi=sysext Make a system extension DDI\n"
6468 " -C --make-ddi=confext Make a configuration extension DDI\n"
6469 " -P --make-ddi=portable Make a portable service DDI\n"
6470 "\nSee the %s for details.\n",
6471 program_invocation_short_name
,
6479 static int parse_argv(int argc
, char *argv
[]) {
6482 ARG_VERSION
= 0x100,
6489 ARG_CAN_FACTORY_RESET
,
6502 ARG_TPM2_DEVICE_KEY
,
6503 ARG_TPM2_SEAL_KEY_HANDLE
,
6505 ARG_TPM2_PUBLIC_KEY
,
6506 ARG_TPM2_PUBLIC_KEY_PCRS
,
6509 ARG_INCLUDE_PARTITIONS
,
6510 ARG_EXCLUDE_PARTITIONS
,
6511 ARG_DEFER_PARTITIONS
,
6513 ARG_SKIP_PARTITIONS
,
6520 static const struct option options
[] = {
6521 { "help", no_argument
, NULL
, 'h' },
6522 { "version", no_argument
, NULL
, ARG_VERSION
},
6523 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
6524 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
6525 { "dry-run", required_argument
, NULL
, ARG_DRY_RUN
},
6526 { "empty", required_argument
, NULL
, ARG_EMPTY
},
6527 { "discard", required_argument
, NULL
, ARG_DISCARD
},
6528 { "factory-reset", required_argument
, NULL
, ARG_FACTORY_RESET
},
6529 { "can-factory-reset", no_argument
, NULL
, ARG_CAN_FACTORY_RESET
},
6530 { "root", required_argument
, NULL
, ARG_ROOT
},
6531 { "image", required_argument
, NULL
, ARG_IMAGE
},
6532 { "image-policy", required_argument
, NULL
, ARG_IMAGE_POLICY
},
6533 { "seed", required_argument
, NULL
, ARG_SEED
},
6534 { "pretty", required_argument
, NULL
, ARG_PRETTY
},
6535 { "definitions", required_argument
, NULL
, ARG_DEFINITIONS
},
6536 { "size", required_argument
, NULL
, ARG_SIZE
},
6537 { "json", required_argument
, NULL
, ARG_JSON
},
6538 { "key-file", required_argument
, NULL
, ARG_KEY_FILE
},
6539 { "private-key", required_argument
, NULL
, ARG_PRIVATE_KEY
},
6540 { "certificate", required_argument
, NULL
, ARG_CERTIFICATE
},
6541 { "tpm2-device", required_argument
, NULL
, ARG_TPM2_DEVICE
},
6542 { "tpm2-device-key", required_argument
, NULL
, ARG_TPM2_DEVICE_KEY
},
6543 { "tpm2-seal-key-handle", required_argument
, NULL
, ARG_TPM2_SEAL_KEY_HANDLE
},
6544 { "tpm2-pcrs", required_argument
, NULL
, ARG_TPM2_PCRS
},
6545 { "tpm2-public-key", required_argument
, NULL
, ARG_TPM2_PUBLIC_KEY
},
6546 { "tpm2-public-key-pcrs", required_argument
, NULL
, ARG_TPM2_PUBLIC_KEY_PCRS
},
6547 { "tpm2-pcrlock", required_argument
, NULL
, ARG_TPM2_PCRLOCK
},
6548 { "split", required_argument
, NULL
, ARG_SPLIT
},
6549 { "include-partitions", required_argument
, NULL
, ARG_INCLUDE_PARTITIONS
},
6550 { "exclude-partitions", required_argument
, NULL
, ARG_EXCLUDE_PARTITIONS
},
6551 { "defer-partitions", required_argument
, NULL
, ARG_DEFER_PARTITIONS
},
6552 { "sector-size", required_argument
, NULL
, ARG_SECTOR_SIZE
},
6553 { "architecture", required_argument
, NULL
, ARG_ARCHITECTURE
},
6554 { "offline", required_argument
, NULL
, ARG_OFFLINE
},
6555 { "copy-from", required_argument
, NULL
, ARG_COPY_FROM
},
6556 { "copy-source", required_argument
, NULL
, 's' },
6557 { "make-ddi", required_argument
, NULL
, ARG_MAKE_DDI
},
6561 bool auto_hash_pcr_values
= true, auto_public_key_pcr_mask
= true, auto_pcrlock
= true;
6567 while ((c
= getopt_long(argc
, argv
, "hs:SCP", options
, NULL
)) >= 0)
6578 arg_pager_flags
|= PAGER_DISABLE
;
6586 r
= parse_boolean_argument("--dry-run=", optarg
, &arg_dry_run
);
6592 if (isempty(optarg
)) {
6593 arg_empty
= EMPTY_UNSET
;
6597 arg_empty
= empty_mode_from_string(optarg
);
6599 return log_error_errno(arg_empty
, "Failed to parse --empty= parameter: %s", optarg
);
6604 r
= parse_boolean_argument("--discard=", optarg
, &arg_discard
);
6609 case ARG_FACTORY_RESET
:
6610 r
= parse_boolean_argument("--factory-reset=", optarg
, NULL
);
6613 arg_factory_reset
= r
;
6616 case ARG_CAN_FACTORY_RESET
:
6617 arg_can_factory_reset
= true;
6621 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_root
);
6627 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_image
);
6632 case ARG_IMAGE_POLICY
:
6633 r
= parse_image_policy_argument(optarg
, &arg_image_policy
);
6639 if (isempty(optarg
)) {
6640 arg_seed
= SD_ID128_NULL
;
6641 arg_randomize
= false;
6642 } else if (streq(optarg
, "random"))
6643 arg_randomize
= true;
6645 r
= sd_id128_from_string(optarg
, &arg_seed
);
6647 return log_error_errno(r
, "Failed to parse seed: %s", optarg
);
6649 arg_randomize
= false;
6655 r
= parse_boolean_argument("--pretty=", optarg
, NULL
);
6661 case ARG_DEFINITIONS
: {
6662 _cleanup_free_
char *path
= NULL
;
6663 r
= parse_path_argument(optarg
, false, &path
);
6666 if (strv_consume(&arg_definitions
, TAKE_PTR(path
)) < 0)
6672 uint64_t parsed
, rounded
;
6674 if (streq(optarg
, "auto")) {
6675 arg_size
= UINT64_MAX
;
6676 arg_size_auto
= true;
6680 r
= parse_size(optarg
, 1024, &parsed
);
6682 return log_error_errno(r
, "Failed to parse --size= parameter: %s", optarg
);
6684 rounded
= round_up_size(parsed
, 4096);
6686 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too small, refusing.");
6687 if (rounded
== UINT64_MAX
)
6688 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too large, refusing.");
6690 if (rounded
!= parsed
)
6691 log_warning("Specified size is not a multiple of 4096, rounding up automatically. (%" PRIu64
" %s %" PRIu64
")",
6692 parsed
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), rounded
);
6695 arg_size_auto
= false;
6700 r
= parse_json_argument(optarg
, &arg_json_format_flags
);
6706 case ARG_KEY_FILE
: {
6707 _cleanup_(erase_and_freep
) char *k
= NULL
;
6710 r
= read_full_file_full(
6711 AT_FDCWD
, optarg
, UINT64_MAX
, SIZE_MAX
,
6712 READ_FULL_FILE_SECURE
|READ_FULL_FILE_WARN_WORLD_READABLE
|READ_FULL_FILE_CONNECT_SOCKET
,
6716 return log_error_errno(r
, "Failed to read key file '%s': %m", optarg
);
6718 erase_and_free(arg_key
);
6719 arg_key
= TAKE_PTR(k
);
6724 case ARG_PRIVATE_KEY
: {
6725 _cleanup_(erase_and_freep
) char *k
= NULL
;
6728 r
= read_full_file_full(
6729 AT_FDCWD
, optarg
, UINT64_MAX
, SIZE_MAX
,
6730 READ_FULL_FILE_SECURE
|READ_FULL_FILE_WARN_WORLD_READABLE
|READ_FULL_FILE_CONNECT_SOCKET
,
6734 return log_error_errno(r
, "Failed to read key file '%s': %m", optarg
);
6736 EVP_PKEY_free(arg_private_key
);
6737 arg_private_key
= NULL
;
6738 r
= parse_private_key(k
, n
, &arg_private_key
);
6744 case ARG_CERTIFICATE
: {
6745 _cleanup_free_
char *cert
= NULL
;
6748 r
= read_full_file_full(
6749 AT_FDCWD
, optarg
, UINT64_MAX
, SIZE_MAX
,
6750 READ_FULL_FILE_CONNECT_SOCKET
,
6754 return log_error_errno(r
, "Failed to read certificate file '%s': %m", optarg
);
6756 X509_free(arg_certificate
);
6757 arg_certificate
= NULL
;
6758 r
= parse_x509_certificate(cert
, n
, &arg_certificate
);
6764 case ARG_TPM2_DEVICE
: {
6765 _cleanup_free_
char *device
= NULL
;
6767 if (streq(optarg
, "list"))
6768 return tpm2_list_devices();
6770 if (!streq(optarg
, "auto")) {
6771 device
= strdup(optarg
);
6776 free(arg_tpm2_device
);
6777 arg_tpm2_device
= TAKE_PTR(device
);
6781 case ARG_TPM2_DEVICE_KEY
:
6782 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_tpm2_device_key
);
6788 case ARG_TPM2_SEAL_KEY_HANDLE
:
6789 r
= safe_atou32_full(optarg
, 16, &arg_tpm2_seal_key_handle
);
6791 return log_error_errno(r
, "Could not parse TPM2 seal key handle index '%s': %m", optarg
);
6796 auto_hash_pcr_values
= false;
6797 r
= tpm2_parse_pcr_argument_append(optarg
, &arg_tpm2_hash_pcr_values
, &arg_tpm2_n_hash_pcr_values
);
6803 case ARG_TPM2_PUBLIC_KEY
:
6804 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_tpm2_public_key
);
6810 case ARG_TPM2_PUBLIC_KEY_PCRS
:
6811 auto_public_key_pcr_mask
= false;
6812 r
= tpm2_parse_pcr_argument_to_mask(optarg
, &arg_tpm2_public_key_pcr_mask
);
6818 case ARG_TPM2_PCRLOCK
:
6819 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_tpm2_pcrlock
);
6823 auto_pcrlock
= false;
6827 r
= parse_boolean_argument("--split=", optarg
, NULL
);
6834 case ARG_INCLUDE_PARTITIONS
:
6835 if (arg_filter_partitions_type
== FILTER_PARTITIONS_EXCLUDE
)
6836 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6837 "Combination of --include-partitions= and --exclude-partitions= is invalid.");
6839 r
= parse_partition_types(optarg
, &arg_filter_partitions
, &arg_n_filter_partitions
);
6843 arg_filter_partitions_type
= FILTER_PARTITIONS_INCLUDE
;
6847 case ARG_EXCLUDE_PARTITIONS
:
6848 if (arg_filter_partitions_type
== FILTER_PARTITIONS_INCLUDE
)
6849 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6850 "Combination of --include-partitions= and --exclude-partitions= is invalid.");
6852 r
= parse_partition_types(optarg
, &arg_filter_partitions
, &arg_n_filter_partitions
);
6856 arg_filter_partitions_type
= FILTER_PARTITIONS_EXCLUDE
;
6860 case ARG_DEFER_PARTITIONS
:
6861 r
= parse_partition_types(optarg
, &arg_defer_partitions
, &arg_n_defer_partitions
);
6867 case ARG_SECTOR_SIZE
:
6868 r
= parse_sector_size(optarg
, &arg_sector_size
);
6874 case ARG_ARCHITECTURE
:
6875 r
= architecture_from_string(optarg
);
6877 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid architecture '%s'", optarg
);
6879 arg_architecture
= r
;
6883 if (streq(optarg
, "auto"))
6886 r
= parse_boolean_argument("--offline=", optarg
, NULL
);
6895 case ARG_COPY_FROM
: {
6896 _cleanup_free_
char *p
= NULL
;
6898 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &p
);
6902 if (strv_consume(&arg_copy_from
, TAKE_PTR(p
)) < 0)
6909 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_copy_source
);
6915 if (!filename_is_valid(optarg
))
6916 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid DDI type: %s", optarg
);
6918 r
= free_and_strdup_warn(&arg_make_ddi
, optarg
);
6924 r
= free_and_strdup_warn(&arg_make_ddi
, "sysext");
6930 r
= free_and_strdup_warn(&arg_make_ddi
, "confext");
6936 r
= free_and_strdup_warn(&arg_make_ddi
, "portable");
6945 assert_not_reached();
6948 if (argc
- optind
> 1)
6949 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6950 "Expected at most one argument, the path to the block device or image file.");
6953 if (arg_definitions
)
6954 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Combination of --make-ddi= and --definitions= is not supported.");
6955 if (!IN_SET(arg_empty
, EMPTY_UNSET
, EMPTY_CREATE
))
6956 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Combination of --make-ddi= and --empty=%s is not supported.", empty_mode_to_string(arg_empty
));
6958 /* Imply automatic sizing in DDI mode */
6959 if (arg_size
== UINT64_MAX
)
6960 arg_size_auto
= true;
6962 if (!arg_copy_source
)
6963 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No --copy-source= specified, refusing.");
6965 r
= dir_is_empty(arg_copy_source
, /* ignore_hidden_or_backup= */ false);
6967 return log_error_errno(r
, "Failed to determine if '%s' is empty: %m", arg_copy_source
);
6969 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
), "Source directory '%s' is empty, refusing to create empty image.", arg_copy_source
);
6971 if (sd_id128_is_null(arg_seed
) && !arg_randomize
) {
6972 /* We don't want that /etc/machine-id leaks into any image built this way, hence
6973 * let's randomize the seed if not specified explicitly */
6974 log_notice("No seed value specified, randomizing generated UUIDs, resulting image will not be reproducible.");
6975 arg_randomize
= true;
6978 arg_empty
= EMPTY_CREATE
;
6981 if (arg_empty
== EMPTY_UNSET
) /* default to refuse mode, if not otherwise specified */
6982 arg_empty
= EMPTY_REFUSE
;
6984 if (arg_factory_reset
> 0 && IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
))
6985 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6986 "Combination of --factory-reset=yes and --empty=force/--empty=require/--empty=create is invalid.");
6988 if (arg_can_factory_reset
)
6989 arg_dry_run
= true; /* When --can-factory-reset is specified we don't make changes, hence
6990 * non-dry-run mode makes no sense. Thus, imply dry run mode so that we
6991 * open things strictly read-only. */
6992 else if (arg_empty
== EMPTY_CREATE
)
6993 arg_dry_run
= false; /* Imply --dry-run=no if we create the loopback file anew. After all we
6994 * cannot really break anyone's partition tables that way. */
6996 /* Disable pager once we are not just reviewing, but doing things. */
6998 arg_pager_flags
|= PAGER_DISABLE
;
7000 if (arg_empty
== EMPTY_CREATE
&& arg_size
== UINT64_MAX
&& !arg_size_auto
)
7001 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
7002 "If --empty=create is specified, --size= must be specified, too.");
7004 if (arg_image
&& arg_root
)
7005 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Please specify either --root= or --image=, the combination of both is not supported.");
7006 else if (!arg_image
&& !arg_root
&& in_initrd()) {
7008 /* By default operate on /sysusr/ or /sysroot/ when invoked in the initrd. We prefer the
7009 * former, if it is mounted, so that we have deterministic behaviour on systems where /usr/
7010 * is vendor-supplied but the root fs formatted on first boot. */
7011 r
= path_is_mount_point("/sysusr/usr", NULL
, 0);
7013 if (r
< 0 && r
!= -ENOENT
)
7014 log_debug_errno(r
, "Unable to determine whether /sysusr/usr is a mount point, assuming it is not: %m");
7016 arg_root
= strdup("/sysroot");
7018 arg_root
= strdup("/sysusr");
7023 arg_node
= argc
> optind
? argv
[optind
] : NULL
;
7025 if (IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
) && !arg_node
&& !arg_image
)
7026 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
7027 "A path to a device node or image file must be specified when --make-ddi=, --empty=force, --empty=require or --empty=create are used.");
7029 if (arg_split
&& !arg_node
)
7030 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
7031 "A path to an image file must be specified when --split is used.");
7034 assert(!arg_tpm2_pcrlock
);
7036 r
= tpm2_pcrlock_search_file(NULL
, NULL
, &arg_tpm2_pcrlock
);
7039 log_warning_errno(r
, "Search for pcrlock.json failed, assuming it does not exist: %m");
7041 log_info("Automatically using pcrlock policy '%s'.", arg_tpm2_pcrlock
);
7044 if (auto_public_key_pcr_mask
) {
7045 assert(arg_tpm2_public_key_pcr_mask
== 0);
7046 arg_tpm2_public_key_pcr_mask
= INDEX_TO_MASK(uint32_t, TPM2_PCR_KERNEL_BOOT
);
7049 if (auto_hash_pcr_values
&& !arg_tpm2_pcrlock
) { /* Only lock to PCR 7 if no pcr policy is specified. */
7050 assert(arg_tpm2_n_hash_pcr_values
== 0);
7052 if (!GREEDY_REALLOC_APPEND(
7053 arg_tpm2_hash_pcr_values
,
7054 arg_tpm2_n_hash_pcr_values
,
7055 &TPM2_PCR_VALUE_MAKE(TPM2_PCR_INDEX_DEFAULT
, /* hash= */ 0, /* value= */ {}),
7060 if (arg_pretty
< 0 && isatty(STDOUT_FILENO
))
7063 if (arg_architecture
>= 0) {
7064 FOREACH_ARRAY(p
, arg_filter_partitions
, arg_n_filter_partitions
)
7065 *p
= gpt_partition_type_override_architecture(*p
, arg_architecture
);
7067 FOREACH_ARRAY(p
, arg_defer_partitions
, arg_n_defer_partitions
)
7068 *p
= gpt_partition_type_override_architecture(*p
, arg_architecture
);
7074 static int parse_proc_cmdline_factory_reset(void) {
7078 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
7081 if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
7084 r
= proc_cmdline_get_bool("systemd.factory_reset", /* flags = */ 0, &b
);
7086 return log_error_errno(r
, "Failed to parse systemd.factory_reset kernel command line argument: %m");
7088 arg_factory_reset
= b
;
7091 log_notice("Honouring factory reset requested via kernel command line.");
7097 static int parse_efi_variable_factory_reset(void) {
7098 _cleanup_free_
char *value
= NULL
;
7101 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
7104 if (!in_initrd()) /* Never honour EFI variable factory reset request outside of the initrd */
7107 r
= efi_get_variable_string(EFI_SYSTEMD_VARIABLE(FactoryReset
), &value
);
7109 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
7111 return log_error_errno(r
, "Failed to read EFI variable FactoryReset: %m");
7114 r
= parse_boolean(value
);
7116 return log_error_errno(r
, "Failed to parse EFI variable FactoryReset: %m");
7118 arg_factory_reset
= r
;
7120 log_notice("Factory reset requested via EFI variable FactoryReset.");
7125 static int remove_efi_variable_factory_reset(void) {
7128 r
= efi_set_variable(EFI_SYSTEMD_VARIABLE(FactoryReset
), NULL
, 0);
7130 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
7132 return log_error_errno(r
, "Failed to remove EFI variable FactoryReset: %m");
7135 log_info("Successfully unset EFI variable FactoryReset.");
7139 static int acquire_root_devno(
7146 _cleanup_free_
char *found_path
= NULL
, *node
= NULL
;
7147 dev_t devno
, fd_devno
= MODE_INVALID
;
7148 _cleanup_close_
int fd
= -EBADF
;
7156 fd
= chase_and_open(p
, root
, CHASE_PREFIX_ROOT
, mode
, &found_path
);
7160 if (fstat(fd
, &st
) < 0)
7163 if (S_ISREG(st
.st_mode
)) {
7164 *ret
= TAKE_PTR(found_path
);
7165 *ret_fd
= TAKE_FD(fd
);
7169 if (S_ISBLK(st
.st_mode
)) {
7170 /* Refuse referencing explicit block devices if a root dir is specified, after all we should
7171 * not be able to leave the image the root path constrains us to. */
7175 fd_devno
= devno
= st
.st_rdev
;
7176 } else if (S_ISDIR(st
.st_mode
)) {
7179 if (major(devno
) == 0) {
7180 r
= btrfs_get_block_device_fd(fd
, &devno
);
7181 if (r
== -ENOTTY
) /* not btrfs */
7189 /* From dm-crypt to backing partition */
7190 r
= block_get_originating(devno
, &devno
);
7192 log_debug_errno(r
, "Device '%s' has no dm-crypt/dm-verity device, no need to look for underlying block device.", p
);
7194 log_debug_errno(r
, "Failed to find underlying block device for '%s', ignoring: %m", p
);
7196 /* From partition to whole disk containing it */
7197 r
= block_get_whole_disk(devno
, &devno
);
7199 log_debug_errno(r
, "Failed to find whole disk block device for '%s', ignoring: %m", p
);
7201 r
= devname_from_devnum(S_IFBLK
, devno
, &node
);
7203 return log_debug_errno(r
, "Failed to determine canonical path for '%s': %m", p
);
7205 /* Only if we still look at the same block device we can reuse the fd. Otherwise return an
7206 * invalidated fd. */
7207 if (fd_devno
!= MODE_INVALID
&& fd_devno
== devno
) {
7208 /* Tell udev not to interfere while we are processing the device */
7209 if (flock(fd
, arg_dry_run
? LOCK_SH
: LOCK_EX
) < 0)
7210 return log_error_errno(errno
, "Failed to lock device '%s': %m", node
);
7212 *ret_fd
= TAKE_FD(fd
);
7216 *ret
= TAKE_PTR(node
);
7220 static int find_root(Context
*context
) {
7221 _cleanup_free_
char *device
= NULL
;
7227 if (arg_empty
== EMPTY_CREATE
) {
7228 _cleanup_close_
int fd
= -EBADF
;
7229 _cleanup_free_
char *s
= NULL
;
7231 s
= strdup(arg_node
);
7235 fd
= open(arg_node
, O_RDONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOFOLLOW
, 0666);
7237 return log_error_errno(errno
, "Failed to create '%s': %m", arg_node
);
7239 context
->node
= TAKE_PTR(s
);
7240 context
->node_is_our_file
= true;
7241 context
->backing_fd
= TAKE_FD(fd
);
7245 /* Note that we don't specify a root argument here: if the user explicitly configured a node
7246 * we'll take it relative to the host, not the image */
7247 r
= acquire_root_devno(arg_node
, NULL
, O_RDONLY
|O_CLOEXEC
, &context
->node
, &context
->backing_fd
);
7249 return btrfs_log_dev_root(LOG_ERR
, r
, arg_node
);
7251 return log_error_errno(r
, "Failed to open file or determine backing device of %s: %m", arg_node
);
7256 assert(IN_SET(arg_empty
, EMPTY_REFUSE
, EMPTY_ALLOW
));
7258 /* If the root mount has been replaced by some form of volatile file system (overlayfs), the
7259 * original root block device node is symlinked in /run/systemd/volatile-root. Let's read that
7261 r
= readlink_malloc("/run/systemd/volatile-root", &device
);
7262 if (r
== -ENOENT
) { /* volatile-root not found */
7263 /* Let's search for the root device. We look for two cases here: first in /, and then in /usr. The
7264 * latter we check for cases where / is a tmpfs and only /usr is an actual persistent block device
7265 * (think: volatile setups) */
7267 FOREACH_STRING(p
, "/", "/usr") {
7269 r
= acquire_root_devno(p
, arg_root
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, &context
->node
,
7270 &context
->backing_fd
);
7273 return btrfs_log_dev_root(LOG_ERR
, r
, p
);
7275 return log_error_errno(r
, "Failed to determine backing device of %s: %m", p
);
7280 return log_error_errno(r
, "Failed to read symlink /run/systemd/volatile-root: %m");
7282 r
= acquire_root_devno(device
, NULL
, O_RDONLY
|O_CLOEXEC
, &context
->node
, &context
->backing_fd
);
7284 return btrfs_log_dev_root(LOG_ERR
, r
, device
);
7286 return log_error_errno(r
, "Failed to open file or determine backing device of %s: %m", device
);
7291 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
), "Failed to discover root block device.");
7294 static int resize_pt(int fd
, uint64_t sector_size
) {
7295 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
7298 /* After resizing the backing file we need to resize the partition table itself too, so that it takes
7299 * possession of the enlarged backing file. For this it suffices to open the device with libfdisk and
7300 * immediately write it again, with no changes. */
7302 r
= fdisk_new_context_at(fd
, /* path= */ NULL
, /* read_only= */ false, sector_size
, &c
);
7304 return log_error_errno(r
, "Failed to open device '%s': %m", FORMAT_PROC_FD_PATH(fd
));
7306 r
= fdisk_has_label(c
);
7308 return log_error_errno(r
, "Failed to determine whether disk '%s' has a disk label: %m", FORMAT_PROC_FD_PATH(fd
));
7310 log_debug("Not resizing partition table, as there currently is none.");
7314 r
= fdisk_write_disklabel(c
);
7316 return log_error_errno(r
, "Failed to write resized partition table: %m");
7318 log_info("Resized partition table.");
7322 static int resize_backing_fd(
7323 const char *node
, /* The primary way we access the disk image to operate on */
7324 int *fd
, /* An O_RDONLY fd referring to that inode */
7325 const char *backing_file
, /* If the above refers to a loopback device, the backing regular file for that, which we can grow */
7326 LoopDevice
*loop_device
,
7327 uint64_t sector_size
) {
7329 _cleanup_close_
int writable_fd
= -EBADF
;
7330 uint64_t current_size
;
7337 if (arg_size
== UINT64_MAX
) /* Nothing to do */
7341 /* Open the file if we haven't opened it yet. Note that we open it read-only here, just to
7342 * keep a reference to the file we can pass around. */
7343 *fd
= open(node
, O_RDONLY
|O_CLOEXEC
);
7345 return log_error_errno(errno
, "Failed to open '%s' in order to adjust size: %m", node
);
7348 if (fstat(*fd
, &st
) < 0)
7349 return log_error_errno(errno
, "Failed to stat '%s': %m", node
);
7351 if (S_ISBLK(st
.st_mode
)) {
7353 return log_error_errno(SYNTHETIC_ERRNO(EBADF
), "Cannot resize block device '%s'.", node
);
7355 assert(loop_device
);
7357 if (ioctl(*fd
, BLKGETSIZE64
, ¤t_size
) < 0)
7358 return log_error_errno(errno
, "Failed to determine size of block device %s: %m", node
);
7360 r
= stat_verify_regular(&st
);
7362 return log_error_errno(r
, "Specified path '%s' is not a regular file or loopback block device, cannot resize: %m", node
);
7364 assert(!backing_file
);
7365 assert(!loop_device
);
7366 current_size
= st
.st_size
;
7369 if (current_size
>= arg_size
) {
7370 log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)",
7371 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
7375 if (S_ISBLK(st
.st_mode
)) {
7376 assert(backing_file
);
7378 /* This is a loopback device. We can't really grow those directly, but we can grow the
7379 * backing file, hence let's do that. */
7381 writable_fd
= open(backing_file
, O_WRONLY
|O_CLOEXEC
|O_NONBLOCK
);
7382 if (writable_fd
< 0)
7383 return log_error_errno(errno
, "Failed to open backing file '%s': %m", backing_file
);
7385 if (fstat(writable_fd
, &st
) < 0)
7386 return log_error_errno(errno
, "Failed to stat() backing file '%s': %m", backing_file
);
7388 r
= stat_verify_regular(&st
);
7390 return log_error_errno(r
, "Backing file '%s' of block device is not a regular file: %m", backing_file
);
7392 if ((uint64_t) st
.st_size
!= current_size
)
7393 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
7394 "Size of backing file '%s' of loopback block device '%s' don't match, refusing.",
7395 node
, backing_file
);
7397 assert(S_ISREG(st
.st_mode
));
7398 assert(!backing_file
);
7400 /* The file descriptor is read-only. In order to grow the file we need to have a writable fd. We
7401 * reopen the file for that temporarily. We keep the writable fd only open for this operation though,
7402 * as fdisk can't accept it anyway. */
7404 writable_fd
= fd_reopen(*fd
, O_WRONLY
|O_CLOEXEC
);
7405 if (writable_fd
< 0)
7406 return log_error_errno(writable_fd
, "Failed to reopen backing file '%s' writable: %m", node
);
7410 if (fallocate(writable_fd
, 0, 0, arg_size
) < 0) {
7411 if (!ERRNO_IS_NOT_SUPPORTED(errno
))
7412 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by allocation: %m",
7413 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
7415 /* Fallback to truncation, if fallocate() is not supported. */
7416 log_debug("Backing file system does not support fallocate(), falling back to ftruncate().");
7418 if (current_size
== 0) /* Likely regular file just created by us */
7419 log_info("Allocated %s for '%s'.", FORMAT_BYTES(arg_size
), node
);
7421 log_info("File '%s' grown from %s to %s by allocation.",
7422 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
7428 if (ftruncate(writable_fd
, arg_size
) < 0)
7429 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by truncation: %m",
7430 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
7432 if (current_size
== 0) /* Likely regular file just created by us */
7433 log_info("Sized '%s' to %s.", node
, FORMAT_BYTES(arg_size
));
7435 log_info("File '%s' grown from %s to %s by truncation.",
7436 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
7439 r
= resize_pt(writable_fd
, sector_size
);
7444 r
= loop_device_refresh_size(loop_device
, UINT64_MAX
, arg_size
);
7446 return log_error_errno(r
, "Failed to update loop device size: %m");
7452 static int determine_auto_size(Context
*c
) {
7457 sum
= round_up_size(GPT_METADATA_SIZE
, 4096);
7459 LIST_FOREACH(partitions
, p
, c
->partitions
) {
7465 m
= partition_min_size_with_padding(c
, p
);
7466 if (m
> UINT64_MAX
- sum
)
7467 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Image would grow too large, refusing.");
7472 if (c
->total
!= UINT64_MAX
)
7473 /* Image already allocated? Then show its size. */
7474 log_info("Automatically determined minimal disk image size as %s, current image size is %s.",
7475 FORMAT_BYTES(sum
), FORMAT_BYTES(c
->total
));
7477 /* If the image is being created right now, then it has no previous size, suppress any comment about it hence. */
7478 log_info("Automatically determined minimal disk image size as %s.",
7485 static int run(int argc
, char *argv
[]) {
7486 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
7487 _cleanup_(umount_and_freep
) char *mounted_dir
= NULL
;
7488 _cleanup_(context_freep
) Context
* context
= NULL
;
7489 bool node_is_our_loop
= false;
7492 log_show_color(true);
7493 log_parse_environment();
7496 r
= parse_argv(argc
, argv
);
7500 r
= parse_proc_cmdline_factory_reset();
7504 r
= parse_efi_variable_factory_reset();
7508 #if HAVE_LIBCRYPTSETUP
7509 cryptsetup_enable_logging(NULL
);
7515 /* Mount this strictly read-only: we shall modify the partition table, not the file
7517 r
= mount_image_privately_interactively(
7520 DISSECT_IMAGE_MOUNT_READ_ONLY
|
7521 (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) */
7522 DISSECT_IMAGE_GPT_ONLY
|
7523 DISSECT_IMAGE_RELAX_VAR_CHECK
|
7524 DISSECT_IMAGE_USR_NO_ROOT
|
7525 DISSECT_IMAGE_REQUIRE_ROOT
,
7527 /* ret_dir_fd= */ NULL
,
7532 arg_root
= strdup(mounted_dir
);
7537 arg_node
= strdup(loop_device
->node
);
7541 /* Remember that the device we are about to manipulate is actually the one we
7542 * allocated here, and thus to increase its backing file we know what to do */
7543 node_is_our_loop
= true;
7547 if (!arg_copy_source
&& arg_root
) {
7548 /* If no explicit copy source is specified, then use --root=/--image= */
7549 arg_copy_source
= strdup(arg_root
);
7550 if (!arg_copy_source
)
7554 context
= context_new(arg_seed
);
7558 r
= context_copy_from(context
);
7563 _cleanup_free_
char *d
= NULL
, *dp
= NULL
;
7564 assert(!arg_definitions
);
7566 d
= strjoin(arg_make_ddi
, ".repart.d/");
7570 r
= search_and_access(d
, F_OK
, arg_root
, CONF_PATHS_USR_STRV("systemd/repart/definitions"), &dp
);
7572 return log_error_errno(errno
, "DDI type '%s' is not defined: %m", arg_make_ddi
);
7574 if (strv_consume(&arg_definitions
, TAKE_PTR(dp
)) < 0)
7577 strv_uniq(arg_definitions
);
7579 r
= context_read_definitions(context
);
7583 r
= find_root(context
);
7585 return 76; /* Special return value which means "Root block device not found, so not doing
7586 * anything". This isn't really an error when called at boot. */
7590 if (arg_size
!= UINT64_MAX
) {
7591 r
= resize_backing_fd(
7593 &context
->backing_fd
,
7594 node_is_our_loop
? arg_image
: NULL
,
7595 node_is_our_loop
? loop_device
: NULL
,
7596 context
->sector_size
);
7601 r
= context_load_partition_table(context
);
7602 if (r
== -EHWPOISON
)
7603 return 77; /* Special return value which means "Not GPT, so not doing anything". This isn't
7604 * really an error when called at boot. */
7607 context
->from_scratch
= r
> 0; /* Starting from scratch */
7609 if (arg_can_factory_reset
) {
7610 r
= context_can_factory_reset(context
);
7614 return EXIT_FAILURE
;
7619 r
= context_factory_reset(context
);
7623 /* We actually did a factory reset! */
7624 r
= remove_efi_variable_factory_reset();
7628 /* Reload the reduced partition table */
7629 context_unload_partition_table(context
);
7630 r
= context_load_partition_table(context
);
7635 r
= context_read_seed(context
, arg_root
);
7639 /* Make sure each partition has a unique UUID and unique label */
7640 r
= context_acquire_partition_uuids_and_labels(context
);
7644 /* Open all files to copy blocks from now, since we want to take their size into consideration */
7645 r
= context_open_copy_block_paths(
7647 loop_device
? loop_device
->devno
: /* if --image= is specified, only allow partitions on the loopback device */
7648 arg_root
&& !arg_image
? 0 : /* if --root= is specified, don't accept any block device */
7649 (dev_t
) -1); /* if neither is specified, make no restrictions */
7653 r
= context_minimize(context
);
7657 if (arg_size_auto
) {
7658 r
= determine_auto_size(context
);
7662 /* Flush out everything again, and let's grow the file first, then start fresh */
7663 context_unload_partition_table(context
);
7665 assert(arg_size
!= UINT64_MAX
);
7666 r
= resize_backing_fd(
7668 &context
->backing_fd
,
7669 node_is_our_loop
? arg_image
: NULL
,
7670 node_is_our_loop
? loop_device
: NULL
,
7671 context
->sector_size
);
7675 r
= context_load_partition_table(context
);
7680 /* First try to fit new partitions in, dropping by priority until it fits */
7682 uint64_t largest_free_area
;
7684 if (context_allocate_partitions(context
, &largest_free_area
))
7685 break; /* Success! */
7687 if (!context_drop_or_foreignize_one_priority(context
)) {
7688 r
= log_error_errno(SYNTHETIC_ERRNO(ENOSPC
),
7689 "Can't fit requested partitions into available free space (%s), refusing.",
7690 FORMAT_BYTES(largest_free_area
));
7691 determine_auto_size(context
);
7696 /* Now assign free space according to the weight logic */
7697 r
= context_grow_partitions(context
);
7701 /* Now calculate where each new partition gets placed */
7702 context_place_partitions(context
);
7704 (void) context_dump(context
, /*late=*/ false);
7706 r
= context_write_partition_table(context
);
7710 r
= context_split(context
);
7714 (void) context_dump(context
, /*late=*/ true);
7716 context
->node
= mfree(context
->node
);
7718 LIST_FOREACH(partitions
, p
, context
->partitions
)
7719 p
->split_path
= mfree(p
->split_path
);
7724 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);