]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/dissect/dissect.c
loop-util: add new loop_device_make_by_path_memory() helper
[thirdparty/systemd.git] / src / dissect / dissect.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a2ea3b2f
LP
2
3#include <fcntl.h>
a2ea3b2f 4#include <getopt.h>
e08f94ac
LP
5#include <linux/loop.h>
6#include <stdio.h>
19df770f 7#include <sys/file.h>
16b74592
LP
8#include <sys/ioctl.h>
9#include <sys/mount.h>
a2ea3b2f 10
ac1f1adf
DDM
11#include "sd-device.h"
12
a2ea3b2f 13#include "architecture.h"
ac1f1adf 14#include "blockdev-util.h"
d6b4d1c7 15#include "build.h"
f4351959 16#include "chase-symlinks.h"
33973b84 17#include "copy.h"
ca822829
YW
18#include "device-util.h"
19#include "devnum-util.h"
0305cf6e 20#include "discover-image.h"
a2ea3b2f 21#include "dissect-image.h"
994c9c70 22#include "env-util.h"
db02190e 23#include "escape.h"
33973b84 24#include "fd-util.h"
89e62e0b 25#include "fileio.h"
89d00f2e 26#include "format-table.h"
16b74592 27#include "format-util.h"
33973b84 28#include "fs-util.h"
4623e8e6 29#include "hexdecoct.h"
a2ea3b2f
LP
30#include "log.h"
31#include "loop-util.h"
149afb45 32#include "main-func.h"
33973b84
LP
33#include "mkdir.h"
34#include "mount-util.h"
ac1f1adf 35#include "mountpoint-util.h"
33973b84 36#include "namespace-util.h"
614b022c 37#include "parse-argument.h"
e475f729 38#include "parse-util.h"
e7cbe5cb 39#include "path-util.h"
5c05f062 40#include "pretty-print.h"
06186c4c 41#include "process-util.h"
0cf16924 42#include "recurse-dir.h"
db02190e 43#include "sha256.h"
33973b84 44#include "stat-util.h"
a2ea3b2f 45#include "string-util.h"
a1edd22e 46#include "strv.h"
5c05f062 47#include "terminal-util.h"
33973b84 48#include "tmpfile-util.h"
2d3a5a73 49#include "user-util.h"
a2ea3b2f
LP
50
51static enum {
52 ACTION_DISSECT,
53 ACTION_MOUNT,
ac1f1adf 54 ACTION_UMOUNT,
0cf16924 55 ACTION_LIST,
db02190e 56 ACTION_MTREE,
06186c4c 57 ACTION_WITH,
33973b84
LP
58 ACTION_COPY_FROM,
59 ACTION_COPY_TO,
0305cf6e 60 ACTION_DISCOVER,
a2ea3b2f
LP
61} arg_action = ACTION_DISSECT;
62static const char *arg_image = NULL;
63static const char *arg_path = NULL;
33973b84
LP
64static const char *arg_source = NULL;
65static const char *arg_target = NULL;
4b5de5dd
LP
66static DissectImageFlags arg_flags =
67 DISSECT_IMAGE_GENERIC_ROOT |
4b5de5dd
LP
68 DISSECT_IMAGE_DISCARD_ON_LOOP |
69 DISSECT_IMAGE_RELAX_VAR_CHECK |
70 DISSECT_IMAGE_FSCK |
74a54bae 71 DISSECT_IMAGE_USR_NO_ROOT |
73d88b80
LP
72 DISSECT_IMAGE_GROWFS |
73 DISSECT_IMAGE_PIN_PARTITION_DEVICES |
74 DISSECT_IMAGE_ADD_PARTITION_DEVICES;
aee36b4e 75static VeritySettings arg_verity_settings = VERITY_SETTINGS_DEFAULT;
6a01ea4a 76static JsonFormatFlags arg_json_format_flags = JSON_FORMAT_OFF;
17547fb5
LP
77static PagerFlags arg_pager_flags = 0;
78static bool arg_legend = true;
ac1f1adf 79static bool arg_rmdir = false;
06186c4c 80static char **arg_argv = NULL;
a2ea3b2f 81
89e62e0b 82STATIC_DESTRUCTOR_REGISTER(arg_verity_settings, verity_settings_done);
06186c4c 83STATIC_DESTRUCTOR_REGISTER(arg_argv, strv_freep);
149afb45 84
5c05f062
LP
85static int help(void) {
86 _cleanup_free_ char *link = NULL;
87 int r;
88
89 r = terminal_urlify_man("systemd-dissect", "1", &link);
90 if (r < 0)
91 return log_oom();
92
93 printf("%1$s [OPTIONS...] IMAGE\n"
33973b84 94 "%1$s [OPTIONS...] --mount IMAGE PATH\n"
1b967529 95 "%1$s [OPTIONS...] --umount PATH\n"
0cf16924 96 "%1$s [OPTIONS...] --list IMAGE\n"
db02190e 97 "%1$s [OPTIONS...] --mtree IMAGE\n"
06186c4c 98 "%1$s [OPTIONS...] --with IMAGE [COMMAND…]\n"
33973b84
LP
99 "%1$s [OPTIONS...] --copy-from IMAGE PATH [TARGET]\n"
100 "%1$s [OPTIONS...] --copy-to IMAGE [SOURCE] PATH\n\n"
a94a199c 101 "%5$sDissect a Discoverable Disk Image (DDI).%6$s\n\n"
5c05f062 102 "%3$sOptions:%4$s\n"
17547fb5
LP
103 " --no-pager Do not pipe output into a pager\n"
104 " --no-legend Do not show the headers and footers\n"
e7cbe5cb
LB
105 " -r --read-only Mount read-only\n"
106 " --fsck=BOOL Run fsck before mounting\n"
74a54bae 107 " --growfs=BOOL Grow file system to partition size, if marked\n"
5c05f062 108 " --mkdir Make mount directory before mounting, if missing\n"
ac1f1adf 109 " --rmdir Remove mount directory after unmounting\n"
e7cbe5cb
LB
110 " --discard=MODE Choose 'discard' mode (disabled, loop, all, crypto)\n"
111 " --root-hash=HASH Specify root hash for verity\n"
c2923fdc
LB
112 " --root-hash-sig=SIG Specify pkcs7 signature of root hash for verity\n"
113 " as a DER encoded PKCS7, either as a path to a file\n"
114 " or as an ASCII base64 encoded string prefixed by\n"
115 " 'base64:'\n"
e7cbe5cb 116 " --verity-data=PATH Specify data file with hash tree for verity if it is\n"
5c05f062 117 " not embedded in IMAGE\n"
de8231b0
LP
118 " --json=pretty|short|off\n"
119 " Generate JSON output\n"
5c05f062
LP
120 "\n%3$sCommands:%4$s\n"
121 " -h --help Show this help\n"
122 " --version Show package version\n"
123 " -m --mount Mount the image to the specified directory\n"
124 " -M Shortcut for --mount --mkdir\n"
ac1f1adf
DDM
125 " -u --umount Unmount the image from the specified directory\n"
126 " -U Shortcut for --umount --rmdir\n"
0cf16924
AAF
127 " -l --list List all the files and directories of the specified\n"
128 " OS image\n"
db02190e 129 " --mtree Show BSD mtree manifest of OS image\n"
06186c4c 130 " --with Mount, run command, unmount\n"
33973b84
LP
131 " -x --copy-from Copy files from image to host\n"
132 " -a --copy-to Copy files from host to image\n"
0305cf6e 133 " --discover Discover DDIs in well known directories\n"
bc556335
DDM
134 "\nSee the %2$s for details.\n",
135 program_invocation_short_name,
136 link,
137 ansi_underline(),
138 ansi_normal(),
139 ansi_highlight(),
140 ansi_normal());
5c05f062
LP
141
142 return 0;
a2ea3b2f
LP
143}
144
06186c4c
LP
145static int patch_argv(int *argc, char ***argv, char ***buf) {
146 _cleanup_free_ char **l = NULL;
147 char **e;
148
149 assert(argc);
150 assert(*argc >= 0);
151 assert(argv);
152 assert(*argv);
153 assert(buf);
154
155 /* Ugly hack: if --with is included in command line, also insert "--" immediately after it, to make
156 * getopt_long() stop processing switches */
157
158 for (e = *argv + 1; e < *argv + *argc; e++) {
159 assert(*e);
160
161 if (streq(*e, "--with"))
162 break;
163 }
164
165 if (e >= *argv + *argc || streq_ptr(e[1], "--")) {
166 /* No --with used? Or already followed by "--"? Then don't do anything */
167 *buf = NULL;
168 return 0;
169 }
170
171 /* Insert the extra "--" right after the --with */
172 l = new(char*, *argc + 2);
173 if (!l)
174 return log_oom();
175
176 size_t idx = e - *argv + 1;
177 memcpy(l, *argv, sizeof(char*) * idx); /* copy everything up to and including the --with */
178 l[idx] = (char*) "--"; /* insert "--" */
179 memcpy(l + idx + 1, e + 1, sizeof(char*) * (*argc - idx + 1)); /* copy the rest, including trailing NULL entry */
180
181 (*argc)++;
182 (*argv) = l;
183
184 *buf = TAKE_PTR(l);
185 return 1;
186}
187
a2ea3b2f
LP
188static int parse_argv(int argc, char *argv[]) {
189
190 enum {
191 ARG_VERSION = 0x100,
17547fb5
LP
192 ARG_NO_PAGER,
193 ARG_NO_LEGEND,
06186c4c 194 ARG_WITH,
18b5886e 195 ARG_DISCARD,
e475f729 196 ARG_FSCK,
74a54bae 197 ARG_GROWFS,
89e62e0b 198 ARG_ROOT_HASH,
c2923fdc 199 ARG_ROOT_HASH_SIG,
89e62e0b 200 ARG_VERITY_DATA,
5c05f062 201 ARG_MKDIR,
ac1f1adf 202 ARG_RMDIR,
de8231b0 203 ARG_JSON,
db02190e 204 ARG_MTREE,
0305cf6e 205 ARG_DISCOVER,
a2ea3b2f
LP
206 };
207
208 static const struct option options[] = {
c2923fdc
LB
209 { "help", no_argument, NULL, 'h' },
210 { "version", no_argument, NULL, ARG_VERSION },
17547fb5
LP
211 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
212 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
c2923fdc 213 { "mount", no_argument, NULL, 'm' },
ac1f1adf 214 { "umount", no_argument, NULL, 'u' },
06186c4c 215 { "with", no_argument, NULL, ARG_WITH },
c2923fdc
LB
216 { "read-only", no_argument, NULL, 'r' },
217 { "discard", required_argument, NULL, ARG_DISCARD },
c2923fdc 218 { "fsck", required_argument, NULL, ARG_FSCK },
74a54bae 219 { "growfs", required_argument, NULL, ARG_GROWFS },
89e62e0b 220 { "root-hash", required_argument, NULL, ARG_ROOT_HASH },
c2923fdc 221 { "root-hash-sig", required_argument, NULL, ARG_ROOT_HASH_SIG },
89e62e0b 222 { "verity-data", required_argument, NULL, ARG_VERITY_DATA },
5c05f062 223 { "mkdir", no_argument, NULL, ARG_MKDIR },
ac1f1adf 224 { "rmdir", no_argument, NULL, ARG_RMDIR },
0cf16924 225 { "list", no_argument, NULL, 'l' },
db02190e 226 { "mtree", no_argument, NULL, ARG_MTREE },
33973b84
LP
227 { "copy-from", no_argument, NULL, 'x' },
228 { "copy-to", no_argument, NULL, 'a' },
de8231b0 229 { "json", required_argument, NULL, ARG_JSON },
0305cf6e 230 { "discover", no_argument, NULL, ARG_DISCOVER },
a2ea3b2f
LP
231 {}
232 };
233
06186c4c 234 _cleanup_free_ char **buf = NULL; /* we use free(), not strv_free() here, as we don't copy the strings here */
4623e8e6 235 int c, r;
a2ea3b2f
LP
236
237 assert(argc >= 0);
238 assert(argv);
239
06186c4c
LP
240 r = patch_argv(&argc, &argv, &buf);
241 if (r < 0)
242 return r;
243
0cf16924 244 while ((c = getopt_long(argc, argv, "hmurMUlxa", options, NULL)) >= 0) {
a2ea3b2f
LP
245
246 switch (c) {
247
248 case 'h':
5c05f062 249 return help();
a2ea3b2f
LP
250
251 case ARG_VERSION:
252 return version();
253
17547fb5
LP
254 case ARG_NO_PAGER:
255 arg_pager_flags |= PAGER_DISABLE;
256 break;
257
258 case ARG_NO_LEGEND:
259 arg_legend = false;
260 break;
261
a2ea3b2f
LP
262 case 'm':
263 arg_action = ACTION_MOUNT;
264 break;
265
5c05f062
LP
266 case ARG_MKDIR:
267 arg_flags |= DISSECT_IMAGE_MKDIR;
268 break;
269
270 case 'M':
271 /* Shortcut combination of the above two */
272 arg_action = ACTION_MOUNT;
273 arg_flags |= DISSECT_IMAGE_MKDIR;
274 break;
275
ac1f1adf
DDM
276 case 'u':
277 arg_action = ACTION_UMOUNT;
278 break;
279
280 case ARG_RMDIR:
281 arg_rmdir = true;
282 break;
283
284 case 'U':
285 /* Shortcut combination of the above two */
286 arg_action = ACTION_UMOUNT;
287 arg_rmdir = true;
288 break;
289
0cf16924
AAF
290 case 'l':
291 arg_action = ACTION_LIST;
292 arg_flags |= DISSECT_IMAGE_READ_ONLY;
293 break;
294
db02190e
LP
295 case ARG_MTREE:
296 arg_action = ACTION_MTREE;
297 arg_flags |= DISSECT_IMAGE_READ_ONLY;
298 break;
299
06186c4c
LP
300 case ARG_WITH:
301 arg_action = ACTION_WITH;
302 break;
303
33973b84
LP
304 case 'x':
305 arg_action = ACTION_COPY_FROM;
306 arg_flags |= DISSECT_IMAGE_READ_ONLY;
307 break;
308
309 case 'a':
310 arg_action = ACTION_COPY_TO;
311 break;
312
a2ea3b2f 313 case 'r':
18b5886e
LP
314 arg_flags |= DISSECT_IMAGE_READ_ONLY;
315 break;
316
971e2ef0
ZJS
317 case ARG_DISCARD: {
318 DissectImageFlags flags;
319
18b5886e 320 if (streq(optarg, "disabled"))
971e2ef0 321 flags = 0;
18b5886e 322 else if (streq(optarg, "loop"))
971e2ef0 323 flags = DISSECT_IMAGE_DISCARD_ON_LOOP;
18b5886e 324 else if (streq(optarg, "all"))
971e2ef0 325 flags = DISSECT_IMAGE_DISCARD_ON_LOOP | DISSECT_IMAGE_DISCARD;
18b5886e 326 else if (streq(optarg, "crypt"))
971e2ef0 327 flags = DISSECT_IMAGE_DISCARD_ANY;
140788f7
LP
328 else if (streq(optarg, "list")) {
329 puts("disabled\n"
330 "all\n"
331 "crypt\n"
332 "loop");
333 return 0;
334 } else
baaa35ad
ZJS
335 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
336 "Unknown --discard= parameter: %s",
337 optarg);
971e2ef0 338 arg_flags = (arg_flags & ~DISSECT_IMAGE_DISCARD_ANY) | flags;
18b5886e 339
a2ea3b2f 340 break;
971e2ef0 341 }
a2ea3b2f 342
4623e8e6 343 case ARG_ROOT_HASH: {
89e62e0b 344 _cleanup_free_ void *p = NULL;
4623e8e6
LP
345 size_t l;
346
347 r = unhexmem(optarg, strlen(optarg), &p, &l);
348 if (r < 0)
63cf2d75 349 return log_error_errno(r, "Failed to parse root hash '%s': %m", optarg);
89e62e0b
LP
350 if (l < sizeof(sd_id128_t))
351 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
352 "Root hash must be at least 128bit long: %s", optarg);
4623e8e6 353
89e62e0b
LP
354 free_and_replace(arg_verity_settings.root_hash, p);
355 arg_verity_settings.root_hash_size = l;
4623e8e6
LP
356 break;
357 }
358
c2923fdc
LB
359 case ARG_ROOT_HASH_SIG: {
360 char *value;
89e62e0b
LP
361 size_t l;
362 void *p;
c2923fdc
LB
363
364 if ((value = startswith(optarg, "base64:"))) {
c2923fdc
LB
365 r = unbase64mem(value, strlen(value), &p, &l);
366 if (r < 0)
367 return log_error_errno(r, "Failed to parse root hash signature '%s': %m", optarg);
c2923fdc 368 } else {
89e62e0b 369 r = read_full_file(optarg, (char**) &p, &l);
c2923fdc 370 if (r < 0)
89e62e0b 371 return log_error_errno(r, "Failed to read root hash signature file '%s': %m", optarg);
c2923fdc
LB
372 }
373
89e62e0b
LP
374 free_and_replace(arg_verity_settings.root_hash_sig, p);
375 arg_verity_settings.root_hash_sig_size = l;
c2923fdc
LB
376 break;
377 }
378
89e62e0b 379 case ARG_VERITY_DATA:
614b022c 380 r = parse_path_argument(optarg, false, &arg_verity_settings.data_path);
89e62e0b
LP
381 if (r < 0)
382 return r;
383 break;
384
e475f729
LP
385 case ARG_FSCK:
386 r = parse_boolean(optarg);
387 if (r < 0)
388 return log_error_errno(r, "Failed to parse --fsck= parameter: %s", optarg);
389
390 SET_FLAG(arg_flags, DISSECT_IMAGE_FSCK, r);
391 break;
392
74a54bae
LP
393 case ARG_GROWFS:
394 r = parse_boolean(optarg);
395 if (r < 0)
396 return log_error_errno(r, "Failed to parse --growfs= parameter: %s", optarg);
397
398 SET_FLAG(arg_flags, DISSECT_IMAGE_GROWFS, r);
399 break;
400
de8231b0 401 case ARG_JSON:
b1e8f46c 402 r = parse_json_argument(optarg, &arg_json_format_flags);
6a01ea4a
LP
403 if (r <= 0)
404 return r;
de8231b0
LP
405
406 break;
407
0305cf6e
LP
408 case ARG_DISCOVER:
409 arg_action = ACTION_DISCOVER;
410 break;
411
a2ea3b2f
LP
412 case '?':
413 return -EINVAL;
414
415 default:
04499a70 416 assert_not_reached();
a2ea3b2f 417 }
a2ea3b2f
LP
418 }
419
420 switch (arg_action) {
421
422 case ACTION_DISSECT:
baaa35ad
ZJS
423 if (optind + 1 != argc)
424 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
33973b84 425 "Expected an image file path as only argument.");
a2ea3b2f
LP
426
427 arg_image = argv[optind];
18b5886e 428 arg_flags |= DISSECT_IMAGE_READ_ONLY;
a2ea3b2f
LP
429 break;
430
431 case ACTION_MOUNT:
baaa35ad
ZJS
432 if (optind + 2 != argc)
433 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
33973b84 434 "Expected an image file path and mount point path as only arguments.");
a2ea3b2f
LP
435
436 arg_image = argv[optind];
437 arg_path = argv[optind + 1];
166ff731 438 arg_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
a2ea3b2f
LP
439 break;
440
ac1f1adf
DDM
441 case ACTION_UMOUNT:
442 if (optind + 1 != argc)
443 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
444 "Expected a mount point path as only argument.");
445
446 arg_path = argv[optind];
447 break;
448
0cf16924 449 case ACTION_LIST:
db02190e 450 case ACTION_MTREE:
0cf16924
AAF
451 if (optind + 1 != argc)
452 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
453 "Expected an image file path as only argument.");
454
455 arg_image = argv[optind];
456 arg_flags |= DISSECT_IMAGE_READ_ONLY | DISSECT_IMAGE_REQUIRE_ROOT;
457 break;
458
33973b84
LP
459 case ACTION_COPY_FROM:
460 if (argc < optind + 2 || argc > optind + 3)
461 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
462 "Expected an image file path, a source path and an optional destination path as only arguments.");
463
464 arg_image = argv[optind];
465 arg_source = argv[optind + 1];
466 arg_target = argc > optind + 2 ? argv[optind + 2] : "-" /* this means stdout */ ;
467
166ff731 468 arg_flags |= DISSECT_IMAGE_READ_ONLY | DISSECT_IMAGE_REQUIRE_ROOT;
33973b84
LP
469 break;
470
471 case ACTION_COPY_TO:
472 if (argc < optind + 2 || argc > optind + 3)
473 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
474 "Expected an image file path, an optional source path and a destination path as only arguments.");
475
476 arg_image = argv[optind];
477
478 if (argc > optind + 2) {
479 arg_source = argv[optind + 1];
480 arg_target = argv[optind + 2];
481 } else {
482 arg_source = "-"; /* this means stdin */
483 arg_target = argv[optind + 1];
484 }
485
166ff731 486 arg_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
33973b84
LP
487 break;
488
06186c4c
LP
489 case ACTION_WITH:
490 if (optind >= argc)
491 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
492 "Expected an image file path and an optional command line.");
493
494 arg_image = argv[optind];
495 if (argc > optind + 1) {
496 arg_argv = strv_copy(argv + optind + 1);
497 if (!arg_argv)
498 return log_oom();
499 }
500
501 break;
502
0305cf6e
LP
503 case ACTION_DISCOVER:
504 if (optind != argc)
505 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
506 "Expected no argument.");
507
508 break;
509
a2ea3b2f 510 default:
04499a70 511 assert_not_reached();
a2ea3b2f
LP
512 }
513
514 return 1;
515}
516
de8231b0
LP
517static int strv_pair_to_json(char **l, JsonVariant **ret) {
518 _cleanup_strv_free_ char **jl = NULL;
de8231b0
LP
519
520 STRV_FOREACH_PAIR(a, b, l) {
521 char *j;
522
523 j = strjoin(*a, "=", *b);
524 if (!j)
525 return log_oom();
526
527 if (strv_consume(&jl, j) < 0)
528 return log_oom();
529 }
530
531 return json_variant_new_array_strv(ret, jl);
532}
533
8570b98b 534static void strv_pair_print(char **l, const char *prefix) {
8570b98b
LP
535 assert(prefix);
536
7f5b2615 537 STRV_FOREACH_PAIR(p, q, l)
8570b98b
LP
538 if (p == l)
539 printf("%s %s=%s\n", prefix, *p, *q);
540 else
541 printf("%*s %s=%s\n", (int) strlen(prefix), "", *p, *q);
8570b98b
LP
542}
543
994c9c70
LP
544static int get_sysext_scopes(DissectedImage *m, char ***ret_scopes) {
545 _cleanup_strv_free_ char **l = NULL;
546 const char *e;
547
548 assert(m);
549 assert(ret_scopes);
550
551 /* If there's no extension-release file its not a system extension. Otherwise the SYSEXT_SCOPE field
552 * indicates which scope it is for — and it defaults to "system" + "portable" if unset. */
553
554 if (!m->extension_release) {
555 *ret_scopes = NULL;
556 return 0;
557 }
558
559 e = strv_env_pairs_get(m->extension_release, "SYSEXT_SCOPE");
560 if (e)
561 l = strv_split(e, WHITESPACE);
562 else
563 l = strv_new("system", "portable");
564 if (!l)
565 return -ENOMEM;
566
567 *ret_scopes = TAKE_PTR(l);
568 return 1;
569}
570
37e44c3f 571static int action_dissect(DissectedImage *m, LoopDevice *d) {
de8231b0 572 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
37e44c3f 573 _cleanup_(table_unrefp) Table *t = NULL;
cfb623b6 574 _cleanup_free_ char *bn = NULL;
de8231b0 575 uint64_t size = UINT64_MAX;
a2ea3b2f
LP
576 int r;
577
37e44c3f
LP
578 assert(m);
579 assert(d);
a2ea3b2f 580
cfb623b6
LP
581 r = path_extract_filename(arg_image, &bn);
582 if (r < 0)
583 return log_error_errno(r, "Failed to extract file name from image path '%s': %m", arg_image);
584
17547fb5 585 if (arg_json_format_flags & (JSON_FORMAT_OFF|JSON_FORMAT_PRETTY|JSON_FORMAT_PRETTY_AUTO))
384c2c32 586 pager_open(arg_pager_flags);
17547fb5 587
6a01ea4a 588 if (arg_json_format_flags & JSON_FORMAT_OFF)
5db8b0bc 589 printf(" Name: %s%s%s\n", ansi_highlight(), bn, ansi_normal());
a2ea3b2f 590
37e44c3f
LP
591 if (ioctl(d->fd, BLKGETSIZE64, &size) < 0)
592 log_debug_errno(errno, "Failed to query size of loopback device: %m");
2b59bf51
ZJS
593 else if (arg_json_format_flags & JSON_FORMAT_OFF)
594 printf(" Size: %s\n", FORMAT_BYTES(size));
a2ea3b2f 595
6a01ea4a 596 if (arg_json_format_flags & JSON_FORMAT_OFF)
de8231b0 597 putc('\n', stdout);
af8219d5 598
22847508 599 r = dissected_image_acquire_metadata(m, 0);
af8219d5
LP
600 if (r == -ENXIO)
601 return log_error_errno(r, "No root partition discovered.");
af8219d5
LP
602 if (r == -EUCLEAN)
603 return log_error_errno(r, "File system check of image failed.");
4f309abb
LP
604 if (r == -EMEDIUMTYPE)
605 log_warning_errno(r, "Not a valid OS image, no os-release file included. Proceeding anyway.");
606 else if (r == -EUNATCH)
af8219d5
LP
607 log_warning_errno(r, "OS image is encrypted, proceeding without showing OS image metadata.");
608 else if (r == -EBUSY)
609 log_warning_errno(r, "OS image is currently in use, proceeding without showing OS image metadata.");
610 else if (r < 0)
611 return log_error_errno(r, "Failed to acquire image metadata: %m");
6a01ea4a 612 else if (arg_json_format_flags & JSON_FORMAT_OFF) {
994c9c70
LP
613 _cleanup_strv_free_ char **sysext_scopes = NULL;
614
b387778c
LP
615 if (!sd_id128_is_null(m->image_uuid))
616 printf("Image UUID: %s\n", SD_ID128_TO_UUID_STRING(m->image_uuid));
617
af8219d5
LP
618 if (m->hostname)
619 printf(" Hostname: %s\n", m->hostname);
a2ea3b2f 620
af8219d5
LP
621 if (!sd_id128_is_null(m->machine_id))
622 printf("Machine ID: " SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(m->machine_id));
a1edd22e 623
8570b98b
LP
624 strv_pair_print(m->machine_info,
625 "Mach. Info:");
626 strv_pair_print(m->os_release,
627 "OS Release:");
fab22946
LP
628 strv_pair_print(m->initrd_release,
629 "initrd R.:");
8570b98b
LP
630 strv_pair_print(m->extension_release,
631 " Ext. Rel.:");
7718ac97 632
4f309abb
LP
633 if (m->hostname ||
634 !sd_id128_is_null(m->machine_id) ||
635 !strv_isempty(m->machine_info) ||
8570b98b 636 !strv_isempty(m->os_release) ||
fab22946 637 !strv_isempty(m->initrd_release) ||
8570b98b 638 !strv_isempty(m->extension_release))
4f309abb 639 putc('\n', stdout);
994c9c70
LP
640
641 printf(" Use As: %s bootable system for UEFI\n", COLOR_MARK_BOOL(m->partitions[PARTITION_ESP].found));
642
643 if (m->has_init_system >= 0)
644 printf(" %s bootable system for container\n", COLOR_MARK_BOOL(m->has_init_system));
645
646 printf(" %s portable service\n",
647 COLOR_MARK_BOOL(strv_env_pairs_get(m->os_release, "PORTABLE_PREFIXES")));
fab22946
LP
648 printf(" %s initrd\n",
649 COLOR_MARK_BOOL(!strv_isempty(m->initrd_release)));
994c9c70
LP
650
651 r = get_sysext_scopes(m, &sysext_scopes);
652 if (r < 0)
653 return log_error_errno(r, "Failed to parse SYSEXT_SCOPE: %m");
654
655 printf(" %s extension for system\n",
656 COLOR_MARK_BOOL(strv_contains(sysext_scopes, "system")));
657 printf(" %s extension for initrd\n",
658 COLOR_MARK_BOOL(strv_contains(sysext_scopes, "initrd")));
659 printf(" %s extension for portable service\n",
660 COLOR_MARK_BOOL(strv_contains(sysext_scopes, "portable")));
661
662 putc('\n', stdout);
4f309abb 663 } else {
fab22946 664 _cleanup_(json_variant_unrefp) JsonVariant *mi = NULL, *osr = NULL, *irdr = NULL, *exr = NULL;
994c9c70 665 _cleanup_strv_free_ char **sysext_scopes = NULL;
de8231b0
LP
666
667 if (!strv_isempty(m->machine_info)) {
668 r = strv_pair_to_json(m->machine_info, &mi);
669 if (r < 0)
670 return log_oom();
671 }
672
673 if (!strv_isempty(m->os_release)) {
674 r = strv_pair_to_json(m->os_release, &osr);
675 if (r < 0)
676 return log_oom();
677 }
678
fab22946
LP
679 if (!strv_isempty(m->initrd_release)) {
680 r = strv_pair_to_json(m->initrd_release, &irdr);
681 if (r < 0)
682 return log_oom();
683 }
684
7718ac97
LB
685 if (!strv_isempty(m->extension_release)) {
686 r = strv_pair_to_json(m->extension_release, &exr);
687 if (r < 0)
688 return log_oom();
689 }
690
994c9c70
LP
691 r = get_sysext_scopes(m, &sysext_scopes);
692 if (r < 0)
693 return log_error_errno(r, "Failed to parse SYSEXT_SCOPE: %m");
694
de8231b0 695 r = json_build(&v, JSON_BUILD_OBJECT(
cfb623b6 696 JSON_BUILD_PAIR("name", JSON_BUILD_STRING(bn)),
b387778c 697 JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(m->image_uuid), "imageUuid", JSON_BUILD_UUID(m->image_uuid)),
de8231b0
LP
698 JSON_BUILD_PAIR("size", JSON_BUILD_INTEGER(size)),
699 JSON_BUILD_PAIR_CONDITION(m->hostname, "hostname", JSON_BUILD_STRING(m->hostname)),
700 JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(m->machine_id), "machineId", JSON_BUILD_ID128(m->machine_id)),
701 JSON_BUILD_PAIR_CONDITION(mi, "machineInfo", JSON_BUILD_VARIANT(mi)),
7718ac97 702 JSON_BUILD_PAIR_CONDITION(osr, "osRelease", JSON_BUILD_VARIANT(osr)),
fab22946 703 JSON_BUILD_PAIR_CONDITION(osr, "initrdRelease", JSON_BUILD_VARIANT(irdr)),
994c9c70
LP
704 JSON_BUILD_PAIR_CONDITION(exr, "extensionRelease", JSON_BUILD_VARIANT(exr)),
705 JSON_BUILD_PAIR("useBootableUefi", JSON_BUILD_BOOLEAN(m->partitions[PARTITION_ESP].found)),
706 JSON_BUILD_PAIR_CONDITION(m->has_init_system >= 0, "useBootableContainer", JSON_BUILD_BOOLEAN(m->has_init_system)),
fab22946 707 JSON_BUILD_PAIR("useInitrd", JSON_BUILD_BOOLEAN(!strv_isempty(m->initrd_release))),
994c9c70
LP
708 JSON_BUILD_PAIR("usePortableService", JSON_BUILD_BOOLEAN(strv_env_pairs_get(m->os_release, "PORTABLE_MATCHES"))),
709 JSON_BUILD_PAIR("useSystemExtension", JSON_BUILD_BOOLEAN(strv_contains(sysext_scopes, "system"))),
710 JSON_BUILD_PAIR("useInitRDExtension", JSON_BUILD_BOOLEAN(strv_contains(sysext_scopes, "initrd"))),
711 JSON_BUILD_PAIR("usePortableExtension", JSON_BUILD_BOOLEAN(strv_contains(sysext_scopes, "portable")))));
de8231b0
LP
712 if (r < 0)
713 return log_oom();
714 }
715
ee8e497d 716 t = table_new("rw", "designator", "partition uuid", "partition label", "fstype", "architecture", "verity", "growfs", "node", "partno");
37e44c3f
LP
717 if (!t)
718 return log_oom();
a1edd22e 719
c8b62cf6 720 table_set_ersatz_string(t, TABLE_ERSATZ_DASH);
37e44c3f 721 (void) table_set_align_percent(t, table_get_cell(t, 0, 7), 100);
a2ea3b2f 722
569a0e42 723 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
37e44c3f 724 DissectedPartition *p = m->partitions + i;
89d00f2e 725
37e44c3f
LP
726 if (!p->found)
727 continue;
89d00f2e 728
37e44c3f
LP
729 r = table_add_many(
730 t,
731 TABLE_STRING, p->rw ? "rw" : "ro",
732 TABLE_STRING, partition_designator_to_string(i));
733 if (r < 0)
734 return table_log_add_error(r);
89d00f2e 735
37e44c3f
LP
736 if (sd_id128_is_null(p->uuid))
737 r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
738 else
739 r = table_add_cell(t, NULL, TABLE_UUID, &p->uuid);
740 if (r < 0)
741 return table_log_add_error(r);
89d00f2e 742
37e44c3f
LP
743 r = table_add_many(
744 t,
1474d7ac 745 TABLE_STRING, p->label,
37e44c3f
LP
746 TABLE_STRING, p->fstype,
747 TABLE_STRING, architecture_to_string(p->architecture));
748 if (r < 0)
749 return table_log_add_error(r);
750
89e62e0b 751 if (arg_verity_settings.data_path)
37e44c3f 752 r = table_add_cell(t, NULL, TABLE_STRING, "external");
49536766 753 else if (dissected_image_verity_candidate(m, i))
8ee9615e
LP
754 r = table_add_cell(t, NULL, TABLE_STRING,
755 dissected_image_verity_sig_ready(m, i) ? "signed" :
756 yes_no(dissected_image_verity_ready(m, i)));
37e44c3f
LP
757 else
758 r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
759 if (r < 0)
760 return table_log_add_error(r);
89d00f2e 761
ee8e497d
LP
762 r = table_add_many(t, TABLE_BOOLEAN, (int) p->growfs);
763 if (r < 0)
764 return table_log_add_error(r);
765
37e44c3f
LP
766 if (p->partno < 0) /* no partition table, naked file system */ {
767 r = table_add_cell(t, NULL, TABLE_STRING, arg_image);
89d00f2e
LP
768 if (r < 0)
769 return table_log_add_error(r);
770
37e44c3f
LP
771 r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
772 } else {
773 r = table_add_cell(t, NULL, TABLE_STRING, p->node);
89d00f2e
LP
774 if (r < 0)
775 return table_log_add_error(r);
776
37e44c3f
LP
777 r = table_add_cell(t, NULL, TABLE_INT, &p->partno);
778 }
779 if (r < 0)
780 return table_log_add_error(r);
781 }
89d00f2e 782
6a01ea4a 783 if (arg_json_format_flags & JSON_FORMAT_OFF) {
17547fb5
LP
784 (void) table_set_header(t, arg_legend);
785
786 r = table_print(t, NULL);
6a01ea4a
LP
787 if (r < 0)
788 return table_log_print_error(r);
789 } else {
de8231b0
LP
790 _cleanup_(json_variant_unrefp) JsonVariant *jt = NULL;
791
792 r = table_to_json(t, &jt);
793 if (r < 0)
794 return log_error_errno(r, "Failed to convert table to JSON: %m");
795
796 r = json_variant_set_field(&v, "mounts", jt);
797 if (r < 0)
798 return log_oom();
799
800 json_variant_dump(v, arg_json_format_flags, stdout, NULL);
de8231b0 801 }
89d00f2e 802
37e44c3f
LP
803 return 0;
804}
89d00f2e 805
37e44c3f 806static int action_mount(DissectedImage *m, LoopDevice *d) {
37e44c3f 807 int r;
89d00f2e 808
37e44c3f
LP
809 assert(m);
810 assert(d);
89d00f2e 811
37e44c3f
LP
812 r = dissected_image_decrypt_interactively(
813 m, NULL,
89e62e0b 814 &arg_verity_settings,
e330f97a 815 arg_flags);
37e44c3f
LP
816 if (r < 0)
817 return r;
89d00f2e 818
21b61b1d 819 r = dissected_image_mount_and_warn(m, arg_path, UID_INVALID, UID_INVALID, arg_flags);
37e44c3f 820 if (r < 0)
af187ab2 821 return r;
89d00f2e 822
41bc4849
LP
823 r = loop_device_flock(d, LOCK_UN);
824 if (r < 0)
825 return log_error_errno(r, "Failed to unlock loopback block device: %m");
826
3044d343
YW
827 r = dissected_image_relinquish(m);
828 if (r < 0)
829 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
a2ea3b2f 830
37e44c3f
LP
831 return 0;
832}
18b5886e 833
0cf16924
AAF
834static int list_print_item(
835 RecurseDirEvent event,
836 const char *path,
837 int dir_fd,
838 int inode_fd,
839 const struct dirent *de,
840 const struct statx *sx,
841 void *userdata) {
842
843 assert_se(path);
844
845 if (event == RECURSE_DIR_ENTER)
bb69ec95 846 printf("%s%s/%s\n", path, ansi_grey(), ansi_normal());
0cf16924
AAF
847 else if (event == RECURSE_DIR_ENTRY)
848 printf("%s\n", path);
849
850 return RECURSE_DIR_CONTINUE;
851}
852
db02190e
LP
853static int get_file_sha256(int inode_fd, uint8_t ret[static SHA256_DIGEST_SIZE]) {
854 _cleanup_close_ int fd = -1;
855 struct sha256_ctx ctx;
856
857 /* convert O_PATH fd into a regular one */
858 fd = fd_reopen(inode_fd, O_RDONLY|O_CLOEXEC);
859 if (fd < 0)
860 return fd;
861
862 /* Calculating the SHA sum might be slow, hence let's flush STDOUT first, to give user an idea where we are slow. */
863 fflush(stdout);
864
865 sha256_init_ctx(&ctx);
866
867 for (;;) {
868 uint8_t buffer[64 * 1024];
869 ssize_t n;
870
871 n = read(fd, buffer, sizeof(buffer));
872 if (n < 0)
873 return -errno;
874 if (n == 0)
875 break;
876
877 sha256_process_bytes(buffer, n, &ctx);
878 }
879
880 sha256_finish_ctx(&ctx, ret);
881 return 0;
882}
883
884static int mtree_print_item(
885 RecurseDirEvent event,
886 const char *path,
887 int dir_fd,
888 int inode_fd,
889 const struct dirent *de,
890 const struct statx *sx,
891 void *userdata) {
892
893 int r;
894
895 assert_se(path);
896 assert_se(sx);
897
898 if (IN_SET(event, RECURSE_DIR_ENTER, RECURSE_DIR_ENTRY)) {
899 _cleanup_free_ char *escaped = NULL;
900
901 if (isempty(path))
902 path = ".";
903 else {
904 /* BSD mtree uses either C or octal escaping, and covers whitespace, comments and glob characters. We use C style escaping and follow suit */
905 escaped = xescape(path, WHITESPACE COMMENTS GLOB_CHARS);
906 if (!escaped)
907 return log_oom();
908
909 path = escaped;
910 }
911
912 printf("%s", isempty(path) ? "." : path);
913
914 if (FLAGS_SET(sx->stx_mask, STATX_TYPE)) {
915 if (S_ISDIR(sx->stx_mode))
916 printf("%s/%s", ansi_grey(), ansi_normal());
917
918 printf(" %stype=%s%s%s%s",
919 ansi_grey(),
920 ansi_normal(),
921 S_ISDIR(sx->stx_mode) ? ansi_highlight_blue() :
922 S_ISLNK(sx->stx_mode) ? ansi_highlight_cyan() :
923 (S_ISFIFO(sx->stx_mode) || S_ISCHR(sx->stx_mode) || S_ISBLK(sx->stx_mode)) ? ansi_highlight_yellow4() :
924 S_ISSOCK(sx->stx_mode) ? ansi_highlight_magenta() : "",
925 ASSERT_PTR(S_ISDIR(sx->stx_mode) ? "dir" :
926 S_ISREG(sx->stx_mode) ? "file" :
927 S_ISLNK(sx->stx_mode) ? "link" :
928 S_ISFIFO(sx->stx_mode) ? "fifo" :
929 S_ISBLK(sx->stx_mode) ? "block" :
930 S_ISCHR(sx->stx_mode) ? "char" :
931 S_ISSOCK(sx->stx_mode) ? "socket" : NULL),
932 ansi_normal());
933 }
934
935 if (FLAGS_SET(sx->stx_mask, STATX_MODE) && (!FLAGS_SET(sx->stx_mask, STATX_TYPE) || !S_ISLNK(sx->stx_mode)))
936 printf(" %smode=%s%04o",
937 ansi_grey(),
938 ansi_normal(),
939 (unsigned) (sx->stx_mode & 0777));
940
941 if (FLAGS_SET(sx->stx_mask, STATX_UID))
942 printf(" %suid=%s" UID_FMT,
943 ansi_grey(),
944 ansi_normal(),
945 sx->stx_uid);
946
947 if (FLAGS_SET(sx->stx_mask, STATX_GID))
948 printf(" %sgid=%s" GID_FMT,
949 ansi_grey(),
950 ansi_normal(),
951 sx->stx_gid);
952
953 if (FLAGS_SET(sx->stx_mask, STATX_TYPE|STATX_SIZE) && S_ISREG(sx->stx_mode)) {
954 printf(" %ssize=%s%" PRIu64,
955 ansi_grey(),
956 ansi_normal(),
957 (uint64_t) sx->stx_size);
958
959 if (inode_fd >= 0 && sx->stx_size > 0) {
960 uint8_t hash[SHA256_DIGEST_SIZE];
961
962 r = get_file_sha256(inode_fd, hash);
963 if (r < 0)
964 log_warning_errno(r, "Failed to calculate file SHA256 sum for '%s', ignoring: %m", path);
965 else {
966 _cleanup_free_ char *h = NULL;
967
968 h = hexmem(hash, sizeof(hash));
969 if (!h)
970 return log_oom();
971
972 printf(" %ssha256sum=%s%s",
973 ansi_grey(),
974 ansi_normal(),
975 h);
976 }
977 }
978 }
979
980 if (FLAGS_SET(sx->stx_mask, STATX_TYPE) && S_ISLNK(sx->stx_mode) && inode_fd >= 0) {
981 _cleanup_free_ char *target = NULL;
982
983 r = readlinkat_malloc(inode_fd, "", &target);
984 if (r < 0)
985 log_warning_errno(r, "Failed to read symlink '%s', ignoring: %m", path);
986 else {
987 _cleanup_free_ char *target_escaped = NULL;
988
989 target_escaped = xescape(target, WHITESPACE COMMENTS GLOB_CHARS);
990 if (!target_escaped)
991 return log_oom();
992
993 printf(" %slink=%s%s",
994 ansi_grey(),
995 ansi_normal(),
996 target_escaped);
997 }
998 }
999
1000 if (FLAGS_SET(sx->stx_mask, STATX_TYPE) && (S_ISBLK(sx->stx_mode) || S_ISCHR(sx->stx_mode)))
1001 printf(" %sdevice=%slinux,%" PRIu64 ",%" PRIu64,
1002 ansi_grey(),
1003 ansi_normal(),
1004 (uint64_t) sx->stx_rdev_major,
1005 (uint64_t) sx->stx_rdev_minor);
1006
1007 printf("\n");
1008 }
1009
1010 return RECURSE_DIR_CONTINUE;
1011}
1012
1013static int action_list_or_mtree_or_copy(DissectedImage *m, LoopDevice *d) {
37e44c3f 1014 _cleanup_(umount_and_rmdir_and_freep) char *mounted_dir = NULL;
37e44c3f
LP
1015 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
1016 _cleanup_free_ char *temp = NULL;
1017 int r;
a2ea3b2f 1018
37e44c3f
LP
1019 assert(m);
1020 assert(d);
18b5886e 1021
37e44c3f
LP
1022 r = dissected_image_decrypt_interactively(
1023 m, NULL,
89e62e0b 1024 &arg_verity_settings,
e330f97a 1025 arg_flags);
37e44c3f
LP
1026 if (r < 0)
1027 return r;
a2ea3b2f 1028
37e44c3f
LP
1029 r = detach_mount_namespace();
1030 if (r < 0)
1031 return log_error_errno(r, "Failed to detach mount namespace: %m");
33973b84 1032
37e44c3f
LP
1033 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
1034 if (r < 0)
1035 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
33973b84 1036
37e44c3f
LP
1037 r = mkdir_p(temp, 0700);
1038 if (r < 0)
1039 return log_error_errno(r, "Failed to create mount point: %m");
33973b84 1040
37e44c3f
LP
1041 created_dir = TAKE_PTR(temp);
1042
21b61b1d 1043 r = dissected_image_mount_and_warn(m, created_dir, UID_INVALID, UID_INVALID, arg_flags);
37e44c3f 1044 if (r < 0)
af187ab2 1045 return r;
33973b84 1046
37e44c3f 1047 mounted_dir = TAKE_PTR(created_dir);
33973b84 1048
41bc4849
LP
1049 r = loop_device_flock(d, LOCK_UN);
1050 if (r < 0)
1051 return log_error_errno(r, "Failed to unlock loopback block device: %m");
1052
3044d343
YW
1053 r = dissected_image_relinquish(m);
1054 if (r < 0)
1055 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
33973b84 1056
37e44c3f
LP
1057 if (arg_action == ACTION_COPY_FROM) {
1058 _cleanup_close_ int source_fd = -1, target_fd = -1;
33973b84 1059
37e44c3f
LP
1060 source_fd = chase_symlinks_and_open(arg_source, mounted_dir, CHASE_PREFIX_ROOT|CHASE_WARN, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
1061 if (source_fd < 0)
1062 return log_error_errno(source_fd, "Failed to open source path '%s' in image '%s': %m", arg_source, arg_image);
1063
1064 /* Copying to stdout? */
1065 if (streq(arg_target, "-")) {
f5fbe71d 1066 r = copy_bytes(source_fd, STDOUT_FILENO, UINT64_MAX, COPY_REFLINK);
33973b84 1067 if (r < 0)
37e44c3f
LP
1068 return log_error_errno(r, "Failed to copy bytes from %s in mage '%s' to stdout: %m", arg_source, arg_image);
1069
38db55ab 1070 /* When we copy to stdout we don't copy any attributes (i.e. no access mode, no ownership, no xattr, no times) */
37e44c3f 1071 return 0;
33973b84
LP
1072 }
1073
37e44c3f 1074 /* Try to copy as directory? */
dd480f78 1075 r = copy_directory_fd(source_fd, arg_target, COPY_REFLINK|COPY_MERGE_EMPTY|COPY_SIGINT|COPY_HARDLINKS);
37e44c3f
LP
1076 if (r >= 0)
1077 return 0;
1078 if (r != -ENOTDIR)
1079 return log_error_errno(r, "Failed to copy %s in image '%s' to '%s': %m", arg_source, arg_image, arg_target);
1080
1081 r = fd_verify_regular(source_fd);
1082 if (r == -EISDIR)
1083 return log_error_errno(r, "Target '%s' exists already and is not a directory.", arg_target);
1084 if (r < 0)
1085 return log_error_errno(r, "Source path %s in image '%s' is neither regular file nor directory, refusing: %m", arg_source, arg_image);
33973b84 1086
37e44c3f
LP
1087 /* Nah, it's a plain file! */
1088 target_fd = open(arg_target, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
1089 if (target_fd < 0)
1090 return log_error_errno(errno, "Failed to create regular file at target path '%s': %m", arg_target);
33973b84 1091
f5fbe71d 1092 r = copy_bytes(source_fd, target_fd, UINT64_MAX, COPY_REFLINK);
37e44c3f
LP
1093 if (r < 0)
1094 return log_error_errno(r, "Failed to copy bytes from %s in mage '%s' to '%s': %m", arg_source, arg_image, arg_target);
33973b84 1095
23e026de 1096 (void) copy_xattr(source_fd, target_fd, 0);
37e44c3f
LP
1097 (void) copy_access(source_fd, target_fd);
1098 (void) copy_times(source_fd, target_fd, 0);
33973b84 1099
37e44c3f 1100 /* When this is a regular file we don't copy ownership! */
33973b84 1101
0cf16924 1102 } else if (arg_action == ACTION_COPY_TO) {
cfb623b6
LP
1103 _cleanup_close_ int source_fd = -1, target_fd = -1, dfd = -1;
1104 _cleanup_free_ char *dn = NULL, *bn = NULL;
33973b84 1105
45519d13
LP
1106 r = path_extract_directory(arg_target, &dn);
1107 if (r < 0)
cfb623b6
LP
1108 return log_error_errno(r, "Failed to extract directory from target path '%s': %m", arg_target);
1109 r = path_extract_filename(arg_target, &bn);
1110 if (r < 0)
1111 return log_error_errno(r, "Failed to extract filename from target path '%s': %m", arg_target);
37e44c3f
LP
1112
1113 r = chase_symlinks(dn, mounted_dir, CHASE_PREFIX_ROOT|CHASE_WARN, NULL, &dfd);
1114 if (r < 0)
1115 return log_error_errno(r, "Failed to open '%s': %m", dn);
33973b84 1116
37e44c3f
LP
1117 /* Are we reading from stdin? */
1118 if (streq(arg_source, "-")) {
cfb623b6 1119 target_fd = openat(dfd, bn, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_EXCL, 0644);
33973b84 1120 if (target_fd < 0)
37e44c3f 1121 return log_error_errno(errno, "Failed to open target file '%s': %m", arg_target);
33973b84 1122
f5fbe71d 1123 r = copy_bytes(STDIN_FILENO, target_fd, UINT64_MAX, COPY_REFLINK);
33973b84 1124 if (r < 0)
37e44c3f 1125 return log_error_errno(r, "Failed to copy bytes from stdin to '%s' in image '%s': %m", arg_target, arg_image);
33973b84 1126
37e44c3f
LP
1127 /* When we copy from stdin we don't copy any attributes (i.e. no access mode, no ownership, no xattr, no times) */
1128 return 0;
1129 }
33973b84 1130
37e44c3f
LP
1131 source_fd = open(arg_source, O_RDONLY|O_CLOEXEC|O_NOCTTY);
1132 if (source_fd < 0)
1133 return log_error_errno(source_fd, "Failed to open source path '%s': %m", arg_source);
33973b84 1134
37e44c3f
LP
1135 r = fd_verify_regular(source_fd);
1136 if (r < 0) {
1137 if (r != -EISDIR)
1138 return log_error_errno(r, "Source '%s' is neither regular file nor directory: %m", arg_source);
33973b84 1139
37e44c3f 1140 /* We are looking at a directory. */
33973b84 1141
cfb623b6 1142 target_fd = openat(dfd, bn, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
37e44c3f
LP
1143 if (target_fd < 0) {
1144 if (errno != ENOENT)
1145 return log_error_errno(errno, "Failed to open destination '%s': %m", arg_target);
33973b84 1146
a424958a 1147 r = copy_tree_at(source_fd, ".", dfd, bn, UID_INVALID, GID_INVALID, COPY_REFLINK|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS, NULL);
37e44c3f 1148 } else
a424958a 1149 r = copy_tree_at(source_fd, ".", target_fd, ".", UID_INVALID, GID_INVALID, COPY_REFLINK|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS, NULL);
33973b84 1150 if (r < 0)
37e44c3f 1151 return log_error_errno(r, "Failed to copy '%s' to '%s' in image '%s': %m", arg_source, arg_target, arg_image);
33973b84 1152
37e44c3f
LP
1153 return 0;
1154 }
33973b84 1155
37e44c3f
LP
1156 /* We area looking at a regular file */
1157 target_fd = openat(dfd, basename(arg_target), O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_EXCL, 0600);
1158 if (target_fd < 0)
1159 return log_error_errno(errno, "Failed to open target file '%s': %m", arg_target);
33973b84 1160
f5fbe71d 1161 r = copy_bytes(source_fd, target_fd, UINT64_MAX, COPY_REFLINK);
37e44c3f
LP
1162 if (r < 0)
1163 return log_error_errno(r, "Failed to copy bytes from '%s' to '%s' in image '%s': %m", arg_source, arg_target, arg_image);
33973b84 1164
23e026de 1165 (void) copy_xattr(source_fd, target_fd, 0);
37e44c3f
LP
1166 (void) copy_access(source_fd, target_fd);
1167 (void) copy_times(source_fd, target_fd, 0);
33973b84 1168
37e44c3f 1169 /* When this is a regular file we don't copy ownership! */
0cf16924
AAF
1170
1171 } else {
1172 _cleanup_close_ int dfd = -1;
0cf16924 1173
0cf16924
AAF
1174 dfd = open(mounted_dir, O_DIRECTORY|O_CLOEXEC|O_RDONLY);
1175 if (dfd < 0)
1176 return log_error_errno(errno, "Failed to open mount directory: %m");
1177
2e1f76f6
LP
1178 pager_open(arg_pager_flags);
1179
db02190e
LP
1180 if (arg_action == ACTION_LIST)
1181 r = recurse_dir(dfd, NULL, 0, UINT_MAX, RECURSE_DIR_SORT, list_print_item, NULL);
1182 else if (arg_action == ACTION_MTREE)
1183 r = recurse_dir(dfd, ".", STATX_TYPE|STATX_MODE|STATX_UID|STATX_GID|STATX_SIZE, UINT_MAX, RECURSE_DIR_SORT|RECURSE_DIR_INODE_FD|RECURSE_DIR_TOPLEVEL, mtree_print_item, NULL);
1184 else
1185 assert_not_reached();
0cf16924
AAF
1186 if (r < 0)
1187 return log_error_errno(r, "Failed to list image: %m");
37e44c3f 1188 }
33973b84 1189
37e44c3f
LP
1190 return 0;
1191}
33973b84 1192
ac1f1adf
DDM
1193static int action_umount(const char *path) {
1194 _cleanup_close_ int fd = -1;
040d3439 1195 _cleanup_free_ char *canonical = NULL;
ac1f1adf 1196 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
040d3439 1197 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
e8383058 1198 int r;
ac1f1adf
DDM
1199
1200 fd = chase_symlinks_and_open(path, NULL, 0, O_DIRECTORY, &canonical);
1201 if (fd == -ENOTDIR)
1202 return log_error_errno(SYNTHETIC_ERRNO(ENOTDIR), "'%s' is not a directory", path);
1203 if (fd < 0)
1204 return log_error_errno(fd, "Failed to resolve path '%s': %m", path);
1205
1206 r = fd_is_mount_point(fd, NULL, 0);
1207 if (r == 0)
1208 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "'%s' is not a mount point", canonical);
1209 if (r < 0)
1210 return log_error_errno(r, "Failed to determine whether '%s' is a mount point: %m", canonical);
1211
040d3439 1212 r = block_device_new_from_fd(fd, BLOCK_DEVICE_LOOKUP_WHOLE_DISK | BLOCK_DEVICE_LOOKUP_BACKING, &dev);
41a95b18
YW
1213 if (r < 0) {
1214 _cleanup_close_ int usr_fd = -1;
1215
1216 /* The command `systemd-dissect --mount` expects that the image at least has the root or /usr
1217 * partition. If it does not have the root partition, then we mount the /usr partition on a
1218 * tmpfs. Hence, let's try to find the backing block device through the /usr partition. */
1219
1220 usr_fd = openat(fd, "usr", O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW);
1221 if (usr_fd < 0)
1222 return log_error_errno(errno, "Failed to open '%s/usr': %m", canonical);
1223
1224 r = block_device_new_from_fd(usr_fd, BLOCK_DEVICE_LOOKUP_WHOLE_DISK | BLOCK_DEVICE_LOOKUP_BACKING, &dev);
1225 }
ac1f1adf
DDM
1226 if (r < 0)
1227 return log_error_errno(r, "Failed to find backing block device for '%s': %m", canonical);
1228
040d3439 1229 r = loop_device_open(dev, 0, LOCK_EX, &d);
ac1f1adf 1230 if (r < 0)
040d3439 1231 return log_device_error_errno(dev, r, "Failed to open loopback block device: %m");
ac1f1adf 1232
ac1f1adf
DDM
1233 /* We've locked the loop device, now we're ready to unmount. To allow the unmount to succeed, we have
1234 * to close the O_PATH fd we opened earlier. */
1235 fd = safe_close(fd);
1236
1237 r = umount_recursive(canonical, 0);
1238 if (r < 0)
1239 return log_error_errno(r, "Failed to unmount '%s': %m", canonical);
1240
1241 /* We managed to lock and unmount successfully? That means we can try to remove the loop device.*/
1242 loop_device_unrelinquish(d);
1243
1244 if (arg_rmdir) {
e8383058
LP
1245 r = RET_NERRNO(rmdir(canonical));
1246 if (r < 0)
1247 return log_error_errno(r, "Failed to remove mount directory '%s': %m", canonical);
ac1f1adf 1248 }
ac1f1adf 1249
e8383058 1250 return 0;
ac1f1adf
DDM
1251}
1252
06186c4c
LP
1253static int action_with(DissectedImage *m, LoopDevice *d) {
1254 _cleanup_(umount_and_rmdir_and_freep) char *mounted_dir = NULL;
1255 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
1256 _cleanup_free_ char *temp = NULL;
1257 int r, rcode;
1258
1259 r = dissected_image_decrypt_interactively(
1260 m, NULL,
1261 &arg_verity_settings,
1262 arg_flags);
1263 if (r < 0)
1264 return r;
1265
1266 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
1267 if (r < 0)
1268 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
1269
1270 r = mkdir_p(temp, 0700);
1271 if (r < 0)
1272 return log_error_errno(r, "Failed to create mount point: %m");
1273
1274 created_dir = TAKE_PTR(temp);
1275
1276 r = dissected_image_mount_and_warn(m, created_dir, UID_INVALID, UID_INVALID, arg_flags);
1277 if (r < 0)
1278 return r;
1279
1280 mounted_dir = TAKE_PTR(created_dir);
1281
1282 r = dissected_image_relinquish(m);
1283 if (r < 0)
1284 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
1285
1286 r = loop_device_flock(d, LOCK_UN);
1287 if (r < 0)
1288 return log_error_errno(r, "Failed to unlock loopback block device: %m");
1289
1290 rcode = safe_fork("(with)", FORK_CLOSE_ALL_FDS|FORK_LOG|FORK_WAIT, NULL);
1291 if (rcode == 0) {
1292 /* Child */
1293
1294 if (chdir(mounted_dir) < 0) {
1295 log_error_errno(errno, "Failed to change to '%s' directory: %m", mounted_dir);
1296 _exit(EXIT_FAILURE);
1297 }
1298
1299 if (setenv("SYSTEMD_DISSECT_ROOT", mounted_dir, /* overwrite= */ true) < 0) {
1300 log_error_errno(errno, "Failed to set $SYSTEMD_DISSECT_ROOT: %m");
1301 _exit(EXIT_FAILURE);
1302 }
1303
1304 if (strv_isempty(arg_argv)) {
1305 const char *sh;
1306
1307 sh = secure_getenv("SHELL");
1308 if (sh) {
1309 execvp(sh, STRV_MAKE(sh));
1310 log_warning_errno(errno, "Failed to execute $SHELL, falling back to /bin/sh: %m");
1311 }
1312
1313 execl("/bin/sh", "sh", NULL);
1314 log_error_errno(errno, "Failed to invoke /bin/sh: %m");
1315 } else {
1316 execvp(arg_argv[0], arg_argv);
1317 log_error_errno(errno, "Failed to execute '%s': %m", arg_argv[0]);
1318 }
1319
1320 _exit(EXIT_FAILURE);
1321 }
1322
1323 /* Let's manually detach everything, to make things synchronous */
1324 r = loop_device_flock(d, LOCK_SH);
1325 if (r < 0)
1326 log_warning_errno(r, "Failed to lock loopback block device, ignoring: %m");
1327
1328 r = umount_recursive(mounted_dir, 0);
1329 if (r < 0)
1330 log_warning_errno(r, "Failed to unmount '%s', ignoring: %m", mounted_dir);
1331 else
1332 loop_device_unrelinquish(d); /* Let's try to destroy the loopback device */
1333
1334 created_dir = TAKE_PTR(mounted_dir);
1335
1336 if (rmdir(created_dir) < 0)
1337 log_warning_errno(r, "Failed to remove directory '%s', ignoring: %m", created_dir);
1338
1339 temp = TAKE_PTR(created_dir);
1340
1341 return rcode;
1342}
1343
0305cf6e
LP
1344static int action_discover(void) {
1345 _cleanup_(hashmap_freep) Hashmap *images = NULL;
1346 _cleanup_(table_unrefp) Table *t = NULL;
1347 Image *img;
1348 int r;
1349
1350 images = hashmap_new(&image_hash_ops);
1351 if (!images)
1352 return log_oom();
1353
1354 for (ImageClass cl = 0; cl < _IMAGE_CLASS_MAX; cl++) {
1355 r = image_discover(cl, NULL, images);
1356 if (r < 0)
1357 return log_error_errno(r, "Failed to discover images: %m");
1358 }
1359
1360 if ((arg_json_format_flags & JSON_FORMAT_OFF) && hashmap_isempty(images)) {
1361 log_info("No images found.");
1362 return 0;
1363 }
1364
1365 t = table_new("name", "type", "class", "ro", "path", "time", "usage");
1366 if (!t)
1367 return log_oom();
1368
1369 HASHMAP_FOREACH(img, images) {
1370
1371 if (!IN_SET(img->type, IMAGE_RAW, IMAGE_BLOCK))
1372 continue;
1373
1374 r = table_add_many(
1375 t,
1376 TABLE_STRING, img->name,
1377 TABLE_STRING, image_type_to_string(img->type),
1378 TABLE_STRING, image_class_to_string(img->class),
1379 TABLE_BOOLEAN, img->read_only,
1380 TABLE_PATH, img->path,
1381 TABLE_TIMESTAMP, img->mtime != 0 ? img->mtime : img->crtime,
1382 TABLE_SIZE, img->usage);
1383 if (r < 0)
1384 return table_log_add_error(r);
1385 }
1386
1387 (void) table_set_sort(t, (size_t) 0);
1388
1389 return table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
1390}
1391
37e44c3f
LP
1392static int run(int argc, char *argv[]) {
1393 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
1394 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
1395 int r;
33973b84 1396
5acb31a6 1397 log_setup();
33973b84 1398
37e44c3f
LP
1399 r = parse_argv(argc, argv);
1400 if (r <= 0)
1401 return r;
33973b84 1402
ac1f1adf
DDM
1403 if (arg_action == ACTION_UMOUNT)
1404 return action_umount(arg_path);
0305cf6e
LP
1405 if (arg_action == ACTION_DISCOVER)
1406 return action_discover();
ac1f1adf 1407
89e62e0b
LP
1408 r = verity_settings_load(
1409 &arg_verity_settings,
1410 arg_image, NULL, NULL);
37e44c3f
LP
1411 if (r < 0)
1412 return log_error_errno(r, "Failed to read verity artifacts for %s: %m", arg_image);
33973b84 1413
89e62e0b
LP
1414 if (arg_verity_settings.data_path)
1415 arg_flags |= DISSECT_IMAGE_NO_PARTITION_TABLE; /* We only support Verity per file system,
1416 * hence if there's external Verity data
1417 * available we turn off partition table
1418 * support */
1419
37e44c3f
LP
1420 r = loop_device_make_by_path(
1421 arg_image,
ef9c184d 1422 FLAGS_SET(arg_flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : O_RDWR,
89e62e0b 1423 FLAGS_SET(arg_flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
7f52206a 1424 LOCK_SH,
37e44c3f
LP
1425 &d);
1426 if (r < 0)
7b87fe4c 1427 return log_error_errno(r, "Failed to set up loopback device for %s: %m", arg_image);
33973b84 1428
bad31660 1429 r = dissect_loop_device_and_warn(
bad31660 1430 d,
89e62e0b 1431 &arg_verity_settings,
37e44c3f
LP
1432 NULL,
1433 arg_flags,
1434 &m);
1435 if (r < 0)
1436 return r;
33973b84 1437
88b3300f
LP
1438 r = dissected_image_load_verity_sig_partition(
1439 m,
1440 d->fd,
1441 &arg_verity_settings);
1442 if (r < 0)
738edfe6 1443 return log_error_errno(r, "Failed to load verity signature partition: %m");
88b3300f 1444
37e44c3f 1445 switch (arg_action) {
33973b84 1446
37e44c3f
LP
1447 case ACTION_DISSECT:
1448 r = action_dissect(m, d);
1449 break;
1450
1451 case ACTION_MOUNT:
1452 r = action_mount(m, d);
1453 break;
1454
0cf16924 1455 case ACTION_LIST:
db02190e 1456 case ACTION_MTREE:
37e44c3f
LP
1457 case ACTION_COPY_FROM:
1458 case ACTION_COPY_TO:
db02190e 1459 r = action_list_or_mtree_or_copy(m, d);
33973b84 1460 break;
33973b84 1461
06186c4c
LP
1462 case ACTION_WITH:
1463 r = action_with(m, d);
1464 break;
1465
a2ea3b2f 1466 default:
04499a70 1467 assert_not_reached();
a2ea3b2f
LP
1468 }
1469
37e44c3f 1470 return r;
a2ea3b2f 1471}
149afb45
YW
1472
1473DEFINE_MAIN_FUNCTION(run);