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