Debian Codegraph @

src/dissect/dissect.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <linux/loop.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <sys/file.h>
8 #include <unistd.h>
9
10 #include "sd-device.h"
11
12 #include "architecture.h"
13 #include "argv-util.h"
14 #include "blockdev-util.h"
15 #include "build.h"
16 #include "capability-util.h"
17 #include "chase.h"
18 #include "copy.h"
19 #include "device-util.h"
20 #include "discover-image.h"
21 #include "dissect-image.h"
22 #include "env-util.h"
23 #include "errno-util.h"
24 #include "escape.h"
25 #include "extract-word.h"
26 #include "fd-util.h"
27 #include "fileio.h"
28 #include "format-table.h"
29 #include "format-util.h"
30 #include "fs-util.h"
31 #include "hashmap.h"
32 #include "hexdecoct.h"
33 #include "image-policy.h"
34 #include "json-util.h"
35 #include "libarchive-util.h"
36 #include "log.h"
37 #include "loop-util.h"
38 #include "main-func.h"
39 #include "mkdir.h"
40 #include "mount-util.h"
41 #include "mountpoint-util.h"
42 #include "namespace-util.h"
43 #include "nsresource.h"
44 #include "options.h"
45 #include "parse-argument.h"
46 #include "parse-util.h"
47 #include "path-util.h"
48 #include "pretty-print.h"
49 #include "process-util.h"
50 #include "recurse-dir.h"
51 #include "runtime-scope.h"
52 #include "sha256.h"
53 #include "shift-uid.h"
54 #include "stat-util.h"
55 #include "string-util.h"
56 #include "strv.h"
57 #include "tar-util.h"
58 #include "terminal-util.h"
59 #include "tmpfile-util.h"
60 #include "uid-classification.h"
61 #include "user-util.h"
62 #include "vpick.h"
63
64 static enum {
65 ACTION_DISSECT,
66 ACTION_MOUNT,
67 ACTION_UMOUNT,
68 ACTION_ATTACH,
69 ACTION_DETACH,
70 ACTION_LIST,
71 ACTION_MTREE,
72 ACTION_WITH,
73 ACTION_COPY_FROM,
74 ACTION_COPY_TO,
75 ACTION_DISCOVER,
76 ACTION_VALIDATE,
77 ACTION_MAKE_ARCHIVE,
78 ACTION_SHIFT,
79 } arg_action = ACTION_DISSECT;
80 static char *arg_image = NULL;
81 static char *arg_root = NULL;
82 static char *arg_path = NULL;
83 static const char *arg_source = NULL;
84 static const char *arg_target = NULL;
85 static DissectImageFlags arg_flags =
86 DISSECT_IMAGE_GENERIC_ROOT |
87 DISSECT_IMAGE_DISCARD_ON_LOOP |
88 DISSECT_IMAGE_RELAX_VAR_CHECK |
89 DISSECT_IMAGE_FSCK |
90 DISSECT_IMAGE_USR_NO_ROOT |
91 DISSECT_IMAGE_GROWFS |
92 DISSECT_IMAGE_PIN_PARTITION_DEVICES |
93 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
94 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
95 static VeritySettings arg_verity_settings = VERITY_SETTINGS_DEFAULT;
96 static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
97 static PagerFlags arg_pager_flags = 0;
98 static bool arg_legend = true;
99 static bool arg_rmdir = false;
100 static bool arg_in_memory = false;
101 static char **arg_argv = NULL;
102 static char *arg_loop_ref = NULL;
103 static bool arg_loop_ref_auto = false;
104 static ImagePolicy *arg_image_policy = NULL;
105 static bool arg_mtree_hash = true;
106 static bool arg_via_service = false;
107 static RuntimeScope arg_runtime_scope = _RUNTIME_SCOPE_INVALID;
108 static bool arg_all = false;
109 static uid_t arg_uid_base = UID_INVALID;
110 static bool arg_quiet = false;
111 static ImageFilter *arg_image_filter = NULL;
112 static int arg_copy_ownership = -1;
113
114 STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
115 STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
116 STATIC_DESTRUCTOR_REGISTER(arg_path, freep);
117 STATIC_DESTRUCTOR_REGISTER(arg_verity_settings, verity_settings_done);
118 STATIC_DESTRUCTOR_REGISTER(arg_argv, strv_freep);
119 STATIC_DESTRUCTOR_REGISTER(arg_loop_ref, freep);
120 STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
121 STATIC_DESTRUCTOR_REGISTER(arg_image_filter, image_filter_freep);
122
123 static int help(void) {
124 _cleanup_free_ char *link = NULL;
125 _cleanup_(table_unrefp) Table *options = NULL, *commands = NULL;
126 int r;
127
128 pager_open(arg_pager_flags);
129
130 r = terminal_urlify_man("systemd-dissect", "1", &link);
131 if (r < 0)
132 return log_oom();
133
134 r = option_parser_get_help_table_ns("systemd-dissect", &options);
135 if (r < 0)
136 return r;
137
138 r = option_parser_get_help_table_full("systemd-dissect", "Commands", &commands);
139 if (r < 0)
140 return r;
141
142 /* Make the 1st column same width in both tables */
143 (void) table_sync_column_widths(0, options, commands);
144
145 printf("%1$s [OPTIONS...] IMAGE\n"
146 "%1$s [OPTIONS...] --mount IMAGE PATH\n"
147 "%1$s [OPTIONS...] --umount PATH\n"
148 "%1$s [OPTIONS...] --attach IMAGE\n"
149 "%1$s [OPTIONS...] --detach PATH\n"
150 "%1$s [OPTIONS...] --list IMAGE\n"
151 "%1$s [OPTIONS...] --mtree IMAGE\n"
152 "%1$s [OPTIONS...] --with IMAGE [COMMAND…]\n"
153 "%1$s [OPTIONS...] --copy-from IMAGE PATH [TARGET]\n"
154 "%1$s [OPTIONS...] --copy-to IMAGE [SOURCE] PATH\n"
155 "%1$s [OPTIONS...] --make-archive IMAGE [TARGET]\n"
156 "%1$s [OPTIONS...] --discover\n"
157 "%1$s [OPTIONS...] --validate IMAGE\n"
158 "%1$s [OPTIONS...] --shift IMAGE UIDBASE\n"
159 "\n%2$sDissect a Discoverable Disk Image (DDI).%3$s\n"
160 "\n%4$sOptions:%5$s\n",
161 program_invocation_short_name,
162 ansi_highlight(),
163 ansi_normal(),
164 ansi_underline(),
165 ansi_normal());
166
167 r = table_print_or_warn(options);
168 if (r < 0)
169 return r;
170
171 printf("\n%sCommands:%s\n", ansi_underline(), ansi_normal());
172
173 r = table_print_or_warn(commands);
174 if (r < 0)
175 return r;
176
177 printf("\nSee the %s for details.\n", link);
178 return 0;
179 }
180
181 static int parse_image_path_argument(const char *path, char **ret_root, char **ret_image) {
182 _cleanup_free_ char *p = NULL;
183 struct stat st;
184 int r;
185
186 assert(ret_image);
187
188 r = parse_path_argument(path, /* suppress_root= */ false, &p);
189 if (r < 0)
190 return r;
191
192 /* If we got a sysfs path (e.g. from a udev-instantiated template unit's %f specifier),
193 * resolve it to the corresponding devnode. */
194 if (path_startswith(p, "/sys/")) {
195 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
196 const char *devname;
197
198 r = sd_device_new_from_syspath(&dev, p);
199 if (r < 0)
200 return log_error_errno(r, "Failed to get device from syspath '%s': %m", p);
201
202 r = sd_device_get_devname(dev, &devname);
203 if (r < 0)
204 return log_error_errno(r, "Failed to get devname for '%s': %m", p);
205
206 r = free_and_strdup(&p, devname);
207 if (r < 0)
208 return log_oom();
209 }
210
211 if (stat(p, &st) < 0)
212 return log_error_errno(errno, "Failed to stat %s: %m", p);
213
214 if (S_ISDIR(st.st_mode)) {
215 if (!ret_root)
216 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "%s is not an image file.", p);
217
218 *ret_root = TAKE_PTR(p);
219 } else
220 *ret_image = TAKE_PTR(p);
221
222 return 0;
223 }
224
225 static int parse_argv(int argc, char *argv[]) {
226 bool system_scope_requested = false, user_scope_requested = false;
227 int r;
228
229 assert(argc >= 0);
230 assert(argv);
231
232 OptionParser opts = { argc, argv, .namespace = "systemd-dissect" };
233
234 FOREACH_OPTION_OR_RETURN(c, &opts)
235 switch (c) {
236
237 OPTION_NAMESPACE("systemd-dissect"): {}
238
239 OPTION_COMMON_NO_PAGER:
240 arg_pager_flags |= PAGER_DISABLE;
241 break;
242
243 OPTION_COMMON_NO_LEGEND:
244 arg_legend = false;
245 break;
246
247 OPTION_LONG("mkdir", NULL, "Make mount directory before mounting, if missing"):
248 arg_flags |= DISSECT_IMAGE_MKDIR;
249 break;
250
251 OPTION_LONG("rmdir", NULL, "Remove mount directory after unmounting"):
252 arg_rmdir = true;
253 break;
254
255 OPTION('r', "read-only", NULL, "Mount read-only"):
256 arg_flags |= DISSECT_IMAGE_READ_ONLY;
257 break;
258
259 OPTION_LONG("discard", "MODE", "Choose discard mode (disabled, loop, all, crypto)"): {
260 DissectImageFlags flags;
261
262 if (streq(opts.arg, "disabled"))
263 flags = 0;
264 else if (streq(opts.arg, "loop"))
265 flags = DISSECT_IMAGE_DISCARD_ON_LOOP;
266 else if (streq(opts.arg, "all"))
267 flags = DISSECT_IMAGE_DISCARD_ON_LOOP | DISSECT_IMAGE_DISCARD;
268 else if (streq(opts.arg, "crypt"))
269 flags = DISSECT_IMAGE_DISCARD_ANY;
270 else if (streq(opts.arg, "list")) {
271 puts("disabled\n"
272 "all\n"
273 "crypt\n"
274 "loop");
275 return 0;
276 } else
277 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
278 "Unknown --discard= parameter: %s", opts.arg);
279 arg_flags = (arg_flags & ~DISSECT_IMAGE_DISCARD_ANY) | flags;
280
281 break;
282 }
283
284 OPTION_LONG("in-memory", NULL, "Copy image into memory"):
285 arg_in_memory = true;
286 break;
287
288 OPTION_LONG("root-hash", "HASH", "Specify root hash for verity"): {}
289 OPTION_LONG("usr-hash", "HASH", "Same, but for the usr partition"): {
290 _cleanup_(iovec_done) struct iovec roothash = {};
291
292 PartitionDesignator d = streq(opts.opt->long_code, "root-hash") ? PARTITION_ROOT : PARTITION_USR;
293 if (arg_verity_settings.designator >= 0 &&
294 arg_verity_settings.designator != d)
295 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
296 "Cannot combine --root-hash=/--root-hash-sig= and --usr-hash=/--usr-hash-sig= options.");
297
298 r = unhexmem(opts.arg, &roothash.iov_base, &roothash.iov_len);
299 if (r < 0)
300 return log_error_errno(r, "Failed to parse root hash '%s': %m", opts.arg);
301 if (roothash.iov_len < sizeof(sd_id128_t))
302 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
303 "Root hash must be at least 128-bit long: %s", opts.arg);
304
305 iovec_done(&arg_verity_settings.root_hash);
306 arg_verity_settings.root_hash = TAKE_STRUCT(roothash);
307 arg_verity_settings.designator = d;
308 break;
309 }
310
311 OPTION_LONG("root-hash-sig", "SIG",
312 "Specify signature of root hash for verity as DER-encoded PKCS7, "
313 "either as a path to a file or as an ASCII base64-encoded string "
314 "prefixed by 'base64:'"): {}
315 OPTION_LONG("usr-hash-sig", "SIG", "Same, but for the usr partition"): {
316 const char *value;
317 _cleanup_(iovec_done) struct iovec sig = {};
318
319 PartitionDesignator d = streq(opts.opt->long_code, "root-hash-sig") ? PARTITION_ROOT : PARTITION_USR;
320 if (arg_verity_settings.designator >= 0 &&
321 arg_verity_settings.designator != d)
322 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
323 "Cannot combine --root-hash=/--root-hash-sig= and --usr-hash=/--usr-hash-sig= options.");
324
325 if ((value = startswith(opts.arg, "base64:"))) {
326 r = unbase64mem(value, &sig.iov_base, &sig.iov_len);
327 if (r < 0)
328 return log_error_errno(r, "Failed to parse root hash signature '%s': %m", opts.arg);
329 } else {
330 r = read_full_file(opts.arg, (char**) &sig.iov_base, &sig.iov_len);
331 if (r < 0)
332 return log_error_errno(r, "Failed to read root hash signature file '%s': %m", opts.arg);
333 }
334
335 iovec_done(&arg_verity_settings.root_hash_sig);
336 arg_verity_settings.root_hash_sig = TAKE_STRUCT(sig);
337 arg_verity_settings.designator = d;
338 break;
339 }
340
341 OPTION_LONG("verity-data", "PATH",
342 "Specify data file with hash tree for verity if it is not embedded in IMAGE"):
343 r = parse_path_argument(opts.arg, false, &arg_verity_settings.data_path);
344 if (r < 0)
345 return r;
346 break;
347
348 OPTION_LONG("fsck", "BOOL", "Run fsck before mounting"):
349 r = parse_boolean(opts.arg);
350 if (r < 0)
351 return log_error_errno(r, "Failed to parse --fsck= parameter: %s", opts.arg);
352
353 SET_FLAG(arg_flags, DISSECT_IMAGE_FSCK, r);
354 break;
355
356 OPTION_LONG("growfs", "BOOL", "Grow file system to partition size, if marked"):
357 r = parse_boolean(opts.arg);
358 if (r < 0)
359 return log_error_errno(r, "Failed to parse --growfs= parameter: %s", opts.arg);
360
361 SET_FLAG(arg_flags, DISSECT_IMAGE_GROWFS, r);
362 break;
363
364 OPTION_COMMON_JSON:
365 r = parse_json_argument(opts.arg, &arg_json_format_flags);
366 if (r <= 0)
367 return r;
368 break;
369
370 OPTION_LONG("loop-ref", "NAME", "Set reference string for loopback device"):
371 if (isempty(opts.arg)) {
372 arg_loop_ref = mfree(arg_loop_ref);
373 arg_loop_ref_auto = false;
374 break;
375 }
376
377 if (strlen(opts.arg) >= sizeof_field(struct loop_info64, lo_file_name))
378 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Loop device ref string '%s' is too long.", opts.arg);
379
380 r = free_and_strdup_warn(&arg_loop_ref, opts.arg);
381 if (r < 0)
382 return r;
383
384 arg_loop_ref_auto = false;
385 break;
386
387 OPTION_LONG("loop-ref-auto", NULL, "Derive reference string from image file name"):
388 arg_loop_ref = mfree(arg_loop_ref);
389 arg_loop_ref_auto = true;
390 break;
391
392 OPTION_LONG("image-policy", "POLICY", "Specify image dissection policy"):
393 r = parse_image_policy_argument(opts.arg, &arg_image_policy);
394 if (r < 0)
395 return r;
396 break;
397
398 OPTION_LONG("mtree-hash", "BOOL", "Whether to include SHA256 hash in the mtree output"):
399 r = parse_boolean_argument("--mtree-hash=", opts.arg, &arg_mtree_hash);
400 if (r < 0)
401 return r;
402 break;
403
404 OPTION_LONG("system", NULL, "Discover system images"):
405 system_scope_requested = true;
406 break;
407
408 OPTION_LONG("user", NULL, "Discover user images"):
409 user_scope_requested = true;
410 break;
411
412 OPTION_LONG("all", NULL, "Show hidden images too"):
413 arg_all = true;
414 break;
415
416 OPTION('q', "quiet", NULL, "Suppress output of chosen loopback block device"):
417 arg_quiet = true;
418 break;
419
420 OPTION_LONG("image-filter", "FILTER", "Specify image dissection filter"): {
421 _cleanup_(image_filter_freep) ImageFilter *f = NULL;
422 r = image_filter_parse(opts.arg, &f);
423 if (r < 0)
424 return log_error_errno(r, "Failed to parse image filter expression: %s", opts.arg);
425
426 image_filter_free(arg_image_filter);
427 arg_image_filter = TAKE_PTR(f);
428 break;
429 }
430
431 OPTION_LONG("copy-ownership", "BOOL", "Whether to copy ownership when copying files"):
432 r = parse_tristate_argument_with_auto("--copy-ownership=", opts.arg, &arg_copy_ownership);
433 if (r < 0)
434 return r;
435 break;
436
437 /************************************ Commands ***************************************/
438 OPTION_GROUP("Commands"): {}
439
440 OPTION_COMMON_HELP:
441 return help();
442
443 OPTION_COMMON_VERSION:
444 return version();
445
446 OPTION('m', "mount", NULL, "Mount the image to the specified directory"):
447 arg_action = ACTION_MOUNT;
448 break;
449
450 OPTION_SHORT('M', NULL, "Shortcut for --mount --mkdir"):
451 arg_action = ACTION_MOUNT;
452 arg_flags |= DISSECT_IMAGE_MKDIR;
453 break;
454
455 OPTION('u', "umount", NULL, "Unmount the image from the specified directory"):
456 arg_action = ACTION_UMOUNT;
457 break;
458
459 OPTION_SHORT('U', NULL, "Shortcut for --umount --rmdir"):
460 arg_action = ACTION_UMOUNT;
461 arg_rmdir = true;
462 break;
463
464 OPTION_LONG("attach", NULL, "Attach the disk image to a loopback block device"):
465 arg_action = ACTION_ATTACH;
466 break;
467
468 OPTION_LONG("detach", NULL, "Detach a loopback block device again"):
469 arg_action = ACTION_DETACH;
470 break;
471
472 OPTION('l', "list", NULL, "List all the files and directories of the specified OS image"):
473 arg_action = ACTION_LIST;
474 arg_flags |= DISSECT_IMAGE_READ_ONLY;
475 break;
476
477 OPTION_LONG("mtree", NULL, "Show BSD mtree manifest of OS image"):
478 arg_action = ACTION_MTREE;
479 arg_flags |= DISSECT_IMAGE_READ_ONLY;
480 break;
481
482 OPTION_FULL(OPTION_STOPS_PARSING, /* sc= */ 0, "with", NULL, "Mount, run command, unmount"):
483 arg_action = ACTION_WITH;
484 break;
485
486 OPTION('x', "copy-from", NULL, "Copy files from image to host"):
487 arg_action = ACTION_COPY_FROM;
488 arg_flags |= DISSECT_IMAGE_READ_ONLY;
489 break;
490
491 OPTION('a', "copy-to", NULL, "Copy files from host to image"):
492 arg_action = ACTION_COPY_TO;
493 break;
494
495 OPTION_LONG("make-archive", NULL, "Convert the DDI to an archive file"):
496 r = DLOPEN_LIBARCHIVE(LOG_ERR, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED);
497 if (r < 0)
498 return r;
499
500 arg_action = ACTION_MAKE_ARCHIVE;
501 break;
502
503 OPTION_LONG("discover", NULL, "Discover DDIs in well known directories"):
504 arg_action = ACTION_DISCOVER;
505 break;
506
507 OPTION_LONG("validate", NULL, "Validate image and image policy"):
508 arg_action = ACTION_VALIDATE;
509 break;
510
511 OPTION_LONG("shift", NULL, "Shift UID range to selected base"):
512 arg_action = ACTION_SHIFT;
513 break;
514 }
515
516 if (system_scope_requested || user_scope_requested)
517 arg_runtime_scope = system_scope_requested && user_scope_requested ? _RUNTIME_SCOPE_INVALID :
518 system_scope_requested ? RUNTIME_SCOPE_SYSTEM : RUNTIME_SCOPE_USER;
519
520 char **args = option_parser_get_args(&opts);
521
522 switch (arg_action) {
523
524 case ACTION_DISSECT:
525 if (strv_length(args) != 1)
526 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
527 "Expected an image file path as only argument.");
528
529 r = parse_image_path_argument(args[0], NULL, &arg_image);
530 if (r < 0)
531 return r;
532
533 /* when dumping image info be even more liberal than otherwise, do not even require a single valid partition */
534 arg_flags |= DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_ALLOW_EMPTY;
535 break;
536
537 case ACTION_MOUNT:
538 if (strv_length(args) != 2)
539 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
540 "Expected an image file path and mount point path as only arguments.");
541
542 r = parse_image_path_argument(args[0], NULL, &arg_image);
543 if (r < 0)
544 return r;
545
546 r = parse_path_argument(args[1], /* suppress_root= */ false, &arg_path);
547 if (r < 0)
548 return r;
549
550 arg_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
551 break;
552
553 case ACTION_UMOUNT:
554 if (strv_length(args) != 1)
555 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
556 "Expected a mount point path as only argument.");
557
558 r = parse_path_argument(args[0], /* suppress_root= */ false, &arg_path);
559 if (r < 0)
560 return r;
561 break;
562
563 case ACTION_ATTACH:
564 if (strv_length(args) != 1)
565 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
566 "Expected an image file path as only argument.");
567
568 r = parse_image_path_argument(args[0], NULL, &arg_image);
569 if (r < 0)
570 return r;
571 break;
572
573 case ACTION_DETACH:
574 if (strv_length(args) != 1)
575 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
576 "Expected an image file path or loopback device as only argument.");
577
578 r = parse_image_path_argument(args[0], NULL, &arg_image);
579 if (r < 0)
580 return r;
581 break;
582
583 case ACTION_LIST:
584 case ACTION_MTREE:
585 if (strv_length(args) != 1)
586 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
587 "Expected an image file or directory path as only argument.");
588
589 r = parse_image_path_argument(args[0], &arg_root, &arg_image);
590 if (r < 0)
591 return r;
592
593 arg_flags |= DISSECT_IMAGE_READ_ONLY | DISSECT_IMAGE_REQUIRE_ROOT;
594 break;
595
596 case ACTION_MAKE_ARCHIVE:
597 if (!IN_SET(strv_length(args), 1, 2))
598 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
599 "Expected an image file, and an optional target path as only arguments.");
600
601 r = parse_image_path_argument(args[0], &arg_root, &arg_image);
602 if (r < 0)
603 return r;
604
605 arg_target = empty_or_dash_to_null(args[1]);
606 arg_flags |= DISSECT_IMAGE_READ_ONLY | DISSECT_IMAGE_REQUIRE_ROOT;
607 break;
608
609 case ACTION_COPY_FROM:
610 if (!IN_SET(strv_length(args), 2, 3))
611 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
612 "Expected an image file or directory path, a source path and an optional destination path as only arguments.");
613
614 r = parse_image_path_argument(args[0], &arg_root, &arg_image);
615 if (r < 0)
616 return r;
617 arg_source = args[1];
618 arg_target = args[2] ?: "-"; /* this means stdout */ ;
619
620 arg_flags |= DISSECT_IMAGE_READ_ONLY | DISSECT_IMAGE_REQUIRE_ROOT;
621 break;
622
623 case ACTION_COPY_TO:
624 if (!IN_SET(strv_length(args), 2, 3))
625 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
626 "Expected an image file or directory path, an optional source path and a destination path as only arguments.");
627
628 r = parse_image_path_argument(args[0], &arg_root, &arg_image);
629 if (r < 0)
630 return r;
631
632 if (args[2]) {
633 arg_source = args[1];
634 arg_target = args[2];
635 } else {
636 arg_source = "-"; /* this means stdin */
637 arg_target = args[1];
638 }
639
640 arg_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
641 break;
642
643 case ACTION_WITH:
644 if (strv_isempty(args))
645 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
646 "Expected an image file path and an optional command line.");
647
648 r = parse_image_path_argument(args[0], NULL, &arg_image);
649 if (r < 0)
650 return r;
651
652 if (args[1]) {
653 arg_argv = strv_copy(args + 1);
654 if (!arg_argv)
655 return log_oom();
656 }
657
658 break;
659
660 case ACTION_DISCOVER:
661 if (!strv_isempty(args))
662 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
663 "Expected no argument.");
664 break;
665
666 case ACTION_VALIDATE:
667 if (strv_length(args) != 1)
668 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
669 "Expected an image file path as only argument.");
670
671 r = parse_image_path_argument(args[0], NULL, &arg_image);
672 if (r < 0)
673 return r;
674
675 arg_flags |= DISSECT_IMAGE_READ_ONLY;
676 arg_flags &= ~(DISSECT_IMAGE_PIN_PARTITION_DEVICES|DISSECT_IMAGE_ADD_PARTITION_DEVICES);
677 break;
678
679 case ACTION_SHIFT:
680 if (strv_length(args) != 2)
681 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
682 "Expected an image path and a UID base as only argument.");
683
684 r = parse_image_path_argument(args[0], &arg_root, &arg_image);
685 if (r < 0)
686 return r;
687
688 if (streq(args[1], "foreign"))
689 arg_uid_base = FOREIGN_UID_BASE;
690 else {
691 r = parse_uid(args[1], &arg_uid_base);
692 if (r < 0)
693 return log_error_errno(r, "Failed to parse UID base: %s", args[1]);
694
695 if ((arg_uid_base & 0xFFFF) != 0)
696 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
697 "Selected UID base not a multiple of 64K: " UID_FMT, arg_uid_base);
698 if (arg_uid_base != 0 &&
699 !uid_is_container(arg_uid_base) &&
700 !uid_is_foreign(arg_uid_base))
701 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
702 "Selected UID range is not in the container range, nor the foreign one, refusing.");
703 }
704
705 arg_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
706 break;
707
708 default:
709 assert_not_reached();
710 }
711
712 r = getenv_bool("SYSTEMD_USE_MOUNTFSD");
713 if (r < 0) {
714 if (r != -ENXIO)
715 return log_error_errno(r, "Failed to parse $SYSTEMD_USE_MOUNTFSD: %m");
716 } else
717 arg_via_service = r;
718
719 if (IN_SET(arg_action, ACTION_MOUNT, ACTION_UMOUNT)) {
720 r = have_effective_cap(CAP_SYS_ADMIN);
721 if (r < 0)
722 return log_error_errno(r, "Failed to determine if we have CAP_SYS_ADMIN: %m");
723 if (r == 0)
724 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to have CAP_SYS_ADMIN to mount/unmount images");
725 }
726
727 if (arg_action == ACTION_SHIFT) {
728 r = have_effective_cap(CAP_CHOWN);
729 if (r < 0)
730 return log_error_errno(r, "Failed to determine if we have CAP_CHOWN: %m");
731 if (r == 0)
732 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Need to have CAP_CHOWN to shift UID ranges");
733 }
734
735 if (IN_SET(arg_action, ACTION_ATTACH, ACTION_DETACH)) {
736 r = must_be_root();
737 if (r < 0)
738 return r;
739 }
740
741 SET_FLAG(arg_flags, DISSECT_IMAGE_ALLOW_INTERACTIVE_AUTH, isatty_safe(STDIN_FILENO));
742
743 return 1;
744 }
745
746 static int parse_argv_as_mount_helper(int argc, char *argv[]) {
747 const char *options = NULL;
748 bool fake = false;
749 int r;
750
751 /* Implements util-linux "external helper" command line interface, as per mount(8) man page. */
752
753 OptionParser opts = { argc, argv, .namespace = "mount.ddi" };
754 FOREACH_OPTION_OR_RETURN(c, &opts)
755 switch (c) {
756
757 OPTION_NAMESPACE("mount.ddi"): {}
758
759 OPTION_SHORT('f', NULL, /* help= */ NULL):
760 fake = true;
761 break;
762
763 OPTION_SHORT('o', "OPTIONS", /* help= */ NULL):
764 options = opts.arg;
765 break;
766
767 OPTION_SHORT('t', "FSTYPE", /* help= */ NULL):
768 if (!streq(opts.arg, "ddi"))
769 log_debug("Unexpected file system type '%s', ignoring.", opts.arg);
770 break;
771
772 OPTION_SHORT('s', NULL, /* help= */ NULL): {} /* sloppy mount options */
773 OPTION_SHORT('n', NULL, /* help= */ NULL): {} /* aka --no-mtab */
774 OPTION_SHORT('v', NULL, /* help= */ NULL): /* aka --verbose */
775 log_debug("Ignoring option -%c, not implemented.", opts.opt->short_code);
776 break;
777
778 OPTION_SHORT('N', "NS", /* help= */ NULL): /* aka --namespace= */
779 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
780 "Option -%c is not implemented, refusing.",
781 opts.opt->short_code);
782 }
783
784 char **args = option_parser_get_args(&opts);
785 size_t n_args = option_parser_get_n_args(&opts);
786
787 if (n_args != 2)
788 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
789 "Expected an image file path and target directory as only argument.");
790
791 for (const char *p = options;;) {
792 _cleanup_free_ char *word = NULL;
793
794 r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
795 if (r < 0)
796 return log_error_errno(r, "Failed to extract mount option: %m");
797 if (r == 0)
798 break;
799
800 if (streq(word, "ro"))
801 SET_FLAG(arg_flags, DISSECT_IMAGE_READ_ONLY, true);
802 else if (streq(word, "rw"))
803 SET_FLAG(arg_flags, DISSECT_IMAGE_READ_ONLY, false);
804 else if (streq(word, "discard"))
805 SET_FLAG(arg_flags, DISSECT_IMAGE_DISCARD_ANY, true);
806 else if (streq(word, "nodiscard"))
807 SET_FLAG(arg_flags, DISSECT_IMAGE_DISCARD_ANY, false);
808 else
809 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
810 "Unknown mount option '%s'.", word);
811 }
812
813 if (fake)
814 return 0;
815
816 r = parse_path_argument(args[0], /* suppress_root= */ false, &arg_image);
817 if (r < 0)
818 return r;
819
820 r = parse_path_argument(args[1], /* suppress_root= */ false, &arg_path);
821 if (r < 0)
822 return r;
823
824 arg_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
825 arg_action = ACTION_MOUNT;
826 return 1;
827 }
828
829 static void strv_pair_print(char **l, const char *prefix) {
830 assert(prefix);
831
832 STRV_FOREACH_PAIR(p, q, l)
833 if (p == l)
834 printf("%s %s=%s\n", prefix, *p, *q);
835 else
836 printf("%*s %s=%s\n", (int) strlen(prefix), "", *p, *q);
837 }
838
839 static int get_extension_scopes(DissectedImage *m, ImageClass class, char ***ret_scopes) {
840 _cleanup_strv_free_ char **l = NULL;
841 const char *e, *field_name;
842 char **release_data;
843
844 assert(m);
845 assert(ret_scopes);
846
847 switch (class) {
848
849 case IMAGE_SYSEXT:
850 release_data = m->sysext_release;
851 field_name = "SYSEXT_SCOPE";
852 break;
853
854 case IMAGE_CONFEXT:
855 release_data = m->confext_release;
856 field_name = "CONFEXT_SCOPE";
857 break;
858
859 default:
860 return -EINVAL;
861 }
862
863 /* If there's no extension-release file its not a system extension. Otherwise the SYSEXT_SCOPE
864 * field for sysext images and the CONFEXT_SCOPE field for confext images indicates which scope
865 * it is for — and it defaults to "system" + "portable" if unset. */
866
867 if (!release_data) {
868 *ret_scopes = NULL;
869 return 0;
870 }
871
872 e = strv_env_pairs_get(release_data, field_name);
873 if (e)
874 l = strv_split(e, WHITESPACE);
875 else
876 l = strv_new("system", "portable");
877 if (!l)
878 return -ENOMEM;
879
880 *ret_scopes = TAKE_PTR(l);
881 return 1;
882 }
883
884 static int action_dissect(
885 DissectedImage *m,
886 LoopDevice *d,
887 int userns_fd) {
888
889 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
890 _cleanup_(table_unrefp) Table *t = NULL;
891 _cleanup_free_ char *bn = NULL;
892 uint64_t size = UINT64_MAX;
893 int r;
894
895 assert(m);
896
897 r = path_extract_filename(arg_image, &bn);
898 if (r < 0)
899 return log_error_errno(r, "Failed to extract file name from image path '%s': %m", arg_image);
900
901 if (arg_json_format_flags & (SD_JSON_FORMAT_OFF|SD_JSON_FORMAT_PRETTY|SD_JSON_FORMAT_PRETTY_AUTO))
902 pager_open(arg_pager_flags);
903
904 if (!sd_json_format_enabled(arg_json_format_flags)) {
905 printf(" File Name: %s%s%s\n",
906 ansi_highlight(), bn, ansi_normal());
907
908 printf(" Size: %s\n",
909 FORMAT_BYTES(m->image_size));
910
911 printf(" Sec. Size: %" PRIu32 "\n",
912 m->sector_size);
913
914 printf(" Arch.: %s\n",
915 strna(architecture_to_string(dissected_image_architecture(m))));
916
917 if (!sd_id128_is_null(m->image_uuid))
918 printf("Image UUID: %s\n",
919 SD_ID128_TO_UUID_STRING(m->image_uuid));
920
921 if (m->image_name && !streq(m->image_name, bn))
922 printf("Image Name: %s\n", m->image_name);
923
924 putc('\n', stdout);
925 fflush(stdout);
926 }
927
928 r = dissected_image_acquire_metadata(m, userns_fd, /* extra_flags= */ 0);
929 if (r == -ENXIO)
930 return log_error_errno(r, "No root partition discovered.");
931 if (r == -EUCLEAN)
932 return log_error_errno(r, "File system check of image failed.");
933 if (r == -EMEDIUMTYPE)
934 log_warning_errno(r, "Not a valid OS image, no os-release file included. Proceeding anyway.");
935 else if (r == -EUNATCH)
936 log_warning_errno(r, "OS image is encrypted, proceeding without showing OS image metadata.");
937 else if (r == -EBUSY)
938 log_warning_errno(r, "OS image is currently in use, proceeding without showing OS image metadata.");
939 else if (r < 0)
940 return log_error_errno(r, "Failed to acquire image metadata: %m");
941 else if (!sd_json_format_enabled(arg_json_format_flags)) {
942
943 if (m->hostname)
944 printf(" Hostname: %s\n", m->hostname);
945
946 if (!sd_id128_is_null(m->machine_id))
947 printf("Machine ID: " SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(m->machine_id));
948
949 strv_pair_print(m->machine_info,
950 "Mach. Info:");
951 strv_pair_print(m->os_release,
952 "OS Release:");
953 strv_pair_print(m->initrd_release,
954 "initrd R.:");
955 strv_pair_print(m->sysext_release,
956 " sysext R.:");
957 strv_pair_print(m->confext_release,
958 "confext R.:");
959
960 if (m->hostname ||
961 !sd_id128_is_null(m->machine_id) ||
962 !strv_isempty(m->machine_info) ||
963 !strv_isempty(m->os_release) ||
964 !strv_isempty(m->initrd_release) ||
965 !strv_isempty(m->sysext_release) ||
966 !strv_isempty(m->confext_release))
967 putc('\n', stdout);
968
969 printf(" Use As: %s bootable system for UEFI\n",
970 COLOR_MARK_BOOL(dissected_image_is_bootable_uefi(m)));
971 printf(" %s bootable system for container\n",
972 COLOR_MARK_BOOL(dissected_image_is_bootable_os(m)));
973 printf(" %s portable service\n",
974 COLOR_MARK_BOOL(dissected_image_is_portable(m)));
975 printf(" %s initrd\n",
976 COLOR_MARK_BOOL(dissected_image_is_initrd(m)));
977
978 for (ImageClass c = _IMAGE_CLASS_EXTENSION_FIRST; c <= _IMAGE_CLASS_EXTENSION_LAST; c++) {
979 const char *string_class = image_class_to_string(c);
980 _cleanup_strv_free_ char **extension_scopes = NULL;
981
982 r = get_extension_scopes(m, c, &extension_scopes);
983 if (r < 0)
984 return log_error_errno(r, "Failed to parse scopes: %m");
985
986 printf(" %s %s for system\n",
987 COLOR_MARK_BOOL(strv_contains(extension_scopes, "system")), string_class);
988 printf(" %s %s for portable service\n",
989 COLOR_MARK_BOOL(strv_contains(extension_scopes, "portable")), string_class);
990 printf(" %s %s for initrd\n",
991 COLOR_MARK_BOOL(strv_contains(extension_scopes, "initrd")), string_class);
992 }
993
994 putc('\n', stdout);
995 } else {
996 _cleanup_strv_free_ char **sysext_scopes = NULL, **confext_scopes = NULL;
997
998 r = get_extension_scopes(m, IMAGE_SYSEXT, &sysext_scopes);
999 if (r < 0)
1000 return log_error_errno(r, "Failed to parse sysext scopes: %m");
1001
1002 r = get_extension_scopes(m, IMAGE_CONFEXT, &confext_scopes);
1003 if (r < 0)
1004 return log_error_errno(r, "Failed to parse confext scopes: %m");
1005
1006 Architecture a = dissected_image_architecture(m);
1007
1008 r = sd_json_buildo(
1009 &v,
1010 SD_JSON_BUILD_PAIR_STRING("name", bn),
1011 SD_JSON_BUILD_PAIR_CONDITION(size != UINT64_MAX, "size", SD_JSON_BUILD_INTEGER(size)),
1012 SD_JSON_BUILD_PAIR_INTEGER("sectorSize", m->sector_size),
1013 SD_JSON_BUILD_PAIR_CONDITION(a >= 0, "architecture", SD_JSON_BUILD_STRING(architecture_to_string(a))),
1014 SD_JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(m->image_uuid), "imageUuid", SD_JSON_BUILD_UUID(m->image_uuid)),
1015 SD_JSON_BUILD_PAIR_CONDITION(!!m->hostname, "hostname", SD_JSON_BUILD_STRING(m->hostname)),
1016 SD_JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(m->machine_id), "machineId", SD_JSON_BUILD_ID128(m->machine_id)),
1017 SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(m->machine_info), "machineInfo", JSON_BUILD_STRV_ENV_PAIR(m->machine_info)),
1018 SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(m->os_release), "osRelease", JSON_BUILD_STRV_ENV_PAIR(m->os_release)),
1019 SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(m->initrd_release), "initrdRelease", JSON_BUILD_STRV_ENV_PAIR(m->initrd_release)),
1020 SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(m->sysext_release), "sysextRelease", JSON_BUILD_STRV_ENV_PAIR(m->sysext_release)),
1021 SD_JSON_BUILD_PAIR_CONDITION(!strv_isempty(m->confext_release), "confextRelease", JSON_BUILD_STRV_ENV_PAIR(m->confext_release)),
1022 SD_JSON_BUILD_PAIR_BOOLEAN("useBootableUefi", dissected_image_is_bootable_uefi(m)),
1023 SD_JSON_BUILD_PAIR_BOOLEAN("useBootableContainer", dissected_image_is_bootable_os(m)),
1024 SD_JSON_BUILD_PAIR_BOOLEAN("useInitrd", dissected_image_is_initrd(m)),
1025 SD_JSON_BUILD_PAIR_BOOLEAN("usePortableService", dissected_image_is_portable(m)),
1026 SD_JSON_BUILD_PAIR_BOOLEAN("useSystemExtension", strv_contains(sysext_scopes, "system")),
1027 SD_JSON_BUILD_PAIR_BOOLEAN("useInitRDSystemExtension", strv_contains(sysext_scopes, "initrd")),
1028 SD_JSON_BUILD_PAIR_BOOLEAN("usePortableSystemExtension", strv_contains(sysext_scopes, "portable")),
1029 SD_JSON_BUILD_PAIR_BOOLEAN("useConfigurationExtension", strv_contains(confext_scopes, "system")),
1030 SD_JSON_BUILD_PAIR_BOOLEAN("useInitRDConfigurationExtension", strv_contains(confext_scopes, "initrd")),
1031 SD_JSON_BUILD_PAIR_BOOLEAN("usePortableConfigurationExtension", strv_contains(confext_scopes, "portable")));
1032 if (r < 0)
1033 return log_oom();
1034 }
1035
1036 t = table_new("rw", "designator", "partition uuid", "partition label", "fstype", "architecture", "verity", "growfs", "node", "partno");
1037 if (!t)
1038 return log_oom();
1039
1040 table_set_ersatz_string(t, TABLE_ERSATZ_DASH);
1041 (void) table_set_align_percent(t, table_get_cell(t, 0, 9), 100);
1042
1043 /* Hide the device path if this is a loopback device that is not relinquished, since that means the
1044 * device node is not going to be useful the instant our command exits */
1045 if ((!d || d->created) && !sd_json_format_enabled(arg_json_format_flags))
1046 table_hide_column_from_display(t, 8);
1047
1048 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1049 DissectedPartition *p = m->partitions + i;
1050
1051 if (!p->found)
1052 continue;
1053
1054 r = table_add_many(
1055 t,
1056 TABLE_STRING, p->rw ? "rw" : "ro",
1057 TABLE_STRING, partition_designator_to_string(i));
1058 if (r < 0)
1059 return table_log_add_error(r);
1060
1061 if (sd_id128_is_null(p->uuid))
1062 r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
1063 else
1064 r = table_add_cell(t, NULL, TABLE_UUID, &p->uuid);
1065 if (r < 0)
1066 return table_log_add_error(r);
1067
1068 r = table_add_many(
1069 t,
1070 TABLE_STRING, p->label,
1071 TABLE_STRING, p->fstype,
1072 TABLE_STRING, architecture_to_string(p->architecture));
1073 if (r < 0)
1074 return table_log_add_error(r);
1075
1076 if (arg_verity_settings.data_path)
1077 r = table_add_cell(t, NULL, TABLE_STRING, "external");
1078 else if (dissected_image_verity_candidate(m, i))
1079 r = table_add_cell(t, NULL, TABLE_STRING,
1080 dissected_image_verity_sig_ready(m, i) ? "signed" :
1081 yes_no(dissected_image_verity_ready(m, i)));
1082 else
1083 r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
1084 if (r < 0)
1085 return table_log_add_error(r);
1086
1087 r = table_add_many(t, TABLE_BOOLEAN, (int) p->growfs);
1088 if (r < 0)
1089 return table_log_add_error(r);
1090
1091 if (p->partno < 0) /* no partition table, naked file system */ {
1092 r = table_add_cell(t, NULL, TABLE_PATH_BASENAME, arg_image);
1093 if (r < 0)
1094 return table_log_add_error(r);
1095
1096 r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
1097 } else {
1098 r = table_add_cell(t, NULL, TABLE_STRING, p->node);
1099 if (r < 0)
1100 return table_log_add_error(r);
1101
1102 r = table_add_cell(t, NULL, TABLE_INT, &p->partno);
1103 }
1104 if (r < 0)
1105 return table_log_add_error(r);
1106 }
1107
1108 if (!sd_json_format_enabled(arg_json_format_flags)) {
1109 table_set_header(t, arg_legend);
1110
1111 r = table_print_or_warn(t);
1112 if (r < 0)
1113 return r;
1114 } else {
1115 _cleanup_(sd_json_variant_unrefp) sd_json_variant *jt = NULL;
1116
1117 r = table_to_json(t, &jt);
1118 if (r < 0)
1119 return log_error_errno(r, "Failed to convert table to JSON: %m");
1120
1121 r = sd_json_variant_set_field(&v, "mounts", jt);
1122 if (r < 0)
1123 return log_oom();
1124
1125 sd_json_variant_dump(v, arg_json_format_flags, stdout, NULL);
1126 }
1127
1128 return 0;
1129 }
1130
1131 static int action_mount(DissectedImage *m, LoopDevice *d) {
1132 int r;
1133
1134 assert(m);
1135 assert(arg_action == ACTION_MOUNT);
1136
1137 r = dissected_image_mount_and_warn(
1138 m,
1139 arg_path,
1140 /* uid_shift= */ UID_INVALID,
1141 /* uid_range= */ UID_INVALID,
1142 /* userns_fd= */ -EBADF,
1143 arg_flags);
1144 if (r < 0)
1145 return r;
1146
1147 if (d) {
1148 r = loop_device_flock(d, LOCK_UN);
1149 if (r < 0)
1150 return log_error_errno(r, "Failed to unlock loopback block device: %m");
1151 }
1152
1153 r = dissected_image_relinquish(m);
1154 if (r < 0)
1155 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
1156
1157 return 0;
1158 }
1159
1160 static int list_print_item(
1161 RecurseDirEvent event,
1162 const char *path,
1163 int dir_fd,
1164 int inode_fd,
1165 const struct dirent *de,
1166 const struct statx *sx,
1167 void *userdata) {
1168
1169 assert(path);
1170
1171 if (event == RECURSE_DIR_ENTER)
1172 printf("%s%s/%s\n", path, ansi_grey(), ansi_normal());
1173 else if (event == RECURSE_DIR_ENTRY)
1174 printf("%s\n", path);
1175
1176 return RECURSE_DIR_CONTINUE;
1177 }
1178
1179 static int get_file_sha256(int inode_fd, uint8_t ret[static SHA256_DIGEST_SIZE]) {
1180 _cleanup_close_ int fd = -EBADF;
1181
1182 /* convert O_PATH fd into a regular one */
1183 fd = fd_reopen(inode_fd, O_RDONLY|O_CLOEXEC);
1184 if (fd < 0)
1185 return fd;
1186
1187 /* Calculating the SHA sum might be slow, hence let's flush STDOUT first, to give user an idea where we are slow. */
1188 fflush(stdout);
1189
1190 return sha256_fd(fd, UINT64_MAX, ret);
1191 }
1192
1193 static const char *pick_color_for_uid_gid(uid_t uid) {
1194 if (uid == UID_NOBODY)
1195 return ansi_highlight_yellow4(); /* files should never be owned by 'nobody' (but might happen due to userns mapping) */
1196 if (uid_is_system(uid))
1197 return ansi_normal(); /* files in disk images are typically owned by root and other system users, no issue there */
1198 if (uid_is_dynamic(uid) || uid_is_greeter(uid))
1199 return ansi_highlight_red(); /* files should never be owned persistently by dynamic users, and there are just no excuses */
1200 if (uid_is_container(uid) || uid_is_foreign(uid))
1201 return ansi_highlight_cyan();
1202
1203 return ansi_highlight();
1204 }
1205
1206 static int mtree_print_item(
1207 RecurseDirEvent event,
1208 const char *path,
1209 int dir_fd,
1210 int inode_fd,
1211 const struct dirent *de,
1212 const struct statx *sx,
1213 void *userdata) {
1214
1215 _cleanup_free_ char *escaped = NULL;
1216 int r;
1217
1218 assert(path);
1219
1220 if (!IN_SET(event, RECURSE_DIR_ENTER, RECURSE_DIR_ENTRY))
1221 return RECURSE_DIR_CONTINUE;
1222
1223 assert(sx);
1224
1225 if (isempty(path))
1226 path = ".";
1227 else {
1228 /* BSD mtree uses either C or octal escaping, and covers whitespace, comments and glob characters. We use C style escaping and follow suit */
1229 path = escaped = xescape(path, WHITESPACE COMMENTS GLOB_CHARS);
1230 if (!escaped)
1231 return log_oom();
1232 }
1233
1234 printf("%s", isempty(path) ? "." : path);
1235
1236 if (FLAGS_SET(sx->stx_mask, STATX_TYPE)) {
1237 if (S_ISDIR(sx->stx_mode))
1238 printf("%s/%s", ansi_grey(), ansi_normal());
1239
1240 printf(" %stype=%s%s%s%s",
1241 ansi_grey(),
1242 ansi_normal(),
1243 S_ISDIR(sx->stx_mode) ? ansi_highlight_blue() :
1244 S_ISLNK(sx->stx_mode) ? ansi_highlight_cyan() :
1245 (S_ISFIFO(sx->stx_mode) || S_ISCHR(sx->stx_mode) || S_ISBLK(sx->stx_mode)) ? ansi_highlight_yellow4() :
1246 S_ISSOCK(sx->stx_mode) ? ansi_highlight_magenta() : "",
1247 ASSERT_PTR(S_ISDIR(sx->stx_mode) ? "dir" :
1248 S_ISREG(sx->stx_mode) ? "file" :
1249 S_ISLNK(sx->stx_mode) ? "link" :
1250 S_ISFIFO(sx->stx_mode) ? "fifo" :
1251 S_ISBLK(sx->stx_mode) ? "block" :
1252 S_ISCHR(sx->stx_mode) ? "char" :
1253 S_ISSOCK(sx->stx_mode) ? "socket" : NULL),
1254 ansi_normal());
1255 }
1256
1257 if (FLAGS_SET(sx->stx_mask, STATX_MODE) && (!FLAGS_SET(sx->stx_mask, STATX_TYPE) || !S_ISLNK(sx->stx_mode)))
1258 printf(" %smode=%s%04o",
1259 ansi_grey(),
1260 ansi_normal(),
1261 (unsigned) (sx->stx_mode & 0777));
1262
1263 if (FLAGS_SET(sx->stx_mask, STATX_UID))
1264 printf(" %suid=%s" UID_FMT "%s",
1265 ansi_grey(),
1266 pick_color_for_uid_gid(sx->stx_uid),
1267 sx->stx_uid,
1268 ansi_normal());
1269
1270 if (FLAGS_SET(sx->stx_mask, STATX_GID))
1271 printf(" %sgid=%s" GID_FMT "%s",
1272 ansi_grey(),
1273 pick_color_for_uid_gid(sx->stx_gid),
1274 sx->stx_gid,
1275 ansi_normal());
1276
1277 if (FLAGS_SET(sx->stx_mask, STATX_TYPE|STATX_SIZE) && S_ISREG(sx->stx_mode)) {
1278 printf(" %ssize=%s%" PRIu64,
1279 ansi_grey(),
1280 ansi_normal(),
1281 (uint64_t) sx->stx_size);
1282
1283 if (arg_mtree_hash && inode_fd >= 0 && sx->stx_size > 0) {
1284 uint8_t hash[SHA256_DIGEST_SIZE];
1285
1286 r = get_file_sha256(inode_fd, hash);
1287 if (r < 0)
1288 log_warning_errno(r, "Failed to calculate file SHA256 sum for '%s', ignoring: %m", path);
1289 else {
1290 _cleanup_free_ char *h = NULL;
1291
1292 h = hexmem(hash, sizeof(hash));
1293 if (!h)
1294 return log_oom();
1295
1296 printf(" %ssha256sum=%s%s",
1297 ansi_grey(),
1298 ansi_normal(),
1299 h);
1300 }
1301 }
1302 }
1303
1304 if (FLAGS_SET(sx->stx_mask, STATX_TYPE) && S_ISLNK(sx->stx_mode) && inode_fd >= 0) {
1305 _cleanup_free_ char *target = NULL;
1306
1307 r = readlinkat_malloc(inode_fd, "", &target);
1308 if (r < 0)
1309 log_warning_errno(r, "Failed to read symlink '%s', ignoring: %m", path);
1310 else {
1311 _cleanup_free_ char *target_escaped = NULL;
1312
1313 target_escaped = xescape(target, WHITESPACE COMMENTS GLOB_CHARS);
1314 if (!target_escaped)
1315 return log_oom();
1316
1317 printf(" %slink=%s%s",
1318 ansi_grey(),
1319 ansi_normal(),
1320 target_escaped);
1321 }
1322 }
1323
1324 if (FLAGS_SET(sx->stx_mask, STATX_TYPE) && (S_ISBLK(sx->stx_mode) || S_ISCHR(sx->stx_mode)))
1325 printf(" %sdevice=%slinux,%" PRIu64 ",%" PRIu64,
1326 ansi_grey(),
1327 ansi_normal(),
1328 (uint64_t) sx->stx_rdev_major,
1329 (uint64_t) sx->stx_rdev_minor);
1330
1331 printf("\n");
1332
1333 return RECURSE_DIR_CONTINUE;
1334 }
1335
1336 static int action_list_or_mtree_or_copy_or_make_archive(DissectedImage *m, LoopDevice *d, int userns_fd) {
1337 _cleanup_(umount_and_freep) char *mounted_dir = NULL;
1338 _cleanup_free_ char *t = NULL;
1339 const char *root;
1340 int r;
1341
1342 assert(IN_SET(arg_action, ACTION_LIST, ACTION_MTREE, ACTION_COPY_FROM, ACTION_COPY_TO, ACTION_MAKE_ARCHIVE, ACTION_SHIFT));
1343
1344 /* Determine whether to copy ownership:
1345 * --copy-ownership=yes: always try to preserve ownership
1346 * --copy-ownership=no: never preserve ownership, use current user
1347 * default: preserve ownership for directory trees,
1348 * but not for regular files (since DDI password tables are typically
1349 * distinct from the host ones, individual file ownership is less meaningful) */
1350
1351 if (arg_image) {
1352 assert(m);
1353
1354 if (userns_fd < 0)
1355 r = detach_mount_namespace_harder(0, 0);
1356 else
1357 r = detach_mount_namespace_userns(userns_fd);
1358 if (r < 0)
1359 return log_error_errno(r, "Failed to detach mount namespace: %m");
1360
1361 /* Create a place we can mount things onto soon. We use a fixed path shared by all invocations. Given
1362 * the mounts are done in a mount namespace there's not going to be a collision here */
1363 r = get_common_dissect_directory(&t);
1364 if (r < 0)
1365 return log_error_errno(r, "Failed to generate private mount directory: %m");
1366
1367 r = dissected_image_mount_and_warn(
1368 m,
1369 t,
1370 /* uid_shift= */ UID_INVALID,
1371 /* uid_range= */ UID_INVALID,
1372 /* userns_fd= */ -EBADF,
1373 arg_flags);
1374 if (r < 0)
1375 return r;
1376
1377 root = mounted_dir = TAKE_PTR(t);
1378
1379 if (d) {
1380 r = loop_device_flock(d, LOCK_UN);
1381 if (r < 0)
1382 return log_error_errno(r, "Failed to unlock loopback block device: %m");
1383 }
1384
1385 r = dissected_image_relinquish(m);
1386 if (r < 0)
1387 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
1388
1389 dissected_image_close(m);
1390 } else
1391 root = arg_root;
1392
1393 switch (arg_action) {
1394
1395 case ACTION_COPY_FROM: {
1396 _cleanup_close_ int source_fd = -EBADF, target_fd = -EBADF;
1397
1398 source_fd = chase_and_open(arg_source, root, CHASE_PREFIX_ROOT|CHASE_WARN, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
1399 if (source_fd < 0)
1400 return log_error_errno(source_fd, "Failed to open source path '%s' in image '%s': %m", arg_source, arg_image);
1401
1402 /* Copying to stdout? */
1403 if (streq(arg_target, "-")) {
1404 r = copy_bytes(source_fd, STDOUT_FILENO, UINT64_MAX, COPY_REFLINK);
1405 if (r < 0)
1406 return log_error_errno(r, "Failed to copy bytes from %s in mage '%s' to stdout: %m", arg_source, arg_image);
1407
1408 /* When we copy to stdout we don't copy any attributes (i.e. no access mode, no ownership, no xattr, no times) */
1409 return 0;
1410 }
1411
1412 /* Try to copy as directory? */
1413 r = copy_directory_at(
1414 source_fd, /* from= */ NULL,
1415 AT_FDCWD, arg_target,
1416 arg_copy_ownership == 0 ? getuid() : UID_INVALID,
1417 arg_copy_ownership == 0 ? getgid() : GID_INVALID,
1418 COPY_REFLINK|COPY_MERGE|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS);
1419 if (r >= 0)
1420 return 0;
1421 if (r != -ENOTDIR)
1422 return log_error_errno(r, "Failed to copy %s in image '%s' to '%s': %m", arg_source, arg_image, arg_target);
1423
1424 r = fd_verify_regular(source_fd);
1425 if (r == -EISDIR)
1426 return log_error_errno(r, "Target '%s' exists already and is not a directory.", arg_target);
1427 if (r < 0)
1428 return log_error_errno(r, "Source path %s in image '%s' is neither regular file nor directory, refusing: %m", arg_source, arg_image);
1429
1430 /* Nah, it's a plain file! */
1431 target_fd = open(arg_target, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
1432 if (target_fd < 0)
1433 return log_error_errno(errno, "Failed to create regular file at target path '%s': %m", arg_target);
1434
1435 r = copy_bytes(source_fd, target_fd, UINT64_MAX, COPY_REFLINK);
1436 if (r < 0)
1437 return log_error_errno(r, "Failed to copy bytes from %s in mage '%s' to '%s': %m", arg_source, arg_image, arg_target);
1438
1439 (void) copy_xattr(source_fd, NULL, target_fd, NULL, 0);
1440 (void) copy_access(source_fd, target_fd);
1441 if (arg_copy_ownership > 0)
1442 (void) copy_owner(source_fd, target_fd);
1443 (void) copy_times(source_fd, target_fd, 0);
1444
1445 return 0;
1446 }
1447
1448 case ACTION_COPY_TO: {
1449 _cleanup_close_ int source_fd = -EBADF, target_fd = -EBADF, dfd = -EBADF;
1450 _cleanup_free_ char *dn = NULL, *bn = NULL;
1451 bool is_dir;
1452
1453 r = path_extract_directory(arg_target, &dn);
1454 if (r < 0)
1455 return log_error_errno(r, "Failed to extract directory from target path '%s': %m", arg_target);
1456 r = path_extract_filename(arg_target, &bn);
1457 if (r < 0)
1458 return log_error_errno(r, "Failed to extract filename from target path '%s': %m", arg_target);
1459 is_dir = r == O_DIRECTORY;
1460
1461 r = chase(dn, root, CHASE_PREFIX_ROOT|CHASE_WARN, NULL, &dfd);
1462 if (r < 0)
1463 return log_error_errno(r, "Failed to open '%s': %m", dn);
1464
1465 /* Are we reading from stdin? */
1466 if (streq(arg_source, "-")) {
1467 if (is_dir)
1468 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot copy STDIN to a directory, refusing.");
1469
1470 target_fd = openat(dfd, bn, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_EXCL, 0644);
1471 if (target_fd < 0)
1472 return log_error_errno(errno, "Failed to open target file '%s': %m", arg_target);
1473
1474 r = copy_bytes(STDIN_FILENO, target_fd, UINT64_MAX, COPY_REFLINK);
1475 if (r < 0)
1476 return log_error_errno(r, "Failed to copy bytes from stdin to '%s' in image '%s': %m", arg_target, arg_image);
1477
1478 /* When we copy from stdin we don't copy any attributes (i.e. no access mode, no ownership, no xattr, no times) */
1479 return 0;
1480 }
1481
1482 source_fd = open(arg_source, O_RDONLY|O_CLOEXEC|O_NOCTTY);
1483 if (source_fd < 0)
1484 return log_error_errno(source_fd, "Failed to open source path '%s': %m", arg_source);
1485
1486 r = fd_verify_regular(source_fd);
1487 if (r < 0) {
1488 if (r != -EISDIR)
1489 return log_error_errno(r, "Source '%s' is neither regular file nor directory: %m", arg_source);
1490
1491 /* We are looking at a directory. */
1492
1493 target_fd = openat(dfd, bn, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
1494 if (target_fd < 0) {
1495 if (errno != ENOENT)
1496 return log_error_errno(errno, "Failed to open destination '%s': %m", arg_target);
1497
1498 r = copy_tree_at(
1499 source_fd, ".",
1500 dfd, bn,
1501 arg_copy_ownership == 0 ? getuid() : UID_INVALID,
1502 arg_copy_ownership == 0 ? getgid() : GID_INVALID,
1503 COPY_REFLINK|COPY_MERGE|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS,
1504 /* denylist= */ NULL,
1505 /* subvolumes= */ NULL);
1506 } else
1507 r = copy_tree_at(
1508 source_fd, ".",
1509 target_fd, ".",
1510 arg_copy_ownership == 0 ? getuid() : UID_INVALID,
1511 arg_copy_ownership == 0 ? getgid() : GID_INVALID,
1512 COPY_REFLINK|COPY_MERGE|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS,
1513 /* denylist= */ NULL,
1514 /* subvolumes= */ NULL);
1515 if (r < 0)
1516 return log_error_errno(r, "Failed to copy '%s' to '%s' in image '%s': %m", arg_source, arg_target, arg_image);
1517
1518 return 0;
1519 }
1520
1521 if (is_dir)
1522 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Source is a regular file, but target is not, refusing.");
1523
1524 /* We area looking at a regular file */
1525 target_fd = openat(dfd, bn, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_EXCL, 0600);
1526 if (target_fd < 0)
1527 return log_error_errno(errno, "Failed to open target file '%s': %m", arg_target);
1528
1529 r = copy_bytes(source_fd, target_fd, UINT64_MAX, COPY_REFLINK);
1530 if (r < 0)
1531 return log_error_errno(r, "Failed to copy bytes from '%s' to '%s' in image '%s': %m", arg_source, arg_target, arg_image);
1532
1533 (void) copy_xattr(source_fd, NULL, target_fd, NULL, 0);
1534 (void) copy_access(source_fd, target_fd);
1535 if (arg_copy_ownership > 0)
1536 (void) copy_owner(source_fd, target_fd);
1537 (void) copy_times(source_fd, target_fd, 0);
1538
1539 return 0;
1540 }
1541
1542 case ACTION_LIST:
1543 case ACTION_MTREE: {
1544 _cleanup_close_ int dfd = -EBADF;
1545
1546 dfd = open(root, O_DIRECTORY|O_CLOEXEC|O_RDONLY);
1547 if (dfd < 0)
1548 return log_error_errno(errno, "Failed to open mount directory: %m");
1549
1550 pager_open(arg_pager_flags);
1551
1552 if (arg_action == ACTION_LIST)
1553 r = recurse_dir(dfd, NULL, 0, UINT_MAX, RECURSE_DIR_SORT, list_print_item, NULL);
1554 else if (arg_action == ACTION_MTREE)
1555 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);
1556 else
1557 assert_not_reached();
1558 if (r < 0)
1559 return log_error_errno(r, "Failed to list image: %m");
1560 return 0;
1561 }
1562
1563 case ACTION_MAKE_ARCHIVE: {
1564 #if HAVE_LIBARCHIVE
1565 _cleanup_close_ int dfd = -EBADF;
1566
1567 dfd = open(root, O_DIRECTORY|O_CLOEXEC|O_RDONLY);
1568 if (dfd < 0)
1569 return log_error_errno(errno, "Failed to open mount directory: %m");
1570
1571 _cleanup_(unlink_and_freep) char *tar = NULL;
1572 _cleanup_close_ int tmp_fd = -EBADF;
1573 int output_fd;
1574 if (arg_target) {
1575 tmp_fd = open_tmpfile_linkable(arg_target, O_WRONLY|O_CLOEXEC, &tar);
1576 if (tmp_fd < 0)
1577 return log_error_errno(tmp_fd, "Failed to create target file '%s': %m", arg_target);
1578
1579 output_fd = tmp_fd;
1580 } else {
1581 if (isatty_safe(STDOUT_FILENO))
1582 return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Refusing to write archive to TTY.");
1583
1584 output_fd = STDOUT_FILENO;
1585 }
1586
1587 r = tar_c(dfd, output_fd, arg_target, /* flags= */ 0);
1588 if (r < 0)
1589 return r;
1590
1591 if (arg_target) {
1592 r = link_tmpfile(tmp_fd, tar, arg_target, LINK_TMPFILE_REPLACE);
1593 if (r < 0)
1594 return log_error_errno(r, "Failed to move archive file into place: %m");
1595
1596 tar = mfree(tar);
1597 }
1598
1599 return 0;
1600 #else
1601 assert_not_reached();
1602 #endif
1603 }
1604
1605 case ACTION_SHIFT:
1606 r = path_patch_uid(root, arg_uid_base, 0x10000);
1607 if (r < 0)
1608 return log_error_errno(r, "Failed to shift UID base: %m");
1609
1610 return 0;
1611
1612 default:
1613 assert_not_reached();
1614 }
1615 }
1616
1617 static int action_umount(const char *path) {
1618 _cleanup_close_ int fd = -EBADF;
1619 _cleanup_free_ char *canonical = NULL;
1620 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
1621 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
1622 int r;
1623
1624 fd = chase_and_open(path, NULL, 0, O_DIRECTORY, &canonical);
1625 if (fd == -ENOTDIR)
1626 return log_error_errno(SYNTHETIC_ERRNO(ENOTDIR), "'%s' is not a directory", path);
1627 if (fd < 0)
1628 return log_error_errno(fd, "Failed to resolve path '%s': %m", path);
1629
1630 r = is_mount_point_at(fd, NULL, 0);
1631 if (r == 0)
1632 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "'%s' is not a mount point", canonical);
1633 if (r < 0)
1634 return log_error_errno(r, "Failed to determine whether '%s' is a mount point: %m", canonical);
1635
1636 r = block_device_new_from_fd(fd, BLOCK_DEVICE_LOOKUP_WHOLE_DISK | BLOCK_DEVICE_LOOKUP_BACKING, &dev);
1637 if (r < 0) {
1638 _cleanup_close_ int usr_fd = -EBADF;
1639
1640 /* The command `systemd-dissect --mount` expects that the image at least has the root or /usr
1641 * partition. If it does not have the root partition, then we mount the /usr partition on a
1642 * tmpfs. Hence, let's try to find the backing block device through the /usr partition. */
1643
1644 usr_fd = openat(fd, "usr", O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW);
1645 if (usr_fd < 0)
1646 return log_error_errno(errno, "Failed to open '%s/usr': %m", canonical);
1647
1648 r = block_device_new_from_fd(usr_fd, BLOCK_DEVICE_LOOKUP_WHOLE_DISK | BLOCK_DEVICE_LOOKUP_BACKING, &dev);
1649 }
1650 if (r < 0)
1651 return log_error_errno(r, "Failed to find backing block device for '%s': %m", canonical);
1652
1653 r = loop_device_open(dev, 0, LOCK_EX, &d);
1654 if (r < 0) {
1655 if (!ERRNO_IS_PRIVILEGE(r))
1656 return log_device_error_errno(dev, r, "Failed to open loopback block device: %m");
1657
1658 log_device_debug_errno(dev, r, "Lacking privileges to open loopback block device, ignoring.");
1659 }
1660
1661 /* We've locked the loop device, now we're ready to unmount. To allow the unmount to succeed, we have
1662 * to close the O_PATH fd we opened earlier. */
1663 fd = safe_close(fd);
1664
1665 r = umount_recursive(canonical, 0);
1666 if (r < 0)
1667 return log_error_errno(r, "Failed to unmount '%s': %m", canonical);
1668
1669 /* We managed to lock and unmount successfully? That means we can try to remove the loop device. */
1670 if (d)
1671 loop_device_unrelinquish(d);
1672
1673 if (arg_rmdir) {
1674 r = RET_NERRNO(rmdir(canonical));
1675 if (r < 0)
1676 return log_error_errno(r, "Failed to remove mount directory '%s': %m", canonical);
1677 }
1678
1679 return 0;
1680 }
1681
1682 static int action_with(DissectedImage *m, LoopDevice *d) {
1683 _cleanup_(umount_and_rmdir_and_freep) char *mounted_dir = NULL;
1684 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
1685 _cleanup_free_ char *temp = NULL;
1686 int r, rcode;
1687
1688 assert(m);
1689 assert(arg_action == ACTION_WITH);
1690
1691 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
1692 if (r < 0)
1693 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
1694
1695 r = mkdir_p(temp, 0700);
1696 if (r < 0)
1697 return log_error_errno(r, "Failed to create mount point: %m");
1698
1699 created_dir = TAKE_PTR(temp);
1700
1701 r = dissected_image_mount_and_warn(
1702 m,
1703 created_dir,
1704 /* uid_shift= */ UID_INVALID,
1705 /* uid_range= */ UID_INVALID,
1706 /* userns_fd= */ -EBADF,
1707 arg_flags);
1708 if (r < 0)
1709 return r;
1710
1711 mounted_dir = TAKE_PTR(created_dir);
1712
1713 r = dissected_image_relinquish(m);
1714 if (r < 0)
1715 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
1716
1717 if (d) {
1718 r = loop_device_flock(d, LOCK_UN);
1719 if (r < 0)
1720 return log_error_errno(r, "Failed to unlock loopback block device: %m");
1721 }
1722
1723 rcode = pidref_safe_fork("(with)", FORK_CLOSE_ALL_FDS|FORK_LOG|FORK_REOPEN_LOG|FORK_WAIT, /* ret= */ NULL);
1724 if (rcode == 0) {
1725 /* Child */
1726
1727 if (chdir(mounted_dir) < 0) {
1728 log_error_errno(errno, "Failed to change to '%s' directory: %m", mounted_dir);
1729 _exit(EXIT_FAILURE);
1730 }
1731
1732 if (setenv("SYSTEMD_DISSECT_ROOT", mounted_dir, /* overwrite= */ true) < 0) {
1733 log_error_errno(errno, "Failed to set $SYSTEMD_DISSECT_ROOT: %m");
1734 _exit(EXIT_FAILURE);
1735 }
1736
1737 if (d && setenv("SYSTEMD_DISSECT_DEVICE", d->node, /* overwrite= */ true) < 0) {
1738 log_error_errno(errno, "Failed to set $SYSTEMD_DISSECT_DEVICE: %m");
1739 _exit(EXIT_FAILURE);
1740 }
1741
1742 if (strv_isempty(arg_argv)) {
1743 const char *sh;
1744
1745 sh = secure_getenv("SHELL");
1746 if (sh) {
1747 execvp(sh, STRV_MAKE(sh));
1748 log_warning_errno(errno, "Failed to execute $SHELL, falling back to /bin/sh: %m");
1749 }
1750
1751 execl("/bin/sh", "sh", NULL);
1752 log_error_errno(errno, "Failed to invoke /bin/sh: %m");
1753 } else {
1754 execvp(arg_argv[0], arg_argv);
1755 log_error_errno(errno, "Failed to execute '%s': %m", arg_argv[0]);
1756 }
1757
1758 _exit(EXIT_FAILURE);
1759 }
1760
1761 /* Let's manually detach everything, to make things synchronous */
1762 if (d) {
1763 r = loop_device_flock(d, LOCK_SH);
1764 if (r < 0)
1765 log_warning_errno(r, "Failed to lock loopback block device, ignoring: %m");
1766 }
1767
1768 r = umount_recursive(mounted_dir, 0);
1769 if (r < 0)
1770 log_warning_errno(r, "Failed to unmount '%s', ignoring: %m", mounted_dir);
1771 else if (d)
1772 loop_device_unrelinquish(d); /* Let's try to destroy the loopback device */
1773
1774 created_dir = TAKE_PTR(mounted_dir);
1775
1776 if (rmdir(created_dir) < 0)
1777 log_warning_errno(errno, "Failed to remove directory '%s', ignoring: %m", created_dir);
1778
1779 temp = TAKE_PTR(created_dir);
1780
1781 return rcode;
1782 }
1783
1784 static int action_discover(void) {
1785 _cleanup_hashmap_free_ Hashmap *images = NULL;
1786 int r;
1787
1788 for (ImageClass cl = 0; cl < _IMAGE_CLASS_MAX; cl++) {
1789 r = image_discover(arg_runtime_scope, cl, NULL, &images);
1790 if (r < 0)
1791 return log_error_errno(r, "Failed to discover images: %m");
1792 }
1793
1794 if (hashmap_isempty(images) && !sd_json_format_enabled(arg_json_format_flags)) {
1795 log_info("No images found.");
1796 return 0;
1797 }
1798
1799 _cleanup_(table_unrefp) Table *t = table_new("name", "type", "class", "ro", "path", "time", "usage");
1800 if (!t)
1801 return log_oom();
1802
1803 table_set_align_percent(t, table_get_cell(t, 0, 6), 100);
1804 table_set_ersatz_string(t, TABLE_ERSATZ_DASH);
1805
1806 Image *img;
1807 HASHMAP_FOREACH(img, images) {
1808
1809 if (!arg_all && startswith(img->name, "."))
1810 continue;
1811
1812 r = table_add_many(
1813 t,
1814 TABLE_STRING, img->name,
1815 TABLE_SET_COLOR, startswith(img->name, ".") ? ANSI_GREY : NULL,
1816 TABLE_STRING, image_type_to_string(img->type),
1817 TABLE_STRING, image_class_to_string(img->class),
1818 TABLE_BOOLEAN, image_is_read_only(img),
1819 TABLE_SET_COLOR, image_is_read_only(img) ? ANSI_HIGHLIGHT_RED : ANSI_HIGHLIGHT_GREEN,
1820 TABLE_PATH, img->path,
1821 TABLE_TIMESTAMP, img->mtime != 0 ? img->mtime : img->crtime,
1822 TABLE_SIZE, img->usage,
1823 TABLE_SET_COLOR, img->usage <= 0 ? ANSI_HIGHLIGHT_RED : NULL);
1824 if (r < 0)
1825 return table_log_add_error(r);
1826 }
1827
1828 (void) table_set_sort(t, (size_t) 0);
1829
1830 return table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
1831 }
1832
1833 static int action_attach(DissectedImage *m, LoopDevice *d) {
1834 int r;
1835
1836 assert(m);
1837 assert(d);
1838
1839 r = loop_device_set_autoclear(d, false);
1840 if (r < 0)
1841 return log_error_errno(r, "Failed to disable auto-clear logic on loopback device: %m");
1842
1843 r = dissected_image_relinquish(m);
1844 if (r < 0)
1845 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
1846
1847 if (!arg_quiet)
1848 puts(d->node);
1849
1850 return 0;
1851 }
1852
1853 static int action_detach(const char *path) {
1854 _cleanup_(loop_device_unrefp) LoopDevice *loop = NULL;
1855 _cleanup_close_ int fd = -EBADF;
1856 struct stat st;
1857 int r;
1858
1859 assert(path);
1860
1861 fd = open(path, O_PATH|O_CLOEXEC);
1862 if (fd < 0)
1863 return log_error_errno(errno, "Failed to open '%s': %m", path);
1864
1865 if (fstat(fd, &st) < 0)
1866 return log_error_errno(errno, "Failed to stat '%s': %m", path);
1867
1868 if (S_ISBLK(st.st_mode)) {
1869 r = loop_device_open_from_fd(fd, O_RDONLY, LOCK_EX, &loop);
1870 if (r < 0)
1871 return log_error_errno(r, "Failed to open '%s' as loopback block device: %m", path);
1872
1873 } else if (S_ISREG(st.st_mode)) {
1874 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
1875
1876 /* If a regular file is specified, search for a loopback block device that is backed by it */
1877
1878 r = sd_device_enumerator_new(&e);
1879 if (r < 0)
1880 return log_error_errno(r, "Failed to allocate enumerator: %m");
1881
1882 r = sd_device_enumerator_add_match_subsystem(e, "block", true);
1883 if (r < 0)
1884 return log_error_errno(r, "Failed to match block devices: %m");
1885
1886 r = sd_device_enumerator_add_match_sysname(e, "loop*");
1887 if (r < 0)
1888 return log_error_errno(r, "Failed to match loopback block devices: %m");
1889
1890 (void) sd_device_enumerator_allow_uninitialized(e);
1891
1892 FOREACH_DEVICE(e, d) {
1893 _cleanup_(loop_device_unrefp) LoopDevice *entry_loop = NULL;
1894
1895 r = device_is_devtype(d, "disk");
1896 if (r < 0) {
1897 log_device_warning_errno(d, r, "Failed to check if device is a whole disk, skipping: %m");
1898 continue;
1899 }
1900 if (r == 0)
1901 continue; /* Filter out partition block devices */
1902
1903 r = loop_device_open(d, O_RDONLY, LOCK_SH, &entry_loop);
1904 if (r < 0) {
1905 log_device_warning_errno(d, r, "Failed to open loopback block device, skipping: %m");
1906 continue;
1907 }
1908
1909 if (entry_loop->backing_devno == st.st_dev && entry_loop->backing_inode == st.st_ino) {
1910 /* Found it! The kernel allows attaching a single file to multiple loopback
1911 * devices. Let's destruct them in reverse order, i.e. find the last matching
1912 * loopback device here, rather than the first. */
1913
1914 loop_device_unref(loop);
1915 loop = TAKE_PTR(entry_loop);
1916 }
1917 }
1918
1919 if (!loop)
1920 return log_error_errno(SYNTHETIC_ERRNO(ENXIO), "No loopback block device backed by '%s' found.", path);
1921
1922 r = loop_device_flock(loop, LOCK_EX);
1923 if (r < 0)
1924 return log_error_errno(r, "Failed to upgrade device lock: %m");
1925 }
1926
1927 r = loop_device_set_autoclear(loop, true);
1928 if (r < 0)
1929 log_warning_errno(r, "Failed to enable autoclear logic on '%s', ignoring: %m", loop->node);
1930
1931 loop_device_unrelinquish(loop);
1932 return 0;
1933 }
1934
1935 static int action_validate(void) {
1936 int r;
1937
1938 r = dissect_image_file_and_warn(
1939 arg_image,
1940 &arg_verity_settings,
1941 /* mount_options= */ NULL,
1942 arg_image_policy,
1943 arg_image_filter,
1944 arg_flags,
1945 /* ret= */ NULL);
1946 if (r < 0)
1947 return r;
1948
1949 if (isatty_safe(STDOUT_FILENO) && emoji_enabled())
1950 printf("%s ", glyph(GLYPH_SPARKLES));
1951
1952 printf("%sOK%s", ansi_highlight_green(), ansi_normal());
1953
1954 if (isatty_safe(STDOUT_FILENO) && emoji_enabled())
1955 printf(" %s", glyph(GLYPH_SPARKLES));
1956
1957 putc('\n', stdout);
1958 return 0;
1959 }
1960
1961 static int run(int argc, char *argv[]) {
1962 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
1963 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
1964 _cleanup_close_ int userns_fd = -EBADF;
1965 int r;
1966
1967 log_setup();
1968
1969 if (invoked_as(argv, "mount.ddi"))
1970 r = parse_argv_as_mount_helper(argc, argv);
1971 else
1972 r = parse_argv(argc, argv);
1973 if (r <= 0)
1974 return r;
1975
1976 if (arg_image) {
1977 r = path_pick_update_warn(
1978 &arg_image,
1979 pick_filter_image_raw,
1980 ELEMENTSOF(pick_filter_image_raw),
1981 PICK_ARCHITECTURE|PICK_TRIES,
1982 /* ret_result= */ NULL);
1983 if (r < 0)
1984 return r;
1985 }
1986
1987 if (arg_root) {
1988 r = path_pick_update_warn(
1989 &arg_root,
1990 pick_filter_image_dir,
1991 ELEMENTSOF(pick_filter_image_dir),
1992 PICK_ARCHITECTURE|PICK_TRIES,
1993 /* ret_result= */ NULL);
1994 if (r < 0)
1995 return r;
1996 }
1997
1998 switch (arg_action) {
1999 case ACTION_UMOUNT:
2000 return action_umount(arg_path);
2001
2002 case ACTION_DETACH:
2003 return action_detach(arg_image);
2004
2005 case ACTION_DISCOVER:
2006 return action_discover();
2007
2008 default:
2009 /* All other actions need the image dissected (except for ACTION_VALIDATE, see below) */
2010 ;
2011 }
2012
2013 if (arg_image) {
2014 r = verity_settings_load(
2015 &arg_verity_settings,
2016 arg_image,
2017 /* root_hash_path= */ NULL,
2018 /* root_hash_sig_path= */ NULL);
2019 if (r < 0)
2020 return log_error_errno(r, "Failed to read verity artifacts for %s: %m", arg_image);
2021
2022 if (arg_verity_settings.data_path)
2023 arg_flags |= DISSECT_IMAGE_NO_PARTITION_TABLE; /* We only support Verity per file system,
2024 * hence if there's external Verity data
2025 * available we turn off partition table
2026 * support */
2027 }
2028
2029 if (!arg_loop_ref && arg_loop_ref_auto) {
2030 r = path_extract_filename(arg_image, &arg_loop_ref);
2031 if (r < 0)
2032 return log_error_errno(r, "Failed to extract file name from image path '%s': %m", arg_image);
2033 }
2034
2035 if (arg_action == ACTION_VALIDATE)
2036 return action_validate();
2037
2038 if (arg_image) {
2039 /* First try locally, if we are allowed to */
2040 if (!arg_via_service) {
2041 uint32_t loop_flags;
2042 int open_flags;
2043
2044 open_flags = FLAGS_SET(arg_flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : -1;
2045 loop_flags = FLAGS_SET(arg_flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN;
2046
2047 if (arg_in_memory)
2048 r = loop_device_make_by_path_memory(arg_image, open_flags, /* sector_size= */ UINT32_MAX, loop_flags, LOCK_SH, &d);
2049 else
2050 r = loop_device_make_by_path(arg_image, open_flags, /* sector_size= */ UINT32_MAX, loop_flags, LOCK_SH, &d);
2051 if (r < 0) {
2052 if ((r != -ENOENT && !ERRNO_IS_PRIVILEGE(r)) || arg_action == ACTION_ATTACH)
2053 return log_error_errno(r, "Failed to set up loopback device for %s: %m", arg_image);
2054
2055 log_debug_errno(r, "Lacking permissions or missing /dev/loop-control to set up loopback block device for %s, using service: %m", arg_image);
2056 arg_via_service = true;
2057 } else {
2058 if (arg_loop_ref && !LOOP_DEVICE_IS_FOREIGN(d)) {
2059 r = loop_device_set_filename(d, arg_loop_ref);
2060 if (r < 0)
2061 log_warning_errno(r, "Failed to set loop reference string to '%s', ignoring: %m", arg_loop_ref);
2062 }
2063
2064 r = dissect_loop_device_and_warn(
2065 d,
2066 &arg_verity_settings,
2067 /* mount_options= */ NULL,
2068 arg_image_policy,
2069 arg_image_filter,
2070 arg_flags,
2071 &m);
2072 if (r < 0)
2073 return r;
2074
2075 if (arg_action == ACTION_ATTACH)
2076 return action_attach(m, d);
2077
2078 r = dissected_image_load_verity_sig_partition(
2079 m,
2080 d->fd,
2081 &arg_verity_settings);
2082 if (r < 0)
2083 return log_error_errno(r, "Failed to load verity signature partition: %m");
2084
2085 r = dissected_image_guess_verity_roothash(
2086 m,
2087 &arg_verity_settings);
2088 if (r < 0)
2089 return log_error_errno(r, "Failed to guess verity root hash: %m");
2090
2091 if (arg_action != ACTION_DISSECT) {
2092 _cleanup_(erase_and_freep) char *envpw = NULL;
2093
2094 r = getenv_steal_erase("PASSWORD", &envpw);
2095 if (r < 0)
2096 return log_error_errno(r, "Failed to acquire password from environment: %m");
2097
2098 r = dissected_image_decrypt_interactively(
2099 m,
2100 envpw,
2101 &arg_verity_settings,
2102 arg_image_policy,
2103 arg_flags);
2104 if (r < 0)
2105 return r;
2106 }
2107 }
2108 }
2109
2110 /* Try via service */
2111 if (arg_via_service) {
2112 if (arg_in_memory)
2113 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "--in-memory= not supported when operating via systemd-mountfsd.");
2114
2115 if (arg_loop_ref || arg_loop_ref_auto) /* yes, the 2nd check is strictly speaking redundant, given the normalization we did above, but let's be explicit here */
2116 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "--loop-ref=/--loop-ref-auto not supported when operating via systemd-mountfsd.");
2117
2118 /* Don't run things in private userns, if the mount shall be attached to the host
2119 * or if we're copying from/to the host. */
2120 if (!IN_SET(arg_action, ACTION_MOUNT, ACTION_WITH, ACTION_COPY_FROM, ACTION_COPY_TO)) {
2121 userns_fd = nsresource_allocate_userns(
2122 /* vl= */ NULL,
2123 /* name= */ NULL,
2124 NSRESOURCE_UIDS_64K); /* allocate 64K users by default */
2125 if (userns_fd < 0)
2126 return log_error_errno(userns_fd, "Failed to allocate user namespace with 64K users: %m");
2127 }
2128
2129 r = mountfsd_mount_image(
2130 /* vl= */ NULL,
2131 arg_image,
2132 userns_fd,
2133 /* options= */ NULL,
2134 arg_image_policy,
2135 &arg_verity_settings,
2136 arg_flags,
2137 &m);
2138 if (r < 0)
2139 return log_error_errno(r, "Failed to mount image via mountfsd: %m");
2140 }
2141 }
2142
2143 switch (arg_action) {
2144
2145 case ACTION_DISSECT:
2146 return action_dissect(m, d, userns_fd);
2147
2148 case ACTION_MOUNT:
2149 return action_mount(m, d);
2150
2151 case ACTION_LIST:
2152 case ACTION_MTREE:
2153 case ACTION_COPY_FROM:
2154 case ACTION_COPY_TO:
2155 case ACTION_MAKE_ARCHIVE:
2156 case ACTION_SHIFT:
2157 return action_list_or_mtree_or_copy_or_make_archive(m, d, userns_fd);
2158
2159 case ACTION_WITH:
2160 return action_with(m, d);
2161
2162 default:
2163 assert_not_reached();
2164 }
2165 }
2166
2167 DEFINE_MAIN_FUNCTION(run);