]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/dissect/dissect.c
Merge pull request #16228 from ddstreet/administrative_state
[thirdparty/systemd.git] / src / dissect / dissect.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <getopt.h>
5 #include <linux/loop.h>
6 #include <stdio.h>
7 #include <sys/ioctl.h>
8 #include <sys/mount.h>
9
10 #include "architecture.h"
11 #include "copy.h"
12 #include "dissect-image.h"
13 #include "fd-util.h"
14 #include "fileio.h"
15 #include "format-table.h"
16 #include "format-util.h"
17 #include "fs-util.h"
18 #include "hexdecoct.h"
19 #include "log.h"
20 #include "loop-util.h"
21 #include "main-func.h"
22 #include "mkdir.h"
23 #include "mount-util.h"
24 #include "namespace-util.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "pretty-print.h"
28 #include "stat-util.h"
29 #include "string-util.h"
30 #include "strv.h"
31 #include "terminal-util.h"
32 #include "tmpfile-util.h"
33 #include "user-util.h"
34 #include "util.h"
35
36 static enum {
37 ACTION_DISSECT,
38 ACTION_MOUNT,
39 ACTION_COPY_FROM,
40 ACTION_COPY_TO,
41 } arg_action = ACTION_DISSECT;
42 static const char *arg_image = NULL;
43 static const char *arg_path = NULL;
44 static const char *arg_source = NULL;
45 static const char *arg_target = NULL;
46 static DissectImageFlags arg_flags = DISSECT_IMAGE_REQUIRE_ROOT|DISSECT_IMAGE_DISCARD_ON_LOOP|DISSECT_IMAGE_RELAX_VAR_CHECK|DISSECT_IMAGE_FSCK;
47 static VeritySettings arg_verity_settings = VERITY_SETTINGS_DEFAULT;
48 static JsonFormatFlags arg_json_format_flags = JSON_FORMAT_OFF;
49 static PagerFlags arg_pager_flags = 0;
50 static bool arg_legend = true;
51
52 STATIC_DESTRUCTOR_REGISTER(arg_verity_settings, verity_settings_done);
53
54 static int help(void) {
55 _cleanup_free_ char *link = NULL;
56 int r;
57
58 r = terminal_urlify_man("systemd-dissect", "1", &link);
59 if (r < 0)
60 return log_oom();
61
62 printf("%1$s [OPTIONS...] IMAGE\n"
63 "%1$s [OPTIONS...] --mount IMAGE PATH\n"
64 "%1$s [OPTIONS...] --copy-from IMAGE PATH [TARGET]\n"
65 "%1$s [OPTIONS...] --copy-to IMAGE [SOURCE] PATH\n\n"
66 "%5$sDissect a file system OS image.%6$s\n\n"
67 "%3$sOptions:%4$s\n"
68 " --no-pager Do not pipe output into a pager\n"
69 " --no-legend Do not show the headers and footers\n"
70 " -r --read-only Mount read-only\n"
71 " --fsck=BOOL Run fsck before mounting\n"
72 " --mkdir Make mount directory before mounting, if missing\n"
73 " --discard=MODE Choose 'discard' mode (disabled, loop, all, crypto)\n"
74 " --root-hash=HASH Specify root hash for verity\n"
75 " --root-hash-sig=SIG Specify pkcs7 signature of root hash for verity\n"
76 " as a DER encoded PKCS7, either as a path to a file\n"
77 " or as an ASCII base64 encoded string prefixed by\n"
78 " 'base64:'\n"
79 " --verity-data=PATH Specify data file with hash tree for verity if it is\n"
80 " not embedded in IMAGE\n"
81 " --json=pretty|short|off\n"
82 " Generate JSON output\n"
83 "\n%3$sCommands:%4$s\n"
84 " -h --help Show this help\n"
85 " --version Show package version\n"
86 " -m --mount Mount the image to the specified directory\n"
87 " -M Shortcut for --mount --mkdir\n"
88 " -x --copy-from Copy files from image to host\n"
89 " -a --copy-to Copy files from host to image\n"
90 "\nSee the %2$s for details.\n"
91 , program_invocation_short_name
92 , link
93 , ansi_underline(), ansi_normal()
94 , ansi_highlight(), ansi_normal());
95
96 return 0;
97 }
98
99 static int parse_argv(int argc, char *argv[]) {
100
101 enum {
102 ARG_VERSION = 0x100,
103 ARG_NO_PAGER,
104 ARG_NO_LEGEND,
105 ARG_DISCARD,
106 ARG_FSCK,
107 ARG_ROOT_HASH,
108 ARG_ROOT_HASH_SIG,
109 ARG_VERITY_DATA,
110 ARG_MKDIR,
111 ARG_JSON,
112 };
113
114 static const struct option options[] = {
115 { "help", no_argument, NULL, 'h' },
116 { "version", no_argument, NULL, ARG_VERSION },
117 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
118 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
119 { "mount", no_argument, NULL, 'm' },
120 { "read-only", no_argument, NULL, 'r' },
121 { "discard", required_argument, NULL, ARG_DISCARD },
122 { "fsck", required_argument, NULL, ARG_FSCK },
123 { "root-hash", required_argument, NULL, ARG_ROOT_HASH },
124 { "root-hash-sig", required_argument, NULL, ARG_ROOT_HASH_SIG },
125 { "verity-data", required_argument, NULL, ARG_VERITY_DATA },
126 { "mkdir", no_argument, NULL, ARG_MKDIR },
127 { "copy-from", no_argument, NULL, 'x' },
128 { "copy-to", no_argument, NULL, 'a' },
129 { "json", required_argument, NULL, ARG_JSON },
130 {}
131 };
132
133 int c, r;
134
135 assert(argc >= 0);
136 assert(argv);
137
138 while ((c = getopt_long(argc, argv, "hmrMxa", options, NULL)) >= 0) {
139
140 switch (c) {
141
142 case 'h':
143 return help();
144
145 case ARG_VERSION:
146 return version();
147
148 case ARG_NO_PAGER:
149 arg_pager_flags |= PAGER_DISABLE;
150 break;
151
152 case ARG_NO_LEGEND:
153 arg_legend = false;
154 break;
155
156 case 'm':
157 arg_action = ACTION_MOUNT;
158 break;
159
160 case ARG_MKDIR:
161 arg_flags |= DISSECT_IMAGE_MKDIR;
162 break;
163
164 case 'M':
165 /* Shortcut combination of the above two */
166 arg_action = ACTION_MOUNT;
167 arg_flags |= DISSECT_IMAGE_MKDIR;
168 break;
169
170 case 'x':
171 arg_action = ACTION_COPY_FROM;
172 arg_flags |= DISSECT_IMAGE_READ_ONLY;
173 break;
174
175 case 'a':
176 arg_action = ACTION_COPY_TO;
177 break;
178
179 case 'r':
180 arg_flags |= DISSECT_IMAGE_READ_ONLY;
181 break;
182
183 case ARG_DISCARD: {
184 DissectImageFlags flags;
185
186 if (streq(optarg, "disabled"))
187 flags = 0;
188 else if (streq(optarg, "loop"))
189 flags = DISSECT_IMAGE_DISCARD_ON_LOOP;
190 else if (streq(optarg, "all"))
191 flags = DISSECT_IMAGE_DISCARD_ON_LOOP | DISSECT_IMAGE_DISCARD;
192 else if (streq(optarg, "crypt"))
193 flags = DISSECT_IMAGE_DISCARD_ANY;
194 else if (streq(optarg, "list")) {
195 puts("disabled\n"
196 "all\n"
197 "crypt\n"
198 "loop");
199 return 0;
200 } else
201 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
202 "Unknown --discard= parameter: %s",
203 optarg);
204 arg_flags = (arg_flags & ~DISSECT_IMAGE_DISCARD_ANY) | flags;
205
206 break;
207 }
208
209 case ARG_ROOT_HASH: {
210 _cleanup_free_ void *p = NULL;
211 size_t l;
212
213 r = unhexmem(optarg, strlen(optarg), &p, &l);
214 if (r < 0)
215 return log_error_errno(r, "Failed to parse root hash '%s': %m", optarg);
216 if (l < sizeof(sd_id128_t))
217 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
218 "Root hash must be at least 128bit long: %s", optarg);
219
220 free_and_replace(arg_verity_settings.root_hash, p);
221 arg_verity_settings.root_hash_size = l;
222 break;
223 }
224
225 case ARG_ROOT_HASH_SIG: {
226 char *value;
227 size_t l;
228 void *p;
229
230 if ((value = startswith(optarg, "base64:"))) {
231 r = unbase64mem(value, strlen(value), &p, &l);
232 if (r < 0)
233 return log_error_errno(r, "Failed to parse root hash signature '%s': %m", optarg);
234 } else {
235 r = read_full_file(optarg, (char**) &p, &l);
236 if (r < 0)
237 return log_error_errno(r, "Failed to read root hash signature file '%s': %m", optarg);
238 }
239
240 free_and_replace(arg_verity_settings.root_hash_sig, p);
241 arg_verity_settings.root_hash_sig_size = l;
242 break;
243 }
244
245 case ARG_VERITY_DATA:
246 r = parse_path_argument_and_warn(optarg, false, &arg_verity_settings.data_path);
247 if (r < 0)
248 return r;
249 break;
250
251 case ARG_FSCK:
252 r = parse_boolean(optarg);
253 if (r < 0)
254 return log_error_errno(r, "Failed to parse --fsck= parameter: %s", optarg);
255
256 SET_FLAG(arg_flags, DISSECT_IMAGE_FSCK, r);
257 break;
258
259 case ARG_JSON:
260 r = json_parse_cmdline_parameter_and_warn(optarg, &arg_json_format_flags);
261 if (r <= 0)
262 return r;
263
264 break;
265
266 case '?':
267 return -EINVAL;
268
269 default:
270 assert_not_reached("Unhandled option");
271 }
272
273 }
274
275 switch (arg_action) {
276
277 case ACTION_DISSECT:
278 if (optind + 1 != argc)
279 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
280 "Expected an image file path as only argument.");
281
282 arg_image = argv[optind];
283 arg_flags |= DISSECT_IMAGE_READ_ONLY;
284 break;
285
286 case ACTION_MOUNT:
287 if (optind + 2 != argc)
288 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
289 "Expected an image file path and mount point path as only arguments.");
290
291 arg_image = argv[optind];
292 arg_path = argv[optind + 1];
293 break;
294
295 case ACTION_COPY_FROM:
296 if (argc < optind + 2 || argc > optind + 3)
297 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
298 "Expected an image file path, a source path and an optional destination path as only arguments.");
299
300 arg_image = argv[optind];
301 arg_source = argv[optind + 1];
302 arg_target = argc > optind + 2 ? argv[optind + 2] : "-" /* this means stdout */ ;
303
304 arg_flags |= DISSECT_IMAGE_READ_ONLY;
305 break;
306
307 case ACTION_COPY_TO:
308 if (argc < optind + 2 || argc > optind + 3)
309 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
310 "Expected an image file path, an optional source path and a destination path as only arguments.");
311
312 arg_image = argv[optind];
313
314 if (argc > optind + 2) {
315 arg_source = argv[optind + 1];
316 arg_target = argv[optind + 2];
317 } else {
318 arg_source = "-"; /* this means stdin */
319 arg_target = argv[optind + 1];
320 }
321
322 break;
323
324 default:
325 assert_not_reached("Unknown action.");
326 }
327
328 return 1;
329 }
330
331 static int strv_pair_to_json(char **l, JsonVariant **ret) {
332 _cleanup_strv_free_ char **jl = NULL;
333 char **a, **b;
334
335 STRV_FOREACH_PAIR(a, b, l) {
336 char *j;
337
338 j = strjoin(*a, "=", *b);
339 if (!j)
340 return log_oom();
341
342 if (strv_consume(&jl, j) < 0)
343 return log_oom();
344 }
345
346 return json_variant_new_array_strv(ret, jl);
347 }
348
349 static int action_dissect(DissectedImage *m, LoopDevice *d) {
350 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
351 _cleanup_(table_unrefp) Table *t = NULL;
352 uint64_t size = UINT64_MAX;
353 int r;
354
355 assert(m);
356 assert(d);
357
358 if (arg_json_format_flags & (JSON_FORMAT_OFF|JSON_FORMAT_PRETTY|JSON_FORMAT_PRETTY_AUTO))
359 (void) pager_open(arg_pager_flags);
360
361 if (arg_json_format_flags & JSON_FORMAT_OFF)
362 printf(" Name: %s\n", basename(arg_image));
363
364 if (ioctl(d->fd, BLKGETSIZE64, &size) < 0)
365 log_debug_errno(errno, "Failed to query size of loopback device: %m");
366 else if (arg_json_format_flags & JSON_FORMAT_OFF) {
367 char s[FORMAT_BYTES_MAX];
368 printf(" Size: %s\n", format_bytes(s, sizeof(s), size));
369 }
370
371 if (arg_json_format_flags & JSON_FORMAT_OFF)
372 putc('\n', stdout);
373
374 r = dissected_image_acquire_metadata(m);
375 if (r == -ENXIO)
376 return log_error_errno(r, "No root partition discovered.");
377 if (r == -EUCLEAN)
378 return log_error_errno(r, "File system check of image failed.");
379 if (r == -EMEDIUMTYPE)
380 log_warning_errno(r, "Not a valid OS image, no os-release file included. Proceeding anyway.");
381 else if (r == -EUNATCH)
382 log_warning_errno(r, "OS image is encrypted, proceeding without showing OS image metadata.");
383 else if (r == -EBUSY)
384 log_warning_errno(r, "OS image is currently in use, proceeding without showing OS image metadata.");
385 else if (r < 0)
386 return log_error_errno(r, "Failed to acquire image metadata: %m");
387 else if (arg_json_format_flags & JSON_FORMAT_OFF) {
388 if (m->hostname)
389 printf(" Hostname: %s\n", m->hostname);
390
391 if (!sd_id128_is_null(m->machine_id))
392 printf("Machine ID: " SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(m->machine_id));
393
394 if (!strv_isempty(m->machine_info)) {
395 char **p, **q;
396
397 STRV_FOREACH_PAIR(p, q, m->machine_info)
398 printf("%s %s=%s\n",
399 p == m->machine_info ? "Mach. Info:" : " ",
400 *p, *q);
401 }
402
403 if (!strv_isempty(m->os_release)) {
404 char **p, **q;
405
406 STRV_FOREACH_PAIR(p, q, m->os_release)
407 printf("%s %s=%s\n",
408 p == m->os_release ? "OS Release:" : " ",
409 *p, *q);
410 }
411
412 if (m->hostname ||
413 !sd_id128_is_null(m->machine_id) ||
414 !strv_isempty(m->machine_info) ||
415 !strv_isempty(m->os_release))
416 putc('\n', stdout);
417 } else {
418 _cleanup_(json_variant_unrefp) JsonVariant *mi = NULL, *osr = NULL;
419
420 if (!strv_isempty(m->machine_info)) {
421 r = strv_pair_to_json(m->machine_info, &mi);
422 if (r < 0)
423 return log_oom();
424 }
425
426 if (!strv_isempty(m->os_release)) {
427 r = strv_pair_to_json(m->os_release, &osr);
428 if (r < 0)
429 return log_oom();
430 }
431
432 r = json_build(&v, JSON_BUILD_OBJECT(
433 JSON_BUILD_PAIR("name", JSON_BUILD_STRING(basename(arg_image))),
434 JSON_BUILD_PAIR("size", JSON_BUILD_INTEGER(size)),
435 JSON_BUILD_PAIR_CONDITION(m->hostname, "hostname", JSON_BUILD_STRING(m->hostname)),
436 JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(m->machine_id), "machineId", JSON_BUILD_ID128(m->machine_id)),
437 JSON_BUILD_PAIR_CONDITION(mi, "machineInfo", JSON_BUILD_VARIANT(mi)),
438 JSON_BUILD_PAIR_CONDITION(osr, "osRelease", JSON_BUILD_VARIANT(osr))));
439 if (r < 0)
440 return log_oom();
441 }
442
443 t = table_new("rw", "designator", "partition uuid", "fstype", "architecture", "verity", "node", "partno");
444 if (!t)
445 return log_oom();
446
447 (void) table_set_empty_string(t, "-");
448 (void) table_set_align_percent(t, table_get_cell(t, 0, 7), 100);
449
450 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
451 DissectedPartition *p = m->partitions + i;
452
453 if (!p->found)
454 continue;
455
456 r = table_add_many(
457 t,
458 TABLE_STRING, p->rw ? "rw" : "ro",
459 TABLE_STRING, partition_designator_to_string(i));
460 if (r < 0)
461 return table_log_add_error(r);
462
463 if (sd_id128_is_null(p->uuid))
464 r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
465 else
466 r = table_add_cell(t, NULL, TABLE_UUID, &p->uuid);
467 if (r < 0)
468 return table_log_add_error(r);
469
470 r = table_add_many(
471 t,
472 TABLE_STRING, p->fstype,
473 TABLE_STRING, architecture_to_string(p->architecture));
474 if (r < 0)
475 return table_log_add_error(r);
476
477 if (arg_verity_settings.data_path)
478 r = table_add_cell(t, NULL, TABLE_STRING, "external");
479 else if (dissected_image_can_do_verity(m, i))
480 r = table_add_cell(t, NULL, TABLE_STRING, yes_no(dissected_image_has_verity(m, i)));
481 else
482 r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
483 if (r < 0)
484 return table_log_add_error(r);
485
486 if (p->partno < 0) /* no partition table, naked file system */ {
487 r = table_add_cell(t, NULL, TABLE_STRING, arg_image);
488 if (r < 0)
489 return table_log_add_error(r);
490
491 r = table_add_cell(t, NULL, TABLE_EMPTY, NULL);
492 } else {
493 r = table_add_cell(t, NULL, TABLE_STRING, p->node);
494 if (r < 0)
495 return table_log_add_error(r);
496
497 r = table_add_cell(t, NULL, TABLE_INT, &p->partno);
498 }
499 if (r < 0)
500 return table_log_add_error(r);
501 }
502
503 if (arg_json_format_flags & JSON_FORMAT_OFF) {
504 (void) table_set_header(t, arg_legend);
505
506 r = table_print(t, NULL);
507 if (r < 0)
508 return table_log_print_error(r);
509 } else {
510 _cleanup_(json_variant_unrefp) JsonVariant *jt = NULL;
511
512 r = table_to_json(t, &jt);
513 if (r < 0)
514 return log_error_errno(r, "Failed to convert table to JSON: %m");
515
516 r = json_variant_set_field(&v, "mounts", jt);
517 if (r < 0)
518 return log_oom();
519
520 json_variant_dump(v, arg_json_format_flags, stdout, NULL);
521 }
522
523 return 0;
524 }
525
526 static int action_mount(DissectedImage *m, LoopDevice *d) {
527 _cleanup_(decrypted_image_unrefp) DecryptedImage *di = NULL;
528 int r;
529
530 assert(m);
531 assert(d);
532
533 r = dissected_image_decrypt_interactively(
534 m, NULL,
535 &arg_verity_settings,
536 arg_flags,
537 &di);
538 if (r < 0)
539 return r;
540
541 r = dissected_image_mount_and_warn(m, arg_path, UID_INVALID, arg_flags);
542 if (r < 0)
543 return r;
544
545 if (di) {
546 r = decrypted_image_relinquish(di);
547 if (r < 0)
548 return log_error_errno(r, "Failed to relinquish DM devices: %m");
549 }
550
551 loop_device_relinquish(d);
552 return 0;
553 }
554
555 static int action_copy(DissectedImage *m, LoopDevice *d) {
556 _cleanup_(umount_and_rmdir_and_freep) char *mounted_dir = NULL;
557 _cleanup_(decrypted_image_unrefp) DecryptedImage *di = NULL;
558 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
559 _cleanup_free_ char *temp = NULL;
560 int r;
561
562 assert(m);
563 assert(d);
564
565 r = dissected_image_decrypt_interactively(
566 m, NULL,
567 &arg_verity_settings,
568 arg_flags,
569 &di);
570 if (r < 0)
571 return r;
572
573 r = detach_mount_namespace();
574 if (r < 0)
575 return log_error_errno(r, "Failed to detach mount namespace: %m");
576
577 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
578 if (r < 0)
579 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
580
581 r = mkdir_p(temp, 0700);
582 if (r < 0)
583 return log_error_errno(r, "Failed to create mount point: %m");
584
585 created_dir = TAKE_PTR(temp);
586
587 r = dissected_image_mount_and_warn(m, created_dir, UID_INVALID, arg_flags);
588 if (r < 0)
589 return r;
590
591 mounted_dir = TAKE_PTR(created_dir);
592
593 if (di) {
594 r = decrypted_image_relinquish(di);
595 if (r < 0)
596 return log_error_errno(r, "Failed to relinquish DM devices: %m");
597 }
598
599 loop_device_relinquish(d);
600
601 if (arg_action == ACTION_COPY_FROM) {
602 _cleanup_close_ int source_fd = -1, target_fd = -1;
603
604 source_fd = chase_symlinks_and_open(arg_source, mounted_dir, CHASE_PREFIX_ROOT|CHASE_WARN, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
605 if (source_fd < 0)
606 return log_error_errno(source_fd, "Failed to open source path '%s' in image '%s': %m", arg_source, arg_image);
607
608 /* Copying to stdout? */
609 if (streq(arg_target, "-")) {
610 r = copy_bytes(source_fd, STDOUT_FILENO, (uint64_t) -1, COPY_REFLINK);
611 if (r < 0)
612 return log_error_errno(r, "Failed to copy bytes from %s in mage '%s' to stdout: %m", arg_source, arg_image);
613
614 /* When we copy to stdou we don't copy any attributes (i.e. no access mode, no ownership, no xattr, no times) */
615 return 0;
616 }
617
618 /* Try to copy as directory? */
619 r = copy_directory_fd(source_fd, arg_target, COPY_REFLINK|COPY_MERGE_EMPTY|COPY_SIGINT|COPY_HARDLINKS);
620 if (r >= 0)
621 return 0;
622 if (r != -ENOTDIR)
623 return log_error_errno(r, "Failed to copy %s in image '%s' to '%s': %m", arg_source, arg_image, arg_target);
624
625 r = fd_verify_regular(source_fd);
626 if (r == -EISDIR)
627 return log_error_errno(r, "Target '%s' exists already and is not a directory.", arg_target);
628 if (r < 0)
629 return log_error_errno(r, "Source path %s in image '%s' is neither regular file nor directory, refusing: %m", arg_source, arg_image);
630
631 /* Nah, it's a plain file! */
632 target_fd = open(arg_target, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
633 if (target_fd < 0)
634 return log_error_errno(errno, "Failed to create regular file at target path '%s': %m", arg_target);
635
636 r = copy_bytes(source_fd, target_fd, (uint64_t) -1, COPY_REFLINK);
637 if (r < 0)
638 return log_error_errno(r, "Failed to copy bytes from %s in mage '%s' to '%s': %m", arg_source, arg_image, arg_target);
639
640 (void) copy_xattr(source_fd, target_fd);
641 (void) copy_access(source_fd, target_fd);
642 (void) copy_times(source_fd, target_fd, 0);
643
644 /* When this is a regular file we don't copy ownership! */
645
646 } else {
647 _cleanup_close_ int source_fd = -1, target_fd = -1;
648 _cleanup_close_ int dfd = -1;
649 _cleanup_free_ char *dn = NULL;
650
651 assert(arg_action == ACTION_COPY_TO);
652
653 dn = dirname_malloc(arg_target);
654 if (!dn)
655 return log_oom();
656
657 r = chase_symlinks(dn, mounted_dir, CHASE_PREFIX_ROOT|CHASE_WARN, NULL, &dfd);
658 if (r < 0)
659 return log_error_errno(r, "Failed to open '%s': %m", dn);
660
661 /* Are we reading from stdin? */
662 if (streq(arg_source, "-")) {
663 target_fd = openat(dfd, basename(arg_target), O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_EXCL, 0644);
664 if (target_fd < 0)
665 return log_error_errno(errno, "Failed to open target file '%s': %m", arg_target);
666
667 r = copy_bytes(STDIN_FILENO, target_fd, (uint64_t) -1, COPY_REFLINK);
668 if (r < 0)
669 return log_error_errno(r, "Failed to copy bytes from stdin to '%s' in image '%s': %m", arg_target, arg_image);
670
671 /* When we copy from stdin we don't copy any attributes (i.e. no access mode, no ownership, no xattr, no times) */
672 return 0;
673 }
674
675 source_fd = open(arg_source, O_RDONLY|O_CLOEXEC|O_NOCTTY);
676 if (source_fd < 0)
677 return log_error_errno(source_fd, "Failed to open source path '%s': %m", arg_source);
678
679 r = fd_verify_regular(source_fd);
680 if (r < 0) {
681 if (r != -EISDIR)
682 return log_error_errno(r, "Source '%s' is neither regular file nor directory: %m", arg_source);
683
684 /* We are looking at a directory. */
685
686 target_fd = openat(dfd, basename(arg_target), O_RDONLY|O_DIRECTORY|O_CLOEXEC);
687 if (target_fd < 0) {
688 if (errno != ENOENT)
689 return log_error_errno(errno, "Failed to open destination '%s': %m", arg_target);
690
691 r = copy_tree_at(source_fd, ".", dfd, basename(arg_target), UID_INVALID, GID_INVALID, COPY_REFLINK|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS);
692 } else
693 r = copy_tree_at(source_fd, ".", target_fd, ".", UID_INVALID, GID_INVALID, COPY_REFLINK|COPY_REPLACE|COPY_SIGINT|COPY_HARDLINKS);
694 if (r < 0)
695 return log_error_errno(r, "Failed to copy '%s' to '%s' in image '%s': %m", arg_source, arg_target, arg_image);
696
697 return 0;
698 }
699
700 /* We area looking at a regular file */
701 target_fd = openat(dfd, basename(arg_target), O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_EXCL, 0600);
702 if (target_fd < 0)
703 return log_error_errno(errno, "Failed to open target file '%s': %m", arg_target);
704
705 r = copy_bytes(source_fd, target_fd, (uint64_t) -1, COPY_REFLINK);
706 if (r < 0)
707 return log_error_errno(r, "Failed to copy bytes from '%s' to '%s' in image '%s': %m", arg_source, arg_target, arg_image);
708
709 (void) copy_xattr(source_fd, target_fd);
710 (void) copy_access(source_fd, target_fd);
711 (void) copy_times(source_fd, target_fd, 0);
712
713 /* When this is a regular file we don't copy ownership! */
714 }
715
716 return 0;
717 }
718
719 static int run(int argc, char *argv[]) {
720 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
721 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
722 int r;
723
724 log_parse_environment();
725 log_open();
726
727 r = parse_argv(argc, argv);
728 if (r <= 0)
729 return r;
730
731 r = verity_settings_load(
732 &arg_verity_settings,
733 arg_image, NULL, NULL);
734 if (r < 0)
735 return log_error_errno(r, "Failed to read verity artifacts for %s: %m", arg_image);
736
737 if (arg_verity_settings.data_path)
738 arg_flags |= DISSECT_IMAGE_NO_PARTITION_TABLE; /* We only support Verity per file system,
739 * hence if there's external Verity data
740 * available we turn off partition table
741 * support */
742
743 r = loop_device_make_by_path(
744 arg_image,
745 FLAGS_SET(arg_flags, DISSECT_IMAGE_READ_ONLY) ? O_RDONLY : O_RDWR,
746 FLAGS_SET(arg_flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
747 &d);
748 if (r < 0)
749 return log_error_errno(r, "Failed to set up loopback device: %m");
750
751 r = dissect_image_and_warn(
752 d->fd,
753 arg_image,
754 &arg_verity_settings,
755 NULL,
756 arg_flags,
757 &m);
758 if (r < 0)
759 return r;
760
761 switch (arg_action) {
762
763 case ACTION_DISSECT:
764 r = action_dissect(m, d);
765 break;
766
767 case ACTION_MOUNT:
768 r = action_mount(m, d);
769 break;
770
771 case ACTION_COPY_FROM:
772 case ACTION_COPY_TO:
773 r = action_copy(m, d);
774 break;
775
776 default:
777 assert_not_reached("Unknown action.");
778 }
779
780 return r;
781 }
782
783 DEFINE_MAIN_FUNCTION(run);