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