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 Tpm2PCRValue
*arg_tpm2_hash_pcr_values
= NULL
;
152 static size_t arg_tpm2_n_hash_pcr_values
= 0;
153 static bool arg_tpm2_hash_pcr_values_use_default
= true;
154 static char *arg_tpm2_public_key
= NULL
;
155 static uint32_t arg_tpm2_public_key_pcr_mask
= 0;
156 static bool arg_tpm2_public_key_pcr_mask_use_default
= true;
157 static bool arg_split
= false;
158 static GptPartitionType
*arg_filter_partitions
= NULL
;
159 static size_t arg_n_filter_partitions
= 0;
160 static FilterPartitionsType arg_filter_partitions_type
= FILTER_PARTITIONS_NONE
;
161 static GptPartitionType
*arg_defer_partitions
= NULL
;
162 static size_t arg_n_defer_partitions
= 0;
163 static uint64_t arg_sector_size
= 0;
164 static ImagePolicy
*arg_image_policy
= NULL
;
165 static Architecture arg_architecture
= _ARCHITECTURE_INVALID
;
166 static int arg_offline
= -1;
167 static char **arg_copy_from
= NULL
;
168 static char *arg_copy_source
= NULL
;
169 static char *arg_make_ddi
= NULL
;
171 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
172 STATIC_DESTRUCTOR_REGISTER(arg_image
, freep
);
173 STATIC_DESTRUCTOR_REGISTER(arg_definitions
, strv_freep
);
174 STATIC_DESTRUCTOR_REGISTER(arg_key
, erase_and_freep
);
175 STATIC_DESTRUCTOR_REGISTER(arg_private_key
, EVP_PKEY_freep
);
176 STATIC_DESTRUCTOR_REGISTER(arg_certificate
, X509_freep
);
177 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device
, freep
);
178 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_hash_pcr_values
, freep
);
179 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_public_key
, freep
);
180 STATIC_DESTRUCTOR_REGISTER(arg_filter_partitions
, freep
);
181 STATIC_DESTRUCTOR_REGISTER(arg_image_policy
, image_policy_freep
);
182 STATIC_DESTRUCTOR_REGISTER(arg_copy_from
, strv_freep
);
183 STATIC_DESTRUCTOR_REGISTER(arg_copy_source
, freep
);
184 STATIC_DESTRUCTOR_REGISTER(arg_make_ddi
, freep
);
186 typedef struct FreeArea FreeArea
;
188 typedef enum EncryptMode
{
192 ENCRYPT_KEY_FILE_TPM2
,
194 _ENCRYPT_MODE_INVALID
= -EINVAL
,
197 typedef enum VerityMode
{
203 _VERITY_MODE_INVALID
= -EINVAL
,
206 typedef enum MinimizeMode
{
211 _MINIMIZE_MODE_INVALID
= -EINVAL
,
214 typedef struct Partition
{
215 char *definition_path
;
216 char **drop_in_files
;
218 GptPartitionType type
;
219 sd_id128_t current_uuid
, new_uuid
;
220 bool new_uuid_is_set
;
221 char *current_label
, *new_label
;
222 sd_id128_t fs_uuid
, luks_uuid
, verity_uuid
;
223 uint8_t verity_salt
[SHA256_DIGEST_SIZE
];
229 uint32_t weight
, padding_weight
;
231 uint64_t current_size
, new_size
;
232 uint64_t size_min
, size_max
;
234 uint64_t current_padding
, new_padding
;
235 uint64_t padding_min
, padding_max
;
240 struct fdisk_partition
*current_partition
;
241 struct fdisk_partition
*new_partition
;
242 FreeArea
*padding_area
;
243 FreeArea
*allocated_to_area
;
245 char *copy_blocks_path
;
246 bool copy_blocks_path_is_our_file
;
247 bool copy_blocks_auto
;
248 const char *copy_blocks_root
;
250 uint64_t copy_blocks_offset
;
251 uint64_t copy_blocks_size
;
255 char **exclude_files_source
;
256 char **exclude_files_target
;
257 char **make_directories
;
261 char *verity_match_key
;
262 MinimizeMode minimize
;
263 uint64_t verity_data_block_size
;
264 uint64_t verity_hash_block_size
;
272 size_t roothash_size
;
274 char *split_name_format
;
277 struct Partition
*siblings
[_VERITY_MODE_MAX
];
279 LIST_FIELDS(struct Partition
, partitions
);
282 #define PARTITION_IS_FOREIGN(p) (!(p)->definition_path)
283 #define PARTITION_EXISTS(p) (!!(p)->current_partition)
291 typedef struct Context
{
292 LIST_HEAD(Partition
, partitions
);
295 FreeArea
**free_areas
;
298 uint64_t start
, end
, total
;
300 struct fdisk_context
*fdisk_context
;
301 uint64_t sector_size
, grain_size
, fs_sector_size
;
306 bool node_is_our_file
;
312 static const char *empty_mode_table
[_EMPTY_MODE_MAX
] = {
313 [EMPTY_UNSET
] = "unset",
314 [EMPTY_REFUSE
] = "refuse",
315 [EMPTY_ALLOW
] = "allow",
316 [EMPTY_REQUIRE
] = "require",
317 [EMPTY_FORCE
] = "force",
318 [EMPTY_CREATE
] = "create",
321 static const char *encrypt_mode_table
[_ENCRYPT_MODE_MAX
] = {
322 [ENCRYPT_OFF
] = "off",
323 [ENCRYPT_KEY_FILE
] = "key-file",
324 [ENCRYPT_TPM2
] = "tpm2",
325 [ENCRYPT_KEY_FILE_TPM2
] = "key-file+tpm2",
328 static const char *verity_mode_table
[_VERITY_MODE_MAX
] = {
329 [VERITY_OFF
] = "off",
330 [VERITY_DATA
] = "data",
331 [VERITY_HASH
] = "hash",
332 [VERITY_SIG
] = "signature",
335 static const char *minimize_mode_table
[_MINIMIZE_MODE_MAX
] = {
336 [MINIMIZE_OFF
] = "off",
337 [MINIMIZE_BEST
] = "best",
338 [MINIMIZE_GUESS
] = "guess",
341 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(empty_mode
, EmptyMode
);
342 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(encrypt_mode
, EncryptMode
, ENCRYPT_KEY_FILE
);
343 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(verity_mode
, VerityMode
);
344 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(minimize_mode
, MinimizeMode
, MINIMIZE_BEST
);
346 static uint64_t round_down_size(uint64_t v
, uint64_t p
) {
350 static uint64_t round_up_size(uint64_t v
, uint64_t p
) {
352 v
= DIV_ROUND_UP(v
, p
);
354 if (v
> UINT64_MAX
/ p
)
355 return UINT64_MAX
; /* overflow */
360 static Partition
*partition_new(void) {
363 p
= new(Partition
, 1);
370 .current_size
= UINT64_MAX
,
371 .new_size
= UINT64_MAX
,
372 .size_min
= UINT64_MAX
,
373 .size_max
= UINT64_MAX
,
374 .current_padding
= UINT64_MAX
,
375 .new_padding
= UINT64_MAX
,
376 .padding_min
= UINT64_MAX
,
377 .padding_max
= UINT64_MAX
,
378 .partno
= UINT64_MAX
,
379 .offset
= UINT64_MAX
,
380 .copy_blocks_fd
= -EBADF
,
381 .copy_blocks_offset
= UINT64_MAX
,
382 .copy_blocks_size
= UINT64_MAX
,
386 .verity_data_block_size
= UINT64_MAX
,
387 .verity_hash_block_size
= UINT64_MAX
,
393 static Partition
* partition_free(Partition
*p
) {
397 free(p
->current_label
);
399 free(p
->definition_path
);
400 strv_free(p
->drop_in_files
);
402 if (p
->current_partition
)
403 fdisk_unref_partition(p
->current_partition
);
404 if (p
->new_partition
)
405 fdisk_unref_partition(p
->new_partition
);
407 if (p
->copy_blocks_path_is_our_file
)
408 unlink_and_free(p
->copy_blocks_path
);
410 free(p
->copy_blocks_path
);
411 safe_close(p
->copy_blocks_fd
);
414 strv_free(p
->copy_files
);
415 strv_free(p
->exclude_files_source
);
416 strv_free(p
->exclude_files_target
);
417 strv_free(p
->make_directories
);
418 strv_free(p
->subvolumes
);
419 free(p
->verity_match_key
);
423 free(p
->split_name_format
);
424 unlink_and_free(p
->split_path
);
429 static void partition_foreignize(Partition
*p
) {
431 assert(PARTITION_EXISTS(p
));
433 /* Reset several parameters set through definition file to make the partition foreign. */
435 p
->definition_path
= mfree(p
->definition_path
);
436 p
->drop_in_files
= strv_free(p
->drop_in_files
);
438 p
->copy_blocks_path
= mfree(p
->copy_blocks_path
);
439 p
->copy_blocks_fd
= safe_close(p
->copy_blocks_fd
);
440 p
->copy_blocks_root
= NULL
;
442 p
->format
= mfree(p
->format
);
443 p
->copy_files
= strv_free(p
->copy_files
);
444 p
->exclude_files_source
= strv_free(p
->exclude_files_source
);
445 p
->exclude_files_target
= strv_free(p
->exclude_files_target
);
446 p
->make_directories
= strv_free(p
->make_directories
);
447 p
->subvolumes
= strv_free(p
->subvolumes
);
448 p
->verity_match_key
= mfree(p
->verity_match_key
);
452 p
->padding_weight
= 0;
453 p
->size_min
= UINT64_MAX
;
454 p
->size_max
= UINT64_MAX
;
455 p
->padding_min
= UINT64_MAX
;
456 p
->padding_max
= UINT64_MAX
;
460 p
->verity
= VERITY_OFF
;
463 static bool partition_type_exclude(const GptPartitionType
*type
) {
464 if (arg_filter_partitions_type
== FILTER_PARTITIONS_NONE
)
467 for (size_t i
= 0; i
< arg_n_filter_partitions
; i
++)
468 if (sd_id128_equal(type
->uuid
, arg_filter_partitions
[i
].uuid
))
469 return arg_filter_partitions_type
== FILTER_PARTITIONS_EXCLUDE
;
471 return arg_filter_partitions_type
== FILTER_PARTITIONS_INCLUDE
;
474 static bool partition_type_defer(const GptPartitionType
*type
) {
475 for (size_t i
= 0; i
< arg_n_defer_partitions
; i
++)
476 if (sd_id128_equal(type
->uuid
, arg_defer_partitions
[i
].uuid
))
482 static Partition
* partition_unlink_and_free(Context
*context
, Partition
*p
) {
486 LIST_REMOVE(partitions
, context
->partitions
, p
);
488 assert(context
->n_partitions
> 0);
489 context
->n_partitions
--;
491 return partition_free(p
);
494 DEFINE_TRIVIAL_CLEANUP_FUNC(Partition
*, partition_free
);
496 static Context
*context_new(sd_id128_t seed
) {
499 context
= new(Context
, 1);
503 *context
= (Context
) {
513 static void context_free_free_areas(Context
*context
) {
516 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
517 free(context
->free_areas
[i
]);
519 context
->free_areas
= mfree(context
->free_areas
);
520 context
->n_free_areas
= 0;
523 static Context
*context_free(Context
*context
) {
527 while (context
->partitions
)
528 partition_unlink_and_free(context
, context
->partitions
);
529 assert(context
->n_partitions
== 0);
531 context_free_free_areas(context
);
533 if (context
->fdisk_context
)
534 fdisk_unref_context(context
->fdisk_context
);
536 safe_close(context
->backing_fd
);
537 if (context
->node_is_our_file
)
538 unlink_and_free(context
->node
);
542 return mfree(context
);
545 DEFINE_TRIVIAL_CLEANUP_FUNC(Context
*, context_free
);
547 static int context_add_free_area(
555 assert(!after
|| !after
->padding_area
);
557 if (!GREEDY_REALLOC(context
->free_areas
, context
->n_free_areas
+ 1))
560 a
= new(FreeArea
, 1);
569 context
->free_areas
[context
->n_free_areas
++] = a
;
572 after
->padding_area
= a
;
577 static void partition_drop_or_foreignize(Partition
*p
) {
578 if (!p
|| p
->dropped
|| PARTITION_IS_FOREIGN(p
))
581 if (PARTITION_EXISTS(p
)) {
582 log_info("Can't grow existing partition %s of priority %" PRIi32
", ignoring.",
583 strna(p
->current_label
?: p
->new_label
), p
->priority
);
585 /* Handle the partition as foreign. Do not set dropped flag. */
586 partition_foreignize(p
);
588 log_info("Can't fit partition %s of priority %" PRIi32
", dropping.",
589 p
->definition_path
, p
->priority
);
592 p
->allocated_to_area
= NULL
;
596 static bool context_drop_or_foreignize_one_priority(Context
*context
) {
597 int32_t priority
= 0;
599 LIST_FOREACH(partitions
, p
, context
->partitions
) {
603 priority
= MAX(priority
, p
->priority
);
606 /* Refuse to drop partitions with 0 or negative priorities or partitions of priorities that have at
607 * least one existing priority */
611 LIST_FOREACH(partitions
, p
, context
->partitions
) {
612 if (p
->priority
< priority
)
615 partition_drop_or_foreignize(p
);
617 /* We ensure that all verity sibling partitions have the same priority, so it's safe
618 * to drop all siblings here as well. */
620 for (VerityMode mode
= VERITY_OFF
+ 1; mode
< _VERITY_MODE_MAX
; mode
++)
621 partition_drop_or_foreignize(p
->siblings
[mode
]);
627 static uint64_t partition_min_size(const Context
*context
, const Partition
*p
) {
633 /* Calculate the disk space we really need at minimum for this partition. If the partition already
634 * exists the current size is what we really need. If it doesn't exist yet refuse to allocate less
637 * DEFAULT_MIN_SIZE is the default SizeMin= we configure if nothing else is specified. */
639 if (PARTITION_IS_FOREIGN(p
)) {
640 /* Don't allow changing size of partitions not managed by us */
641 assert(p
->current_size
!= UINT64_MAX
);
642 return p
->current_size
;
645 if (p
->verity
== VERITY_SIG
)
646 return VERITY_SIG_SIZE
;
648 sz
= p
->current_size
!= UINT64_MAX
? p
->current_size
: HARD_MIN_SIZE
;
650 if (!PARTITION_EXISTS(p
)) {
653 if (p
->encrypt
!= ENCRYPT_OFF
)
654 d
+= round_up_size(LUKS2_METADATA_KEEP_FREE
, context
->grain_size
);
656 if (p
->copy_blocks_size
!= UINT64_MAX
)
657 d
+= round_up_size(p
->copy_blocks_size
, context
->grain_size
);
658 else if (p
->format
|| p
->encrypt
!= ENCRYPT_OFF
) {
661 /* If we shall synthesize a file system, take minimal fs size into account (assumed to be 4K if not known) */
662 f
= p
->format
? round_up_size(minimal_size_by_fs_name(p
->format
), context
->grain_size
) : UINT64_MAX
;
663 d
+= f
== UINT64_MAX
? context
->grain_size
: f
;
670 return MAX(round_up_size(p
->size_min
!= UINT64_MAX
? p
->size_min
: DEFAULT_MIN_SIZE
, context
->grain_size
), sz
);
673 static uint64_t partition_max_size(const Context
*context
, const Partition
*p
) {
676 /* Calculate how large the partition may become at max. This is generally the configured maximum
677 * size, except when it already exists and is larger than that. In that case it's the existing size,
678 * since we never want to shrink partitions. */
683 if (PARTITION_IS_FOREIGN(p
)) {
684 /* Don't allow changing size of partitions not managed by us */
685 assert(p
->current_size
!= UINT64_MAX
);
686 return p
->current_size
;
689 if (p
->verity
== VERITY_SIG
)
690 return VERITY_SIG_SIZE
;
692 if (p
->size_max
== UINT64_MAX
)
695 sm
= round_down_size(p
->size_max
, context
->grain_size
);
697 if (p
->current_size
!= UINT64_MAX
)
698 sm
= MAX(p
->current_size
, sm
);
700 return MAX(partition_min_size(context
, p
), sm
);
703 static uint64_t partition_min_padding(const Partition
*p
) {
705 return p
->padding_min
!= UINT64_MAX
? p
->padding_min
: 0;
708 static uint64_t partition_max_padding(const Partition
*p
) {
710 return p
->padding_max
;
713 static uint64_t partition_min_size_with_padding(Context
*context
, const Partition
*p
) {
716 /* Calculate the disk space we need for this partition plus any free space coming after it. This
717 * takes user configured padding into account as well as any additional whitespace needed to align
718 * the next partition to 4K again. */
723 sz
= partition_min_size(context
, p
) + partition_min_padding(p
);
725 if (PARTITION_EXISTS(p
)) {
726 /* If the partition wasn't aligned, add extra space so that any we might add will be aligned */
727 assert(p
->offset
!= UINT64_MAX
);
728 return round_up_size(p
->offset
+ sz
, context
->grain_size
) - p
->offset
;
731 /* If this is a new partition we'll place it aligned, hence we just need to round up the required size here */
732 return round_up_size(sz
, context
->grain_size
);
735 static uint64_t free_area_available(const FreeArea
*a
) {
738 /* Determines how much of this free area is not allocated yet */
740 assert(a
->size
>= a
->allocated
);
741 return a
->size
- a
->allocated
;
744 static uint64_t free_area_current_end(Context
*context
, const FreeArea
*a
) {
749 return free_area_available(a
);
751 assert(a
->after
->offset
!= UINT64_MAX
);
752 assert(a
->after
->current_size
!= UINT64_MAX
);
754 /* Calculate where the free area ends, based on the offset of the partition preceding it. */
755 return round_up_size(a
->after
->offset
+ a
->after
->current_size
, context
->grain_size
) + free_area_available(a
);
758 static uint64_t free_area_min_end(Context
*context
, const FreeArea
*a
) {
765 assert(a
->after
->offset
!= UINT64_MAX
);
766 assert(a
->after
->current_size
!= UINT64_MAX
);
768 /* Calculate where the partition would end when we give it as much as it needs. */
769 return round_up_size(a
->after
->offset
+ partition_min_size_with_padding(context
, a
->after
), context
->grain_size
);
772 static uint64_t free_area_available_for_new_partitions(Context
*context
, const FreeArea
*a
) {
776 /* Similar to free_area_available(), but takes into account that the required size and padding of the
777 * preceding partition is honoured. */
779 return LESS_BY(free_area_current_end(context
, a
), free_area_min_end(context
, a
));
782 static int free_area_compare(FreeArea
*const *a
, FreeArea
*const*b
, Context
*context
) {
785 return CMP(free_area_available_for_new_partitions(context
, *a
),
786 free_area_available_for_new_partitions(context
, *b
));
789 static uint64_t charge_size(Context
*context
, uint64_t total
, uint64_t amount
) {
791 /* Subtract the specified amount from total, rounding up to multiple of 4K if there's room */
792 assert(amount
<= total
);
793 return LESS_BY(total
, round_up_size(amount
, context
->grain_size
));
796 static uint64_t charge_weight(uint64_t total
, uint64_t amount
) {
797 assert(amount
<= total
);
798 return total
- amount
;
801 static bool context_allocate_partitions(Context
*context
, uint64_t *ret_largest_free_area
) {
804 /* This may be called multiple times. Reset previous assignments. */
805 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
806 context
->free_areas
[i
]->allocated
= 0;
808 /* Sort free areas by size, putting smallest first */
809 typesafe_qsort_r(context
->free_areas
, context
->n_free_areas
, free_area_compare
, context
);
811 /* In any case return size of the largest free area (i.e. not the size of all free areas
813 if (ret_largest_free_area
)
814 *ret_largest_free_area
=
815 context
->n_free_areas
== 0 ? 0 :
816 free_area_available_for_new_partitions(context
, context
->free_areas
[context
->n_free_areas
-1]);
818 /* Check that each existing partition can fit its area. */
819 for (size_t i
= 0; i
< context
->n_free_areas
; i
++)
820 if (free_area_current_end(context
, context
->free_areas
[i
]) <
821 free_area_min_end(context
, context
->free_areas
[i
]))
824 /* A simple first-fit algorithm. We return true if we can fit the partitions in, otherwise false. */
825 LIST_FOREACH(partitions
, p
, context
->partitions
) {
830 /* Skip partitions we already dropped or that already exist */
831 if (p
->dropped
|| PARTITION_EXISTS(p
))
834 /* How much do we need to fit? */
835 required
= partition_min_size_with_padding(context
, p
);
836 assert(required
% context
->grain_size
== 0);
838 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
839 a
= context
->free_areas
[i
];
841 if (free_area_available_for_new_partitions(context
, a
) >= required
) {
848 return false; /* 😢 Oh no! We can't fit this partition into any free area! */
850 /* Assign the partition to this free area */
851 p
->allocated_to_area
= a
;
853 /* Budget the minimal partition size */
854 a
->allocated
+= required
;
860 static int context_sum_weights(Context
*context
, FreeArea
*a
, uint64_t *ret
) {
861 uint64_t weight_sum
= 0;
867 /* Determine the sum of the weights of all partitions placed in or before the specified free area */
869 LIST_FOREACH(partitions
, p
, context
->partitions
) {
870 if (p
->padding_area
!= a
&& p
->allocated_to_area
!= a
)
873 if (p
->weight
> UINT64_MAX
- weight_sum
)
875 weight_sum
+= p
->weight
;
877 if (p
->padding_weight
> UINT64_MAX
- weight_sum
)
879 weight_sum
+= p
->padding_weight
;
886 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Combined weight of partition exceeds unsigned 64-bit range, refusing.");
889 static uint64_t scale_by_weight(uint64_t value
, uint64_t weight
, uint64_t weight_sum
) {
890 assert(weight_sum
>= weight
);
895 if (weight
== weight_sum
)
897 if (value
<= UINT64_MAX
/ weight
)
898 return value
* weight
/ weight_sum
;
900 /* Rescale weight and weight_sum to make not the calculation overflow. To satisfy the
901 * following conditions, 'weight_sum' is rounded up but 'weight' is rounded down:
902 * - the sum of scale_by_weight() for all weights must not be larger than the input value,
903 * - scale_by_weight() must not be larger than the ideal value (i.e. calculated with uint128_t). */
904 weight_sum
= DIV_ROUND_UP(weight_sum
, 2);
909 typedef enum GrowPartitionPhase
{
910 /* The zeroth phase: do not touch foreign partitions (i.e. those we don't manage). */
913 /* The first phase: we charge partitions which need more (according to constraints) than their weight-based share. */
916 /* The second phase: we charge partitions which need less (according to constraints) than their weight-based share. */
919 /* The third phase: we distribute what remains among the remaining partitions, according to the weights */
922 _GROW_PARTITION_PHASE_MAX
,
923 } GrowPartitionPhase
;
925 static bool context_grow_partitions_phase(
928 GrowPartitionPhase phase
,
930 uint64_t *weight_sum
) {
932 bool try_again
= false;
939 /* Now let's look at the intended weights and adjust them taking the minimum space assignments into
940 * account. i.e. if a partition has a small weight but a high minimum space value set it should not
941 * get any additional room from the left-overs. Similar, if two partitions have the same weight they
942 * should get the same space if possible, even if one has a smaller minimum size than the other. */
943 LIST_FOREACH(partitions
, p
, context
->partitions
) {
945 /* Look only at partitions associated with this free area, i.e. immediately
946 * preceding it, or allocated into it */
947 if (p
->allocated_to_area
!= a
&& p
->padding_area
!= a
)
950 if (p
->new_size
== UINT64_MAX
) {
951 uint64_t share
, rsz
, xsz
;
954 /* Calculate how much this space this partition needs if everyone would get
955 * the weight based share */
956 share
= scale_by_weight(*span
, p
->weight
, *weight_sum
);
958 rsz
= partition_min_size(context
, p
);
959 xsz
= partition_max_size(context
, p
);
961 if (phase
== PHASE_FOREIGN
&& PARTITION_IS_FOREIGN(p
)) {
962 /* Never change of foreign partitions (i.e. those we don't manage) */
964 p
->new_size
= p
->current_size
;
967 } else if (phase
== PHASE_OVERCHARGE
&& rsz
> share
) {
968 /* This partition needs more than its calculated share. Let's assign
969 * it that, and take this partition out of all calculations and start
973 charge
= try_again
= true;
975 } else if (phase
== PHASE_UNDERCHARGE
&& xsz
< share
) {
976 /* This partition accepts less than its calculated
977 * share. Let's assign it that, and take this partition out
978 * of all calculations and start again. */
981 charge
= try_again
= true;
983 } else if (phase
== PHASE_DISTRIBUTE
) {
984 /* This partition can accept its calculated share. Let's
985 * assign it. There's no need to restart things here since
986 * assigning this shouldn't impact the shares of the other
989 assert(share
>= rsz
);
990 p
->new_size
= CLAMP(round_down_size(share
, context
->grain_size
), rsz
, xsz
);
995 *span
= charge_size(context
, *span
, p
->new_size
);
996 *weight_sum
= charge_weight(*weight_sum
, p
->weight
);
1000 if (p
->new_padding
== UINT64_MAX
) {
1001 uint64_t share
, rsz
, xsz
;
1002 bool charge
= false;
1004 share
= scale_by_weight(*span
, p
->padding_weight
, *weight_sum
);
1006 rsz
= partition_min_padding(p
);
1007 xsz
= partition_max_padding(p
);
1009 if (phase
== PHASE_OVERCHARGE
&& rsz
> share
) {
1010 p
->new_padding
= rsz
;
1011 charge
= try_again
= true;
1012 } else if (phase
== PHASE_UNDERCHARGE
&& xsz
< share
) {
1013 p
->new_padding
= xsz
;
1014 charge
= try_again
= true;
1015 } else if (phase
== PHASE_DISTRIBUTE
) {
1016 assert(share
>= rsz
);
1017 p
->new_padding
= CLAMP(round_down_size(share
, context
->grain_size
), rsz
, xsz
);
1022 *span
= charge_size(context
, *span
, p
->new_padding
);
1023 *weight_sum
= charge_weight(*weight_sum
, p
->padding_weight
);
1031 static void context_grow_partition_one(Context
*context
, FreeArea
*a
, Partition
*p
, uint64_t *span
) {
1042 if (p
->allocated_to_area
!= a
)
1045 if (PARTITION_IS_FOREIGN(p
))
1048 assert(p
->new_size
!= UINT64_MAX
);
1050 /* Calculate new size and align. */
1051 m
= round_down_size(p
->new_size
+ *span
, context
->grain_size
);
1052 /* But ensure this doesn't shrink the size. */
1053 m
= MAX(m
, p
->new_size
);
1054 /* And ensure this doesn't exceed the maximum size. */
1055 m
= MIN(m
, partition_max_size(context
, p
));
1057 assert(m
>= p
->new_size
);
1059 *span
= charge_size(context
, *span
, m
- p
->new_size
);
1063 static int context_grow_partitions_on_free_area(Context
*context
, FreeArea
*a
) {
1064 uint64_t weight_sum
= 0, span
;
1070 r
= context_sum_weights(context
, a
, &weight_sum
);
1074 /* Let's calculate the total area covered by this free area and the partition before it */
1077 assert(a
->after
->offset
!= UINT64_MAX
);
1078 assert(a
->after
->current_size
!= UINT64_MAX
);
1080 span
+= round_up_size(a
->after
->offset
+ a
->after
->current_size
, context
->grain_size
) - a
->after
->offset
;
1083 for (GrowPartitionPhase phase
= 0; phase
< _GROW_PARTITION_PHASE_MAX
;)
1084 if (context_grow_partitions_phase(context
, a
, phase
, &span
, &weight_sum
))
1085 phase
++; /* go to the next phase */
1087 /* We still have space left over? Donate to preceding partition if we have one */
1088 if (span
> 0 && a
->after
)
1089 context_grow_partition_one(context
, a
, a
->after
, &span
);
1091 /* What? Even still some space left (maybe because there was no preceding partition, or it had a
1092 * size limit), then let's donate it to whoever wants it. */
1094 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1095 context_grow_partition_one(context
, a
, p
, &span
);
1100 /* Yuck, still no one? Then make it padding */
1101 if (span
> 0 && a
->after
) {
1102 assert(a
->after
->new_padding
!= UINT64_MAX
);
1103 a
->after
->new_padding
+= span
;
1109 static int context_grow_partitions(Context
*context
) {
1114 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
1115 r
= context_grow_partitions_on_free_area(context
, context
->free_areas
[i
]);
1120 /* All existing partitions that have no free space after them can't change size */
1121 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1125 if (!PARTITION_EXISTS(p
) || p
->padding_area
) {
1126 /* The algorithm above must have initialized this already */
1127 assert(p
->new_size
!= UINT64_MAX
);
1131 assert(p
->new_size
== UINT64_MAX
);
1132 p
->new_size
= p
->current_size
;
1134 assert(p
->new_padding
== UINT64_MAX
);
1135 p
->new_padding
= p
->current_padding
;
1141 static uint64_t find_first_unused_partno(Context
*context
) {
1142 uint64_t partno
= 0;
1146 for (partno
= 0;; partno
++) {
1148 LIST_FOREACH(partitions
, p
, context
->partitions
)
1149 if (p
->partno
!= UINT64_MAX
&& p
->partno
== partno
)
1158 static void context_place_partitions(Context
*context
) {
1162 for (size_t i
= 0; i
< context
->n_free_areas
; i
++) {
1163 FreeArea
*a
= context
->free_areas
[i
];
1164 _unused_
uint64_t left
;
1168 assert(a
->after
->offset
!= UINT64_MAX
);
1169 assert(a
->after
->new_size
!= UINT64_MAX
);
1170 assert(a
->after
->new_padding
!= UINT64_MAX
);
1172 start
= a
->after
->offset
+ a
->after
->new_size
+ a
->after
->new_padding
;
1174 start
= context
->start
;
1176 start
= round_up_size(start
, context
->grain_size
);
1179 LIST_FOREACH(partitions
, p
, context
->partitions
) {
1180 if (p
->allocated_to_area
!= a
)
1184 p
->partno
= find_first_unused_partno(context
);
1186 assert(left
>= p
->new_size
);
1187 start
+= p
->new_size
;
1188 left
-= p
->new_size
;
1190 assert(left
>= p
->new_padding
);
1191 start
+= p
->new_padding
;
1192 left
-= p
->new_padding
;
1197 static int config_parse_type(
1199 const char *filename
,
1201 const char *section
,
1202 unsigned section_line
,
1209 GptPartitionType
*type
= ASSERT_PTR(data
);
1214 r
= gpt_partition_type_from_string(rvalue
, type
);
1216 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to parse partition type: %s", rvalue
);
1218 if (arg_architecture
>= 0)
1219 *type
= gpt_partition_type_override_architecture(*type
, arg_architecture
);
1224 static int config_parse_label(
1226 const char *filename
,
1228 const char *section
,
1229 unsigned section_line
,
1236 _cleanup_free_
char *resolved
= NULL
;
1237 char **label
= ASSERT_PTR(data
);
1242 /* Nota bene: the empty label is a totally valid one. Let's hence not follow our usual rule of
1243 * assigning the empty string to reset to default here, but really accept it as label to set. */
1245 r
= specifier_printf(rvalue
, GPT_LABEL_MAX
, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved
);
1247 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1248 "Failed to expand specifiers in Label=, ignoring: %s", rvalue
);
1252 if (!utf8_is_valid(resolved
)) {
1253 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1254 "Partition label not valid UTF-8, ignoring: %s", rvalue
);
1258 r
= gpt_partition_label_valid(resolved
);
1260 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1261 "Failed to check if string is valid as GPT partition label, ignoring: \"%s\" (from \"%s\")",
1266 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1267 "Partition label too long for GPT table, ignoring: \"%s\" (from \"%s\")",
1272 free_and_replace(*label
, resolved
);
1276 static int config_parse_weight(
1278 const char *filename
,
1280 const char *section
,
1281 unsigned section_line
,
1288 uint32_t *w
= ASSERT_PTR(data
), v
;
1293 r
= safe_atou32(rvalue
, &v
);
1295 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1296 "Failed to parse weight value, ignoring: %s", rvalue
);
1300 if (v
> 1000U*1000U) {
1301 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1302 "Weight needs to be in range 0…10000000, ignoring: %" PRIu32
, v
);
1310 static int config_parse_size4096(
1312 const char *filename
,
1314 const char *section
,
1315 unsigned section_line
,
1322 uint64_t *sz
= data
, parsed
;
1328 r
= parse_size(rvalue
, 1024, &parsed
);
1330 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
,
1331 "Failed to parse size value: %s", rvalue
);
1334 *sz
= round_up_size(parsed
, 4096);
1336 *sz
= round_down_size(parsed
, 4096);
1341 log_syntax(unit
, LOG_NOTICE
, filename
, line
, r
, "Rounded %s= size %" PRIu64
" %s %" PRIu64
", a multiple of 4096.",
1342 lvalue
, parsed
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), *sz
);
1347 static int config_parse_block_size(
1349 const char *filename
,
1351 const char *section
,
1352 unsigned section_line
,
1359 uint64_t *blksz
= ASSERT_PTR(data
), parsed
;
1364 r
= parse_size(rvalue
, 1024, &parsed
);
1366 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
,
1367 "Failed to parse size value: %s", rvalue
);
1369 if (parsed
< 512 || parsed
> 4096)
1370 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1371 "Value not between 512 and 4096: %s", rvalue
);
1373 if (!ISPOWEROF2(parsed
))
1374 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1375 "Value not a power of 2: %s", rvalue
);
1381 static int config_parse_fstype(
1383 const char *filename
,
1385 const char *section
,
1386 unsigned section_line
,
1393 char **fstype
= ASSERT_PTR(data
);
1398 /* Let's provide an easy way to override the chosen fstype for file system partitions */
1399 e
= secure_getenv("SYSTEMD_REPART_OVERRIDE_FSTYPE");
1400 if (e
&& !streq(rvalue
, e
)) {
1401 log_syntax(unit
, LOG_NOTICE
, filename
, line
, 0,
1402 "Overriding defined file system type '%s' with '%s'.", rvalue
, e
);
1406 if (!filename_is_valid(rvalue
))
1407 return log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1408 "File system type is not valid, refusing: %s", rvalue
);
1410 return free_and_strdup_warn(fstype
, rvalue
);
1413 static int config_parse_copy_files(
1415 const char *filename
,
1417 const char *section
,
1418 unsigned section_line
,
1425 _cleanup_free_
char *source
= NULL
, *buffer
= NULL
, *resolved_source
= NULL
, *resolved_target
= NULL
;
1426 const char *p
= rvalue
, *target
;
1427 char ***copy_files
= ASSERT_PTR(data
);
1432 r
= extract_first_word(&p
, &source
, ":", EXTRACT_CUNESCAPE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
1434 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to extract source path: %s", rvalue
);
1436 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0, "No argument specified: %s", rvalue
);
1440 r
= extract_first_word(&p
, &buffer
, ":", EXTRACT_CUNESCAPE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
1442 return log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to extract target path: %s", rvalue
);
1444 target
= source
; /* No target, then it's the same as the source */
1449 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
), "Too many arguments: %s", rvalue
);
1451 r
= specifier_printf(source
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_source
);
1453 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1454 "Failed to expand specifiers in CopyFiles= source, ignoring: %s", rvalue
);
1458 r
= path_simplify_and_warn(resolved_source
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1462 r
= specifier_printf(target
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_target
);
1464 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1465 "Failed to expand specifiers in CopyFiles= target, ignoring: %s", resolved_target
);
1469 r
= path_simplify_and_warn(resolved_target
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1473 r
= strv_consume_pair(copy_files
, TAKE_PTR(resolved_source
), TAKE_PTR(resolved_target
));
1480 static int config_parse_exclude_files(
1482 const char *filename
,
1484 const char *section
,
1485 unsigned section_line
,
1491 _cleanup_free_
char *resolved
= NULL
;
1492 char ***exclude_files
= ASSERT_PTR(data
);
1495 if (isempty(rvalue
)) {
1496 *exclude_files
= strv_free(*exclude_files
);
1500 r
= specifier_printf(rvalue
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved
);
1502 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1503 "Failed to expand specifiers in ExcludeFiles= path, ignoring: %s", rvalue
);
1507 r
= path_simplify_and_warn(resolved
, PATH_CHECK_ABSOLUTE
|PATH_KEEP_TRAILING_SLASH
, unit
, filename
, line
, lvalue
);
1511 if (strv_consume(exclude_files
, TAKE_PTR(resolved
)) < 0)
1517 static int config_parse_copy_blocks(
1519 const char *filename
,
1521 const char *section
,
1522 unsigned section_line
,
1529 _cleanup_free_
char *d
= NULL
;
1530 Partition
*partition
= ASSERT_PTR(data
);
1535 if (isempty(rvalue
)) {
1536 partition
->copy_blocks_path
= mfree(partition
->copy_blocks_path
);
1537 partition
->copy_blocks_auto
= false;
1541 if (streq(rvalue
, "auto")) {
1542 partition
->copy_blocks_path
= mfree(partition
->copy_blocks_path
);
1543 partition
->copy_blocks_auto
= true;
1544 partition
->copy_blocks_root
= arg_root
;
1548 r
= specifier_printf(rvalue
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &d
);
1550 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1551 "Failed to expand specifiers in CopyBlocks= source path, ignoring: %s", rvalue
);
1555 r
= path_simplify_and_warn(d
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1559 free_and_replace(partition
->copy_blocks_path
, d
);
1560 partition
->copy_blocks_auto
= false;
1561 partition
->copy_blocks_root
= arg_root
;
1565 static int config_parse_make_dirs(
1567 const char *filename
,
1569 const char *section
,
1570 unsigned section_line
,
1577 char ***sv
= ASSERT_PTR(data
);
1578 const char *p
= ASSERT_PTR(rvalue
);
1582 _cleanup_free_
char *word
= NULL
, *d
= NULL
;
1584 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_UNQUOTE
);
1588 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Invalid syntax, ignoring: %s", rvalue
);
1594 r
= specifier_printf(word
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &d
);
1596 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1597 "Failed to expand specifiers in MakeDirectories= parameter, ignoring: %s", word
);
1601 r
= path_simplify_and_warn(d
, PATH_CHECK_ABSOLUTE
, unit
, filename
, line
, lvalue
);
1605 r
= strv_consume(sv
, TAKE_PTR(d
));
1611 static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_encrypt
, encrypt_mode
, EncryptMode
, ENCRYPT_OFF
, "Invalid encryption mode");
1613 static int config_parse_gpt_flags(
1615 const char *filename
,
1617 const char *section
,
1618 unsigned section_line
,
1625 uint64_t *gpt_flags
= ASSERT_PTR(data
);
1630 r
= safe_atou64(rvalue
, gpt_flags
);
1632 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
,
1633 "Failed to parse Flags= value, ignoring: %s", rvalue
);
1640 static int config_parse_uuid(
1642 const char *filename
,
1644 const char *section
,
1645 unsigned section_line
,
1652 Partition
*partition
= ASSERT_PTR(data
);
1655 if (isempty(rvalue
)) {
1656 partition
->new_uuid
= SD_ID128_NULL
;
1657 partition
->new_uuid_is_set
= false;
1661 if (streq(rvalue
, "null")) {
1662 partition
->new_uuid
= SD_ID128_NULL
;
1663 partition
->new_uuid_is_set
= true;
1667 r
= sd_id128_from_string(rvalue
, &partition
->new_uuid
);
1669 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse 128-bit ID/UUID, ignoring: %s", rvalue
);
1673 partition
->new_uuid_is_set
= true;
1678 static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_verity
, verity_mode
, VerityMode
, VERITY_OFF
, "Invalid verity mode");
1679 static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_minimize
, minimize_mode
, MinimizeMode
, MINIMIZE_OFF
, "Invalid minimize mode");
1681 static int partition_read_definition(Partition
*p
, const char *path
, const char *const *conf_file_dirs
) {
1683 ConfigTableItem table
[] = {
1684 { "Partition", "Type", config_parse_type
, 0, &p
->type
},
1685 { "Partition", "Label", config_parse_label
, 0, &p
->new_label
},
1686 { "Partition", "UUID", config_parse_uuid
, 0, p
},
1687 { "Partition", "Priority", config_parse_int32
, 0, &p
->priority
},
1688 { "Partition", "Weight", config_parse_weight
, 0, &p
->weight
},
1689 { "Partition", "PaddingWeight", config_parse_weight
, 0, &p
->padding_weight
},
1690 { "Partition", "SizeMinBytes", config_parse_size4096
, 1, &p
->size_min
},
1691 { "Partition", "SizeMaxBytes", config_parse_size4096
, -1, &p
->size_max
},
1692 { "Partition", "PaddingMinBytes", config_parse_size4096
, 1, &p
->padding_min
},
1693 { "Partition", "PaddingMaxBytes", config_parse_size4096
, -1, &p
->padding_max
},
1694 { "Partition", "FactoryReset", config_parse_bool
, 0, &p
->factory_reset
},
1695 { "Partition", "CopyBlocks", config_parse_copy_blocks
, 0, p
},
1696 { "Partition", "Format", config_parse_fstype
, 0, &p
->format
},
1697 { "Partition", "CopyFiles", config_parse_copy_files
, 0, &p
->copy_files
},
1698 { "Partition", "ExcludeFiles", config_parse_exclude_files
, 0, &p
->exclude_files_source
},
1699 { "Partition", "ExcludeFilesTarget", config_parse_exclude_files
, 0, &p
->exclude_files_target
},
1700 { "Partition", "MakeDirectories", config_parse_make_dirs
, 0, &p
->make_directories
},
1701 { "Partition", "Encrypt", config_parse_encrypt
, 0, &p
->encrypt
},
1702 { "Partition", "Verity", config_parse_verity
, 0, &p
->verity
},
1703 { "Partition", "VerityMatchKey", config_parse_string
, 0, &p
->verity_match_key
},
1704 { "Partition", "Flags", config_parse_gpt_flags
, 0, &p
->gpt_flags
},
1705 { "Partition", "ReadOnly", config_parse_tristate
, 0, &p
->read_only
},
1706 { "Partition", "NoAuto", config_parse_tristate
, 0, &p
->no_auto
},
1707 { "Partition", "GrowFileSystem", config_parse_tristate
, 0, &p
->growfs
},
1708 { "Partition", "SplitName", config_parse_string
, 0, &p
->split_name_format
},
1709 { "Partition", "Minimize", config_parse_minimize
, 0, &p
->minimize
},
1710 { "Partition", "Subvolumes", config_parse_make_dirs
, 0, &p
->subvolumes
},
1711 { "Partition", "VerityDataBlockSizeBytes", config_parse_block_size
, 0, &p
->verity_data_block_size
},
1712 { "Partition", "VerityHashBlockSizeBytes", config_parse_block_size
, 0, &p
->verity_hash_block_size
},
1716 _cleanup_free_
char *filename
= NULL
;
1717 const char* dropin_dirname
;
1719 r
= path_extract_filename(path
, &filename
);
1721 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1723 dropin_dirname
= strjoina(filename
, ".d");
1725 r
= config_parse_many(
1726 STRV_MAKE_CONST(path
),
1729 arg_definitions
? NULL
: arg_root
,
1731 config_item_table_lookup
, table
,
1739 if (partition_type_exclude(&p
->type
))
1742 if (p
->size_min
!= UINT64_MAX
&& p
->size_max
!= UINT64_MAX
&& p
->size_min
> p
->size_max
)
1743 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1744 "SizeMinBytes= larger than SizeMaxBytes=, refusing.");
1746 if (p
->padding_min
!= UINT64_MAX
&& p
->padding_max
!= UINT64_MAX
&& p
->padding_min
> p
->padding_max
)
1747 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1748 "PaddingMinBytes= larger than PaddingMaxBytes=, refusing.");
1750 if (sd_id128_is_null(p
->type
.uuid
))
1751 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1752 "Type= not defined, refusing.");
1754 if ((p
->copy_blocks_path
|| p
->copy_blocks_auto
) &&
1755 (p
->format
|| !strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
)))
1756 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1757 "Format=/CopyFiles=/MakeDirectories= and CopyBlocks= cannot be combined, refusing.");
1759 if ((!strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
)) && streq_ptr(p
->format
, "swap"))
1760 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1761 "Format=swap and CopyFiles= cannot be combined, refusing.");
1764 const char *format
= NULL
;
1766 if (!strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
) || (p
->encrypt
!= ENCRYPT_OFF
&& !(p
->copy_blocks_path
|| p
->copy_blocks_auto
)))
1767 /* Pick "vfat" as file system for esp and xbootldr partitions, otherwise default to "ext4". */
1768 format
= IN_SET(p
->type
.designator
, PARTITION_ESP
, PARTITION_XBOOTLDR
) ? "vfat" : "ext4";
1769 else if (p
->type
.designator
== PARTITION_SWAP
)
1773 p
->format
= strdup(format
);
1779 if (p
->minimize
!= MINIMIZE_OFF
&& !p
->format
&& p
->verity
!= VERITY_HASH
)
1780 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1781 "Minimize= can only be enabled if Format= or Verity=hash are set");
1783 if (p
->minimize
== MINIMIZE_BEST
&& (p
->format
&& !fstype_is_ro(p
->format
)) && p
->verity
!= VERITY_HASH
)
1784 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1785 "Minimize=best can only be used with read-only filesystems or Verity=hash");
1787 if ((!strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
)) && !mkfs_supports_root_option(p
->format
) && geteuid() != 0)
1788 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EPERM
),
1789 "Need to be root to populate %s filesystems with CopyFiles=/MakeDirectories=",
1792 if (p
->format
&& fstype_is_ro(p
->format
) && strv_isempty(p
->copy_files
) && strv_isempty(p
->make_directories
))
1793 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1794 "Cannot format %s filesystem without source files, refusing", p
->format
);
1796 if (p
->verity
!= VERITY_OFF
|| p
->encrypt
!= ENCRYPT_OFF
) {
1797 r
= dlopen_cryptsetup();
1799 return log_syntax(NULL
, LOG_ERR
, path
, 1, r
,
1800 "libcryptsetup not found, Verity=/Encrypt= are not supported: %m");
1803 if (p
->verity
!= VERITY_OFF
&& !p
->verity_match_key
)
1804 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1805 "VerityMatchKey= must be set if Verity=%s", verity_mode_to_string(p
->verity
));
1807 if (p
->verity
== VERITY_OFF
&& p
->verity_match_key
)
1808 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1809 "VerityMatchKey= can only be set if Verity= is not \"%s\"",
1810 verity_mode_to_string(p
->verity
));
1812 if (IN_SET(p
->verity
, VERITY_HASH
, VERITY_SIG
) &&
1813 (p
->copy_files
|| p
->copy_blocks_path
|| p
->copy_blocks_auto
|| p
->format
|| p
->make_directories
))
1814 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1815 "CopyBlocks=/CopyFiles=/Format=/MakeDirectories= cannot be used with Verity=%s",
1816 verity_mode_to_string(p
->verity
));
1818 if (p
->verity
!= VERITY_OFF
&& p
->encrypt
!= ENCRYPT_OFF
)
1819 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1820 "Encrypting verity hash/data partitions is not supported");
1822 if (p
->verity
== VERITY_SIG
&& !arg_private_key
)
1823 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1824 "Verity signature partition requested but no private key provided (--private-key=)");
1826 if (p
->verity
== VERITY_SIG
&& !arg_certificate
)
1827 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1828 "Verity signature partition requested but no PEM certificate provided (--certificate=)");
1830 if (p
->verity
== VERITY_SIG
&& (p
->size_min
!= UINT64_MAX
|| p
->size_max
!= UINT64_MAX
))
1831 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EINVAL
),
1832 "SizeMinBytes=/SizeMaxBytes= cannot be used with Verity=%s",
1833 verity_mode_to_string(p
->verity
));
1835 if (!strv_isempty(p
->subvolumes
) && arg_offline
> 0)
1836 return log_syntax(NULL
, LOG_ERR
, path
, 1, SYNTHETIC_ERRNO(EOPNOTSUPP
),
1837 "Subvolumes= cannot be used with --offline=yes");
1839 /* Verity partitions are read only, let's imply the RO flag hence, unless explicitly configured otherwise. */
1840 if ((IN_SET(p
->type
.designator
,
1841 PARTITION_ROOT_VERITY
,
1842 PARTITION_USR_VERITY
) || p
->verity
== VERITY_DATA
) && p
->read_only
< 0)
1843 p
->read_only
= true;
1845 /* Default to "growfs" on, unless read-only */
1846 if (gpt_partition_type_knows_growfs(p
->type
) &&
1850 if (!p
->split_name_format
) {
1851 char *s
= strdup("%t");
1855 p
->split_name_format
= s
;
1856 } else if (streq(p
->split_name_format
, "-"))
1857 p
->split_name_format
= mfree(p
->split_name_format
);
1862 static int find_verity_sibling(Context
*context
, Partition
*p
, VerityMode mode
, Partition
**ret
) {
1863 Partition
*s
= NULL
;
1866 assert(p
->verity
!= VERITY_OFF
);
1867 assert(p
->verity_match_key
);
1868 assert(mode
!= VERITY_OFF
);
1869 assert(p
->verity
!= mode
);
1872 /* Try to find the matching sibling partition of the given type for a verity partition. For a data
1873 * partition, this is the corresponding hash partition with the same verity name (and vice versa for
1874 * the hash partition). */
1876 LIST_FOREACH(partitions
, q
, context
->partitions
) {
1880 if (q
->verity
!= mode
)
1883 assert(q
->verity_match_key
);
1885 if (!streq(p
->verity_match_key
, q
->verity_match_key
))
1902 static int context_open_and_lock_backing_fd(const char *node
, int operation
, int *backing_fd
) {
1903 _cleanup_close_
int fd
= -EBADF
;
1908 if (*backing_fd
>= 0)
1911 fd
= open(node
, O_RDONLY
|O_CLOEXEC
);
1913 return log_error_errno(errno
, "Failed to open device '%s': %m", node
);
1915 /* Tell udev not to interfere while we are processing the device */
1916 if (flock(fd
, operation
) < 0)
1917 return log_error_errno(errno
, "Failed to lock device '%s': %m", node
);
1919 log_debug("Device %s opened and locked.", node
);
1920 *backing_fd
= TAKE_FD(fd
);
1924 static int determine_current_padding(
1925 struct fdisk_context
*c
,
1926 struct fdisk_table
*t
,
1927 struct fdisk_partition
*p
,
1932 size_t n_partitions
;
1933 uint64_t offset
, next
= UINT64_MAX
;
1940 if (!fdisk_partition_has_end(p
))
1941 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition has no end!");
1943 offset
= fdisk_partition_get_end(p
);
1944 assert(offset
< UINT64_MAX
);
1945 offset
++; /* The end is one sector before the next partition or padding. */
1946 assert(offset
< UINT64_MAX
/ secsz
);
1949 n_partitions
= fdisk_table_get_nents(t
);
1950 for (size_t i
= 0; i
< n_partitions
; i
++) {
1951 struct fdisk_partition
*q
;
1954 q
= fdisk_table_get_partition(t
, i
);
1956 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
1958 if (fdisk_partition_is_used(q
) <= 0)
1961 if (!fdisk_partition_has_start(q
))
1964 start
= fdisk_partition_get_start(q
);
1965 assert(start
< UINT64_MAX
/ secsz
);
1968 if (start
>= offset
&& (next
== UINT64_MAX
|| next
> start
))
1972 if (next
== UINT64_MAX
) {
1973 /* No later partition? In that case check the end of the usable area */
1974 next
= fdisk_get_last_lba(c
);
1975 assert(next
< UINT64_MAX
);
1976 next
++; /* The last LBA is one sector before the end */
1978 assert(next
< UINT64_MAX
/ secsz
);
1982 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
1985 assert(next
>= offset
);
1986 offset
= round_up_size(offset
, grainsz
);
1987 next
= round_down_size(next
, grainsz
);
1989 *ret
= LESS_BY(next
, offset
); /* Saturated subtraction, rounding might have fucked things up */
1993 static int context_copy_from_one(Context
*context
, const char *src
) {
1994 _cleanup_close_
int fd
= -EBADF
;
1995 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
1996 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
1997 Partition
*last
= NULL
;
1998 unsigned long secsz
, grainsz
;
1999 size_t n_partitions
;
2004 r
= context_open_and_lock_backing_fd(src
, LOCK_SH
, &fd
);
2008 r
= fd_verify_regular(fd
);
2010 return log_error_errno(r
, "%s is not a file: %m", src
);
2012 r
= fdisk_new_context_at(fd
, /* path = */ NULL
, /* read_only = */ true, /* sector_size = */ UINT32_MAX
, &c
);
2014 return log_error_errno(r
, "Failed to create fdisk context: %m");
2016 secsz
= fdisk_get_sector_size(c
);
2017 grainsz
= fdisk_get_grain_size(c
);
2019 /* Insist on a power of two, and that it's a multiple of 512, i.e. the traditional sector size. */
2020 if (secsz
< 512 || !ISPOWEROF2(secsz
))
2021 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Sector size %lu is not a power of two larger than 512? Refusing.", secsz
);
2023 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2024 return log_error_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Cannot copy from disk %s with no GPT disk label.", src
);
2026 r
= fdisk_get_partitions(c
, &t
);
2028 return log_error_errno(r
, "Failed to acquire partition table: %m");
2030 n_partitions
= fdisk_table_get_nents(t
);
2031 for (size_t i
= 0; i
< n_partitions
; i
++) {
2032 _cleanup_(partition_freep
) Partition
*np
= NULL
;
2033 _cleanup_free_
char *label_copy
= NULL
;
2034 struct fdisk_partition
*p
;
2036 uint64_t sz
, start
, padding
;
2037 sd_id128_t ptid
, id
;
2038 GptPartitionType type
;
2040 p
= fdisk_table_get_partition(t
, i
);
2042 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
2044 if (fdisk_partition_is_used(p
) <= 0)
2047 if (fdisk_partition_has_start(p
) <= 0 ||
2048 fdisk_partition_has_size(p
) <= 0 ||
2049 fdisk_partition_has_partno(p
) <= 0)
2050 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a position, size or number.");
2052 r
= fdisk_partition_get_type_as_id128(p
, &ptid
);
2054 return log_error_errno(r
, "Failed to query partition type UUID: %m");
2056 type
= gpt_partition_type_from_uuid(ptid
);
2058 r
= fdisk_partition_get_uuid_as_id128(p
, &id
);
2060 return log_error_errno(r
, "Failed to query partition UUID: %m");
2062 label
= fdisk_partition_get_name(p
);
2063 if (!isempty(label
)) {
2064 label_copy
= strdup(label
);
2069 sz
= fdisk_partition_get_size(p
);
2070 assert(sz
<= UINT64_MAX
/secsz
);
2073 start
= fdisk_partition_get_start(p
);
2074 assert(start
<= UINT64_MAX
/secsz
);
2077 if (partition_type_exclude(&type
))
2080 np
= partition_new();
2086 np
->new_uuid_is_set
= true;
2087 np
->size_min
= np
->size_max
= sz
;
2088 np
->new_label
= TAKE_PTR(label_copy
);
2090 np
->definition_path
= strdup(src
);
2091 if (!np
->definition_path
)
2094 r
= determine_current_padding(c
, t
, p
, secsz
, grainsz
, &padding
);
2098 np
->padding_min
= np
->padding_max
= padding
;
2100 np
->copy_blocks_path
= strdup(src
);
2101 if (!np
->copy_blocks_path
)
2104 np
->copy_blocks_fd
= fcntl(fd
, F_DUPFD_CLOEXEC
, 3);
2105 if (np
->copy_blocks_fd
< 0)
2106 return log_error_errno(r
, "Failed to duplicate file descriptor of %s: %m", src
);
2108 np
->copy_blocks_offset
= start
;
2109 np
->copy_blocks_size
= sz
;
2111 r
= fdisk_partition_get_attrs_as_uint64(p
, &np
->gpt_flags
);
2113 return log_error_errno(r
, "Failed to get partition flags: %m");
2115 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, np
);
2116 last
= TAKE_PTR(np
);
2117 context
->n_partitions
++;
2123 static int context_copy_from(Context
*context
) {
2128 STRV_FOREACH(src
, arg_copy_from
) {
2129 r
= context_copy_from_one(context
, *src
);
2137 static int context_read_definitions(Context
*context
) {
2138 _cleanup_strv_free_
char **files
= NULL
;
2139 Partition
*last
= LIST_FIND_TAIL(partitions
, context
->partitions
);
2140 const char *const *dirs
;
2145 dirs
= (const char* const*) (arg_definitions
?: CONF_PATHS_STRV("repart.d"));
2147 r
= conf_files_list_strv(&files
, ".conf", arg_definitions
? NULL
: arg_root
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, dirs
);
2149 return log_error_errno(r
, "Failed to enumerate *.conf files: %m");
2151 STRV_FOREACH(f
, files
) {
2152 _cleanup_(partition_freep
) Partition
*p
= NULL
;
2154 p
= partition_new();
2158 p
->definition_path
= strdup(*f
);
2159 if (!p
->definition_path
)
2162 r
= partition_read_definition(p
, *f
, dirs
);
2168 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, p
);
2170 context
->n_partitions
++;
2173 /* Check that each configured verity hash/data partition has a matching verity data/hash partition. */
2175 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2176 if (p
->verity
== VERITY_OFF
)
2179 for (VerityMode mode
= VERITY_OFF
+ 1; mode
< _VERITY_MODE_MAX
; mode
++) {
2180 Partition
*q
= NULL
;
2182 if (p
->verity
== mode
)
2185 if (p
->siblings
[mode
])
2188 r
= find_verity_sibling(context
, p
, mode
, &q
);
2190 if (mode
!= VERITY_SIG
)
2191 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, SYNTHETIC_ERRNO(EINVAL
),
2192 "Missing verity %s partition for verity %s partition with VerityMatchKey=%s",
2193 verity_mode_to_string(mode
), verity_mode_to_string(p
->verity
), p
->verity_match_key
);
2194 } else if (r
== -ENOTUNIQ
)
2195 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, SYNTHETIC_ERRNO(EINVAL
),
2196 "Multiple verity %s partitions found for verity %s partition with VerityMatchKey=%s",
2197 verity_mode_to_string(mode
), verity_mode_to_string(p
->verity
), p
->verity_match_key
);
2199 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, r
,
2200 "Failed to find verity %s partition for verity %s partition with VerityMatchKey=%s",
2201 verity_mode_to_string(mode
), verity_mode_to_string(p
->verity
), p
->verity_match_key
);
2204 if (q
->priority
!= p
->priority
)
2205 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, SYNTHETIC_ERRNO(EINVAL
),
2206 "Priority mismatch (%i != %i) for verity sibling partitions with VerityMatchKey=%s",
2207 p
->priority
, q
->priority
, p
->verity_match_key
);
2209 p
->siblings
[mode
] = q
;
2214 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2217 if (p
->verity
!= VERITY_HASH
)
2220 if (p
->minimize
== MINIMIZE_OFF
)
2223 assert_se(dp
= p
->siblings
[VERITY_DATA
]);
2225 if (dp
->minimize
== MINIMIZE_OFF
&& !(dp
->copy_blocks_path
|| dp
->copy_blocks_auto
))
2226 return log_syntax(NULL
, LOG_ERR
, p
->definition_path
, 1, SYNTHETIC_ERRNO(EINVAL
),
2227 "Minimize= set for verity hash partition but data partition does "
2228 "not set CopyBlocks= or Minimize=");
2235 static int fdisk_ask_cb(struct fdisk_context
*c
, struct fdisk_ask
*ask
, void *data
) {
2236 _cleanup_free_
char *ids
= NULL
;
2239 if (fdisk_ask_get_type(ask
) != FDISK_ASKTYPE_STRING
)
2242 ids
= new(char, SD_ID128_UUID_STRING_MAX
);
2246 r
= fdisk_ask_string_set_result(ask
, sd_id128_to_uuid_string(*(sd_id128_t
*) data
, ids
));
2254 static int fdisk_set_disklabel_id_by_uuid(struct fdisk_context
*c
, sd_id128_t id
) {
2257 r
= fdisk_set_ask(c
, fdisk_ask_cb
, &id
);
2261 r
= fdisk_set_disklabel_id(c
);
2265 return fdisk_set_ask(c
, NULL
, NULL
);
2268 static int derive_uuid(sd_id128_t base
, const char *token
, sd_id128_t
*ret
) {
2270 uint8_t md
[SHA256_DIGEST_SIZE
];
2277 /* Derive a new UUID from the specified UUID in a stable and reasonably safe way. Specifically, we
2278 * calculate the HMAC-SHA256 of the specified token string, keyed by the supplied base (typically the
2279 * machine ID). We use the machine ID as key (and not as cleartext!) of the HMAC operation since it's
2280 * the machine ID we don't want to leak. */
2282 hmac_sha256(base
.bytes
, sizeof(base
.bytes
), token
, strlen(token
), result
.md
);
2284 /* Take the first half, mark it as v4 UUID */
2285 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
2286 *ret
= id128_make_v4_uuid(result
.id
);
2290 static void derive_salt(sd_id128_t base
, const char *token
, uint8_t ret
[static SHA256_DIGEST_SIZE
]) {
2293 hmac_sha256(base
.bytes
, sizeof(base
.bytes
), token
, strlen(token
), ret
);
2296 static int context_load_partition_table(Context
*context
) {
2297 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
2298 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*t
= NULL
;
2299 uint64_t left_boundary
= UINT64_MAX
, first_lba
, last_lba
, nsectors
;
2300 _cleanup_free_
char *disk_uuid_string
= NULL
;
2301 bool from_scratch
= false;
2302 sd_id128_t disk_uuid
;
2303 size_t n_partitions
;
2304 unsigned long secsz
;
2305 uint64_t grainsz
, fs_secsz
= DEFAULT_FILESYSTEM_SECTOR_SIZE
;
2309 assert(!context
->fdisk_context
);
2310 assert(!context
->free_areas
);
2311 assert(context
->start
== UINT64_MAX
);
2312 assert(context
->end
== UINT64_MAX
);
2313 assert(context
->total
== UINT64_MAX
);
2315 c
= fdisk_new_context();
2319 if (arg_sector_size
> 0) {
2320 fs_secsz
= arg_sector_size
;
2321 r
= fdisk_save_user_sector_size(c
, /* phy= */ 0, arg_sector_size
);
2326 r
= context_open_and_lock_backing_fd(context
->node
, arg_dry_run
? LOCK_SH
: LOCK_EX
,
2327 &context
->backing_fd
);
2331 if (fstat(context
->backing_fd
, &st
) < 0)
2332 return log_error_errno(r
, "Failed to stat %s: %m", context
->node
);
2334 /* Auto-detect sector size if not specified. */
2335 r
= probe_sector_size_prefer_ioctl(context
->backing_fd
, &ssz
);
2337 return log_error_errno(r
, "Failed to probe sector size of '%s': %m", context
->node
);
2339 /* If we found the sector size and we're operating on a block device, use it as the file
2340 * system sector size as well, as we know its the sector size of the actual block device and
2341 * not just the offset at which we found the GPT header. */
2342 if (r
> 0 && S_ISBLK(st
.st_mode
))
2345 r
= fdisk_save_user_sector_size(c
, /* phy= */ 0, ssz
);
2348 return log_error_errno(r
, "Failed to set sector size: %m");
2350 /* libfdisk doesn't have an API to operate on arbitrary fds, hence reopen the fd going via the
2351 * /proc/self/fd/ magic path if we have an existing fd. Open the original file otherwise. */
2352 r
= fdisk_assign_device(
2354 context
->backing_fd
>= 0 ? FORMAT_PROC_FD_PATH(context
->backing_fd
) : context
->node
,
2356 if (r
== -EINVAL
&& arg_size_auto
) {
2359 /* libfdisk returns EINVAL if opening a file of size zero. Let's check for that, and accept
2360 * it if automatic sizing is requested. */
2362 if (context
->backing_fd
< 0)
2363 r
= stat(context
->node
, &st
);
2365 r
= fstat(context
->backing_fd
, &st
);
2367 return log_error_errno(errno
, "Failed to stat block device '%s': %m", context
->node
);
2369 if (S_ISREG(st
.st_mode
) && st
.st_size
== 0) {
2370 /* Use the fallback values if we have no better idea */
2371 context
->sector_size
= fdisk_get_sector_size(c
);
2372 context
->fs_sector_size
= fs_secsz
;
2373 context
->grain_size
= 4096;
2374 return /* from_scratch = */ true;
2380 return log_error_errno(r
, "Failed to open device '%s': %m", context
->node
);
2382 if (context
->backing_fd
< 0) {
2383 /* If we have no fd referencing the device yet, make a copy of the fd now, so that we have one */
2384 r
= context_open_and_lock_backing_fd(FORMAT_PROC_FD_PATH(fdisk_get_devfd(c
)),
2385 arg_dry_run
? LOCK_SH
: LOCK_EX
,
2386 &context
->backing_fd
);
2391 /* The offsets/sizes libfdisk returns to us will be in multiple of the sector size of the
2392 * device. This is typically 512, and sometimes 4096. Let's query libfdisk once for it, and then use
2393 * it for all our needs. Note that the values we use ourselves always are in bytes though, thus mean
2394 * the same thing universally. Also note that regardless what kind of sector size is in use we'll
2395 * place partitions at multiples of 4K. */
2396 secsz
= fdisk_get_sector_size(c
);
2398 /* Insist on a power of two, and that it's a multiple of 512, i.e. the traditional sector size. */
2399 if (secsz
< 512 || !ISPOWEROF2(secsz
))
2400 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Sector size %lu is not a power of two larger than 512? Refusing.", secsz
);
2402 /* Use at least 4K, and ensure it's a multiple of the sector size, regardless if that is smaller or
2404 grainsz
= secsz
< 4096 ? 4096 : secsz
;
2406 log_debug("Sector size of device is %lu bytes. Using grain size of %" PRIu64
".", secsz
, grainsz
);
2408 switch (arg_empty
) {
2411 /* Refuse empty disks, insist on an existing GPT partition table */
2412 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2413 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has no GPT disk label, not repartitioning.", context
->node
);
2418 /* Require an empty disk, refuse any existing partition table */
2419 r
= fdisk_has_label(c
);
2421 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", context
->node
);
2423 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s already has a disk label, refusing.", context
->node
);
2425 from_scratch
= true;
2429 /* Allow both an empty disk and an existing partition table, but only GPT */
2430 r
= fdisk_has_label(c
);
2432 return log_error_errno(r
, "Failed to determine whether disk %s has a disk label: %m", context
->node
);
2434 if (!fdisk_is_labeltype(c
, FDISK_DISKLABEL_GPT
))
2435 return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON
), "Disk %s has non-GPT disk label, not repartitioning.", context
->node
);
2437 from_scratch
= true;
2443 /* Always reinitiaize the disk, don't consider what there was on the disk before */
2444 from_scratch
= true;
2448 assert_not_reached();
2452 r
= fdisk_create_disklabel(c
, "gpt");
2454 return log_error_errno(r
, "Failed to create GPT disk label: %m");
2456 r
= derive_uuid(context
->seed
, "disk-uuid", &disk_uuid
);
2458 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
2460 r
= fdisk_set_disklabel_id_by_uuid(c
, disk_uuid
);
2462 return log_error_errno(r
, "Failed to set GPT disk label: %m");
2464 goto add_initial_free_area
;
2467 r
= fdisk_get_disklabel_id(c
, &disk_uuid_string
);
2469 return log_error_errno(r
, "Failed to get current GPT disk label UUID: %m");
2471 r
= id128_from_string_nonzero(disk_uuid_string
, &disk_uuid
);
2473 r
= derive_uuid(context
->seed
, "disk-uuid", &disk_uuid
);
2475 return log_error_errno(r
, "Failed to acquire disk GPT uuid: %m");
2477 r
= fdisk_set_disklabel_id(c
);
2479 return log_error_errno(r
, "Failed to set GPT disk label: %m");
2481 return log_error_errno(r
, "Failed to parse current GPT disk label UUID: %m");
2483 r
= fdisk_get_partitions(c
, &t
);
2485 return log_error_errno(r
, "Failed to acquire partition table: %m");
2487 n_partitions
= fdisk_table_get_nents(t
);
2488 for (size_t i
= 0; i
< n_partitions
; i
++) {
2489 _cleanup_free_
char *label_copy
= NULL
;
2490 Partition
*last
= NULL
;
2491 struct fdisk_partition
*p
;
2495 sd_id128_t ptid
, id
;
2498 p
= fdisk_table_get_partition(t
, i
);
2500 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to read partition metadata: %m");
2502 if (fdisk_partition_is_used(p
) <= 0)
2505 if (fdisk_partition_has_start(p
) <= 0 ||
2506 fdisk_partition_has_size(p
) <= 0 ||
2507 fdisk_partition_has_partno(p
) <= 0)
2508 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Found a partition without a position, size or number.");
2510 r
= fdisk_partition_get_type_as_id128(p
, &ptid
);
2512 return log_error_errno(r
, "Failed to query partition type UUID: %m");
2514 r
= fdisk_partition_get_uuid_as_id128(p
, &id
);
2516 return log_error_errno(r
, "Failed to query partition UUID: %m");
2518 label
= fdisk_partition_get_name(p
);
2519 if (!isempty(label
)) {
2520 label_copy
= strdup(label
);
2525 sz
= fdisk_partition_get_size(p
);
2526 assert(sz
<= UINT64_MAX
/secsz
);
2529 start
= fdisk_partition_get_start(p
);
2530 assert(start
<= UINT64_MAX
/secsz
);
2533 partno
= fdisk_partition_get_partno(p
);
2535 if (left_boundary
== UINT64_MAX
|| left_boundary
> start
)
2536 left_boundary
= start
;
2538 /* Assign this existing partition to the first partition of the right type that doesn't have
2539 * an existing one assigned yet. */
2540 LIST_FOREACH(partitions
, pp
, context
->partitions
) {
2543 if (!sd_id128_equal(pp
->type
.uuid
, ptid
))
2546 if (!pp
->current_partition
) {
2547 pp
->current_uuid
= id
;
2548 pp
->current_size
= sz
;
2550 pp
->partno
= partno
;
2551 pp
->current_label
= TAKE_PTR(label_copy
);
2553 pp
->current_partition
= p
;
2554 fdisk_ref_partition(p
);
2556 r
= determine_current_padding(c
, t
, p
, secsz
, grainsz
, &pp
->current_padding
);
2560 if (pp
->current_padding
> 0) {
2561 r
= context_add_free_area(context
, pp
->current_padding
, pp
);
2571 /* If we have no matching definition, create a new one. */
2573 _cleanup_(partition_freep
) Partition
*np
= NULL
;
2575 np
= partition_new();
2579 np
->current_uuid
= id
;
2580 np
->type
= gpt_partition_type_from_uuid(ptid
);
2581 np
->current_size
= sz
;
2583 np
->partno
= partno
;
2584 np
->current_label
= TAKE_PTR(label_copy
);
2586 np
->current_partition
= p
;
2587 fdisk_ref_partition(p
);
2589 r
= determine_current_padding(c
, t
, p
, secsz
, grainsz
, &np
->current_padding
);
2593 if (np
->current_padding
> 0) {
2594 r
= context_add_free_area(context
, np
->current_padding
, np
);
2599 LIST_INSERT_AFTER(partitions
, context
->partitions
, last
, TAKE_PTR(np
));
2600 context
->n_partitions
++;
2604 add_initial_free_area
:
2605 nsectors
= fdisk_get_nsectors(c
);
2606 assert(nsectors
<= UINT64_MAX
/secsz
);
2609 first_lba
= fdisk_get_first_lba(c
);
2610 assert(first_lba
<= UINT64_MAX
/secsz
);
2613 last_lba
= fdisk_get_last_lba(c
);
2614 assert(last_lba
< UINT64_MAX
);
2616 assert(last_lba
<= UINT64_MAX
/secsz
);
2619 assert(last_lba
>= first_lba
);
2621 if (left_boundary
== UINT64_MAX
) {
2622 /* No partitions at all? Then the whole disk is up for grabs. */
2624 first_lba
= round_up_size(first_lba
, grainsz
);
2625 last_lba
= round_down_size(last_lba
, grainsz
);
2627 if (last_lba
> first_lba
) {
2628 r
= context_add_free_area(context
, last_lba
- first_lba
, NULL
);
2633 /* Add space left of first partition */
2634 assert(left_boundary
>= first_lba
);
2636 first_lba
= round_up_size(first_lba
, grainsz
);
2637 left_boundary
= round_down_size(left_boundary
, grainsz
);
2638 last_lba
= round_down_size(last_lba
, grainsz
);
2640 if (left_boundary
> first_lba
) {
2641 r
= context_add_free_area(context
, left_boundary
- first_lba
, NULL
);
2647 context
->start
= first_lba
;
2648 context
->end
= last_lba
;
2649 context
->total
= nsectors
;
2650 context
->sector_size
= secsz
;
2651 context
->fs_sector_size
= fs_secsz
;
2652 context
->grain_size
= grainsz
;
2653 context
->fdisk_context
= TAKE_PTR(c
);
2655 return from_scratch
;
2658 static void context_unload_partition_table(Context
*context
) {
2661 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2663 /* Entirely remove partitions that have no configuration */
2664 if (PARTITION_IS_FOREIGN(p
)) {
2665 partition_unlink_and_free(context
, p
);
2669 /* Otherwise drop all data we read off the block device and everything we might have
2670 * calculated based on it */
2673 p
->current_size
= UINT64_MAX
;
2674 p
->new_size
= UINT64_MAX
;
2675 p
->current_padding
= UINT64_MAX
;
2676 p
->new_padding
= UINT64_MAX
;
2677 p
->partno
= UINT64_MAX
;
2678 p
->offset
= UINT64_MAX
;
2680 if (p
->current_partition
) {
2681 fdisk_unref_partition(p
->current_partition
);
2682 p
->current_partition
= NULL
;
2685 if (p
->new_partition
) {
2686 fdisk_unref_partition(p
->new_partition
);
2687 p
->new_partition
= NULL
;
2690 p
->padding_area
= NULL
;
2691 p
->allocated_to_area
= NULL
;
2693 p
->current_uuid
= SD_ID128_NULL
;
2694 p
->current_label
= mfree(p
->current_label
);
2697 context
->start
= UINT64_MAX
;
2698 context
->end
= UINT64_MAX
;
2699 context
->total
= UINT64_MAX
;
2701 if (context
->fdisk_context
) {
2702 fdisk_unref_context(context
->fdisk_context
);
2703 context
->fdisk_context
= NULL
;
2706 context_free_free_areas(context
);
2709 static int format_size_change(uint64_t from
, uint64_t to
, char **ret
) {
2712 if (from
!= UINT64_MAX
) {
2713 if (from
== to
|| to
== UINT64_MAX
)
2714 t
= strdup(FORMAT_BYTES(from
));
2716 t
= strjoin(FORMAT_BYTES(from
), " ", special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), " ", FORMAT_BYTES(to
));
2717 } else if (to
!= UINT64_MAX
)
2718 t
= strjoin(special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), " ", FORMAT_BYTES(to
));
2731 static const char *partition_label(const Partition
*p
) {
2735 return p
->new_label
;
2737 if (p
->current_label
)
2738 return p
->current_label
;
2740 return gpt_partition_type_uuid_to_string(p
->type
.uuid
);
2743 static int context_dump_partitions(Context
*context
) {
2744 _cleanup_(table_unrefp
) Table
*t
= NULL
;
2745 uint64_t sum_padding
= 0, sum_size
= 0;
2747 const size_t roothash_col
= 14, dropin_files_col
= 15, split_path_col
= 16;
2748 bool has_roothash
= false, has_dropin_files
= false, has_split_path
= false;
2750 if ((arg_json_format_flags
& JSON_FORMAT_OFF
) && context
->n_partitions
== 0) {
2751 log_info("Empty partition table.");
2755 t
= table_new("type",
2775 if (!DEBUG_LOGGING
) {
2776 if (arg_json_format_flags
& JSON_FORMAT_OFF
)
2777 (void) table_set_display(t
, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4,
2778 (size_t) 8, (size_t) 9, (size_t) 12, roothash_col
, dropin_files_col
,
2781 (void) table_set_display(t
, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4,
2782 (size_t) 5, (size_t) 6, (size_t) 7, (size_t) 8, (size_t) 10,
2783 (size_t) 11, (size_t) 13, roothash_col
, dropin_files_col
,
2787 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 5), 100);
2788 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 6), 100);
2789 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 7), 100);
2790 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 8), 100);
2791 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 9), 100);
2792 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 10), 100);
2793 (void) table_set_align_percent(t
, table_get_cell(t
, 0, 11), 100);
2795 LIST_FOREACH(partitions
, p
, context
->partitions
) {
2796 _cleanup_free_
char *size_change
= NULL
, *padding_change
= NULL
, *partname
= NULL
, *rh
= NULL
;
2797 char uuid_buffer
[SD_ID128_UUID_STRING_MAX
];
2798 const char *label
, *activity
= NULL
;
2803 if (p
->current_size
== UINT64_MAX
)
2804 activity
= "create";
2805 else if (p
->current_size
!= p
->new_size
)
2806 activity
= "resize";
2808 label
= partition_label(p
);
2809 partname
= p
->partno
!= UINT64_MAX
? fdisk_partname(context
->node
, p
->partno
+1) : NULL
;
2811 r
= format_size_change(p
->current_size
, p
->new_size
, &size_change
);
2815 r
= format_size_change(p
->current_padding
, p
->new_padding
, &padding_change
);
2819 if (p
->new_size
!= UINT64_MAX
)
2820 sum_size
+= p
->new_size
;
2821 if (p
->new_padding
!= UINT64_MAX
)
2822 sum_padding
+= p
->new_padding
;
2824 if (p
->verity
!= VERITY_OFF
) {
2825 Partition
*hp
= p
->verity
== VERITY_HASH
? p
: p
->siblings
[VERITY_HASH
];
2827 rh
= hp
->roothash
? hexmem(hp
->roothash
, hp
->roothash_size
) : strdup("TBD");
2834 TABLE_STRING
, gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, uuid_buffer
),
2835 TABLE_STRING
, empty_to_null(label
) ?: "-", TABLE_SET_COLOR
, empty_to_null(label
) ? NULL
: ansi_grey(),
2836 TABLE_UUID
, p
->new_uuid_is_set
? p
->new_uuid
: p
->current_uuid
,
2837 TABLE_UINT64
, p
->partno
,
2838 TABLE_PATH_BASENAME
, p
->definition_path
, TABLE_SET_COLOR
, p
->definition_path
? NULL
: ansi_grey(),
2839 TABLE_STRING
, partname
?: "-", TABLE_SET_COLOR
, partname
? NULL
: ansi_highlight(),
2840 TABLE_UINT64
, p
->offset
,
2841 TABLE_UINT64
, p
->current_size
== UINT64_MAX
? 0 : p
->current_size
,
2842 TABLE_UINT64
, p
->new_size
,
2843 TABLE_STRING
, size_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_size
> 0 ? ansi_underline() : NULL
,
2844 TABLE_UINT64
, p
->current_padding
== UINT64_MAX
? 0 : p
->current_padding
,
2845 TABLE_UINT64
, p
->new_padding
,
2846 TABLE_STRING
, padding_change
, TABLE_SET_COLOR
, !p
->partitions_next
&& sum_padding
> 0 ? ansi_underline() : NULL
,
2847 TABLE_STRING
, activity
?: "unchanged",
2849 TABLE_STRV
, p
->drop_in_files
,
2850 TABLE_STRING
, empty_to_null(p
->split_path
) ?: "-");
2852 return table_log_add_error(r
);
2854 has_roothash
= has_roothash
|| !isempty(rh
);
2855 has_dropin_files
= has_dropin_files
|| !strv_isempty(p
->drop_in_files
);
2856 has_split_path
= has_split_path
|| !isempty(p
->split_path
);
2859 if ((arg_json_format_flags
& JSON_FORMAT_OFF
) && (sum_padding
> 0 || sum_size
> 0)) {
2862 a
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", FORMAT_BYTES(sum_size
));
2863 b
= strjoina(special_glyph(SPECIAL_GLYPH_SIGMA
), " = ", FORMAT_BYTES(sum_padding
));
2885 return table_log_add_error(r
);
2888 if (!has_roothash
) {
2889 r
= table_hide_column_from_display(t
, roothash_col
);
2891 return log_error_errno(r
, "Failed to set columns to display: %m");
2894 if (!has_dropin_files
) {
2895 r
= table_hide_column_from_display(t
, dropin_files_col
);
2897 return log_error_errno(r
, "Failed to set columns to display: %m");
2900 if (!has_split_path
) {
2901 r
= table_hide_column_from_display(t
, split_path_col
);
2903 return log_error_errno(r
, "Failed to set columns to display: %m");
2906 return table_print_with_pager(t
, arg_json_format_flags
, arg_pager_flags
, arg_legend
);
2909 static void context_bar_char_process_partition(
2914 size_t *ret_start
) {
2916 uint64_t from
, to
, total
;
2927 assert(p
->offset
!= UINT64_MAX
);
2928 assert(p
->new_size
!= UINT64_MAX
);
2931 to
= from
+ p
->new_size
;
2933 assert(context
->total
> 0);
2934 total
= context
->total
;
2936 assert(from
<= total
);
2937 x
= from
* n
/ total
;
2939 assert(to
<= total
);
2945 for (size_t i
= x
; i
< y
; i
++)
2951 static int partition_hint(const Partition
*p
, const char *node
, char **ret
) {
2952 _cleanup_free_
char *buf
= NULL
;
2956 /* Tries really hard to find a suitable description for this partition */
2958 if (p
->definition_path
)
2959 return path_extract_filename(p
->definition_path
, ret
);
2961 label
= partition_label(p
);
2962 if (!isempty(label
)) {
2963 buf
= strdup(label
);
2967 if (p
->partno
!= UINT64_MAX
) {
2968 buf
= fdisk_partname(node
, p
->partno
+1);
2972 if (p
->new_uuid_is_set
)
2974 else if (!sd_id128_is_null(p
->current_uuid
))
2975 id
= p
->current_uuid
;
2979 buf
= strdup(SD_ID128_TO_UUID_STRING(id
));
2985 *ret
= TAKE_PTR(buf
);
2989 static int context_dump_partition_bar(Context
*context
) {
2990 _cleanup_free_ Partition
**bar
= NULL
;
2991 _cleanup_free_
size_t *start_array
= NULL
;
2992 Partition
*last
= NULL
;
2996 assert_se((c
= columns()) >= 2);
2997 c
-= 2; /* We do not use the leftmost and rightmost character cell */
2999 bar
= new0(Partition
*, c
);
3003 start_array
= new(size_t, context
->n_partitions
);
3007 LIST_FOREACH(partitions
, p
, context
->partitions
)
3008 context_bar_char_process_partition(context
, bar
, c
, p
, start_array
+ j
++);
3012 for (size_t i
= 0; i
< c
; i
++) {
3017 fputs(z
? ansi_green() : ansi_yellow(), stdout
);
3018 fputs(special_glyph(SPECIAL_GLYPH_DARK_SHADE
), stdout
);
3020 fputs(ansi_normal(), stdout
);
3021 fputs(special_glyph(SPECIAL_GLYPH_LIGHT_SHADE
), stdout
);
3027 fputs(ansi_normal(), stdout
);
3030 for (size_t i
= 0; i
< context
->n_partitions
; i
++) {
3031 _cleanup_free_
char **line
= NULL
;
3033 line
= new0(char*, c
);
3038 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3039 _cleanup_free_
char *d
= NULL
;
3042 if (i
< context
->n_partitions
- j
) {
3044 if (line
[start_array
[j
-1]]) {
3047 /* Upgrade final corner to the right with a branch to the right */
3048 e
= startswith(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_RIGHT
));
3050 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), e
);
3057 d
= strdup(special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
));
3062 } else if (i
== context
->n_partitions
- j
) {
3063 _cleanup_free_
char *hint
= NULL
;
3065 (void) partition_hint(p
, context
->node
, &hint
);
3067 if (streq_ptr(line
[start_array
[j
-1]], special_glyph(SPECIAL_GLYPH_TREE_VERTICAL
)))
3068 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_BRANCH
), " ", strna(hint
));
3070 d
= strjoin(special_glyph(SPECIAL_GLYPH_TREE_RIGHT
), " ", strna(hint
));
3077 free_and_replace(line
[start_array
[j
-1]], d
);
3085 fputs(line
[j
], stdout
);
3086 j
+= utf8_console_width(line
[j
]);
3095 for (j
= 0; j
< c
; j
++)
3102 static bool context_has_roothash(Context
*context
) {
3103 LIST_FOREACH(partitions
, p
, context
->partitions
)
3110 static int context_dump(Context
*context
, bool late
) {
3115 if (arg_pretty
== 0 && FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
))
3118 /* If we're outputting JSON, only dump after doing all operations so we can include the roothashes
3120 if (!late
&& !FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
))
3123 /* If we're not outputting JSON, only dump again after doing all operations if there are any
3124 * roothashes that we need to communicate to the user. */
3125 if (late
&& FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
) && !context_has_roothash(context
))
3128 r
= context_dump_partitions(context
);
3132 /* Make sure we only write the partition bar once, even if we're writing the partition table twice to
3133 * communicate roothashes. */
3134 if (FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
) && !late
) {
3137 r
= context_dump_partition_bar(context
);
3150 static bool context_changed(const Context
*context
) {
3153 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3157 if (p
->allocated_to_area
)
3160 if (p
->new_size
!= p
->current_size
)
3167 static int context_wipe_range(Context
*context
, uint64_t offset
, uint64_t size
) {
3168 _cleanup_(blkid_free_probep
) blkid_probe probe
= NULL
;
3172 assert(offset
!= UINT64_MAX
);
3173 assert(size
!= UINT64_MAX
);
3175 probe
= blkid_new_probe();
3180 r
= blkid_probe_set_device(probe
, fdisk_get_devfd(context
->fdisk_context
), offset
, size
);
3182 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to allocate device probe for wiping.");
3185 if (blkid_probe_enable_superblocks(probe
, true) < 0 ||
3186 blkid_probe_set_superblocks_flags(probe
, BLKID_SUBLKS_MAGIC
|BLKID_SUBLKS_BADCSUM
) < 0 ||
3187 blkid_probe_enable_partitions(probe
, true) < 0 ||
3188 blkid_probe_set_partitions_flags(probe
, BLKID_PARTS_MAGIC
) < 0)
3189 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to enable superblock and partition probing.");
3193 r
= blkid_do_probe(probe
);
3195 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to probe for file systems.");
3200 if (blkid_do_wipe(probe
, false) < 0)
3201 return log_error_errno(errno
?: SYNTHETIC_ERRNO(EIO
), "Failed to wipe file system signature.");
3207 static int context_wipe_partition(Context
*context
, Partition
*p
) {
3212 assert(!PARTITION_EXISTS(p
)); /* Safety check: never wipe existing partitions */
3214 assert(p
->offset
!= UINT64_MAX
);
3215 assert(p
->new_size
!= UINT64_MAX
);
3217 r
= context_wipe_range(context
, p
->offset
, p
->new_size
);
3221 log_info("Successfully wiped file system signatures from future partition %" PRIu64
".", p
->partno
);
3225 static int context_discard_range(
3234 assert(offset
!= UINT64_MAX
);
3235 assert(size
!= UINT64_MAX
);
3240 assert_se((fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
3242 if (fstat(fd
, &st
) < 0)
3245 if (S_ISREG(st
.st_mode
)) {
3246 if (fallocate(fd
, FALLOC_FL_PUNCH_HOLE
|FALLOC_FL_KEEP_SIZE
, offset
, size
) < 0) {
3247 if (ERRNO_IS_NOT_SUPPORTED(errno
))
3256 if (S_ISBLK(st
.st_mode
)) {
3257 uint64_t range
[2], end
;
3259 range
[0] = round_up_size(offset
, context
->sector_size
);
3261 if (offset
> UINT64_MAX
- size
)
3264 end
= offset
+ size
;
3265 if (end
<= range
[0])
3268 range
[1] = round_down_size(end
- range
[0], context
->sector_size
);
3272 if (ioctl(fd
, BLKDISCARD
, range
) < 0) {
3273 if (ERRNO_IS_NOT_SUPPORTED(errno
))
3285 static int context_discard_partition(Context
*context
, Partition
*p
) {
3291 assert(p
->offset
!= UINT64_MAX
);
3292 assert(p
->new_size
!= UINT64_MAX
);
3293 assert(!PARTITION_EXISTS(p
)); /* Safety check: never discard existing partitions */
3298 r
= context_discard_range(context
, p
->offset
, p
->new_size
);
3299 if (r
== -EOPNOTSUPP
) {
3300 log_info("Storage does not support discard, not discarding data in future partition %" PRIu64
".", p
->partno
);
3304 /* Let's handle this gracefully: https://bugzilla.kernel.org/show_bug.cgi?id=211167 */
3305 log_info("Block device is busy, not discarding partition %" PRIu64
" because it probably is mounted.", p
->partno
);
3309 log_info("Partition %" PRIu64
" too short for discard, skipping.", p
->partno
);
3313 return log_error_errno(r
, "Failed to discard data for future partition %" PRIu64
".", p
->partno
);
3315 log_info("Successfully discarded data from future partition %" PRIu64
".", p
->partno
);
3319 static int context_discard_gap_after(Context
*context
, Partition
*p
) {
3320 uint64_t gap
, next
= UINT64_MAX
;
3324 assert(!p
|| (p
->offset
!= UINT64_MAX
&& p
->new_size
!= UINT64_MAX
));
3330 gap
= p
->offset
+ p
->new_size
;
3332 /* The context start gets rounded up to grain_size, however
3333 * existing partitions may be before that so ensure the gap
3334 * starts at the first actually usable lba
3336 gap
= fdisk_get_first_lba(context
->fdisk_context
) * context
->sector_size
;
3338 LIST_FOREACH(partitions
, q
, context
->partitions
) {
3342 assert(q
->offset
!= UINT64_MAX
);
3343 assert(q
->new_size
!= UINT64_MAX
);
3345 if (q
->offset
< gap
)
3348 if (next
== UINT64_MAX
|| q
->offset
< next
)
3352 if (next
== UINT64_MAX
) {
3353 next
= (fdisk_get_last_lba(context
->fdisk_context
) + 1) * context
->sector_size
;
3355 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Partition end beyond disk end.");
3358 assert(next
>= gap
);
3359 r
= context_discard_range(context
, gap
, next
- gap
);
3360 if (r
== -EOPNOTSUPP
) {
3362 log_info("Storage does not support discard, not discarding gap after partition %" PRIu64
".", p
->partno
);
3364 log_info("Storage does not support discard, not discarding gap at beginning of disk.");
3367 if (r
== 0) /* Too short */
3371 return log_error_errno(r
, "Failed to discard gap after partition %" PRIu64
".", p
->partno
);
3373 return log_error_errno(r
, "Failed to discard gap at beginning of disk.");
3377 log_info("Successfully discarded gap after partition %" PRIu64
".", p
->partno
);
3379 log_info("Successfully discarded gap at beginning of disk.");
3384 static int context_wipe_and_discard(Context
*context
) {
3389 if (arg_empty
== EMPTY_CREATE
) /* If we just created the image, no need to wipe */
3392 /* Wipe and discard the contents of all partitions we are about to create. We skip the discarding if
3393 * we were supposed to start from scratch anyway, as in that case we just discard the whole block
3394 * device in one go early on. */
3396 LIST_FOREACH(partitions
, p
, context
->partitions
) {
3398 if (!p
->allocated_to_area
)
3401 if (partition_type_defer(&p
->type
))
3404 r
= context_wipe_partition(context
, p
);
3408 if (!context
->from_scratch
) {
3409 r
= context_discard_partition(context
, p
);
3413 r
= context_discard_gap_after(context
, p
);
3419 if (!context
->from_scratch
) {
3420 r
= context_discard_gap_after(context
, NULL
);
3428 typedef struct DecryptedPartitionTarget
{
3432 struct crypt_device
*device
;
3433 } DecryptedPartitionTarget
;
3435 static DecryptedPartitionTarget
* decrypted_partition_target_free(DecryptedPartitionTarget
*t
) {
3436 #if HAVE_LIBCRYPTSETUP
3444 /* udev or so might access out block device in the background while we are done. Let's hence
3445 * force detach the volume. We sync'ed before, hence this should be safe. */
3446 r
= sym_crypt_deactivate_by_name(t
->device
, t
->dm_name
, CRYPT_DEACTIVATE_FORCE
);
3448 log_warning_errno(r
, "Failed to deactivate LUKS device, ignoring: %m");
3450 sym_crypt_free(t
->device
);
3463 DecryptedPartitionTarget
*decrypted
;
3466 static int partition_target_fd(PartitionTarget
*t
) {
3468 assert(t
->loop
|| t
->fd
>= 0 || t
->whole_fd
>= 0);
3471 return t
->decrypted
->fd
;
3482 static const char* partition_target_path(PartitionTarget
*t
) {
3484 assert(t
->loop
|| t
->path
);
3487 return t
->decrypted
->volume
;
3490 return t
->loop
->node
;
3495 static PartitionTarget
*partition_target_free(PartitionTarget
*t
) {
3499 decrypted_partition_target_free(t
->decrypted
);
3500 loop_device_unref(t
->loop
);
3502 unlink_and_free(t
->path
);
3507 DEFINE_TRIVIAL_CLEANUP_FUNC(PartitionTarget
*, partition_target_free
);
3509 static int prepare_temporary_file(PartitionTarget
*t
, uint64_t size
) {
3510 _cleanup_(unlink_and_freep
) char *temp
= NULL
;
3511 _cleanup_close_
int fd
= -EBADF
;
3517 r
= var_tmp_dir(&vt
);
3519 return log_error_errno(r
, "Could not determine temporary directory: %m");
3521 temp
= path_join(vt
, "repart-XXXXXX");
3525 fd
= mkostemp_safe(temp
);
3527 return log_error_errno(fd
, "Failed to create temporary file: %m");
3529 if (ftruncate(fd
, size
) < 0)
3530 return log_error_errno(errno
, "Failed to truncate temporary file to %s: %m",
3531 FORMAT_BYTES(size
));
3533 t
->fd
= TAKE_FD(fd
);
3534 t
->path
= TAKE_PTR(temp
);
3539 static int partition_target_prepare(
3544 PartitionTarget
**ret
) {
3546 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
3547 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
3554 assert_se((whole_fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
3556 t
= new(PartitionTarget
, 1);
3559 *t
= (PartitionTarget
) {
3565 if (lseek(whole_fd
, p
->offset
, SEEK_SET
) == (off_t
) -1)
3566 return log_error_errno(errno
, "Failed to seek to partition offset: %m");
3568 t
->whole_fd
= whole_fd
;
3573 /* Loopback block devices are not only useful to turn regular files into block devices, but
3574 * also to cut out sections of block devices into new block devices. */
3576 if (arg_offline
<= 0) {
3577 r
= loop_device_make(whole_fd
, O_RDWR
, p
->offset
, size
, context
->sector_size
, 0, LOCK_EX
, &d
);
3578 if (r
< 0 && (arg_offline
== 0 || (r
!= -ENOENT
&& !ERRNO_IS_PRIVILEGE(r
)) || !strv_isempty(p
->subvolumes
)))
3579 return log_error_errno(r
, "Failed to make loopback device of future partition %" PRIu64
": %m", p
->partno
);
3581 t
->loop
= TAKE_PTR(d
);
3586 log_debug_errno(r
, "No access to loop devices, falling back to a regular file");
3589 /* If we can't allocate a loop device, let's write to a regular file that we copy into the final
3590 * image so we can run in containers and without needing root privileges. On filesystems with
3591 * reflinking support, we can take advantage of this and just reflink the result into the image.
3594 r
= prepare_temporary_file(t
, size
);
3603 static int partition_target_grow(PartitionTarget
*t
, uint64_t size
) {
3607 assert(!t
->decrypted
);
3610 r
= loop_device_refresh_size(t
->loop
, UINT64_MAX
, size
);
3612 return log_error_errno(r
, "Failed to refresh loopback device size: %m");
3613 } else if (t
->fd
>= 0) {
3614 if (ftruncate(t
->fd
, size
) < 0)
3615 return log_error_errno(errno
, "Failed to grow '%s' to %s by truncation: %m",
3616 t
->path
, FORMAT_BYTES(size
));
3622 static int partition_target_sync(Context
*context
, Partition
*p
, PartitionTarget
*t
) {
3629 assert_se((whole_fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
3631 if (t
->decrypted
&& fsync(t
->decrypted
->fd
) < 0)
3632 return log_error_errno(errno
, "Failed to sync changes to '%s': %m", t
->decrypted
->volume
);
3635 r
= loop_device_sync(t
->loop
);
3637 return log_error_errno(r
, "Failed to sync loopback device: %m");
3638 } else if (t
->fd
>= 0) {
3641 if (lseek(whole_fd
, p
->offset
, SEEK_SET
) == (off_t
) -1)
3642 return log_error_errno(errno
, "Failed to seek to partition offset: %m");
3644 if (lseek(t
->fd
, 0, SEEK_SET
) == (off_t
) -1)
3645 return log_error_errno(errno
, "Failed to seek to start of temporary file: %m");
3647 if (fstat(t
->fd
, &st
) < 0)
3648 return log_error_errno(errno
, "Failed to stat temporary file: %m");
3650 if (st
.st_size
> (off_t
) p
->new_size
)
3651 return log_error_errno(SYNTHETIC_ERRNO(ENOSPC
),
3652 "Partition %" PRIu64
"'s contents (%s) don't fit in the partition (%s)",
3653 p
->partno
, FORMAT_BYTES(st
.st_size
), FORMAT_BYTES(p
->new_size
));
3655 r
= copy_bytes(t
->fd
, whole_fd
, UINT64_MAX
, COPY_REFLINK
|COPY_HOLES
|COPY_FSYNC
);
3657 return log_error_errno(r
, "Failed to copy bytes to partition: %m");
3659 if (fsync(t
->whole_fd
) < 0)
3660 return log_error_errno(errno
, "Failed to sync changes: %m");
3666 static int partition_encrypt(Context
*context
, Partition
*p
, PartitionTarget
*target
, bool offline
) {
3667 #if HAVE_LIBCRYPTSETUP && HAVE_CRYPT_SET_DATA_OFFSET && HAVE_CRYPT_REENCRYPT_INIT_BY_PASSPHRASE && HAVE_CRYPT_REENCRYPT
3668 const char *node
= partition_target_path(target
);
3669 struct crypt_params_luks2 luks_params
= {
3670 .label
= strempty(ASSERT_PTR(p
)->new_label
),
3671 .sector_size
= ASSERT_PTR(context
)->fs_sector_size
,
3672 .data_device
= offline
? node
: NULL
,
3674 struct crypt_params_reencrypt reencrypt_params
= {
3675 .mode
= CRYPT_REENCRYPT_ENCRYPT
,
3676 .direction
= CRYPT_REENCRYPT_BACKWARD
,
3677 .resilience
= "datashift",
3678 .data_shift
= LUKS2_METADATA_SIZE
/ 512,
3679 .luks2
= &luks_params
,
3680 .flags
= CRYPT_REENCRYPT_INITIALIZE_ONLY
|CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT
,
3682 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
3683 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
3684 _cleanup_fclose_
FILE *h
= NULL
;
3685 _cleanup_free_
char *hp
= NULL
, *vol
= NULL
, *dm_name
= NULL
;
3686 const char *passphrase
= NULL
;
3687 size_t passphrase_size
= 0;
3693 assert(p
->encrypt
!= ENCRYPT_OFF
);
3695 r
= dlopen_cryptsetup();
3697 return log_error_errno(r
, "libcryptsetup not found, cannot encrypt: %m");
3699 log_info("Encrypting future partition %" PRIu64
"...", p
->partno
);
3702 r
= var_tmp_dir(&vt
);
3704 return log_error_errno(r
, "Failed to determine temporary files directory: %m");
3706 r
= fopen_temporary_child(vt
, &h
, &hp
);
3708 return log_error_errno(r
, "Failed to create temporary LUKS header file: %m");
3710 /* Weird cryptsetup requirement which requires the header file to be the size of at least one
3712 r
= ftruncate(fileno(h
), luks_params
.sector_size
);
3714 return log_error_errno(r
, "Failed to grow temporary LUKS header file: %m");
3716 if (asprintf(&dm_name
, "luks-repart-%08" PRIx64
, random_u64()) < 0)
3719 vol
= path_join("/dev/mapper/", dm_name
);
3724 r
= sym_crypt_init(&cd
, offline
? hp
: node
);
3726 return log_error_errno(r
, "Failed to allocate libcryptsetup context for %s: %m", hp
);
3728 cryptsetup_enable_logging(cd
);
3731 /* Disable kernel keyring usage by libcryptsetup as a workaround for
3732 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/273. This makes sure that we can
3733 * do offline encryption even when repart is running in a container. */
3734 r
= sym_crypt_volume_key_keyring(cd
, false);
3736 return log_error_errno(r
, "Failed to disable kernel keyring: %m");
3738 r
= sym_crypt_metadata_locking(cd
, false);
3740 return log_error_errno(r
, "Failed to disable metadata locking: %m");
3742 r
= sym_crypt_set_data_offset(cd
, LUKS2_METADATA_SIZE
/ 512);
3744 return log_error_errno(r
, "Failed to set data offset: %m");
3747 r
= sym_crypt_format(cd
,
3751 SD_ID128_TO_UUID_STRING(p
->luks_uuid
),
3756 return log_error_errno(r
, "Failed to LUKS2 format future partition: %m");
3758 if (IN_SET(p
->encrypt
, ENCRYPT_KEY_FILE
, ENCRYPT_KEY_FILE_TPM2
)) {
3759 r
= sym_crypt_keyslot_add_by_volume_key(
3767 return log_error_errno(r
, "Failed to add LUKS2 key: %m");
3769 passphrase
= strempty(arg_key
);
3770 passphrase_size
= arg_key_size
;
3773 if (IN_SET(p
->encrypt
, ENCRYPT_TPM2
, ENCRYPT_KEY_FILE_TPM2
)) {
3775 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
3776 _cleanup_(erase_and_freep
) void *secret
= NULL
;
3777 _cleanup_free_
void *pubkey
= NULL
;
3778 _cleanup_free_
void *blob
= NULL
, *srk_buf
= NULL
;
3779 size_t secret_size
, blob_size
, pubkey_size
= 0, srk_buf_size
= 0;
3780 ssize_t base64_encoded_size
;
3783 if (arg_tpm2_public_key_pcr_mask
!= 0) {
3784 r
= tpm2_load_pcr_public_key(arg_tpm2_public_key
, &pubkey
, &pubkey_size
);
3786 if (arg_tpm2_public_key
|| r
!= -ENOENT
)
3787 return log_error_errno(r
, "Failed read TPM PCR public key: %m");
3789 log_debug_errno(r
, "Failed to read TPM2 PCR public key, proceeding without: %m");
3790 arg_tpm2_public_key_pcr_mask
= 0;
3794 _cleanup_(tpm2_context_unrefp
) Tpm2Context
*tpm2_context
= NULL
;
3795 r
= tpm2_context_new(arg_tpm2_device
, &tpm2_context
);
3797 return log_error_errno(r
, "Failed to create TPM2 context: %m");
3799 TPM2B_PUBLIC
public;
3801 r
= tpm2_tpm2b_public_from_pem(pubkey
, pubkey_size
, &public);
3803 return log_error_errno(r
, "Could not convert public key to TPM2B_PUBLIC: %m");
3806 r
= tpm2_pcr_read_missing_values(tpm2_context
, arg_tpm2_hash_pcr_values
, arg_tpm2_n_hash_pcr_values
);
3808 return log_error_errno(r
, "Could not read pcr values: %m");
3810 uint16_t hash_pcr_bank
= 0;
3811 uint32_t hash_pcr_mask
= 0;
3812 if (arg_tpm2_n_hash_pcr_values
> 0) {
3814 r
= tpm2_pcr_values_hash_count(arg_tpm2_hash_pcr_values
, arg_tpm2_n_hash_pcr_values
, &hash_count
);
3816 return log_error_errno(r
, "Could not get hash count: %m");
3819 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Multiple PCR banks selected.");
3821 hash_pcr_bank
= arg_tpm2_hash_pcr_values
[0].hash
;
3822 r
= tpm2_pcr_values_to_mask(arg_tpm2_hash_pcr_values
, arg_tpm2_n_hash_pcr_values
, hash_pcr_bank
, &hash_pcr_mask
);
3824 return log_error_errno(r
, "Could not get hash mask: %m");
3827 TPM2B_DIGEST policy
= TPM2B_DIGEST_MAKE(NULL
, TPM2_SHA256_DIGEST_SIZE
);
3828 r
= tpm2_calculate_sealing_policy(arg_tpm2_hash_pcr_values
, arg_tpm2_n_hash_pcr_values
, pubkey
? &public : NULL
, /* use_pin= */ false, &policy
);
3830 return log_error_errno(r
, "Could not calculate sealing policy digest: %m");
3832 r
= tpm2_seal(tpm2_context
,
3833 /* seal_key_handle= */ 0,
3836 &secret
, &secret_size
,
3838 /* ret_primary_alg= */ NULL
,
3839 &srk_buf
, &srk_buf_size
);
3841 return log_error_errno(r
, "Failed to seal to TPM2: %m");
3843 base64_encoded_size
= base64mem(secret
, secret_size
, &base64_encoded
);
3844 if (base64_encoded_size
< 0)
3845 return log_error_errno(base64_encoded_size
, "Failed to base64 encode secret key: %m");
3847 r
= cryptsetup_set_minimal_pbkdf(cd
);
3849 return log_error_errno(r
, "Failed to set minimal PBKDF: %m");
3851 keyslot
= sym_crypt_keyslot_add_by_volume_key(
3857 base64_encoded_size
);
3859 return log_error_errno(keyslot
, "Failed to add new TPM2 key: %m");
3861 r
= tpm2_make_luks2_json(
3865 pubkey
, pubkey_size
,
3866 arg_tpm2_public_key_pcr_mask
,
3867 /* primary_alg= */ 0,
3869 policy
.buffer
, policy
.size
,
3870 NULL
, 0, /* no salt because tpm2_seal has no pin */
3871 srk_buf
, srk_buf_size
,
3875 return log_error_errno(r
, "Failed to prepare TPM2 JSON token object: %m");
3877 r
= cryptsetup_add_token_json(cd
, v
);
3879 return log_error_errno(r
, "Failed to add TPM2 JSON token to LUKS2 header: %m");
3881 passphrase
= base64_encoded
;
3882 passphrase_size
= strlen(base64_encoded
);
3884 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3885 "Support for TPM2 enrollment not enabled.");
3890 r
= sym_crypt_reencrypt_init_by_passphrase(
3897 sym_crypt_get_cipher(cd
),
3898 sym_crypt_get_cipher_mode(cd
),
3901 return log_error_errno(r
, "Failed to prepare for reencryption: %m");
3903 /* crypt_reencrypt_init_by_passphrase() doesn't actually put the LUKS header at the front, we
3904 * have to do that ourselves. */
3909 r
= sym_crypt_init(&cd
, node
);
3911 return log_error_errno(r
, "Failed to allocate libcryptsetup context for %s: %m", node
);
3913 r
= sym_crypt_header_restore(cd
, CRYPT_LUKS2
, hp
);
3915 return log_error_errno(r
, "Failed to place new LUKS header at head of %s: %m", node
);
3917 reencrypt_params
.flags
&= ~CRYPT_REENCRYPT_INITIALIZE_ONLY
;
3919 r
= sym_crypt_reencrypt_init_by_passphrase(
3930 return log_error_errno(r
, "Failed to load reencryption context: %m");
3932 r
= sym_crypt_reencrypt(cd
, NULL
);
3934 return log_error_errno(r
, "Failed to encrypt %s: %m", node
);
3936 _cleanup_free_ DecryptedPartitionTarget
*t
= NULL
;
3937 _cleanup_close_
int dev_fd
= -1;
3939 r
= sym_crypt_activate_by_volume_key(
3944 arg_discard
? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0);
3946 return log_error_errno(r
, "Failed to activate LUKS superblock: %m");
3948 dev_fd
= open(vol
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
);
3950 return log_error_errno(errno
, "Failed to open LUKS volume '%s': %m", vol
);
3952 if (flock(dev_fd
, LOCK_EX
) < 0)
3953 return log_error_errno(errno
, "Failed to lock '%s': %m", vol
);
3955 t
= new(DecryptedPartitionTarget
, 1);
3959 *t
= (DecryptedPartitionTarget
) {
3960 .fd
= TAKE_FD(dev_fd
),
3961 .dm_name
= TAKE_PTR(dm_name
),
3962 .volume
= TAKE_PTR(vol
),
3963 .device
= TAKE_PTR(cd
),
3966 target
->decrypted
= TAKE_PTR(t
);
3969 log_info("Successfully encrypted future partition %" PRIu64
".", p
->partno
);
3973 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3974 "libcryptsetup is not supported or is missing required symbols, cannot encrypt: %m");
3978 static int partition_format_verity_hash(
3982 const char *data_node
) {
3984 #if HAVE_LIBCRYPTSETUP
3986 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
3987 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
3988 _cleanup_free_
char *hint
= NULL
;
3989 _cleanup_free_
uint8_t *rh
= NULL
;
3995 assert(p
->verity
== VERITY_HASH
);
4001 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
4004 /* Minimized partitions will use the copy blocks logic so let's make sure to skip those here. */
4005 if (p
->copy_blocks_fd
>= 0)
4008 assert_se(dp
= p
->siblings
[VERITY_DATA
]);
4009 assert(!dp
->dropped
);
4011 (void) partition_hint(p
, node
, &hint
);
4013 r
= dlopen_cryptsetup();
4015 return log_error_errno(r
, "libcryptsetup not found, cannot setup verity: %m");
4018 r
= partition_target_prepare(context
, p
, p
->new_size
, /*need_path=*/ true, &t
);
4022 node
= partition_target_path(t
);
4025 if (p
->verity_data_block_size
== UINT64_MAX
)
4026 p
->verity_data_block_size
= context
->fs_sector_size
;
4027 if (p
->verity_hash_block_size
== UINT64_MAX
)
4028 p
->verity_hash_block_size
= context
->fs_sector_size
;
4030 r
= sym_crypt_init(&cd
, node
);
4032 return log_error_errno(r
, "Failed to allocate libcryptsetup context for %s: %m", node
);
4034 cryptsetup_enable_logging(cd
);
4036 r
= sym_crypt_format(
4037 cd
, CRYPT_VERITY
, NULL
, NULL
, SD_ID128_TO_UUID_STRING(p
->verity_uuid
), NULL
, 0,
4038 &(struct crypt_params_verity
){
4039 .data_device
= data_node
,
4040 .flags
= CRYPT_VERITY_CREATE_HASH
,
4041 .hash_name
= "sha256",
4043 .data_block_size
= p
->verity_data_block_size
,
4044 .hash_block_size
= p
->verity_hash_block_size
,
4045 .salt_size
= sizeof(p
->verity_salt
),
4046 .salt
= (const char*)p
->verity_salt
,
4049 /* libcryptsetup reports non-descriptive EIO errors for every I/O failure. Luckily, it
4050 * doesn't clobber errno so let's check for ENOSPC so we can report a better error if the
4051 * partition is too small. */
4052 if (r
== -EIO
&& errno
== ENOSPC
)
4053 return log_error_errno(errno
,
4054 "Verity hash data does not fit in partition %s with size %s",
4055 strna(hint
), FORMAT_BYTES(p
->new_size
));
4057 return log_error_errno(r
, "Failed to setup verity hash data of partition %s: %m", strna(hint
));
4061 r
= partition_target_sync(context
, p
, t
);
4066 r
= sym_crypt_get_volume_key_size(cd
);
4068 return log_error_errno(r
, "Failed to determine verity root hash size of partition %s: %m", strna(hint
));
4075 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, (char *) rh
, &rhs
, NULL
, 0);
4077 return log_error_errno(r
, "Failed to get verity root hash of partition %s: %m", strna(hint
));
4079 assert(rhs
>= sizeof(sd_id128_t
) * 2);
4081 if (!dp
->new_uuid_is_set
) {
4082 memcpy_safe(dp
->new_uuid
.bytes
, rh
, sizeof(sd_id128_t
));
4083 dp
->new_uuid_is_set
= true;
4086 if (!p
->new_uuid_is_set
) {
4087 memcpy_safe(p
->new_uuid
.bytes
, rh
+ rhs
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
4088 p
->new_uuid_is_set
= true;
4091 p
->roothash
= TAKE_PTR(rh
);
4092 p
->roothash_size
= rhs
;
4096 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "libcryptsetup is not supported, cannot setup verity hashes: %m");
4100 static int sign_verity_roothash(
4101 const uint8_t *roothash
,
4102 size_t roothash_size
,
4103 uint8_t **ret_signature
,
4104 size_t *ret_signature_size
) {
4107 _cleanup_(BIO_freep
) BIO
*rb
= NULL
;
4108 _cleanup_(PKCS7_freep
) PKCS7
*p7
= NULL
;
4109 _cleanup_free_
char *hex
= NULL
;
4110 _cleanup_free_
uint8_t *sig
= NULL
;
4114 assert(roothash_size
> 0);
4115 assert(ret_signature
);
4116 assert(ret_signature_size
);
4118 hex
= hexmem(roothash
, roothash_size
);
4122 rb
= BIO_new_mem_buf(hex
, -1);
4126 p7
= PKCS7_sign(arg_certificate
, arg_private_key
, NULL
, rb
, PKCS7_DETACHED
|PKCS7_NOATTR
|PKCS7_BINARY
);
4128 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to calculate PKCS7 signature: %s",
4129 ERR_error_string(ERR_get_error(), NULL
));
4131 sigsz
= i2d_PKCS7(p7
, &sig
);
4133 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to convert PKCS7 signature to DER: %s",
4134 ERR_error_string(ERR_get_error(), NULL
));
4136 *ret_signature
= TAKE_PTR(sig
);
4137 *ret_signature_size
= sigsz
;
4141 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "openssl is not supported, cannot setup verity signature: %m");
4145 static int partition_format_verity_sig(Context
*context
, Partition
*p
) {
4146 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
4147 _cleanup_free_
uint8_t *sig
= NULL
;
4148 _cleanup_free_
char *text
= NULL
, *hint
= NULL
;
4150 uint8_t fp
[X509_FINGERPRINT_SIZE
];
4151 size_t sigsz
= 0; /* avoid false maybe-uninitialized warning */
4154 assert(p
->verity
== VERITY_SIG
);
4159 if (PARTITION_EXISTS(p
))
4162 (void) partition_hint(p
, context
->node
, &hint
);
4164 assert_se(hp
= p
->siblings
[VERITY_HASH
]);
4165 assert(!hp
->dropped
);
4167 assert(arg_certificate
);
4169 assert_se((whole_fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
4171 r
= sign_verity_roothash(hp
->roothash
, hp
->roothash_size
, &sig
, &sigsz
);
4175 r
= x509_fingerprint(arg_certificate
, fp
);
4177 return log_error_errno(r
, "Unable to calculate X509 certificate fingerprint: %m");
4181 JSON_BUILD_PAIR("rootHash", JSON_BUILD_HEX(hp
->roothash
, hp
->roothash_size
)),
4183 "certificateFingerprint",
4184 JSON_BUILD_HEX(fp
, sizeof(fp
))
4186 JSON_BUILD_PAIR("signature", JSON_BUILD_BASE64(sig
, sigsz
))
4190 return log_error_errno(r
, "Failed to build verity signature JSON object: %m");
4192 r
= json_variant_format(v
, 0, &text
);
4194 return log_error_errno(r
, "Failed to format verity signature JSON object: %m");
4196 if (strlen(text
)+1 > p
->new_size
)
4197 return log_error_errno(SYNTHETIC_ERRNO(E2BIG
), "Verity signature too long for partition: %m");
4199 r
= strgrowpad0(&text
, p
->new_size
);
4201 return log_error_errno(r
, "Failed to pad string to %s", FORMAT_BYTES(p
->new_size
));
4203 if (lseek(whole_fd
, p
->offset
, SEEK_SET
) == (off_t
) -1)
4204 return log_error_errno(errno
, "Failed to seek to partition %s offset: %m", strna(hint
));
4206 r
= loop_write(whole_fd
, text
, p
->new_size
);
4208 return log_error_errno(r
, "Failed to write verity signature to partition %s: %m", strna(hint
));
4210 if (fsync(whole_fd
) < 0)
4211 return log_error_errno(errno
, "Failed to synchronize partition %s: %m", strna(hint
));
4216 static int context_copy_blocks(Context
*context
) {
4221 /* Copy in file systems on the block level */
4223 LIST_FOREACH(partitions
, p
, context
->partitions
) {
4224 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
4226 if (p
->copy_blocks_fd
< 0)
4232 if (PARTITION_EXISTS(p
)) /* Never copy over existing partitions */
4235 if (partition_type_defer(&p
->type
))
4238 assert(p
->new_size
!= UINT64_MAX
);
4239 assert(p
->copy_blocks_size
!= UINT64_MAX
);
4240 assert(p
->new_size
>= p
->copy_blocks_size
+ (p
->encrypt
!= ENCRYPT_OFF
? LUKS2_METADATA_KEEP_FREE
: 0));
4242 r
= partition_target_prepare(context
, p
, p
->new_size
,
4243 /*need_path=*/ p
->encrypt
!= ENCRYPT_OFF
|| p
->siblings
[VERITY_HASH
],
4248 if (p
->encrypt
!= ENCRYPT_OFF
&& t
->loop
) {
4249 r
= partition_encrypt(context
, p
, t
, /* offline = */ false);
4254 log_info("Copying in '%s' (%s) on block level into future partition %" PRIu64
".",
4255 p
->copy_blocks_path
, FORMAT_BYTES(p
->copy_blocks_size
), p
->partno
);
4257 if (p
->copy_blocks_offset
!= UINT64_MAX
&& lseek(p
->copy_blocks_fd
, p
->copy_blocks_offset
, SEEK_SET
) < 0)
4258 return log_error_errno(errno
, "Failed to seek to copy blocks offset in %s: %m", p
->copy_blocks_path
);
4260 r
= copy_bytes(p
->copy_blocks_fd
, partition_target_fd(t
), p
->copy_blocks_size
, COPY_REFLINK
);
4262 return log_error_errno(r
, "Failed to copy in data from '%s': %m", p
->copy_blocks_path
);
4264 log_info("Copying in of '%s' on block level completed.", p
->copy_blocks_path
);
4266 if (p
->encrypt
!= ENCRYPT_OFF
&& !t
->loop
) {
4267 r
= partition_encrypt(context
, p
, t
, /* offline = */ true);
4272 r
= partition_target_sync(context
, p
, t
);
4276 if (p
->siblings
[VERITY_HASH
] && !partition_type_defer(&p
->siblings
[VERITY_HASH
]->type
)) {
4277 r
= partition_format_verity_hash(context
, p
->siblings
[VERITY_HASH
],
4278 /* node = */ NULL
, partition_target_path(t
));
4283 if (p
->siblings
[VERITY_SIG
] && !partition_type_defer(&p
->siblings
[VERITY_SIG
]->type
)) {
4284 r
= partition_format_verity_sig(context
, p
->siblings
[VERITY_SIG
]);
4293 static int add_exclude_path(const char *path
, Hashmap
**denylist
, DenyType type
) {
4294 _cleanup_free_
struct stat
*st
= NULL
;
4300 st
= new(struct stat
, 1);
4304 r
= chase_and_stat(path
, arg_copy_source
, CHASE_PREFIX_ROOT
, NULL
, st
);
4308 return log_error_errno(r
, "Failed to stat source file '%s/%s': %m", strempty(arg_copy_source
), path
);
4310 r
= hashmap_ensure_put(denylist
, &inode_hash_ops
, st
, INT_TO_PTR(type
));
4321 static int make_copy_files_denylist(
4328 _cleanup_hashmap_free_ Hashmap
*denylist
= NULL
;
4337 /* Always exclude the top level APIVFS and temporary directories since the contents of these
4338 * directories are almost certainly not intended to end up in an image. */
4340 NULSTR_FOREACH(s
, APIVFS_TMP_DIRS_NULSTR
) {
4341 r
= add_exclude_path(s
, &denylist
, DENY_CONTENTS
);
4346 /* Add the user configured excludes. */
4348 STRV_FOREACH(e
, p
->exclude_files_source
) {
4349 r
= add_exclude_path(*e
, &denylist
, endswith(*e
, "/") ? DENY_CONTENTS
: DENY_INODE
);
4354 STRV_FOREACH(e
, p
->exclude_files_target
) {
4355 _cleanup_free_
char *path
= NULL
;
4357 const char *s
= path_startswith(*e
, target
);
4361 path
= path_join(source
, s
);
4365 r
= add_exclude_path(path
, &denylist
, endswith(*e
, "/") ? DENY_CONTENTS
: DENY_INODE
);
4370 /* If we're populating a root partition, we don't want any files to end up under the APIVFS mount
4371 * points. While we already exclude <source>/proc, users could still do something such as
4372 * "CopyFiles=/abc:/". Now, if /abc has a proc subdirectory with files in it, those will end up in
4373 * the top level proc directory in the root partition, which we want to avoid. To deal with these
4374 * cases, whenever we're populating a root partition and the target of CopyFiles= is the root
4375 * directory of the root partition, we exclude all directories under the source that are named after
4376 * APIVFS directories or named after mount points of other partitions that are also going to be part
4379 if (p
->type
.designator
== PARTITION_ROOT
&& empty_or_root(target
)) {
4380 LIST_FOREACH(partitions
, q
, context
->partitions
) {
4381 if (q
->type
.designator
== PARTITION_ROOT
)
4384 const char *sources
= gpt_partition_type_mountpoint_nulstr(q
->type
);
4388 NULSTR_FOREACH(s
, sources
) {
4389 _cleanup_free_
char *path
= NULL
;
4391 /* Exclude only the children of partition mount points so that the nested
4392 * partition mount point itself still ends up in the upper partition. */
4394 path
= path_join(source
, s
);
4398 r
= add_exclude_path(path
, &denylist
, DENY_CONTENTS
);
4404 NULSTR_FOREACH(s
, APIVFS_TMP_DIRS_NULSTR
) {
4405 _cleanup_free_
char *path
= NULL
;
4407 path
= path_join(source
, s
);
4411 r
= add_exclude_path(path
, &denylist
, DENY_CONTENTS
);
4417 *ret
= TAKE_PTR(denylist
);
4421 static int add_subvolume_path(const char *path
, Set
**subvolumes
) {
4422 _cleanup_free_
struct stat
*st
= NULL
;
4428 st
= new(struct stat
, 1);
4432 r
= chase_and_stat(path
, arg_copy_source
, CHASE_PREFIX_ROOT
, NULL
, st
);
4436 return log_error_errno(r
, "Failed to stat source file '%s/%s': %m", strempty(arg_copy_source
), path
);
4438 r
= set_ensure_consume(subvolumes
, &inode_hash_ops
, TAKE_PTR(st
));
4445 static int make_subvolumes_set(
4451 _cleanup_set_free_ Set
*subvolumes
= NULL
;
4459 STRV_FOREACH(subvolume
, p
->subvolumes
) {
4460 _cleanup_free_
char *path
= NULL
;
4462 const char *s
= path_startswith(*subvolume
, target
);
4466 path
= path_join(source
, s
);
4470 r
= add_subvolume_path(path
, &subvolumes
);
4475 *ret
= TAKE_PTR(subvolumes
);
4479 static int do_copy_files(Context
*context
, Partition
*p
, const char *root
) {
4485 /* copy_tree_at() automatically copies the permissions of source directories to target directories if
4486 * it created them. However, the root directory is created by us, so we have to manually take care
4487 * that it is initialized. We use the first source directory targeting "/" as the metadata source for
4488 * the root directory. */
4489 STRV_FOREACH_PAIR(source
, target
, p
->copy_files
) {
4490 _cleanup_close_
int rfd
= -EBADF
, sfd
= -EBADF
;
4492 if (!path_equal(*target
, "/"))
4495 rfd
= open(root
, O_DIRECTORY
|O_CLOEXEC
|O_NOFOLLOW
);
4499 sfd
= chase_and_open(*source
, arg_copy_source
, CHASE_PREFIX_ROOT
, O_PATH
|O_DIRECTORY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
4501 return log_error_errno(sfd
, "Failed to open source file '%s%s': %m", strempty(arg_copy_source
), *source
);
4503 (void) copy_xattr(sfd
, NULL
, rfd
, NULL
, COPY_ALL_XATTRS
);
4504 (void) copy_access(sfd
, rfd
);
4505 (void) copy_times(sfd
, rfd
, 0);
4510 STRV_FOREACH_PAIR(source
, target
, p
->copy_files
) {
4511 _cleanup_hashmap_free_ Hashmap
*denylist
= NULL
;
4512 _cleanup_set_free_ Set
*subvolumes_by_source_inode
= NULL
;
4513 _cleanup_close_
int sfd
= -EBADF
, pfd
= -EBADF
, tfd
= -EBADF
;
4515 r
= make_copy_files_denylist(context
, p
, *source
, *target
, &denylist
);
4519 r
= make_subvolumes_set(context
, p
, *source
, *target
, &subvolumes_by_source_inode
);
4523 sfd
= chase_and_open(*source
, arg_copy_source
, CHASE_PREFIX_ROOT
, O_CLOEXEC
|O_NOCTTY
, NULL
);
4524 if (sfd
== -ENOENT
) {
4525 log_notice_errno(sfd
, "Failed to open source file '%s%s', skipping: %m", strempty(arg_copy_source
), *source
);
4529 return log_error_errno(sfd
, "Failed to open source file '%s%s': %m", strempty(arg_copy_source
), *source
);
4531 r
= fd_verify_regular(sfd
);
4534 return log_error_errno(r
, "Failed to check type of source file '%s': %m", *source
);
4536 /* We are looking at a directory */
4537 tfd
= chase_and_open(*target
, root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
4539 _cleanup_free_
char *dn
= NULL
, *fn
= NULL
;
4542 return log_error_errno(tfd
, "Failed to open target directory '%s': %m", *target
);
4544 r
= path_extract_filename(*target
, &fn
);
4546 return log_error_errno(r
, "Failed to extract filename from '%s': %m", *target
);
4548 r
= path_extract_directory(*target
, &dn
);
4550 return log_error_errno(r
, "Failed to extract directory from '%s': %m", *target
);
4552 r
= mkdir_p_root(root
, dn
, UID_INVALID
, GID_INVALID
, 0755, p
->subvolumes
);
4554 return log_error_errno(r
, "Failed to create parent directory '%s': %m", dn
);
4556 pfd
= chase_and_open(dn
, root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
4558 return log_error_errno(pfd
, "Failed to open parent directory of target: %m");
4563 UID_INVALID
, GID_INVALID
,
4564 COPY_REFLINK
|COPY_HOLES
|COPY_MERGE
|COPY_REPLACE
|COPY_SIGINT
|COPY_HARDLINKS
|COPY_ALL_XATTRS
|COPY_GRACEFUL_WARN
|COPY_TRUNCATE
,
4565 denylist
, subvolumes_by_source_inode
);
4570 UID_INVALID
, GID_INVALID
,
4571 COPY_REFLINK
|COPY_HOLES
|COPY_MERGE
|COPY_REPLACE
|COPY_SIGINT
|COPY_HARDLINKS
|COPY_ALL_XATTRS
|COPY_GRACEFUL_WARN
|COPY_TRUNCATE
,
4572 denylist
, subvolumes_by_source_inode
);
4574 return log_error_errno(r
, "Failed to copy '%s%s' to '%s%s': %m",
4575 strempty(arg_copy_source
), *source
, strempty(root
), *target
);
4577 _cleanup_free_
char *dn
= NULL
, *fn
= NULL
;
4579 /* We are looking at a regular file */
4581 r
= path_extract_filename(*target
, &fn
);
4582 if (r
== -EADDRNOTAVAIL
|| r
== O_DIRECTORY
)
4583 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
),
4584 "Target path '%s' refers to a directory, but source path '%s' refers to regular file, can't copy.", *target
, *source
);
4586 return log_error_errno(r
, "Failed to extract filename from '%s': %m", *target
);
4588 r
= path_extract_directory(*target
, &dn
);
4590 return log_error_errno(r
, "Failed to extract directory from '%s': %m", *target
);
4592 r
= mkdir_p_root(root
, dn
, UID_INVALID
, GID_INVALID
, 0755, p
->subvolumes
);
4594 return log_error_errno(r
, "Failed to create parent directory: %m");
4596 pfd
= chase_and_open(dn
, root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, NULL
);
4598 return log_error_errno(pfd
, "Failed to open parent directory of target: %m");
4600 tfd
= openat(pfd
, fn
, O_CREAT
|O_EXCL
|O_WRONLY
|O_CLOEXEC
, 0700);
4602 return log_error_errno(errno
, "Failed to create target file '%s': %m", *target
);
4604 r
= copy_bytes(sfd
, tfd
, UINT64_MAX
, COPY_REFLINK
|COPY_HOLES
|COPY_SIGINT
|COPY_TRUNCATE
);
4606 return log_error_errno(r
, "Failed to copy '%s' to '%s%s': %m", *source
, strempty(arg_copy_source
), *target
);
4608 (void) copy_xattr(sfd
, NULL
, tfd
, NULL
, COPY_ALL_XATTRS
);
4609 (void) copy_access(sfd
, tfd
);
4610 (void) copy_times(sfd
, tfd
, 0);
4617 static int do_make_directories(Partition
*p
, const char *root
) {
4623 STRV_FOREACH(d
, p
->make_directories
) {
4624 r
= mkdir_p_root(root
, *d
, UID_INVALID
, GID_INVALID
, 0755, p
->subvolumes
);
4626 return log_error_errno(r
, "Failed to create directory '%s' in file system: %m", *d
);
4632 static bool partition_needs_populate(Partition
*p
) {
4634 return !strv_isempty(p
->copy_files
) || !strv_isempty(p
->make_directories
);
4637 static int partition_populate_directory(Context
*context
, Partition
*p
, char **ret
) {
4638 _cleanup_(rm_rf_physical_and_freep
) char *root
= NULL
;
4644 log_info("Populating %s filesystem.", p
->format
);
4646 r
= var_tmp_dir(&vt
);
4648 return log_error_errno(r
, "Could not determine temporary directory: %m");
4650 r
= tempfn_random_child(vt
, "repart", &root
);
4652 return log_error_errno(r
, "Failed to generate temporary directory: %m");
4654 r
= mkdir(root
, 0755);
4656 return log_error_errno(errno
, "Failed to create temporary directory: %m");
4658 r
= do_copy_files(context
, p
, root
);
4662 r
= do_make_directories(p
, root
);
4666 log_info("Successfully populated %s filesystem.", p
->format
);
4668 *ret
= TAKE_PTR(root
);
4672 static int partition_populate_filesystem(Context
*context
, Partition
*p
, const char *node
) {
4678 log_info("Populating %s filesystem.", p
->format
);
4680 /* We copy in a child process, since we have to mount the fs for that, and we don't want that fs to
4681 * appear in the host namespace. Hence we fork a child that has its own file system namespace and
4682 * detached mount propagation. */
4684 r
= safe_fork("(sd-copy)", FORK_DEATHSIG
|FORK_LOG
|FORK_WAIT
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, NULL
);
4688 static const char fs
[] = "/run/systemd/mount-root";
4689 /* This is a child process with its own mount namespace and propagation to host turned off */
4691 r
= mkdir_p(fs
, 0700);
4693 log_error_errno(r
, "Failed to create mount point: %m");
4694 _exit(EXIT_FAILURE
);
4697 if (mount_nofollow_verbose(LOG_ERR
, node
, fs
, p
->format
, MS_NOATIME
|MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
) < 0)
4698 _exit(EXIT_FAILURE
);
4700 if (do_copy_files(context
, p
, fs
) < 0)
4701 _exit(EXIT_FAILURE
);
4703 if (do_make_directories(p
, fs
) < 0)
4704 _exit(EXIT_FAILURE
);
4706 r
= syncfs_path(AT_FDCWD
, fs
);
4708 log_error_errno(r
, "Failed to synchronize written files: %m");
4709 _exit(EXIT_FAILURE
);
4712 _exit(EXIT_SUCCESS
);
4715 log_info("Successfully populated %s filesystem.", p
->format
);
4719 static int context_mkfs(Context
*context
) {
4724 /* Make a file system */
4726 LIST_FOREACH(partitions
, p
, context
->partitions
) {
4727 _cleanup_(rm_rf_physical_and_freep
) char *root
= NULL
;
4728 _cleanup_(partition_target_freep
) PartitionTarget
*t
= NULL
;
4729 _cleanup_strv_free_
char **extra_mkfs_options
= NULL
;
4734 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
4740 /* Minimized partitions will use the copy blocks logic so let's make sure to skip those here. */
4741 if (p
->copy_blocks_fd
>= 0)
4744 if (partition_type_defer(&p
->type
))
4747 assert(p
->offset
!= UINT64_MAX
);
4748 assert(p
->new_size
!= UINT64_MAX
);
4749 assert(p
->new_size
>= (p
->encrypt
!= ENCRYPT_OFF
? LUKS2_METADATA_KEEP_FREE
: 0));
4751 /* If we're doing encryption, we make sure we keep free space at the end which is required
4752 * for cryptsetup's offline encryption. */
4753 r
= partition_target_prepare(context
, p
,
4754 p
->new_size
- (p
->encrypt
!= ENCRYPT_OFF
? LUKS2_METADATA_KEEP_FREE
: 0),
4755 /*need_path=*/ true,
4760 if (p
->encrypt
!= ENCRYPT_OFF
&& t
->loop
) {
4761 r
= partition_target_grow(t
, p
->new_size
);
4765 r
= partition_encrypt(context
, p
, t
, /* offline = */ false);
4767 return log_error_errno(r
, "Failed to encrypt device: %m");
4770 log_info("Formatting future partition %" PRIu64
".", p
->partno
);
4772 /* If we're not writing to a loop device or if we're populating a read-only filesystem, we
4773 * have to populate using the filesystem's mkfs's --root (or equivalent) option. To do that,
4774 * we need to set up the final directory tree beforehand. */
4776 if (partition_needs_populate(p
) && (!t
->loop
|| fstype_is_ro(p
->format
))) {
4777 if (!mkfs_supports_root_option(p
->format
))
4778 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
),
4779 "Loop device access is required to populate %s filesystems.",
4782 r
= partition_populate_directory(context
, p
, &root
);
4787 r
= mkfs_options_from_env("REPART", p
->format
, &extra_mkfs_options
);
4789 return log_error_errno(r
,
4790 "Failed to determine mkfs command line options for '%s': %m",
4793 r
= make_filesystem(partition_target_path(t
), p
->format
, strempty(p
->new_label
), root
,
4794 p
->fs_uuid
, arg_discard
, /* quiet = */ false,
4795 context
->fs_sector_size
, extra_mkfs_options
);
4799 log_info("Successfully formatted future partition %" PRIu64
".", p
->partno
);
4801 /* If we're writing to a loop device, we can now mount the empty filesystem and populate it. */
4802 if (partition_needs_populate(p
) && !root
) {
4805 r
= partition_populate_filesystem(context
, p
, partition_target_path(t
));
4810 if (p
->encrypt
!= ENCRYPT_OFF
&& !t
->loop
) {
4811 r
= partition_target_grow(t
, p
->new_size
);
4815 r
= partition_encrypt(context
, p
, t
, /* offline = */ true);
4817 return log_error_errno(r
, "Failed to encrypt device: %m");
4820 /* Note that we always sync explicitly here, since mkfs.fat doesn't do that on its own, and
4821 * if we don't sync before detaching a block device the in-flight sectors possibly won't hit
4824 r
= partition_target_sync(context
, p
, t
);
4828 if (p
->siblings
[VERITY_HASH
] && !partition_type_defer(&p
->siblings
[VERITY_HASH
]->type
)) {
4829 r
= partition_format_verity_hash(context
, p
->siblings
[VERITY_HASH
],
4830 /* node = */ NULL
, partition_target_path(t
));
4835 if (p
->siblings
[VERITY_SIG
] && !partition_type_defer(&p
->siblings
[VERITY_SIG
]->type
)) {
4836 r
= partition_format_verity_sig(context
, p
->siblings
[VERITY_SIG
]);
4845 static int parse_x509_certificate(const char *certificate
, size_t certificate_size
, X509
**ret
) {
4847 _cleanup_(X509_freep
) X509
*cert
= NULL
;
4848 _cleanup_(BIO_freep
) BIO
*cb
= NULL
;
4850 assert(certificate
);
4851 assert(certificate_size
> 0);
4854 cb
= BIO_new_mem_buf(certificate
, certificate_size
);
4858 cert
= PEM_read_bio_X509(cb
, NULL
, NULL
, NULL
);
4860 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Failed to parse X.509 certificate: %s",
4861 ERR_error_string(ERR_get_error(), NULL
));
4864 *ret
= TAKE_PTR(cert
);
4868 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "openssl is not supported, cannot parse X509 certificate.");
4872 static int parse_private_key(const char *key
, size_t key_size
, EVP_PKEY
**ret
) {
4874 _cleanup_(BIO_freep
) BIO
*kb
= NULL
;
4875 _cleanup_(EVP_PKEY_freep
) EVP_PKEY
*pk
= NULL
;
4878 assert(key_size
> 0);
4881 kb
= BIO_new_mem_buf(key
, key_size
);
4885 pk
= PEM_read_bio_PrivateKey(kb
, NULL
, NULL
, NULL
);
4887 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse PEM private key: %s",
4888 ERR_error_string(ERR_get_error(), NULL
));
4891 *ret
= TAKE_PTR(pk
);
4895 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "openssl is not supported, cannot parse private key.");
4899 static int partition_acquire_uuid(Context
*context
, Partition
*p
, sd_id128_t
*ret
) {
4901 sd_id128_t type_uuid
;
4903 } _packed_ plaintext
= {};
4905 uint8_t md
[SHA256_DIGEST_SIZE
];
4916 /* Calculate a good UUID for the indicated partition. We want a certain degree of reproducibility,
4917 * hence we won't generate the UUIDs randomly. Instead we use a cryptographic hash (precisely:
4918 * HMAC-SHA256) to derive them from a single seed. The seed is generally the machine ID of the
4919 * installation we are processing, but if random behaviour is desired can be random, too. We use the
4920 * seed value as key for the HMAC (since the machine ID is something we generally don't want to leak)
4921 * and the partition type as plaintext. The partition type is suffixed with a counter (only for the
4922 * second and later partition of the same type) if we have more than one partition of the same
4923 * time. Or in other words:
4926 * SEED := /etc/machine-id
4928 * If first partition instance of type TYPE_UUID:
4929 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
4931 * For all later partition instances of type TYPE_UUID with INSTANCE being the LE64 encoded instance number:
4932 * PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID || INSTANCE)
4935 LIST_FOREACH(partitions
, q
, context
->partitions
) {
4939 if (!sd_id128_equal(p
->type
.uuid
, q
->type
.uuid
))
4945 plaintext
.type_uuid
= p
->type
.uuid
;
4946 plaintext
.counter
= htole64(k
);
4948 hmac_sha256(context
->seed
.bytes
, sizeof(context
->seed
.bytes
),
4950 k
== 0 ? sizeof(sd_id128_t
) : sizeof(plaintext
),
4953 /* Take the first half, mark it as v4 UUID */
4954 assert_cc(sizeof(result
.md
) == sizeof(result
.id
) * 2);
4955 result
.id
= id128_make_v4_uuid(result
.id
);
4957 /* Ensure this partition UUID is actually unique, and there's no remaining partition from an earlier run? */
4958 LIST_FOREACH(partitions
, q
, context
->partitions
) {
4962 if (sd_id128_in_set(result
.id
, q
->current_uuid
, q
->new_uuid
)) {
4963 log_warning("Partition UUID calculated from seed for partition %" PRIu64
" already used, reverting to randomized UUID.", p
->partno
);
4965 r
= sd_id128_randomize(&result
.id
);
4967 return log_error_errno(r
, "Failed to generate randomized UUID: %m");
4977 static int partition_acquire_label(Context
*context
, Partition
*p
, char **ret
) {
4978 _cleanup_free_
char *label
= NULL
;
4986 prefix
= gpt_partition_type_uuid_to_string(p
->type
.uuid
);
4991 const char *ll
= label
?: prefix
;
4994 LIST_FOREACH(partitions
, q
, context
->partitions
) {
4998 if (streq_ptr(ll
, q
->current_label
) ||
4999 streq_ptr(ll
, q
->new_label
)) {
5008 label
= mfree(label
);
5009 if (asprintf(&label
, "%s-%u", prefix
, ++k
) < 0)
5014 label
= strdup(prefix
);
5019 *ret
= TAKE_PTR(label
);
5023 static int context_acquire_partition_uuids_and_labels(Context
*context
) {
5028 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5031 /* Never touch foreign partitions */
5032 if (PARTITION_IS_FOREIGN(p
)) {
5033 p
->new_uuid
= p
->current_uuid
;
5035 if (p
->current_label
) {
5036 r
= free_and_strdup_warn(&p
->new_label
, strempty(p
->current_label
));
5044 if (!sd_id128_is_null(p
->current_uuid
))
5045 p
->new_uuid
= uuid
= p
->current_uuid
; /* Never change initialized UUIDs */
5046 else if (p
->new_uuid_is_set
)
5049 /* Not explicitly set by user! */
5050 r
= partition_acquire_uuid(context
, p
, &uuid
);
5054 /* The final verity hash/data UUIDs can only be determined after formatting the
5055 * verity hash partition. However, we still want to use the generated partition UUID
5056 * to derive other UUIDs to keep things unique and reproducible, so we always
5057 * generate a UUID if none is set, but we only use it as the actual partition UUID if
5058 * verity is not configured. */
5059 if (!IN_SET(p
->verity
, VERITY_DATA
, VERITY_HASH
)) {
5061 p
->new_uuid_is_set
= true;
5065 /* Calculate the UUID for the file system as HMAC-SHA256 of the string "file-system-uuid",
5066 * keyed off the partition UUID. */
5067 r
= derive_uuid(uuid
, "file-system-uuid", &p
->fs_uuid
);
5071 if (p
->encrypt
!= ENCRYPT_OFF
) {
5072 r
= derive_uuid(uuid
, "luks-uuid", &p
->luks_uuid
);
5077 /* Derive the verity salt and verity superblock UUID from the seed to keep them reproducible */
5078 if (p
->verity
== VERITY_HASH
) {
5079 derive_salt(context
->seed
, "verity-salt", p
->verity_salt
);
5081 r
= derive_uuid(context
->seed
, "verity-uuid", &p
->verity_uuid
);
5083 return log_error_errno(r
, "Failed to acquire verity uuid: %m");
5086 if (!isempty(p
->current_label
)) {
5087 /* never change initialized labels */
5088 r
= free_and_strdup_warn(&p
->new_label
, p
->current_label
);
5091 } else if (!p
->new_label
) {
5092 /* Not explicitly set by user! */
5094 r
= partition_acquire_label(context
, p
, &p
->new_label
);
5103 static int set_gpt_flags(struct fdisk_partition
*q
, uint64_t flags
) {
5104 _cleanup_free_
char *a
= NULL
;
5106 for (unsigned i
= 0; i
< sizeof(flags
) * 8; i
++) {
5107 uint64_t bit
= UINT64_C(1) << i
;
5108 char buf
[DECIMAL_STR_MAX(unsigned)+1];
5110 if (!FLAGS_SET(flags
, bit
))
5113 xsprintf(buf
, "%u", i
);
5114 if (!strextend_with_separator(&a
, ",", buf
))
5118 return fdisk_partition_set_attrs(q
, a
);
5121 static uint64_t partition_merge_flags(Partition
*p
) {
5128 if (p
->no_auto
>= 0) {
5129 if (gpt_partition_type_knows_no_auto(p
->type
))
5130 SET_FLAG(f
, SD_GPT_FLAG_NO_AUTO
, p
->no_auto
);
5132 char buffer
[SD_ID128_UUID_STRING_MAX
];
5133 log_warning("Configured NoAuto=%s for partition type '%s' that doesn't support it, ignoring.",
5135 gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, buffer
));
5139 if (p
->read_only
>= 0) {
5140 if (gpt_partition_type_knows_read_only(p
->type
))
5141 SET_FLAG(f
, SD_GPT_FLAG_READ_ONLY
, p
->read_only
);
5143 char buffer
[SD_ID128_UUID_STRING_MAX
];
5144 log_warning("Configured ReadOnly=%s for partition type '%s' that doesn't support it, ignoring.",
5145 yes_no(p
->read_only
),
5146 gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, buffer
));
5150 if (p
->growfs
>= 0) {
5151 if (gpt_partition_type_knows_growfs(p
->type
))
5152 SET_FLAG(f
, SD_GPT_FLAG_GROWFS
, p
->growfs
);
5154 char buffer
[SD_ID128_UUID_STRING_MAX
];
5155 log_warning("Configured GrowFileSystem=%s for partition type '%s' that doesn't support it, ignoring.",
5157 gpt_partition_type_uuid_to_string_harder(p
->type
.uuid
, buffer
));
5164 static int context_mangle_partitions(Context
*context
) {
5169 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5173 if (partition_type_defer(&p
->type
))
5176 assert(p
->new_size
!= UINT64_MAX
);
5177 assert(p
->offset
!= UINT64_MAX
);
5178 assert(p
->partno
!= UINT64_MAX
);
5180 if (PARTITION_EXISTS(p
)) {
5181 bool changed
= false;
5183 assert(p
->current_partition
);
5185 if (p
->new_size
!= p
->current_size
) {
5186 assert(p
->new_size
>= p
->current_size
);
5187 assert(p
->new_size
% context
->sector_size
== 0);
5189 r
= fdisk_partition_size_explicit(p
->current_partition
, true);
5191 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
5193 r
= fdisk_partition_set_size(p
->current_partition
, p
->new_size
/ context
->sector_size
);
5195 return log_error_errno(r
, "Failed to grow partition: %m");
5197 log_info("Growing existing partition %" PRIu64
".", p
->partno
);
5201 if (!sd_id128_equal(p
->new_uuid
, p
->current_uuid
)) {
5202 r
= fdisk_partition_set_uuid(p
->current_partition
, SD_ID128_TO_UUID_STRING(p
->new_uuid
));
5204 return log_error_errno(r
, "Failed to set partition UUID: %m");
5206 log_info("Initializing UUID of existing partition %" PRIu64
".", p
->partno
);
5210 if (!streq_ptr(p
->new_label
, p
->current_label
)) {
5211 r
= fdisk_partition_set_name(p
->current_partition
, strempty(p
->new_label
));
5213 return log_error_errno(r
, "Failed to set partition label: %m");
5215 log_info("Setting partition label of existing partition %" PRIu64
".", p
->partno
);
5220 assert(!PARTITION_IS_FOREIGN(p
)); /* never touch foreign partitions */
5222 r
= fdisk_set_partition(context
->fdisk_context
, p
->partno
, p
->current_partition
);
5224 return log_error_errno(r
, "Failed to update partition: %m");
5227 _cleanup_(fdisk_unref_partitionp
) struct fdisk_partition
*q
= NULL
;
5228 _cleanup_(fdisk_unref_parttypep
) struct fdisk_parttype
*t
= NULL
;
5230 assert(!p
->new_partition
);
5231 assert(p
->offset
% context
->sector_size
== 0);
5232 assert(p
->new_size
% context
->sector_size
== 0);
5233 assert(p
->new_label
);
5235 t
= fdisk_new_parttype();
5239 r
= fdisk_parttype_set_typestr(t
, SD_ID128_TO_UUID_STRING(p
->type
.uuid
));
5241 return log_error_errno(r
, "Failed to initialize partition type: %m");
5243 q
= fdisk_new_partition();
5247 r
= fdisk_partition_set_type(q
, t
);
5249 return log_error_errno(r
, "Failed to set partition type: %m");
5251 r
= fdisk_partition_size_explicit(q
, true);
5253 return log_error_errno(r
, "Failed to enable explicit sizing: %m");
5255 r
= fdisk_partition_set_start(q
, p
->offset
/ context
->sector_size
);
5257 return log_error_errno(r
, "Failed to position partition: %m");
5259 r
= fdisk_partition_set_size(q
, p
->new_size
/ context
->sector_size
);
5261 return log_error_errno(r
, "Failed to grow partition: %m");
5263 r
= fdisk_partition_set_partno(q
, p
->partno
);
5265 return log_error_errno(r
, "Failed to set partition number: %m");
5267 r
= fdisk_partition_set_uuid(q
, SD_ID128_TO_UUID_STRING(p
->new_uuid
));
5269 return log_error_errno(r
, "Failed to set partition UUID: %m");
5271 r
= fdisk_partition_set_name(q
, strempty(p
->new_label
));
5273 return log_error_errno(r
, "Failed to set partition label: %m");
5275 /* Merge the no auto + read only + growfs setting with the literal flags, and set them for the partition */
5276 r
= set_gpt_flags(q
, partition_merge_flags(p
));
5278 return log_error_errno(r
, "Failed to set GPT partition flags: %m");
5280 log_info("Adding new partition %" PRIu64
" to partition table.", p
->partno
);
5282 r
= fdisk_add_partition(context
->fdisk_context
, q
, NULL
);
5284 return log_error_errno(r
, "Failed to add partition: %m");
5286 assert(!p
->new_partition
);
5287 p
->new_partition
= TAKE_PTR(q
);
5294 static int split_name_printf(Partition
*p
, char **ret
) {
5297 const Specifier table
[] = {
5298 { 't', specifier_string
, GPT_PARTITION_TYPE_UUID_TO_STRING_HARDER(p
->type
.uuid
) },
5299 { 'T', specifier_id128
, &p
->type
.uuid
},
5300 { 'U', specifier_id128
, &p
->new_uuid
},
5301 { 'n', specifier_uint64
, &p
->partno
},
5303 COMMON_SYSTEM_SPECIFIERS
,
5307 return specifier_printf(p
->split_name_format
, NAME_MAX
, table
, arg_root
, p
, ret
);
5310 static int split_node(const char *node
, char **ret_base
, char **ret_ext
) {
5311 _cleanup_free_
char *base
= NULL
, *ext
= NULL
;
5319 r
= path_extract_filename(node
, &base
);
5320 if (r
== O_DIRECTORY
|| r
== -EADDRNOTAVAIL
)
5321 return log_error_errno(r
, "Device node %s cannot be a directory", node
);
5323 return log_error_errno(r
, "Failed to extract filename from %s: %m", node
);
5325 e
= endswith(base
, ".raw");
5334 *ret_base
= TAKE_PTR(base
);
5335 *ret_ext
= TAKE_PTR(ext
);
5340 static int split_name_resolve(Context
*context
) {
5341 _cleanup_free_
char *parent
= NULL
, *base
= NULL
, *ext
= NULL
;
5346 r
= path_extract_directory(context
->node
, &parent
);
5347 if (r
< 0 && r
!= -EDESTADDRREQ
)
5348 return log_error_errno(r
, "Failed to extract directory from %s: %m", context
->node
);
5350 r
= split_node(context
->node
, &base
, &ext
);
5354 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5355 _cleanup_free_
char *resolved
= NULL
;
5360 if (!p
->split_name_format
)
5363 r
= split_name_printf(p
, &resolved
);
5365 return log_error_errno(r
, "Failed to resolve specifiers in %s: %m", p
->split_name_format
);
5368 p
->split_path
= strjoin(parent
, "/", base
, ".", resolved
, ext
);
5370 p
->split_path
= strjoin(base
, ".", resolved
, ext
);
5375 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5379 LIST_FOREACH(partitions
, q
, context
->partitions
) {
5386 if (!streq(p
->split_path
, q
->split_path
))
5389 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
5390 "%s and %s have the same resolved split name \"%s\", refusing",
5391 p
->definition_path
, q
->definition_path
, p
->split_path
);
5398 static int context_split(Context
*context
) {
5406 /* We can't do resolution earlier because the partition UUIDs for verity partitions are only filled
5407 * in after they've been generated. */
5409 r
= split_name_resolve(context
);
5413 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5414 _cleanup_close_
int fdt
= -EBADF
;
5422 if (partition_type_defer(&p
->type
))
5425 fdt
= open(p
->split_path
, O_WRONLY
|O_NOCTTY
|O_CLOEXEC
|O_NOFOLLOW
|O_CREAT
|O_EXCL
, 0666);
5427 return log_error_errno(fdt
, "Failed to open split partition file %s: %m", p
->split_path
);
5430 assert_se((fd
= fdisk_get_devfd(context
->fdisk_context
)) >= 0);
5432 if (lseek(fd
, p
->offset
, SEEK_SET
) < 0)
5433 return log_error_errno(errno
, "Failed to seek to partition offset: %m");
5435 r
= copy_bytes(fd
, fdt
, p
->new_size
, COPY_REFLINK
|COPY_HOLES
|COPY_TRUNCATE
);
5437 return log_error_errno(r
, "Failed to copy to split partition %s: %m", p
->split_path
);
5443 static int context_write_partition_table(Context
*context
) {
5444 _cleanup_(fdisk_unref_tablep
) struct fdisk_table
*original_table
= NULL
;
5449 if (!context
->from_scratch
&& !context_changed(context
)) {
5450 log_info("No changes.");
5455 log_notice("Refusing to repartition, please re-run with --dry-run=no.");
5459 log_info("Applying changes.");
5461 if (context
->from_scratch
&& arg_empty
!= EMPTY_CREATE
) {
5462 /* Erase everything if we operate from scratch, except if the image was just created anyway, and thus is definitely empty. */
5463 r
= context_wipe_range(context
, 0, context
->total
);
5467 log_info("Wiped block device.");
5470 r
= context_discard_range(context
, 0, context
->total
);
5471 if (r
== -EOPNOTSUPP
)
5472 log_info("Storage does not support discard, not discarding entire block device data.");
5474 return log_error_errno(r
, "Failed to discard entire block device: %m");
5476 log_info("Discarded entire block device.");
5480 r
= fdisk_get_partitions(context
->fdisk_context
, &original_table
);
5482 return log_error_errno(r
, "Failed to acquire partition table: %m");
5484 /* Wipe fs signatures and discard sectors where the new partitions are going to be placed and in the
5485 * gaps between partitions, just to be sure. */
5486 r
= context_wipe_and_discard(context
);
5490 r
= context_copy_blocks(context
);
5494 r
= context_mkfs(context
);
5498 r
= context_mangle_partitions(context
);
5502 log_info("Writing new partition table.");
5504 r
= fdisk_write_disklabel(context
->fdisk_context
);
5506 return log_error_errno(r
, "Failed to write partition table: %m");
5508 capable
= blockdev_partscan_enabled(fdisk_get_devfd(context
->fdisk_context
));
5509 if (capable
== -ENOTBLK
)
5510 log_debug("Not telling kernel to reread partition table, since we are not operating on a block device.");
5511 else if (capable
< 0)
5512 return log_error_errno(capable
, "Failed to check if block device supports partition scanning: %m");
5513 else if (capable
> 0) {
5514 log_info("Telling kernel to reread partition table.");
5516 if (context
->from_scratch
)
5517 r
= fdisk_reread_partition_table(context
->fdisk_context
);
5519 r
= fdisk_reread_changes(context
->fdisk_context
, original_table
);
5521 return log_error_errno(r
, "Failed to reread partition table: %m");
5523 log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
5525 log_info("All done.");
5530 static int context_read_seed(Context
*context
, const char *root
) {
5535 if (!sd_id128_is_null(context
->seed
))
5538 if (!arg_randomize
) {
5539 r
= id128_get_machine(root
, &context
->seed
);
5543 if (!ERRNO_IS_MACHINE_ID_UNSET(r
))
5544 return log_error_errno(r
, "Failed to parse machine ID of image: %m");
5546 log_info("No machine ID set, using randomized partition UUIDs.");
5549 r
= sd_id128_randomize(&context
->seed
);
5551 return log_error_errno(r
, "Failed to generate randomized seed: %m");
5556 static int context_factory_reset(Context
*context
) {
5562 if (arg_factory_reset
<= 0)
5565 if (context
->from_scratch
) /* Nothing to reset if we start from scratch */
5569 log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
5573 log_info("Applying factory reset.");
5575 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5577 if (!p
->factory_reset
|| !PARTITION_EXISTS(p
))
5580 assert(p
->partno
!= UINT64_MAX
);
5582 log_info("Removing partition %" PRIu64
" for factory reset.", p
->partno
);
5584 r
= fdisk_delete_partition(context
->fdisk_context
, p
->partno
);
5586 return log_error_errno(r
, "Failed to remove partition %" PRIu64
": %m", p
->partno
);
5592 log_info("Factory reset requested, but no partitions to delete found.");
5596 r
= fdisk_write_disklabel(context
->fdisk_context
);
5598 return log_error_errno(r
, "Failed to write disk label: %m");
5600 log_info("Successfully deleted %zu partitions.", n
);
5604 static int context_can_factory_reset(Context
*context
) {
5607 LIST_FOREACH(partitions
, p
, context
->partitions
)
5608 if (p
->factory_reset
&& PARTITION_EXISTS(p
))
5614 static int resolve_copy_blocks_auto_candidate(
5615 dev_t partition_devno
,
5616 GptPartitionType partition_type
,
5617 dev_t restrict_devno
,
5618 sd_id128_t
*ret_uuid
) {
5620 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
5621 _cleanup_close_
int fd
= -EBADF
;
5622 _cleanup_free_
char *p
= NULL
;
5623 const char *pttype
, *t
;
5624 sd_id128_t pt_parsed
, u
;
5630 /* Checks if the specified partition has the specified GPT type UUID, and is located on the specified
5631 * 'restrict_devno' device. The type check is particularly relevant if we have Verity volume which is
5632 * backed by two separate partitions: the data and the hash partitions, and we need to find the right
5633 * one of the two. */
5635 r
= block_get_whole_disk(partition_devno
, &whole_devno
);
5637 return log_error_errno(
5639 "Unable to determine containing block device of partition %u:%u: %m",
5640 major(partition_devno
), minor(partition_devno
));
5642 if (restrict_devno
!= (dev_t
) -1 &&
5643 restrict_devno
!= whole_devno
)
5644 return log_error_errno(
5645 SYNTHETIC_ERRNO(EPERM
),
5646 "Partition %u:%u is located outside of block device %u:%u, refusing.",
5647 major(partition_devno
), minor(partition_devno
),
5648 major(restrict_devno
), minor(restrict_devno
));
5650 fd
= r
= device_open_from_devnum(S_IFBLK
, whole_devno
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &p
);
5652 return log_error_errno(r
, "Failed to open block device " DEVNUM_FORMAT_STR
": %m",
5653 DEVNUM_FORMAT_VAL(whole_devno
));
5655 b
= blkid_new_probe();
5660 r
= blkid_probe_set_device(b
, fd
, 0, 0);
5662 return log_error_errno(errno_or_else(ENOMEM
), "Failed to open block device '%s': %m", p
);
5664 (void) blkid_probe_enable_partitions(b
, 1);
5665 (void) blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
5668 r
= blkid_do_safeprobe(b
);
5669 if (r
== _BLKID_SAFEPROBE_ERROR
)
5670 return log_error_errno(errno_or_else(EIO
), "Unable to probe for partition table of '%s': %m", p
);
5671 if (IN_SET(r
, _BLKID_SAFEPROBE_AMBIGUOUS
, _BLKID_SAFEPROBE_NOT_FOUND
)) {
5672 log_debug("Didn't find partition table on block device '%s'.", p
);
5676 assert(r
== _BLKID_SAFEPROBE_FOUND
);
5678 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
5679 if (!streq_ptr(pttype
, "gpt")) {
5680 log_debug("Didn't find a GPT partition table on '%s'.", p
);
5685 pl
= blkid_probe_get_partitions(b
);
5687 return log_error_errno(errno_or_else(EIO
), "Unable read partition table of '%s': %m", p
);
5689 pp
= blkid_partlist_devno_to_partition(pl
, partition_devno
);
5691 log_debug("Partition %u:%u has no matching partition table entry on '%s'.",
5692 major(partition_devno
), minor(partition_devno
), p
);
5696 t
= blkid_partition_get_type_string(pp
);
5698 log_debug("Partition %u:%u has no type on '%s'.",
5699 major(partition_devno
), minor(partition_devno
), p
);
5703 r
= sd_id128_from_string(t
, &pt_parsed
);
5705 log_debug_errno(r
, "Failed to parse partition type \"%s\": %m", t
);
5709 if (!sd_id128_equal(pt_parsed
, partition_type
.uuid
)) {
5710 log_debug("Partition %u:%u has non-matching partition type " SD_ID128_FORMAT_STR
" (needed: " SD_ID128_FORMAT_STR
"), ignoring.",
5711 major(partition_devno
), minor(partition_devno
),
5712 SD_ID128_FORMAT_VAL(pt_parsed
), SD_ID128_FORMAT_VAL(partition_type
.uuid
));
5716 r
= blkid_partition_get_uuid_id128(pp
, &u
);
5718 log_debug_errno(r
, "Partition " DEVNUM_FORMAT_STR
" has no UUID.", DEVNUM_FORMAT_VAL(partition_devno
));
5722 log_debug_errno(r
, "Failed to read partition UUID of " DEVNUM_FORMAT_STR
": %m", DEVNUM_FORMAT_VAL(partition_devno
));
5726 log_debug("Automatically found partition " DEVNUM_FORMAT_STR
" of right type " SD_ID128_FORMAT_STR
".",
5727 DEVNUM_FORMAT_VAL(partition_devno
),
5728 SD_ID128_FORMAT_VAL(pt_parsed
));
5736 static int find_backing_devno(
5741 _cleanup_free_
char *resolved
= NULL
;
5746 r
= chase(path
, root
, CHASE_PREFIX_ROOT
, &resolved
, NULL
);
5750 r
= path_is_mount_point(resolved
, NULL
, 0);
5753 if (r
== 0) /* Not a mount point, then it's not a partition of its own, let's not automatically use it. */
5756 r
= get_block_device(resolved
, ret
);
5759 if (r
== 0) /* Not backed by physical file system, we can't use this */
5765 static int resolve_copy_blocks_auto(
5766 GptPartitionType type
,
5768 dev_t restrict_devno
,
5770 sd_id128_t
*ret_uuid
) {
5772 const char *try1
= NULL
, *try2
= NULL
;
5773 char p
[SYS_BLOCK_PATH_MAX("/slaves")];
5774 _cleanup_closedir_
DIR *d
= NULL
;
5775 sd_id128_t found_uuid
= SD_ID128_NULL
;
5776 dev_t devno
, found
= 0;
5779 /* Enforce some security restrictions: CopyBlocks=auto should not be an avenue to get outside of the
5780 * --root=/--image= confinement. Specifically, refuse CopyBlocks= in combination with --root= at all,
5781 * and restrict block device references in the --image= case to loopback block device we set up.
5783 * restrict_devno contain the dev_t of the loop back device we operate on in case of --image=, and
5784 * thus declares which device (and its partition subdevices) we shall limit access to. If
5785 * restrict_devno is zero no device probing access shall be allowed at all (used for --root=) and if
5786 * it is (dev_t) -1 then free access shall be allowed (if neither switch is used). */
5788 if (restrict_devno
== 0)
5789 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
5790 "Automatic discovery of backing block devices not permitted in --root= mode, refusing.");
5792 /* Handles CopyBlocks=auto, and finds the right source partition to copy from. We look for matching
5793 * partitions in the host, using the appropriate directory as key and ensuring that the partition
5796 if (type
.designator
== PARTITION_ROOT
)
5798 else if (type
.designator
== PARTITION_USR
)
5800 else if (type
.designator
== PARTITION_ROOT_VERITY
)
5802 else if (type
.designator
== PARTITION_USR_VERITY
)
5804 else if (type
.designator
== PARTITION_ESP
) {
5807 } else if (type
.designator
== PARTITION_XBOOTLDR
)
5810 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
5811 "Partition type " SD_ID128_FORMAT_STR
" not supported from automatic source block device discovery.",
5812 SD_ID128_FORMAT_VAL(type
.uuid
));
5814 r
= find_backing_devno(try1
, root
, &devno
);
5815 if (r
== -ENOENT
&& try2
)
5816 r
= find_backing_devno(try2
, root
, &devno
);
5818 return log_error_errno(r
, "Failed to resolve automatic CopyBlocks= path for partition type " SD_ID128_FORMAT_STR
", sorry: %m",
5819 SD_ID128_FORMAT_VAL(type
.uuid
));
5821 xsprintf_sys_block_path(p
, "/slaves", devno
);
5827 _cleanup_free_
char *q
= NULL
, *t
= NULL
;
5832 de
= readdir_no_dot(d
);
5835 return log_error_errno(errno
, "Failed to read directory '%s': %m", p
);
5840 if (!IN_SET(de
->d_type
, DT_LNK
, DT_UNKNOWN
))
5843 q
= path_join(p
, de
->d_name
, "/dev");
5847 r
= read_one_line_file(q
, &t
);
5849 return log_error_errno(r
, "Failed to read %s: %m", q
);
5851 r
= parse_devnum(t
, &sl
);
5853 log_debug_errno(r
, "Failed to parse %s, ignoring: %m", q
);
5856 if (major(sl
) == 0) {
5857 log_debug("Device backing %s is special, ignoring.", q
);
5861 r
= resolve_copy_blocks_auto_candidate(sl
, type
, restrict_devno
, &u
);
5865 /* We found a matching one! */
5867 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
5868 "Multiple matching partitions found, refusing.");
5874 } else if (errno
!= ENOENT
)
5875 return log_error_errno(errno
, "Failed open %s: %m", p
);
5877 r
= resolve_copy_blocks_auto_candidate(devno
, type
, restrict_devno
, &found_uuid
);
5885 return log_error_errno(SYNTHETIC_ERRNO(ENXIO
),
5886 "Unable to automatically discover suitable partition to copy blocks from.");
5892 *ret_uuid
= found_uuid
;
5897 static int context_open_copy_block_paths(
5899 dev_t restrict_devno
) {
5905 LIST_FOREACH(partitions
, p
, context
->partitions
) {
5906 _cleanup_close_
int source_fd
= -EBADF
;
5907 _cleanup_free_
char *opened
= NULL
;
5908 sd_id128_t uuid
= SD_ID128_NULL
;
5912 if (p
->copy_blocks_fd
>= 0)
5915 assert(p
->copy_blocks_size
== UINT64_MAX
);
5917 if (PARTITION_EXISTS(p
)) /* Never copy over partitions that already exist! */
5920 if (p
->copy_blocks_path
) {
5922 source_fd
= chase_and_open(p
->copy_blocks_path
, p
->copy_blocks_root
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &opened
);
5924 return log_error_errno(source_fd
, "Failed to open '%s': %m", p
->copy_blocks_path
);
5926 if (fstat(source_fd
, &st
) < 0)
5927 return log_error_errno(errno
, "Failed to stat block copy file '%s': %m", opened
);
5929 if (!S_ISREG(st
.st_mode
) && restrict_devno
!= (dev_t
) -1)
5930 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
5931 "Copying from block device node is not permitted in --image=/--root= mode, refusing.");
5933 } else if (p
->copy_blocks_auto
) {
5934 dev_t devno
= 0; /* Fake initialization to appease gcc. */
5936 r
= resolve_copy_blocks_auto(p
->type
, p
->copy_blocks_root
, restrict_devno
, &devno
, &uuid
);
5941 source_fd
= r
= device_open_from_devnum(S_IFBLK
, devno
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &opened
);
5943 return log_error_errno(r
, "Failed to open automatically determined source block copy device " DEVNUM_FORMAT_STR
": %m",
5944 DEVNUM_FORMAT_VAL(devno
));
5946 if (fstat(source_fd
, &st
) < 0)
5947 return log_error_errno(errno
, "Failed to stat block copy file '%s': %m", opened
);
5951 if (S_ISDIR(st
.st_mode
)) {
5952 _cleanup_free_
char *bdev
= NULL
;
5955 /* If the file is a directory, automatically find the backing block device */
5957 if (major(st
.st_dev
) != 0)
5960 /* Special support for btrfs */
5961 r
= btrfs_get_block_device_fd(source_fd
, &devt
);
5963 return btrfs_log_dev_root(LOG_ERR
, r
, opened
);
5965 return log_error_errno(r
, "Unable to determine backing block device of '%s': %m", opened
);
5968 safe_close(source_fd
);
5970 source_fd
= r
= device_open_from_devnum(S_IFBLK
, devt
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, &bdev
);
5972 return log_error_errno(r
, "Failed to open block device backing '%s': %m", opened
);
5974 if (fstat(source_fd
, &st
) < 0)
5975 return log_error_errno(errno
, "Failed to stat block device '%s': %m", bdev
);
5978 if (S_ISREG(st
.st_mode
))
5980 else if (S_ISBLK(st
.st_mode
)) {
5981 if (ioctl(source_fd
, BLKGETSIZE64
, &size
) != 0)
5982 return log_error_errno(errno
, "Failed to determine size of block device to copy from: %m");
5984 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
);
5987 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "File to copy bytes from '%s' has zero size, refusing.", opened
);
5988 if (size
% 512 != 0)
5989 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "File to copy bytes from '%s' has size that is not multiple of 512, refusing.", opened
);
5991 p
->copy_blocks_fd
= TAKE_FD(source_fd
);
5992 p
->copy_blocks_size
= size
;
5994 free_and_replace(p
->copy_blocks_path
, opened
);
5996 /* When copying from an existing partition copy that partitions UUID if none is configured explicitly */
5997 if (!p
->new_uuid_is_set
&& !sd_id128_is_null(uuid
)) {
5999 p
->new_uuid_is_set
= true;
6006 static int fd_apparent_size(int fd
, uint64_t *ret
) {
6013 initial
= lseek(fd
, 0, SEEK_CUR
);
6015 return log_error_errno(errno
, "Failed to get file offset: %m");
6017 for (off_t off
= 0;;) {
6020 r
= lseek(fd
, off
, SEEK_DATA
);
6021 if (r
< 0 && errno
== ENXIO
)
6022 /* If errno == ENXIO, that means we've reached the final hole of the file and
6023 * that hole isn't followed by more data. */
6026 return log_error_errno(errno
, "Failed to seek data in file from offset %"PRIi64
": %m", off
);
6028 off
= r
; /* Set the offset to the start of the data segment. */
6030 /* After copying a potential hole, find the end of the data segment by looking for
6031 * the next hole. If we get ENXIO, we're at EOF. */
6032 r
= lseek(fd
, off
, SEEK_HOLE
);
6036 return log_error_errno(errno
, "Failed to seek hole in file from offset %"PRIi64
": %m", off
);
6043 if (lseek(fd
, initial
, SEEK_SET
) < 0)
6044 return log_error_errno(errno
, "Failed to reset file offset: %m");
6051 static int context_minimize(Context
*context
) {
6052 const char *vt
= NULL
;
6057 LIST_FOREACH(partitions
, p
, context
->partitions
) {
6058 _cleanup_(rm_rf_physical_and_freep
) char *root
= NULL
;
6059 _cleanup_(unlink_and_freep
) char *temp
= NULL
;
6060 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
6061 _cleanup_strv_free_
char **extra_mkfs_options
= NULL
;
6062 _cleanup_close_
int fd
= -EBADF
;
6063 _cleanup_free_
char *hint
= NULL
;
6071 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
6077 if (p
->copy_blocks_fd
>= 0)
6080 if (p
->minimize
== MINIMIZE_OFF
)
6083 if (!partition_needs_populate(p
))
6086 assert(!p
->copy_blocks_path
);
6088 (void) partition_hint(p
, context
->node
, &hint
);
6090 log_info("Pre-populating %s filesystem of partition %s twice to calculate minimal partition size",
6091 p
->format
, strna(hint
));
6094 r
= var_tmp_dir(&vt
);
6096 return log_error_errno(r
, "Could not determine temporary directory: %m");
6099 r
= tempfn_random_child(vt
, "repart", &temp
);
6101 return log_error_errno(r
, "Failed to generate temporary file path: %m");
6103 if (fstype_is_ro(p
->format
))
6104 fs_uuid
= p
->fs_uuid
;
6106 fd
= open(temp
, O_CREAT
|O_EXCL
|O_CLOEXEC
|O_RDWR
|O_NOCTTY
, 0600);
6108 return log_error_errno(errno
, "Failed to open temporary file %s: %m", temp
);
6110 /* This may seem huge but it will be created sparse so it doesn't take up any space
6111 * on disk until written to. */
6112 if (ftruncate(fd
, 1024ULL * 1024ULL * 1024ULL * 1024ULL) < 0)
6113 return log_error_errno(errno
, "Failed to truncate temporary file to %s: %m",
6114 FORMAT_BYTES(1024ULL * 1024ULL * 1024ULL * 1024ULL));
6116 if (arg_offline
<= 0) {
6117 r
= loop_device_make(fd
, O_RDWR
, 0, UINT64_MAX
, context
->sector_size
, 0, LOCK_EX
, &d
);
6118 if (r
< 0 && (arg_offline
== 0 || (r
!= -ENOENT
&& !ERRNO_IS_PRIVILEGE(r
)) || !strv_isempty(p
->subvolumes
)))
6119 return log_error_errno(r
, "Failed to make loopback device of %s: %m", temp
);
6122 /* We're going to populate this filesystem twice so use a random UUID the first time
6123 * to avoid UUID conflicts. */
6124 r
= sd_id128_randomize(&fs_uuid
);
6129 if (!d
|| fstype_is_ro(p
->format
)) {
6130 if (!mkfs_supports_root_option(p
->format
))
6131 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
),
6132 "Loop device access is required to populate %s filesystems",
6135 r
= partition_populate_directory(context
, p
, &root
);
6140 r
= mkfs_options_from_env("REPART", p
->format
, &extra_mkfs_options
);
6142 return log_error_errno(r
,
6143 "Failed to determine mkfs command line options for '%s': %m",
6146 r
= make_filesystem(d
? d
->node
: temp
,
6148 strempty(p
->new_label
),
6151 arg_discard
, /* quiet = */ false,
6152 context
->fs_sector_size
,
6153 extra_mkfs_options
);
6157 /* Read-only filesystems are minimal from the first try because they create and size the
6158 * loopback file for us. */
6159 if (fstype_is_ro(p
->format
)) {
6162 fd
= open(temp
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
);
6164 return log_error_errno(errno
, "Failed to open temporary file %s: %m", temp
);
6166 if (fstat(fd
, &st
) < 0)
6167 return log_error_errno(errno
, "Failed to stat temporary file: %m");
6169 log_info("Minimal partition size of %s filesystem of partition %s is %s",
6170 p
->format
, strna(hint
), FORMAT_BYTES(st
.st_size
));
6172 p
->copy_blocks_path
= TAKE_PTR(temp
);
6173 p
->copy_blocks_path_is_our_file
= true;
6174 p
->copy_blocks_fd
= TAKE_FD(fd
);
6175 p
->copy_blocks_size
= st
.st_size
;
6182 r
= partition_populate_filesystem(context
, p
, d
->node
);
6187 /* Other filesystems need to be provided with a pre-sized loopback file and will adapt to
6188 * fully occupy it. Because we gave the filesystem a 1T sparse file, we need to shrink the
6189 * filesystem down to a reasonable size again to fit it in the disk image. While there are
6190 * some filesystems that support shrinking, it doesn't always work properly (e.g. shrinking
6191 * btrfs gives us a 2.0G filesystem regardless of what we put in it). Instead, let's populate
6192 * the filesystem again, but this time, instead of providing the filesystem with a 1T sparse
6193 * loopback file, let's size the loopback file based on the actual data used by the
6194 * filesystem in the sparse file after the first attempt. This should be a good guess of the
6195 * minimal amount of space needed in the filesystem to fit all the required data.
6197 r
= fd_apparent_size(fd
, &fsz
);
6201 /* Massage the size a bit because just going by actual data used in the sparse file isn't
6203 uint64_t heuristic
= streq(p
->format
, "xfs") ? fsz
: fsz
/ 2;
6204 fsz
= round_up_size(fsz
+ heuristic
, context
->grain_size
);
6205 if (minimal_size_by_fs_name(p
->format
) != UINT64_MAX
)
6206 fsz
= MAX(minimal_size_by_fs_name(p
->format
), fsz
);
6208 log_info("Minimal partition size of %s filesystem of partition %s is %s",
6209 p
->format
, strna(hint
), FORMAT_BYTES(fsz
));
6211 d
= loop_device_unref(d
);
6213 /* Erase the previous filesystem first. */
6214 if (ftruncate(fd
, 0))
6215 return log_error_errno(errno
, "Failed to erase temporary file: %m");
6217 if (ftruncate(fd
, fsz
))
6218 return log_error_errno(errno
, "Failed to truncate temporary file to %s: %m", FORMAT_BYTES(fsz
));
6220 if (arg_offline
<= 0) {
6221 r
= loop_device_make(fd
, O_RDWR
, 0, UINT64_MAX
, context
->sector_size
, 0, LOCK_EX
, &d
);
6222 if (r
< 0 && (arg_offline
== 0 || (r
!= -ENOENT
&& !ERRNO_IS_PRIVILEGE(r
)) || !strv_isempty(p
->subvolumes
)))
6223 return log_error_errno(r
, "Failed to make loopback device of %s: %m", temp
);
6226 r
= make_filesystem(d
? d
->node
: temp
,
6228 strempty(p
->new_label
),
6232 /* quiet = */ false,
6233 context
->fs_sector_size
,
6234 extra_mkfs_options
);
6241 r
= partition_populate_filesystem(context
, p
, d
->node
);
6246 if (fstat(fd
, &st
) < 0)
6247 return log_error_errno(errno
, "Failed to stat temporary file: %m");
6249 p
->copy_blocks_path
= TAKE_PTR(temp
);
6250 p
->copy_blocks_path_is_our_file
= true;
6251 p
->copy_blocks_fd
= TAKE_FD(fd
);
6252 p
->copy_blocks_size
= st
.st_size
;
6255 /* Now that we've done the data partitions, do the verity hash partitions. We do these in a separate
6256 * step because they might depend on data generated in the previous step. */
6258 LIST_FOREACH(partitions
, p
, context
->partitions
) {
6259 _cleanup_(unlink_and_freep
) char *temp
= NULL
;
6260 _cleanup_free_
char *hint
= NULL
;
6261 _cleanup_close_
int fd
= -EBADF
;
6268 if (PARTITION_EXISTS(p
)) /* Never format existing partitions */
6271 if (p
->minimize
== MINIMIZE_OFF
)
6274 if (p
->verity
!= VERITY_HASH
)
6277 assert_se(dp
= p
->siblings
[VERITY_DATA
]);
6278 assert(!dp
->dropped
);
6279 assert(dp
->copy_blocks_path
);
6281 (void) partition_hint(p
, context
->node
, &hint
);
6283 log_info("Pre-populating verity hash data of partition %s to calculate minimal partition size",
6287 r
= var_tmp_dir(&vt
);
6289 return log_error_errno(r
, "Could not determine temporary directory: %m");
6292 r
= tempfn_random_child(vt
, "repart", &temp
);
6294 return log_error_errno(r
, "Failed to generate temporary file path: %m");
6298 return log_error_errno(r
, "Failed to create temporary file: %m");
6300 r
= partition_format_verity_hash(context
, p
, temp
, dp
->copy_blocks_path
);
6304 fd
= open(temp
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
);
6306 return log_error_errno(errno
, "Failed to open temporary file %s: %m", temp
);
6308 if (fstat(fd
, &st
) < 0)
6309 return log_error_errno(r
, "Failed to stat temporary file: %m");
6311 log_info("Minimal partition size of verity hash partition %s is %s",
6312 strna(hint
), FORMAT_BYTES(st
.st_size
));
6314 p
->copy_blocks_path
= TAKE_PTR(temp
);
6315 p
->copy_blocks_path_is_our_file
= true;
6316 p
->copy_blocks_fd
= TAKE_FD(fd
);
6317 p
->copy_blocks_size
= st
.st_size
;
6323 static int parse_partition_types(const char *p
, GptPartitionType
**partitions
, size_t *n_partitions
) {
6327 assert(n_partitions
);
6330 _cleanup_free_
char *name
= NULL
;
6331 GptPartitionType type
;
6333 r
= extract_first_word(&p
, &name
, ",", EXTRACT_CUNESCAPE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
6337 return log_error_errno(r
, "Failed to extract partition type identifier or GUID: %s", p
);
6339 r
= gpt_partition_type_from_string(name
, &type
);
6341 return log_error_errno(r
, "'%s' is not a valid partition type identifier or GUID", name
);
6343 if (!GREEDY_REALLOC(*partitions
, *n_partitions
+ 1))
6346 (*partitions
)[(*n_partitions
)++] = type
;
6352 static int help(void) {
6353 _cleanup_free_
char *link
= NULL
;
6356 r
= terminal_urlify_man("systemd-repart", "8", &link
);
6360 printf("%s [OPTIONS...] [DEVICE]\n"
6361 "\n%sGrow and add partitions to partition table.%s\n\n"
6362 " -h --help Show this help\n"
6363 " --version Show package version\n"
6364 " --no-pager Do not pipe output into a pager\n"
6365 " --no-legend Do not show the headers and footers\n"
6366 " --dry-run=BOOL Whether to run dry-run operation\n"
6367 " --empty=MODE One of refuse, allow, require, force, create; controls\n"
6368 " how to handle empty disks lacking partition tables\n"
6369 " --discard=BOOL Whether to discard backing blocks for new partitions\n"
6370 " --pretty=BOOL Whether to show pretty summary before doing changes\n"
6371 " --factory-reset=BOOL Whether to remove data partitions before recreating\n"
6373 " --can-factory-reset Test whether factory reset is defined\n"
6374 " --root=PATH Operate relative to root path\n"
6375 " --image=PATH Operate relative to image file\n"
6376 " --image-policy=POLICY\n"
6377 " Specify disk image dissection policy\n"
6378 " --definitions=DIR Find partition definitions in specified directory\n"
6379 " --key-file=PATH Key to use when encrypting partitions\n"
6380 " --private-key=PATH Private key to use when generating verity roothash\n"
6382 " --certificate=PATH PEM certificate to use when generating verity\n"
6383 " roothash signatures\n"
6384 " --tpm2-device=PATH Path to TPM2 device node to use\n"
6385 " --tpm2-pcrs=PCR1+PCR2+PCR3+…\n"
6386 " TPM2 PCR indexes to use for TPM2 enrollment\n"
6387 " --tpm2-public-key=PATH\n"
6388 " Enroll signed TPM2 PCR policy against PEM public key\n"
6389 " --tpm2-public-key-pcrs=PCR1+PCR2+PCR3+…\n"
6390 " Enroll signed TPM2 PCR policy for specified TPM2 PCRs\n"
6391 " --seed=UUID 128-bit seed UUID to derive all UUIDs from\n"
6392 " --size=BYTES Grow loopback file to specified size\n"
6393 " --json=pretty|short|off\n"
6394 " Generate JSON output\n"
6395 " --split=BOOL Whether to generate split artifacts\n"
6396 " --include-partitions=PARTITION1,PARTITION2,PARTITION3,…\n"
6397 " Ignore partitions not of the specified types\n"
6398 " --exclude-partitions=PARTITION1,PARTITION2,PARTITION3,…\n"
6399 " Ignore partitions of the specified types\n"
6400 " --defer-partitions=PARTITION1,PARTITION2,PARTITION3,…\n"
6401 " Take partitions of the specified types into account\n"
6402 " but don't populate them yet\n"
6403 " --sector-size=SIZE Set the logical sector size for the image\n"
6404 " --architecture=ARCH Set the generic architecture for the image\n"
6405 " --offline=BOOL Whether to build the image offline\n"
6406 " -s --copy-source=PATH Specify the primary source tree to copy files from\n"
6407 " --copy-from=IMAGE Copy partitions from the given image(s)\n"
6408 " -S --make-ddi=sysext Make a system extension DDI\n"
6409 " -C --make-ddi=confext Make a configuration extension DDI\n"
6410 " -P --make-ddi=portable Make a portable service DDI\n"
6411 "\nSee the %s for details.\n",
6412 program_invocation_short_name
,
6420 static int parse_argv(int argc
, char *argv
[]) {
6423 ARG_VERSION
= 0x100,
6430 ARG_CAN_FACTORY_RESET
,
6444 ARG_TPM2_PUBLIC_KEY
,
6445 ARG_TPM2_PUBLIC_KEY_PCRS
,
6447 ARG_INCLUDE_PARTITIONS
,
6448 ARG_EXCLUDE_PARTITIONS
,
6449 ARG_DEFER_PARTITIONS
,
6451 ARG_SKIP_PARTITIONS
,
6458 static const struct option options
[] = {
6459 { "help", no_argument
, NULL
, 'h' },
6460 { "version", no_argument
, NULL
, ARG_VERSION
},
6461 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
6462 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
6463 { "dry-run", required_argument
, NULL
, ARG_DRY_RUN
},
6464 { "empty", required_argument
, NULL
, ARG_EMPTY
},
6465 { "discard", required_argument
, NULL
, ARG_DISCARD
},
6466 { "factory-reset", required_argument
, NULL
, ARG_FACTORY_RESET
},
6467 { "can-factory-reset", no_argument
, NULL
, ARG_CAN_FACTORY_RESET
},
6468 { "root", required_argument
, NULL
, ARG_ROOT
},
6469 { "image", required_argument
, NULL
, ARG_IMAGE
},
6470 { "image-policy", required_argument
, NULL
, ARG_IMAGE_POLICY
},
6471 { "seed", required_argument
, NULL
, ARG_SEED
},
6472 { "pretty", required_argument
, NULL
, ARG_PRETTY
},
6473 { "definitions", required_argument
, NULL
, ARG_DEFINITIONS
},
6474 { "size", required_argument
, NULL
, ARG_SIZE
},
6475 { "json", required_argument
, NULL
, ARG_JSON
},
6476 { "key-file", required_argument
, NULL
, ARG_KEY_FILE
},
6477 { "private-key", required_argument
, NULL
, ARG_PRIVATE_KEY
},
6478 { "certificate", required_argument
, NULL
, ARG_CERTIFICATE
},
6479 { "tpm2-device", required_argument
, NULL
, ARG_TPM2_DEVICE
},
6480 { "tpm2-pcrs", required_argument
, NULL
, ARG_TPM2_PCRS
},
6481 { "tpm2-public-key", required_argument
, NULL
, ARG_TPM2_PUBLIC_KEY
},
6482 { "tpm2-public-key-pcrs", required_argument
, NULL
, ARG_TPM2_PUBLIC_KEY_PCRS
},
6483 { "split", required_argument
, NULL
, ARG_SPLIT
},
6484 { "include-partitions", required_argument
, NULL
, ARG_INCLUDE_PARTITIONS
},
6485 { "exclude-partitions", required_argument
, NULL
, ARG_EXCLUDE_PARTITIONS
},
6486 { "defer-partitions", required_argument
, NULL
, ARG_DEFER_PARTITIONS
},
6487 { "sector-size", required_argument
, NULL
, ARG_SECTOR_SIZE
},
6488 { "architecture", required_argument
, NULL
, ARG_ARCHITECTURE
},
6489 { "offline", required_argument
, NULL
, ARG_OFFLINE
},
6490 { "copy-from", required_argument
, NULL
, ARG_COPY_FROM
},
6491 { "copy-source", required_argument
, NULL
, 's' },
6492 { "make-ddi", required_argument
, NULL
, ARG_MAKE_DDI
},
6501 while ((c
= getopt_long(argc
, argv
, "hs:SCP", options
, NULL
)) >= 0)
6512 arg_pager_flags
|= PAGER_DISABLE
;
6520 r
= parse_boolean_argument("--dry-run=", optarg
, &arg_dry_run
);
6526 if (isempty(optarg
)) {
6527 arg_empty
= EMPTY_UNSET
;
6531 arg_empty
= empty_mode_from_string(optarg
);
6533 return log_error_errno(arg_empty
, "Failed to parse --empty= parameter: %s", optarg
);
6538 r
= parse_boolean_argument("--discard=", optarg
, &arg_discard
);
6543 case ARG_FACTORY_RESET
:
6544 r
= parse_boolean_argument("--factory-reset=", optarg
, NULL
);
6547 arg_factory_reset
= r
;
6550 case ARG_CAN_FACTORY_RESET
:
6551 arg_can_factory_reset
= true;
6555 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_root
);
6561 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_image
);
6566 case ARG_IMAGE_POLICY
:
6567 r
= parse_image_policy_argument(optarg
, &arg_image_policy
);
6573 if (isempty(optarg
)) {
6574 arg_seed
= SD_ID128_NULL
;
6575 arg_randomize
= false;
6576 } else if (streq(optarg
, "random"))
6577 arg_randomize
= true;
6579 r
= sd_id128_from_string(optarg
, &arg_seed
);
6581 return log_error_errno(r
, "Failed to parse seed: %s", optarg
);
6583 arg_randomize
= false;
6589 r
= parse_boolean_argument("--pretty=", optarg
, NULL
);
6595 case ARG_DEFINITIONS
: {
6596 _cleanup_free_
char *path
= NULL
;
6597 r
= parse_path_argument(optarg
, false, &path
);
6600 if (strv_consume(&arg_definitions
, TAKE_PTR(path
)) < 0)
6606 uint64_t parsed
, rounded
;
6608 if (streq(optarg
, "auto")) {
6609 arg_size
= UINT64_MAX
;
6610 arg_size_auto
= true;
6614 r
= parse_size(optarg
, 1024, &parsed
);
6616 return log_error_errno(r
, "Failed to parse --size= parameter: %s", optarg
);
6618 rounded
= round_up_size(parsed
, 4096);
6620 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too small, refusing.");
6621 if (rounded
== UINT64_MAX
)
6622 return log_error_errno(SYNTHETIC_ERRNO(ERANGE
), "Specified image size too large, refusing.");
6624 if (rounded
!= parsed
)
6625 log_warning("Specified size is not a multiple of 4096, rounding up automatically. (%" PRIu64
" %s %" PRIu64
")",
6626 parsed
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), rounded
);
6629 arg_size_auto
= false;
6634 r
= parse_json_argument(optarg
, &arg_json_format_flags
);
6640 case ARG_KEY_FILE
: {
6641 _cleanup_(erase_and_freep
) char *k
= NULL
;
6644 r
= read_full_file_full(
6645 AT_FDCWD
, optarg
, UINT64_MAX
, SIZE_MAX
,
6646 READ_FULL_FILE_SECURE
|READ_FULL_FILE_WARN_WORLD_READABLE
|READ_FULL_FILE_CONNECT_SOCKET
,
6650 return log_error_errno(r
, "Failed to read key file '%s': %m", optarg
);
6652 erase_and_free(arg_key
);
6653 arg_key
= TAKE_PTR(k
);
6658 case ARG_PRIVATE_KEY
: {
6659 _cleanup_(erase_and_freep
) char *k
= NULL
;
6662 r
= read_full_file_full(
6663 AT_FDCWD
, optarg
, UINT64_MAX
, SIZE_MAX
,
6664 READ_FULL_FILE_SECURE
|READ_FULL_FILE_WARN_WORLD_READABLE
|READ_FULL_FILE_CONNECT_SOCKET
,
6668 return log_error_errno(r
, "Failed to read key file '%s': %m", optarg
);
6670 EVP_PKEY_free(arg_private_key
);
6671 arg_private_key
= NULL
;
6672 r
= parse_private_key(k
, n
, &arg_private_key
);
6678 case ARG_CERTIFICATE
: {
6679 _cleanup_free_
char *cert
= NULL
;
6682 r
= read_full_file_full(
6683 AT_FDCWD
, optarg
, UINT64_MAX
, SIZE_MAX
,
6684 READ_FULL_FILE_CONNECT_SOCKET
,
6688 return log_error_errno(r
, "Failed to read certificate file '%s': %m", optarg
);
6690 X509_free(arg_certificate
);
6691 arg_certificate
= NULL
;
6692 r
= parse_x509_certificate(cert
, n
, &arg_certificate
);
6698 case ARG_TPM2_DEVICE
: {
6699 _cleanup_free_
char *device
= NULL
;
6701 if (streq(optarg
, "list"))
6702 return tpm2_list_devices();
6704 if (!streq(optarg
, "auto")) {
6705 device
= strdup(optarg
);
6710 free(arg_tpm2_device
);
6711 arg_tpm2_device
= TAKE_PTR(device
);
6716 arg_tpm2_hash_pcr_values_use_default
= false;
6717 r
= tpm2_parse_pcr_argument_append(optarg
, &arg_tpm2_hash_pcr_values
, &arg_tpm2_n_hash_pcr_values
);
6723 case ARG_TPM2_PUBLIC_KEY
:
6724 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_tpm2_public_key
);
6730 case ARG_TPM2_PUBLIC_KEY_PCRS
:
6731 arg_tpm2_public_key_pcr_mask_use_default
= false;
6732 r
= tpm2_parse_pcr_argument_to_mask(optarg
, &arg_tpm2_public_key_pcr_mask
);
6739 r
= parse_boolean_argument("--split=", optarg
, NULL
);
6746 case ARG_INCLUDE_PARTITIONS
:
6747 if (arg_filter_partitions_type
== FILTER_PARTITIONS_EXCLUDE
)
6748 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6749 "Combination of --include-partitions= and --exclude-partitions= is invalid.");
6751 r
= parse_partition_types(optarg
, &arg_filter_partitions
, &arg_n_filter_partitions
);
6755 arg_filter_partitions_type
= FILTER_PARTITIONS_INCLUDE
;
6759 case ARG_EXCLUDE_PARTITIONS
:
6760 if (arg_filter_partitions_type
== FILTER_PARTITIONS_INCLUDE
)
6761 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6762 "Combination of --include-partitions= and --exclude-partitions= is invalid.");
6764 r
= parse_partition_types(optarg
, &arg_filter_partitions
, &arg_n_filter_partitions
);
6768 arg_filter_partitions_type
= FILTER_PARTITIONS_EXCLUDE
;
6772 case ARG_DEFER_PARTITIONS
:
6773 r
= parse_partition_types(optarg
, &arg_defer_partitions
, &arg_n_defer_partitions
);
6779 case ARG_SECTOR_SIZE
:
6780 r
= parse_sector_size(optarg
, &arg_sector_size
);
6786 case ARG_ARCHITECTURE
:
6787 r
= architecture_from_string(optarg
);
6789 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid architecture '%s'", optarg
);
6791 arg_architecture
= r
;
6795 if (streq(optarg
, "auto"))
6798 r
= parse_boolean_argument("--offline=", optarg
, NULL
);
6807 case ARG_COPY_FROM
: {
6808 _cleanup_free_
char *p
= NULL
;
6810 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &p
);
6814 if (strv_consume(&arg_copy_from
, TAKE_PTR(p
)) < 0)
6821 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_copy_source
);
6827 if (!filename_is_valid(optarg
))
6828 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid DDI type: %s", optarg
);
6830 r
= free_and_strdup_warn(&arg_make_ddi
, optarg
);
6836 r
= free_and_strdup_warn(&arg_make_ddi
, "sysext");
6842 r
= free_and_strdup_warn(&arg_make_ddi
, "confext");
6848 r
= free_and_strdup_warn(&arg_make_ddi
, "portable");
6857 assert_not_reached();
6860 if (argc
- optind
> 1)
6861 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6862 "Expected at most one argument, the path to the block device or image file.");
6865 if (arg_definitions
)
6866 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Combination of --make-ddi= and --definitions= is not supported.");
6867 if (!IN_SET(arg_empty
, EMPTY_UNSET
, EMPTY_CREATE
))
6868 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Combination of --make-ddi= and --empty=%s is not supported.", empty_mode_to_string(arg_empty
));
6870 /* Imply automatic sizing in DDI mode */
6871 if (arg_size
== UINT64_MAX
)
6872 arg_size_auto
= true;
6874 if (!arg_copy_source
)
6875 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No --copy-source= specified, refusing.");
6877 r
= dir_is_empty(arg_copy_source
, /* ignore_hidden_or_backup= */ false);
6879 return log_error_errno(r
, "Failed to determine if '%s' is empty: %m", arg_copy_source
);
6881 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
), "Source directory '%s' is empty, refusing to create empty image.", arg_copy_source
);
6883 if (sd_id128_is_null(arg_seed
) && !arg_randomize
) {
6884 /* We don't want that /etc/machine-id leaks into any image built this way, hence
6885 * let's randomize the seed if not specified explicitly */
6886 log_notice("No seed value specified, randomizing generated UUIDs, resulting image will not be reproducible.");
6887 arg_randomize
= true;
6890 arg_empty
= EMPTY_CREATE
;
6893 if (arg_empty
== EMPTY_UNSET
) /* default to refuse mode, if not otherwise specified */
6894 arg_empty
= EMPTY_REFUSE
;
6896 if (arg_factory_reset
> 0 && IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
))
6897 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6898 "Combination of --factory-reset=yes and --empty=force/--empty=require/--empty=create is invalid.");
6900 if (arg_can_factory_reset
)
6901 arg_dry_run
= true; /* When --can-factory-reset is specified we don't make changes, hence
6902 * non-dry-run mode makes no sense. Thus, imply dry run mode so that we
6903 * open things strictly read-only. */
6904 else if (arg_empty
== EMPTY_CREATE
)
6905 arg_dry_run
= false; /* Imply --dry-run=no if we create the loopback file anew. After all we
6906 * cannot really break anyone's partition tables that way. */
6908 /* Disable pager once we are not just reviewing, but doing things. */
6910 arg_pager_flags
|= PAGER_DISABLE
;
6912 if (arg_empty
== EMPTY_CREATE
&& arg_size
== UINT64_MAX
&& !arg_size_auto
)
6913 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6914 "If --empty=create is specified, --size= must be specified, too.");
6916 if (arg_image
&& arg_root
)
6917 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Please specify either --root= or --image=, the combination of both is not supported.");
6918 else if (!arg_image
&& !arg_root
&& in_initrd()) {
6920 /* By default operate on /sysusr/ or /sysroot/ when invoked in the initrd. We prefer the
6921 * former, if it is mounted, so that we have deterministic behaviour on systems where /usr/
6922 * is vendor-supplied but the root fs formatted on first boot. */
6923 r
= path_is_mount_point("/sysusr/usr", NULL
, 0);
6925 if (r
< 0 && r
!= -ENOENT
)
6926 log_debug_errno(r
, "Unable to determine whether /sysusr/usr is a mount point, assuming it is not: %m");
6928 arg_root
= strdup("/sysroot");
6930 arg_root
= strdup("/sysusr");
6935 arg_node
= argc
> optind
? argv
[optind
] : NULL
;
6937 if (IN_SET(arg_empty
, EMPTY_FORCE
, EMPTY_REQUIRE
, EMPTY_CREATE
) && !arg_node
&& !arg_image
)
6938 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6939 "A path to a device node or image file must be specified when --make-ddi=, --empty=force, --empty=require or --empty=create are used.");
6941 if (arg_split
&& !arg_node
)
6942 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
6943 "A path to an image file must be specified when --split is used.");
6945 if (arg_tpm2_public_key_pcr_mask_use_default
&& arg_tpm2_public_key
)
6946 arg_tpm2_public_key_pcr_mask
= INDEX_TO_MASK(uint32_t, TPM2_PCR_KERNEL_BOOT
);
6948 if (arg_tpm2_hash_pcr_values_use_default
&& !GREEDY_REALLOC_APPEND(
6949 arg_tpm2_hash_pcr_values
,
6950 arg_tpm2_n_hash_pcr_values
,
6951 &TPM2_PCR_VALUE_MAKE(TPM2_PCR_INDEX_DEFAULT
, /* hash= */ 0, /* value= */ {}),
6955 if (arg_pretty
< 0 && isatty(STDOUT_FILENO
))
6958 if (arg_architecture
>= 0) {
6959 FOREACH_ARRAY(p
, arg_filter_partitions
, arg_n_filter_partitions
)
6960 *p
= gpt_partition_type_override_architecture(*p
, arg_architecture
);
6962 FOREACH_ARRAY(p
, arg_defer_partitions
, arg_n_defer_partitions
)
6963 *p
= gpt_partition_type_override_architecture(*p
, arg_architecture
);
6969 static int parse_proc_cmdline_factory_reset(void) {
6973 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
6976 if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
6979 r
= proc_cmdline_get_bool("systemd.factory_reset", /* flags = */ 0, &b
);
6981 return log_error_errno(r
, "Failed to parse systemd.factory_reset kernel command line argument: %m");
6983 arg_factory_reset
= b
;
6986 log_notice("Honouring factory reset requested via kernel command line.");
6992 static int parse_efi_variable_factory_reset(void) {
6993 _cleanup_free_
char *value
= NULL
;
6996 if (arg_factory_reset
>= 0) /* Never override what is specified on the process command line */
6999 if (!in_initrd()) /* Never honour EFI variable factory reset request outside of the initrd */
7002 r
= efi_get_variable_string(EFI_SYSTEMD_VARIABLE(FactoryReset
), &value
);
7004 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
7006 return log_error_errno(r
, "Failed to read EFI variable FactoryReset: %m");
7009 r
= parse_boolean(value
);
7011 return log_error_errno(r
, "Failed to parse EFI variable FactoryReset: %m");
7013 arg_factory_reset
= r
;
7015 log_notice("Factory reset requested via EFI variable FactoryReset.");
7020 static int remove_efi_variable_factory_reset(void) {
7023 r
= efi_set_variable(EFI_SYSTEMD_VARIABLE(FactoryReset
), NULL
, 0);
7025 if (r
== -ENOENT
|| ERRNO_IS_NOT_SUPPORTED(r
))
7027 return log_error_errno(r
, "Failed to remove EFI variable FactoryReset: %m");
7030 log_info("Successfully unset EFI variable FactoryReset.");
7034 static int acquire_root_devno(
7041 _cleanup_free_
char *found_path
= NULL
, *node
= NULL
;
7042 dev_t devno
, fd_devno
= MODE_INVALID
;
7043 _cleanup_close_
int fd
= -EBADF
;
7051 fd
= chase_and_open(p
, root
, CHASE_PREFIX_ROOT
, mode
, &found_path
);
7055 if (fstat(fd
, &st
) < 0)
7058 if (S_ISREG(st
.st_mode
)) {
7059 *ret
= TAKE_PTR(found_path
);
7060 *ret_fd
= TAKE_FD(fd
);
7064 if (S_ISBLK(st
.st_mode
)) {
7065 /* Refuse referencing explicit block devices if a root dir is specified, after all we should
7066 * not be able to leave the image the root path constrains us to. */
7070 fd_devno
= devno
= st
.st_rdev
;
7071 } else if (S_ISDIR(st
.st_mode
)) {
7074 if (major(devno
) == 0) {
7075 r
= btrfs_get_block_device_fd(fd
, &devno
);
7076 if (r
== -ENOTTY
) /* not btrfs */
7084 /* From dm-crypt to backing partition */
7085 r
= block_get_originating(devno
, &devno
);
7087 log_debug_errno(r
, "Device '%s' has no dm-crypt/dm-verity device, no need to look for underlying block device.", p
);
7089 log_debug_errno(r
, "Failed to find underlying block device for '%s', ignoring: %m", p
);
7091 /* From partition to whole disk containing it */
7092 r
= block_get_whole_disk(devno
, &devno
);
7094 log_debug_errno(r
, "Failed to find whole disk block device for '%s', ignoring: %m", p
);
7096 r
= devname_from_devnum(S_IFBLK
, devno
, &node
);
7098 return log_debug_errno(r
, "Failed to determine canonical path for '%s': %m", p
);
7100 /* Only if we still look at the same block device we can reuse the fd. Otherwise return an
7101 * invalidated fd. */
7102 if (fd_devno
!= MODE_INVALID
&& fd_devno
== devno
) {
7103 /* Tell udev not to interfere while we are processing the device */
7104 if (flock(fd
, arg_dry_run
? LOCK_SH
: LOCK_EX
) < 0)
7105 return log_error_errno(errno
, "Failed to lock device '%s': %m", node
);
7107 *ret_fd
= TAKE_FD(fd
);
7111 *ret
= TAKE_PTR(node
);
7115 static int find_root(Context
*context
) {
7116 _cleanup_free_
char *device
= NULL
;
7122 if (arg_empty
== EMPTY_CREATE
) {
7123 _cleanup_close_
int fd
= -EBADF
;
7124 _cleanup_free_
char *s
= NULL
;
7126 s
= strdup(arg_node
);
7130 fd
= open(arg_node
, O_RDONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOFOLLOW
, 0666);
7132 return log_error_errno(errno
, "Failed to create '%s': %m", arg_node
);
7134 context
->node
= TAKE_PTR(s
);
7135 context
->node_is_our_file
= true;
7136 context
->backing_fd
= TAKE_FD(fd
);
7140 /* Note that we don't specify a root argument here: if the user explicitly configured a node
7141 * we'll take it relative to the host, not the image */
7142 r
= acquire_root_devno(arg_node
, NULL
, O_RDONLY
|O_CLOEXEC
, &context
->node
, &context
->backing_fd
);
7144 return btrfs_log_dev_root(LOG_ERR
, r
, arg_node
);
7146 return log_error_errno(r
, "Failed to open file or determine backing device of %s: %m", arg_node
);
7151 assert(IN_SET(arg_empty
, EMPTY_REFUSE
, EMPTY_ALLOW
));
7153 /* If the root mount has been replaced by some form of volatile file system (overlayfs), the
7154 * original root block device node is symlinked in /run/systemd/volatile-root. Let's read that
7156 r
= readlink_malloc("/run/systemd/volatile-root", &device
);
7157 if (r
== -ENOENT
) { /* volatile-root not found */
7158 /* Let's search for the root device. We look for two cases here: first in /, and then in /usr. The
7159 * latter we check for cases where / is a tmpfs and only /usr is an actual persistent block device
7160 * (think: volatile setups) */
7162 FOREACH_STRING(p
, "/", "/usr") {
7164 r
= acquire_root_devno(p
, arg_root
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, &context
->node
,
7165 &context
->backing_fd
);
7168 return btrfs_log_dev_root(LOG_ERR
, r
, p
);
7170 return log_error_errno(r
, "Failed to determine backing device of %s: %m", p
);
7175 return log_error_errno(r
, "Failed to read symlink /run/systemd/volatile-root: %m");
7177 r
= acquire_root_devno(device
, NULL
, O_RDONLY
|O_CLOEXEC
, &context
->node
, &context
->backing_fd
);
7179 return btrfs_log_dev_root(LOG_ERR
, r
, device
);
7181 return log_error_errno(r
, "Failed to open file or determine backing device of %s: %m", device
);
7186 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
), "Failed to discover root block device.");
7189 static int resize_pt(int fd
, uint64_t sector_size
) {
7190 _cleanup_(fdisk_unref_contextp
) struct fdisk_context
*c
= NULL
;
7193 /* After resizing the backing file we need to resize the partition table itself too, so that it takes
7194 * possession of the enlarged backing file. For this it suffices to open the device with libfdisk and
7195 * immediately write it again, with no changes. */
7197 r
= fdisk_new_context_at(fd
, /* path= */ NULL
, /* read_only= */ false, sector_size
, &c
);
7199 return log_error_errno(r
, "Failed to open device '%s': %m", FORMAT_PROC_FD_PATH(fd
));
7201 r
= fdisk_has_label(c
);
7203 return log_error_errno(r
, "Failed to determine whether disk '%s' has a disk label: %m", FORMAT_PROC_FD_PATH(fd
));
7205 log_debug("Not resizing partition table, as there currently is none.");
7209 r
= fdisk_write_disklabel(c
);
7211 return log_error_errno(r
, "Failed to write resized partition table: %m");
7213 log_info("Resized partition table.");
7217 static int resize_backing_fd(
7218 const char *node
, /* The primary way we access the disk image to operate on */
7219 int *fd
, /* An O_RDONLY fd referring to that inode */
7220 const char *backing_file
, /* If the above refers to a loopback device, the backing regular file for that, which we can grow */
7221 LoopDevice
*loop_device
,
7222 uint64_t sector_size
) {
7224 _cleanup_close_
int writable_fd
= -EBADF
;
7225 uint64_t current_size
;
7232 if (arg_size
== UINT64_MAX
) /* Nothing to do */
7236 /* Open the file if we haven't opened it yet. Note that we open it read-only here, just to
7237 * keep a reference to the file we can pass around. */
7238 *fd
= open(node
, O_RDONLY
|O_CLOEXEC
);
7240 return log_error_errno(errno
, "Failed to open '%s' in order to adjust size: %m", node
);
7243 if (fstat(*fd
, &st
) < 0)
7244 return log_error_errno(errno
, "Failed to stat '%s': %m", node
);
7246 if (S_ISBLK(st
.st_mode
)) {
7248 return log_error_errno(SYNTHETIC_ERRNO(EBADF
), "Cannot resize block device '%s'.", node
);
7250 assert(loop_device
);
7252 if (ioctl(*fd
, BLKGETSIZE64
, ¤t_size
) < 0)
7253 return log_error_errno(errno
, "Failed to determine size of block device %s: %m", node
);
7255 r
= stat_verify_regular(&st
);
7257 return log_error_errno(r
, "Specified path '%s' is not a regular file or loopback block device, cannot resize: %m", node
);
7259 assert(!backing_file
);
7260 assert(!loop_device
);
7261 current_size
= st
.st_size
;
7264 if (current_size
>= arg_size
) {
7265 log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)",
7266 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
7270 if (S_ISBLK(st
.st_mode
)) {
7271 assert(backing_file
);
7273 /* This is a loopback device. We can't really grow those directly, but we can grow the
7274 * backing file, hence let's do that. */
7276 writable_fd
= open(backing_file
, O_WRONLY
|O_CLOEXEC
|O_NONBLOCK
);
7277 if (writable_fd
< 0)
7278 return log_error_errno(errno
, "Failed to open backing file '%s': %m", backing_file
);
7280 if (fstat(writable_fd
, &st
) < 0)
7281 return log_error_errno(errno
, "Failed to stat() backing file '%s': %m", backing_file
);
7283 r
= stat_verify_regular(&st
);
7285 return log_error_errno(r
, "Backing file '%s' of block device is not a regular file: %m", backing_file
);
7287 if ((uint64_t) st
.st_size
!= current_size
)
7288 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
7289 "Size of backing file '%s' of loopback block device '%s' don't match, refusing.",
7290 node
, backing_file
);
7292 assert(S_ISREG(st
.st_mode
));
7293 assert(!backing_file
);
7295 /* The file descriptor is read-only. In order to grow the file we need to have a writable fd. We
7296 * reopen the file for that temporarily. We keep the writable fd only open for this operation though,
7297 * as fdisk can't accept it anyway. */
7299 writable_fd
= fd_reopen(*fd
, O_WRONLY
|O_CLOEXEC
);
7300 if (writable_fd
< 0)
7301 return log_error_errno(writable_fd
, "Failed to reopen backing file '%s' writable: %m", node
);
7305 if (fallocate(writable_fd
, 0, 0, arg_size
) < 0) {
7306 if (!ERRNO_IS_NOT_SUPPORTED(errno
))
7307 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by allocation: %m",
7308 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
7310 /* Fallback to truncation, if fallocate() is not supported. */
7311 log_debug("Backing file system does not support fallocate(), falling back to ftruncate().");
7313 if (current_size
== 0) /* Likely regular file just created by us */
7314 log_info("Allocated %s for '%s'.", FORMAT_BYTES(arg_size
), node
);
7316 log_info("File '%s' grown from %s to %s by allocation.",
7317 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
7323 if (ftruncate(writable_fd
, arg_size
) < 0)
7324 return log_error_errno(errno
, "Failed to grow '%s' from %s to %s by truncation: %m",
7325 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
7327 if (current_size
== 0) /* Likely regular file just created by us */
7328 log_info("Sized '%s' to %s.", node
, FORMAT_BYTES(arg_size
));
7330 log_info("File '%s' grown from %s to %s by truncation.",
7331 node
, FORMAT_BYTES(current_size
), FORMAT_BYTES(arg_size
));
7334 r
= resize_pt(writable_fd
, sector_size
);
7339 r
= loop_device_refresh_size(loop_device
, UINT64_MAX
, arg_size
);
7341 return log_error_errno(r
, "Failed to update loop device size: %m");
7347 static int determine_auto_size(Context
*c
) {
7352 sum
= round_up_size(GPT_METADATA_SIZE
, 4096);
7354 LIST_FOREACH(partitions
, p
, c
->partitions
) {
7360 m
= partition_min_size_with_padding(c
, p
);
7361 if (m
> UINT64_MAX
- sum
)
7362 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "Image would grow too large, refusing.");
7367 if (c
->total
!= UINT64_MAX
)
7368 /* Image already allocated? Then show its size. */
7369 log_info("Automatically determined minimal disk image size as %s, current image size is %s.",
7370 FORMAT_BYTES(sum
), FORMAT_BYTES(c
->total
));
7372 /* If the image is being created right now, then it has no previous size, suppress any comment about it hence. */
7373 log_info("Automatically determined minimal disk image size as %s.",
7380 static int run(int argc
, char *argv
[]) {
7381 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
7382 _cleanup_(umount_and_freep
) char *mounted_dir
= NULL
;
7383 _cleanup_(context_freep
) Context
* context
= NULL
;
7384 bool node_is_our_loop
= false;
7387 log_show_color(true);
7388 log_parse_environment();
7391 r
= parse_argv(argc
, argv
);
7395 r
= parse_proc_cmdline_factory_reset();
7399 r
= parse_efi_variable_factory_reset();
7403 #if HAVE_LIBCRYPTSETUP
7404 cryptsetup_enable_logging(NULL
);
7410 /* Mount this strictly read-only: we shall modify the partition table, not the file
7412 r
= mount_image_privately_interactively(
7415 DISSECT_IMAGE_MOUNT_READ_ONLY
|
7416 (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) */
7417 DISSECT_IMAGE_GPT_ONLY
|
7418 DISSECT_IMAGE_RELAX_VAR_CHECK
|
7419 DISSECT_IMAGE_USR_NO_ROOT
|
7420 DISSECT_IMAGE_REQUIRE_ROOT
,
7422 /* ret_dir_fd= */ NULL
,
7427 arg_root
= strdup(mounted_dir
);
7432 arg_node
= strdup(loop_device
->node
);
7436 /* Remember that the device we are about to manipulate is actually the one we
7437 * allocated here, and thus to increase its backing file we know what to do */
7438 node_is_our_loop
= true;
7442 if (!arg_copy_source
&& arg_root
) {
7443 /* If no explicit copy source is specified, then use --root=/--image= */
7444 arg_copy_source
= strdup(arg_root
);
7445 if (!arg_copy_source
)
7449 context
= context_new(arg_seed
);
7453 r
= context_copy_from(context
);
7458 _cleanup_free_
char *d
= NULL
, *dp
= NULL
;
7459 assert(!arg_definitions
);
7461 d
= strjoin(arg_make_ddi
, ".repart.d/");
7465 r
= search_and_access(d
, F_OK
, arg_root
, CONF_PATHS_USR_STRV("systemd/repart/definitions"), &dp
);
7467 return log_error_errno(errno
, "DDI type '%s' is not defined: %m", arg_make_ddi
);
7469 if (strv_consume(&arg_definitions
, TAKE_PTR(dp
)) < 0)
7472 strv_uniq(arg_definitions
);
7474 r
= context_read_definitions(context
);
7478 r
= find_root(context
);
7480 return 76; /* Special return value which means "Root block device not found, so not doing
7481 * anything". This isn't really an error when called at boot. */
7485 if (arg_size
!= UINT64_MAX
) {
7486 r
= resize_backing_fd(
7488 &context
->backing_fd
,
7489 node_is_our_loop
? arg_image
: NULL
,
7490 node_is_our_loop
? loop_device
: NULL
,
7491 context
->sector_size
);
7496 r
= context_load_partition_table(context
);
7497 if (r
== -EHWPOISON
)
7498 return 77; /* Special return value which means "Not GPT, so not doing anything". This isn't
7499 * really an error when called at boot. */
7502 context
->from_scratch
= r
> 0; /* Starting from scratch */
7504 if (arg_can_factory_reset
) {
7505 r
= context_can_factory_reset(context
);
7509 return EXIT_FAILURE
;
7514 r
= context_factory_reset(context
);
7518 /* We actually did a factory reset! */
7519 r
= remove_efi_variable_factory_reset();
7523 /* Reload the reduced partition table */
7524 context_unload_partition_table(context
);
7525 r
= context_load_partition_table(context
);
7530 r
= context_read_seed(context
, arg_root
);
7534 /* Make sure each partition has a unique UUID and unique label */
7535 r
= context_acquire_partition_uuids_and_labels(context
);
7539 /* Open all files to copy blocks from now, since we want to take their size into consideration */
7540 r
= context_open_copy_block_paths(
7542 loop_device
? loop_device
->devno
: /* if --image= is specified, only allow partitions on the loopback device */
7543 arg_root
&& !arg_image
? 0 : /* if --root= is specified, don't accept any block device */
7544 (dev_t
) -1); /* if neither is specified, make no restrictions */
7548 r
= context_minimize(context
);
7552 if (arg_size_auto
) {
7553 r
= determine_auto_size(context
);
7557 /* Flush out everything again, and let's grow the file first, then start fresh */
7558 context_unload_partition_table(context
);
7560 assert(arg_size
!= UINT64_MAX
);
7561 r
= resize_backing_fd(
7563 &context
->backing_fd
,
7564 node_is_our_loop
? arg_image
: NULL
,
7565 node_is_our_loop
? loop_device
: NULL
,
7566 context
->sector_size
);
7570 r
= context_load_partition_table(context
);
7575 /* First try to fit new partitions in, dropping by priority until it fits */
7577 uint64_t largest_free_area
;
7579 if (context_allocate_partitions(context
, &largest_free_area
))
7580 break; /* Success! */
7582 if (!context_drop_or_foreignize_one_priority(context
)) {
7583 r
= log_error_errno(SYNTHETIC_ERRNO(ENOSPC
),
7584 "Can't fit requested partitions into available free space (%s), refusing.",
7585 FORMAT_BYTES(largest_free_area
));
7586 determine_auto_size(context
);
7591 /* Now assign free space according to the weight logic */
7592 r
= context_grow_partitions(context
);
7596 /* Now calculate where each new partition gets placed */
7597 context_place_partitions(context
);
7599 (void) context_dump(context
, /*late=*/ false);
7601 r
= context_write_partition_table(context
);
7605 r
= context_split(context
);
7609 (void) context_dump(context
, /*late=*/ true);
7611 context
->node
= mfree(context
->node
);
7613 LIST_FOREACH(partitions
, p
, context
->partitions
)
7614 p
->split_path
= mfree(p
->split_path
);
7619 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);