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