summaryrefslogtreecommitdiffstats
path: root/src/import/importctl.c
blob: f939d80815dcae13642006c6c546683f7069f3ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
/* SPDX-License-Identifier: LGPL-2.1-or-later */

#include <getopt.h>

#include "sd-bus.h"

#include "alloc-util.h"
#include "build.h"
#include "bus-error.h"
#include "bus-locator.h"
#include "bus-util.h"
#include "discover-image.h"
#include "fd-util.h"
#include "format-table.h"
#include "hostname-util.h"
#include "import-common.h"
#include "import-util.h"
#include "locale-util.h"
#include "log.h"
#include "macro.h"
#include "main-func.h"
#include "os-util.h"
#include "pager.h"
#include "parse-argument.h"
#include "parse-util.h"
#include "path-util.h"
#include "pretty-print.h"
#include "signal-util.h"
#include "sort-util.h"
#include "spawn-polkit-agent.h"
#include "string-table.h"
#include "verbs.h"
#include "web-util.h"

static PagerFlags arg_pager_flags = 0;
static bool arg_legend = true;
static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
static const char *arg_host = NULL;
static ImportFlags arg_import_flags = 0;
static ImportFlags arg_import_flags_mask = 0; /* Indicates which flags have been explicitly set to on or to off */
static bool arg_quiet = false;
static bool arg_ask_password = true;
static ImportVerify arg_verify = IMPORT_VERIFY_SIGNATURE;
static const char* arg_format = NULL;
static JsonFormatFlags arg_json_format_flags = JSON_FORMAT_OFF;
static ImageClass arg_image_class = _IMAGE_CLASS_INVALID;

#define PROGRESS_PREFIX "Total: "

static int settle_image_class(void) {

        if (arg_image_class < 0) {
                _cleanup_free_ char *j = NULL;

                for (ImageClass class = 0; class < _IMAGE_CLASS_MAX; class++)
                        if (strextendf_with_separator(&j, ", ", "%s (downloads to %s/)",
                                                      image_class_to_string(class),
                                                      image_root_to_string(class)) < 0)
                                return log_oom();

                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "No image class specified, retry with --class= set to one of: %s.", j);
        }

        /* Keep the original pristine downloaded file as a copy only when dealing with machine images,
         * because unlike sysext/confext/portable they are typically modified during runtime. */
        if (!FLAGS_SET(arg_import_flags_mask, IMPORT_PULL_KEEP_DOWNLOAD))
                SET_FLAG(arg_import_flags, IMPORT_PULL_KEEP_DOWNLOAD, arg_image_class == IMAGE_MACHINE);

        return 0;
}

typedef struct Context {
        const char *object_path;
        double progress;
} Context;

static int match_log_message(sd_bus_message *m, void *userdata, sd_bus_error *error) {
        Context *c = ASSERT_PTR(userdata);
        const char *line;
        unsigned priority;
        int r;

        assert(m);

        if (!streq_ptr(c->object_path, sd_bus_message_get_path(m)))
                return 0;

        r = sd_bus_message_read(m, "us", &priority, &line);
        if (r < 0) {
                bus_log_parse_error(r);
                return 0;
        }

        if (arg_quiet && LOG_PRI(priority) >= LOG_INFO)
                return 0;

        if (!arg_quiet)
                clear_progress_bar(PROGRESS_PREFIX);

        log_full(priority, "%s", line);

        if (!arg_quiet)
                draw_progress_bar(PROGRESS_PREFIX, c->progress * 100);

        return 0;
}

static int match_progress_update(sd_bus_message *m, void *userdata, sd_bus_error *error) {
        Context *c = ASSERT_PTR(userdata);
        int r;

        assert(m);

        if (!streq_ptr(c->object_path, sd_bus_message_get_path(m)))
                return 0;

        r = sd_bus_message_read(m, "d", &c->progress);
        if (r < 0) {
                bus_log_parse_error(r);
                return 0;
        }

        if (!arg_quiet)
                draw_progress_bar(PROGRESS_PREFIX, c->progress * 100);

        return 0;
}

static int match_transfer_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
        Context *c = ASSERT_PTR(userdata);
        const char *path, *result;
        uint32_t id;
        int r;

        assert(m);

        if (!arg_quiet)
                clear_progress_bar(PROGRESS_PREFIX);

        r = sd_bus_message_read(m, "uos", &id, &path, &result);
        if (r < 0) {
                bus_log_parse_error(r);
                return 0;
        }

        if (!streq_ptr(c->object_path, path))
                return 0;

        sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), !streq_ptr(result, "done"));
        return 0;
}

static int transfer_signal_handler(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
        assert(s);
        assert(si);

        if (!arg_quiet)
                clear_progress_bar(PROGRESS_PREFIX);

        if (!arg_quiet)
                log_info("Continuing download in the background. Use \"%s cancel-transfer %" PRIu32 "\" to abort transfer.",
                         program_invocation_short_name,
                         PTR_TO_UINT32(userdata));

        sd_event_exit(sd_event_source_get_event(s), EINTR);
        return 0;
}

static int transfer_image_common(sd_bus *bus, sd_bus_message *m) {
        _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot_job_removed = NULL, *slot_log_message = NULL, *slot_progress_update = NULL;
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
        _cleanup_(sd_event_unrefp) sd_event* event = NULL;
        Context c = {};
        uint32_t id;
        int r;

        assert(bus);
        assert(m);

        polkit_agent_open_if_enabled(arg_transport, arg_ask_password);

        r = sd_event_default(&event);
        if (r < 0)
                return log_error_errno(r, "Failed to get event loop: %m");

        r = sd_bus_attach_event(bus, event, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to attach bus to event loop: %m");

        r = bus_match_signal_async(
                        bus,
                        &slot_job_removed,
                        bus_import_mgr,
                        "TransferRemoved",
                        match_transfer_removed,
                        /* add_callback= */ NULL,
                        &c);
        if (r < 0)
                return log_error_errno(r, "Failed to request match: %m");

        r = sd_bus_match_signal_async(
                        bus,
                        &slot_log_message,
                        "org.freedesktop.import1",
                        /* object_path= */ NULL,
                        "org.freedesktop.import1.Transfer",
                        "LogMessage",
                        match_log_message,
                        /* add_callback= */ NULL,
                        &c);
        if (r < 0)
                return log_error_errno(r, "Failed to request match: %m");

        r = sd_bus_match_signal_async(
                        bus,
                        &slot_progress_update,
                        "org.freedesktop.import1",
                        /* object_path= */ NULL,
                        "org.freedesktop.import1.Transfer",
                        "ProgressUpdate",
                        match_progress_update,
                        /* add_callback= */ NULL,
                        &c);
        if (r < 0)
                return log_error_errno(r, "Failed to request match: %m");

        r = sd_bus_call(bus, m, 0, &error, &reply);
        if (r < 0)
                return log_error_errno(r, "Failed to transfer image: %s", bus_error_message(&error, r));

        r = sd_bus_message_read(reply, "uo", &id, &c.object_path);
        if (r < 0)
                return bus_log_parse_error(r);

        if (!arg_quiet) {
                clear_progress_bar(PROGRESS_PREFIX);
                log_info("Enqueued transfer job %u. Press C-c to continue download in background.", id);
                draw_progress_bar(PROGRESS_PREFIX, c.progress);
        }

        (void) sd_event_add_signal(event, NULL, SIGINT|SD_EVENT_SIGNAL_PROCMASK, transfer_signal_handler, UINT32_TO_PTR(id));
        (void) sd_event_add_signal(event, NULL, SIGTERM|SD_EVENT_SIGNAL_PROCMASK, transfer_signal_handler, UINT32_TO_PTR(id));

        r = sd_event_loop(event);
        if (r < 0)
                return log_error_errno(r, "Failed to run event loop: %m");

        return -r;
}

static int import_tar(int argc, char *argv[], void *userdata) {
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
        _cleanup_free_ char *ll = NULL, *fn = NULL;
        const char *local = NULL, *path = NULL;
        _cleanup_close_ int fd = -EBADF;
        sd_bus *bus = ASSERT_PTR(userdata);
        int r;

        r = settle_image_class();
        if (r < 0)
                return r;

        if (argc >= 2)
                path = empty_or_dash_to_null(argv[1]);

        if (argc >= 3)
                local = empty_or_dash_to_null(argv[2]);
        else if (path) {
                r = path_extract_filename(path, &fn);
                if (r < 0)
                        return log_error_errno(r, "Cannot extract container name from filename: %m");
                if (r == O_DIRECTORY)
                        return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
                                               "Path '%s' refers to directory, but we need a regular file: %m", path);

                local = fn;
        }
        if (!local)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Need either path or local name.");

        r = tar_strip_suffixes(local, &ll);
        if (r < 0)
                return log_oom();

        local = ll;

        if (!image_name_is_valid(local))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Local name %s is not a suitable image name.",
                                       local);

        if (path) {
                fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
                if (fd < 0)
                        return log_error_errno(errno, "Failed to open %s: %m", path);
        }

        if (arg_image_class == IMAGE_MACHINE && (arg_import_flags & ~(IMPORT_FORCE|IMPORT_READ_ONLY)) == 0) {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportTar");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "hsbb",
                                fd >= 0 ? fd : STDIN_FILENO,
                                local,
                                FLAGS_SET(arg_import_flags, IMPORT_FORCE),
                                FLAGS_SET(arg_import_flags, IMPORT_READ_ONLY));
        } else {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportTarEx");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "hsst",
                                fd >= 0 ? fd : STDIN_FILENO,
                                local,
                                image_class_to_string(arg_image_class),
                                (uint64_t) arg_import_flags & (IMPORT_FORCE|IMPORT_READ_ONLY));
        }
        if (r < 0)
                return bus_log_create_error(r);

        return transfer_image_common(bus, m);
}

static int import_raw(int argc, char *argv[], void *userdata) {
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
        _cleanup_free_ char *ll = NULL, *fn = NULL;
        const char *local = NULL, *path = NULL;
        _cleanup_close_ int fd = -EBADF;
        sd_bus *bus = ASSERT_PTR(userdata);
        int r;

        r = settle_image_class();
        if (r < 0)
                return r;

        if (argc >= 2)
                path = empty_or_dash_to_null(argv[1]);

        if (argc >= 3)
                local = empty_or_dash_to_null(argv[2]);
        else if (path) {
                r = path_extract_filename(path, &fn);
                if (r < 0)
                        return log_error_errno(r, "Cannot extract container name from filename: %m");
                if (r == O_DIRECTORY)
                        return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
                                               "Path '%s' refers to directory, but we need a regular file: %m", path);

                local = fn;
        }
        if (!local)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Need either path or local name.");

        r = raw_strip_suffixes(local, &ll);
        if (r < 0)
                return log_oom();

        local = ll;

        if (!image_name_is_valid(local))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Local name %s is not a suitable image name.",
                                       local);

        if (path) {
                fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
                if (fd < 0)
                        return log_error_errno(errno, "Failed to open %s: %m", path);
        }

        if (arg_image_class == IMAGE_MACHINE && (arg_import_flags & ~(IMPORT_FORCE|IMPORT_READ_ONLY)) == 0) {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportRaw");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "hsbb",
                                fd >= 0 ? fd : STDIN_FILENO,
                                local,
                                FLAGS_SET(arg_import_flags, IMPORT_FORCE),
                                FLAGS_SET(arg_import_flags, IMPORT_READ_ONLY));
        } else {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportRawEx");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "hsst",
                                fd >= 0 ? fd : STDIN_FILENO,
                                local,
                                image_class_to_string(arg_image_class),
                                (uint64_t) arg_import_flags & (IMPORT_FORCE|IMPORT_READ_ONLY));
        }
        if (r < 0)
                return bus_log_create_error(r);

        return transfer_image_common(bus, m);
}

static int import_fs(int argc, char *argv[], void *userdata) {
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
        const char *local = NULL, *path = NULL;
        _cleanup_free_ char *fn = NULL;
        _cleanup_close_ int fd = -EBADF;
        sd_bus *bus = ASSERT_PTR(userdata);
        int r;

        r = settle_image_class();
        if (r < 0)
                return r;

        if (argc >= 2)
                path = empty_or_dash_to_null(argv[1]);

        if (argc >= 3)
                local = empty_or_dash_to_null(argv[2]);
        else if (path) {
                r = path_extract_filename(path, &fn);
                if (r < 0)
                        return log_error_errno(r, "Cannot extract container name from filename: %m");

                local = fn;
        }
        if (!local)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Need either path or local name.");

        if (!image_name_is_valid(local))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Local name %s is not a suitable image name.",
                                       local);

        if (path) {
                fd = open(path, O_DIRECTORY|O_RDONLY|O_CLOEXEC);
                if (fd < 0)
                        return log_error_errno(errno, "Failed to open directory '%s': %m", path);
        }

        if (arg_image_class == IMAGE_MACHINE && (arg_import_flags & ~(IMPORT_FORCE|IMPORT_READ_ONLY)) == 0) {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportFileSystem");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "hsbb",
                                fd >= 0 ? fd : STDIN_FILENO,
                                local,
                                FLAGS_SET(arg_import_flags, IMPORT_FORCE),
                                FLAGS_SET(arg_import_flags, IMPORT_READ_ONLY));
        } else {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportFileSystemEx");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "hsst",
                                fd >= 0 ? fd : STDIN_FILENO,
                                local,
                                image_class_to_string(arg_image_class),
                                (uint64_t) arg_import_flags & (IMPORT_FORCE|IMPORT_READ_ONLY));
        }
        if (r < 0)
                return bus_log_create_error(r);


        return transfer_image_common(bus, m);
}

static void determine_compression_from_filename(const char *p) {
        if (arg_format)
                return;

        if (!p)
                return;

        if (endswith(p, ".xz"))
                arg_format = "xz";
        else if (endswith(p, ".gz"))
                arg_format = "gzip";
        else if (endswith(p, ".bz2"))
                arg_format = "bzip2";
}

static int export_tar(int argc, char *argv[], void *userdata) {
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
        _cleanup_close_ int fd = -EBADF;
        const char *local = NULL, *path = NULL;
        sd_bus *bus = ASSERT_PTR(userdata);
        int r;

        r = settle_image_class();
        if (r < 0)
                return r;

        local = argv[1];
        if (!image_name_is_valid(local))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Image name %s is not valid.", local);

        if (argc >= 3)
                path = argv[2];
        path = empty_or_dash_to_null(path);

        if (path) {
                determine_compression_from_filename(path);

                fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC|O_NOCTTY, 0666);
                if (fd < 0)
                        return log_error_errno(errno, "Failed to open %s: %m", path);
        }

        if (arg_image_class == IMAGE_MACHINE && arg_import_flags == 0) {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ExportTar");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "shs",
                                local,
                                fd >= 0 ? fd : STDOUT_FILENO,
                                arg_format);
        } else {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ExportTarEx");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "sshst",
                                local,
                                image_class_to_string(arg_image_class),
                                fd >= 0 ? fd : STDOUT_FILENO,
                                arg_format,
                                /* flags= */ UINT64_C(0));
        }
        if (r < 0)
                return bus_log_create_error(r);

        return transfer_image_common(bus, m);
}

static int export_raw(int argc, char *argv[], void *userdata) {
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
        _cleanup_close_ int fd = -EBADF;
        const char *local = NULL, *path = NULL;
        sd_bus *bus = ASSERT_PTR(userdata);
        int r;

        r = settle_image_class();
        if (r < 0)
                return r;

        local = argv[1];
        if (!image_name_is_valid(local))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Image name %s is not valid.", local);

        if (argc >= 3)
                path = argv[2];
        path = empty_or_dash_to_null(path);

        if (path) {
                determine_compression_from_filename(path);

                fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC|O_NOCTTY, 0666);
                if (fd < 0)
                        return log_error_errno(errno, "Failed to open %s: %m", path);
        }

        if (arg_image_class == IMAGE_MACHINE && arg_import_flags == 0) {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ExportRaw");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "shs",
                                local,
                                fd >= 0 ? fd : STDOUT_FILENO,
                                arg_format);
        } else {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ExportRawEx");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "sshst",
                                local,
                                image_class_to_string(arg_image_class),
                                fd >= 0 ? fd : STDOUT_FILENO,
                                arg_format,
                                /* flags= */ UINT64_C(0));
        }
        if (r < 0)
                return bus_log_create_error(r);

        return transfer_image_common(bus, m);
}

static int pull_tar(int argc, char *argv[], void *userdata) {
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
        _cleanup_free_ char *l = NULL, *ll = NULL;
        const char *local, *remote;
        sd_bus *bus = ASSERT_PTR(userdata);
        int r;

        r = settle_image_class();
        if (r < 0)
                return r;

        remote = argv[1];
        if (!http_url_is_valid(remote) && !file_url_is_valid(remote))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "URL '%s' is not valid.", remote);

        if (argc >= 3)
                local = argv[2];
        else {
                r = import_url_last_component(remote, &l);
                if (r < 0)
                        return log_error_errno(r, "Failed to get final component of URL: %m");

                local = l;
        }

        local = empty_or_dash_to_null(local);

        if (local) {
                r = tar_strip_suffixes(local, &ll);
                if (r < 0)
                        return log_oom();

                local = ll;

                if (!image_name_is_valid(local))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Local name %s is not a suitable image name.",
                                               local);
        }

        if (arg_image_class == IMAGE_MACHINE && (arg_import_flags & ~IMPORT_FORCE) == 0) {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "PullTar");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "sssb",
                                remote,
                                local,
                                import_verify_to_string(arg_verify),
                                FLAGS_SET(arg_import_flags, IMPORT_FORCE));
        } else {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "PullTarEx");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "sssst",
                                remote,
                                local,
                                image_class_to_string(arg_image_class),
                                import_verify_to_string(arg_verify),
                                (uint64_t) arg_import_flags & (IMPORT_FORCE|IMPORT_READ_ONLY|IMPORT_PULL_KEEP_DOWNLOAD));
        }
        if (r < 0)
                return bus_log_create_error(r);

        return transfer_image_common(bus, m);
}

static int pull_raw(int argc, char *argv[], void *userdata) {
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
        _cleanup_free_ char *l = NULL, *ll = NULL;
        const char *local, *remote;
        sd_bus *bus = ASSERT_PTR(userdata);
        int r;

        r = settle_image_class();
        if (r < 0)
                return r;

        remote = argv[1];
        if (!http_url_is_valid(remote) && !file_url_is_valid(remote))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "URL '%s' is not valid.", remote);

        if (argc >= 3)
                local = argv[2];
        else {
                r = import_url_last_component(remote, &l);
                if (r < 0)
                        return log_error_errno(r, "Failed to get final component of URL: %m");

                local = l;
        }

        local = empty_or_dash_to_null(local);

        if (local) {
                r = raw_strip_suffixes(local, &ll);
                if (r < 0)
                        return log_oom();

                local = ll;

                if (!image_name_is_valid(local))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Local name %s is not a suitable image name.",
                                               local);
        }

        if (arg_image_class == IMAGE_MACHINE && (arg_import_flags & ~IMPORT_FORCE) == 0) {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "PullRaw");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "sssb",
                                remote,
                                local,
                                import_verify_to_string(arg_verify),
                                FLAGS_SET(arg_import_flags, IMPORT_FORCE));
        } else {
                r = bus_message_new_method_call(bus, &m, bus_import_mgr, "PullRawEx");
                if (r < 0)
                        return bus_log_create_error(r);

                r = sd_bus_message_append(
                                m,
                                "sssst",
                                remote,
                                local,
                                image_class_to_string(arg_image_class),
                                import_verify_to_string(arg_verify),
                                (uint64_t) arg_import_flags & (IMPORT_FORCE|IMPORT_READ_ONLY|IMPORT_PULL_KEEP_DOWNLOAD));
        }
        if (r < 0)
                return bus_log_create_error(r);

        return transfer_image_common(bus, m);
}

static int list_transfers(int argc, char *argv[], void *userdata) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
        _cleanup_(table_unrefp) Table *t = NULL;
        sd_bus *bus = ASSERT_PTR(userdata);
        int r;

        pager_open(arg_pager_flags);

        bool ex;
        r = bus_call_method(bus, bus_import_mgr, "ListTransfersEx", &error, &reply, "st", image_class_to_string(arg_image_class), UINT64_C(0));
        if (r < 0) {
                if (sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_METHOD)) {
                        sd_bus_error_free(&error);

                        r = bus_call_method(bus, bus_import_mgr, "ListTransfers", &error, &reply, NULL);
                }
                if (r < 0)
                        return log_error_errno(r, "Could not get transfers: %s", bus_error_message(&error, r));

                ex = false;
                r = sd_bus_message_enter_container(reply, 'a', "(usssdo)");
        } else {
                ex = true;
                r = sd_bus_message_enter_container(reply, 'a', "(ussssdo)");
        }
        if (r < 0)
                return bus_log_parse_error(r);

        t = table_new("id", "progress", "type", "class", "local", "remote");
        if (!t)
                return log_oom();

        (void) table_set_sort(t, (size_t) 4, (size_t) 0);
        table_set_ersatz_string(t, TABLE_ERSATZ_DASH);

        for (;;) {
                const char *type, *remote, *local, *class = "machine";
                double progress;
                uint32_t id;

                if (ex)
                        r = sd_bus_message_read(reply, "(ussssdo)", &id, &type, &remote, &local, &class, &progress, NULL);
                else
                        r = sd_bus_message_read(reply, "(usssdo)", &id, &type, &remote, &local, &progress, NULL);
                if (r < 0)
                        return bus_log_parse_error(r);
                if (r == 0)
                        break;

                /* Ideally we use server-side filtering. But if the server can't do it, we need to do it client side */
                if (arg_image_class >= 0 && image_class_from_string(class) != arg_image_class)
                        continue;

                r = table_add_many(
                                t,
                                TABLE_UINT32, id,
                                TABLE_SET_ALIGN_PERCENT, 100);
                if (r < 0)
                        return table_log_add_error(r);

                if (progress < 0)
                        r = table_add_many(
                                        t,
                                        TABLE_EMPTY,
                                        TABLE_SET_ALIGN_PERCENT, 100);
                else
                        r = table_add_many(
                                        t,
                                        TABLE_PERCENT, (int) (progress * 100),
                                        TABLE_SET_ALIGN_PERCENT, 100);
                if (r < 0)
                        return table_log_add_error(r);
                r = table_add_many(
                                t,
                                TABLE_STRING, type,
                                TABLE_STRING, class,
                                TABLE_STRING, local,
                                TABLE_STRING, remote,
                                TABLE_SET_URL, remote);
                if (r < 0)
                        return table_log_add_error(r);
        }

        r = sd_bus_message_exit_container(reply);
        if (r < 0)
                return bus_log_parse_error(r);

        if (!table_isempty(t)) {
                r = table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
                if (r < 0)
                        return log_error_errno(r, "Failed to output table: %m");
        }

        if (arg_legend) {
                if (!table_isempty(t))
                        printf("\n%zu transfers listed.\n", table_get_rows(t) - 1);
                else
                        printf("No transfers.\n");
        }

        return 0;
}

static int cancel_transfer(int argc, char *argv[], void *userdata) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        sd_bus *bus = ASSERT_PTR(userdata);
        int r;

        polkit_agent_open_if_enabled(arg_transport, arg_ask_password);

        for (int i = 1; i < argc; i++) {
                uint32_t id;

                r = safe_atou32(argv[i], &id);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse transfer id: %s", argv[i]);

                r = bus_call_method(bus, bus_import_mgr, "CancelTransfer", &error, NULL, "u", id);
                if (r < 0)
                        return log_error_errno(r, "Could not cancel transfer: %s", bus_error_message(&error, r));
        }

        return 0;
}

static int list_images(int argc, char *argv[], void *userdata) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
        _cleanup_(table_unrefp) Table *t = NULL;
        sd_bus *bus = ASSERT_PTR(userdata);
        int r;

        pager_open(arg_pager_flags);

        r = bus_call_method(bus, bus_import_mgr, "ListImages", &error, &reply, "st", image_class_to_string(arg_image_class), UINT64_C(0));
        if (r < 0)
                return log_error_errno(r, "Could not list images: %s", bus_error_message(&error, r));

        r = sd_bus_message_enter_container(reply, 'a', "(ssssbtttttt)");
        if (r < 0)
                return bus_log_parse_error(r);

        t = table_new("class", "name", "type", "path", "ro", "crtime", "mtime", "usage", "usage-exclusive", "limit", "limit-exclusive");
        if (!t)
                return log_oom();

        (void) table_set_sort(t, (size_t) 0, (size_t) 1);
        table_set_ersatz_string(t, TABLE_ERSATZ_DASH);

        /* Hide the exclusive columns for now */
        (void) table_hide_column_from_display(t, 8);
        (void) table_hide_column_from_display(t, 10);

        for (;;) {
                uint64_t crtime, mtime, usage, usage_exclusive, limit, limit_exclusive;
                const char *class, *name, *type, *path;
                int read_only;

                r = sd_bus_message_read(reply, "(ssssbtttttt)", &class, &name, &type, &path, &read_only, &crtime, &mtime, &usage, &usage_exclusive, &limit, &limit_exclusive);
                if (r < 0)
                        return bus_log_parse_error(r);
                if (r == 0)
                        break;

                r = table_add_many(
                                t,
                                TABLE_STRING, class,
                                TABLE_STRING, name,
                                TABLE_STRING, type,
                                TABLE_PATH, path);
                if (r < 0)
                        return table_log_add_error(r);

                if (FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF))
                        r = table_add_many(
                                        t,
                                        TABLE_STRING, read_only ? "ro" : "rw",
                                        TABLE_SET_COLOR, read_only ? ANSI_HIGHLIGHT_RED : ANSI_HIGHLIGHT_GREEN);
                else
                        r = table_add_many(
                                        t,
                                        TABLE_BOOLEAN, read_only);
                if (r < 0)
                        return table_log_add_error(r);

                r = table_add_many(
                                t,
                                TABLE_TIMESTAMP, crtime,
                                TABLE_TIMESTAMP, mtime,
                                TABLE_SIZE, usage,
                                TABLE_SIZE, usage_exclusive,
                                TABLE_SIZE, limit,
                                TABLE_SIZE, limit_exclusive);
                if (r < 0)
                        return table_log_add_error(r);
        }

        r = sd_bus_message_exit_container(reply);
        if (r < 0)
                return bus_log_parse_error(r);

        if (!table_isempty(t)) {
                r = table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
                if (r < 0)
                        return log_error_errno(r, "Failed to output table: %m");
        }

        if (arg_legend) {
                if (!table_isempty(t))
                        printf("\n%zu images listed.\n", table_get_rows(t) - 1);
                else
                        printf("No images.\n");
        }

        return 0;
}

static int help(int argc, char *argv[], void *userdata) {
        _cleanup_free_ char *link = NULL;
        int r;

        pager_open(arg_pager_flags);

        r = terminal_urlify_man("importctl", "1", &link);
        if (r < 0)
                return log_oom();

        printf("%1$s [OPTIONS...] COMMAND ...\n\n"
               "%5$sDownload, import or export disk images%6$s\n"
               "\n%3$sCommands:%4$s\n"
               "  pull-tar URL [NAME]         Download a TAR container image\n"
               "  pull-raw URL [NAME]         Download a RAW container or VM image\n"
               "  import-tar FILE [NAME]      Import a local TAR container image\n"
               "  import-raw FILE [NAME]      Import a local RAW container or VM image\n"
               "  import-fs DIRECTORY [NAME]  Import a local directory container image\n"
               "  export-tar NAME [FILE]      Export a TAR container image locally\n"
               "  export-raw NAME [FILE]      Export a RAW container or VM image locally\n"
               "  list-transfers              Show list of transfers in progress\n"
               "  cancel-transfer [ID...]     Cancel a transfer\n"
               "  list-images                 Show list of installed images\n"
               "\n%3$sOptions:%4$s\n"
               "  -h --help                   Show this help\n"
               "     --version                Show package version\n"
               "     --no-pager               Do not pipe output into a pager\n"
               "     --no-legend              Do not show the headers and footers\n"
               "     --no-ask-password        Do not ask for system passwords\n"
               "  -H --host=[USER@]HOST       Operate on remote host\n"
               "  -M --machine=CONTAINER      Operate on local container\n"
               "     --read-only              Create read-only image\n"
               "  -q --quiet                  Suppress output\n"
               "     --json=pretty|short|off  Generate JSON output\n"
               "  -j                          Equvilant to --json=pretty on TTY, --json=short\n"
               "                              otherwise\n"
               "     --verify=MODE            Verification mode for downloaded images (no,\n"
               "                               checksum, signature)\n"
               "     --format=xz|gzip|bzip2   Desired output format for export\n"
               "     --force                  Install image even if already exists\n"
               "  -m --class=machine          Install as machine image\n"
               "  -P --class=portable         Install as portable service image\n"
               "  -S --class=sysext           Install as system extension image\n"
               "  -C --class=confext          Install as configuration extension image\n"
               "     --keep-download=BOOL     Control whether to keep pristine copy of download\n"
               "  -N                          Shortcut for --keep-download=no\n"
               "\nSee the %2$s for details.\n",
               program_invocation_short_name,
               link,
               ansi_underline(),
               ansi_normal(),
               ansi_highlight(),
               ansi_normal());

        return 0;
}

static int parse_argv(int argc, char *argv[]) {

        enum {
                ARG_VERSION = 0x100,
                ARG_NO_PAGER,
                ARG_NO_LEGEND,
                ARG_NO_ASK_PASSWORD,
                ARG_READ_ONLY,
                ARG_JSON,
                ARG_VERIFY,
                ARG_FORCE,
                ARG_FORMAT,
                ARG_CLASS,
                ARG_KEEP_DOWNLOAD,
        };

        static const struct option options[] = {
                { "help",            no_argument,       NULL, 'h'                 },
                { "version",         no_argument,       NULL, ARG_VERSION         },
                { "no-pager",        no_argument,       NULL, ARG_NO_PAGER        },
                { "no-legend",       no_argument,       NULL, ARG_NO_LEGEND       },
                { "no-ask-password", no_argument,       NULL, ARG_NO_ASK_PASSWORD },
                { "host",            required_argument, NULL, 'H'                 },
                { "machine",         required_argument, NULL, 'M'                 },
                { "read-only",       no_argument,       NULL, ARG_READ_ONLY       },
                { "json",            required_argument, NULL, ARG_JSON            },
                { "quiet",           no_argument,       NULL, 'q'                 },
                { "verify",          required_argument, NULL, ARG_VERIFY          },
                { "force",           no_argument,       NULL, ARG_FORCE           },
                { "format",          required_argument, NULL, ARG_FORMAT          },
                { "class",           required_argument, NULL, ARG_CLASS           },
                { "keep-download",   required_argument, NULL, ARG_KEEP_DOWNLOAD   },
                {}
        };

        int c, r;

        assert(argc >= 0);
        assert(argv);

        for (;;) {
                c = getopt_long(argc, argv, "hH:M:jqmPSCN", options, NULL);
                if (c < 0)
                        break;

                switch (c) {

                case 'h':
                        return help(0, NULL, NULL);

                case ARG_VERSION:
                        return version();

                case ARG_NO_PAGER:
                        arg_pager_flags |= PAGER_DISABLE;
                        break;

                case ARG_NO_LEGEND:
                        arg_legend = false;
                        break;

                case ARG_NO_ASK_PASSWORD:
                        arg_ask_password = false;
                        break;

                case 'H':
                        arg_transport = BUS_TRANSPORT_REMOTE;
                        arg_host = optarg;
                        break;

                case 'M':
                        arg_transport = BUS_TRANSPORT_MACHINE;
                        arg_host = optarg;
                        break;

                case ARG_READ_ONLY:
                        arg_import_flags |= IMPORT_READ_ONLY;
                        arg_import_flags_mask |= IMPORT_READ_ONLY;
                        break;

                case 'q':
                        arg_quiet = true;
                        break;

                case ARG_VERIFY:
                        if (streq(optarg, "help")) {
                                DUMP_STRING_TABLE(import_verify, ImportVerify, _IMPORT_VERIFY_MAX);
                                return 0;
                        }

                        r = import_verify_from_string(optarg);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --verify= setting: %s", optarg);
                        arg_verify = r;
                        break;

                case ARG_FORCE:
                        arg_import_flags |= IMPORT_FORCE;
                        arg_import_flags_mask |= IMPORT_FORCE;
                        break;

                case ARG_FORMAT:
                        if (!STR_IN_SET(optarg, "uncompressed", "xz", "gzip", "bzip2"))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Unknown format: %s", optarg);

                        arg_format = optarg;
                        break;

                case ARG_JSON:
                        r = parse_json_argument(optarg, &arg_json_format_flags);
                        if (r <= 0)
                                return r;

                        arg_legend = false;
                        break;

                case 'j':
                        arg_json_format_flags = JSON_FORMAT_PRETTY_AUTO|JSON_FORMAT_COLOR_AUTO;
                        arg_legend = false;
                        break;

                case ARG_CLASS:
                        arg_image_class = image_class_from_string(optarg);
                        if (arg_image_class < 0)
                                return log_error_errno(arg_image_class, "Failed to parse --class= parameter: %s", optarg);
                        break;

                case 'm':
                        arg_image_class = IMAGE_MACHINE;
                        break;

                case 'P':
                        arg_image_class = IMAGE_PORTABLE;
                        break;

                case 'S':
                        arg_image_class = IMAGE_SYSEXT;
                        break;

                case 'C':
                        arg_image_class = IMAGE_CONFEXT;
                        break;

                case ARG_KEEP_DOWNLOAD:
                        r = parse_boolean(optarg);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --keep-download= value: %s", optarg);

                        SET_FLAG(arg_import_flags, IMPORT_PULL_KEEP_DOWNLOAD, r);
                        arg_import_flags_mask |= IMPORT_PULL_KEEP_DOWNLOAD;
                        break;

                case 'N':
                        arg_import_flags_mask &= ~IMPORT_PULL_KEEP_DOWNLOAD;
                        arg_import_flags_mask |= IMPORT_PULL_KEEP_DOWNLOAD;
                        break;

                case '?':
                        return -EINVAL;

                default:
                        assert_not_reached();
                }
        }

        return 1;
}

static int importctl_main(int argc, char *argv[], sd_bus *bus) {

        static const Verb verbs[] = {
                { "help",            VERB_ANY, VERB_ANY, 0,            help              },
                { "import-tar",      2,        3,        0,            import_tar        },
                { "import-raw",      2,        3,        0,            import_raw        },
                { "import-fs",       2,        3,        0,            import_fs         },
                { "export-tar",      2,        3,        0,            export_tar        },
                { "export-raw",      2,        3,        0,            export_raw        },
                { "pull-tar",        2,        3,        0,            pull_tar          },
                { "pull-raw",        2,        3,        0,            pull_raw          },
                { "list-transfers",  VERB_ANY, 1,        VERB_DEFAULT, list_transfers    },
                { "cancel-transfer", 2,        VERB_ANY, 0,            cancel_transfer   },
                { "list-images",     VERB_ANY, 1,        0,            list_images       },
                {}
        };

        return dispatch_verb(argc, argv, verbs, bus);
}

static int run(int argc, char *argv[]) {
        _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
        int r;

        setlocale(LC_ALL, "");
        log_setup();

        r = parse_argv(argc, argv);
        if (r <= 0)
                return r;

        r = bus_connect_transport(arg_transport, arg_host, RUNTIME_SCOPE_SYSTEM, &bus);
        if (r < 0)
                return bus_log_connect_error(r, arg_transport);

        (void) sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);

        return importctl_main(argc, argv, bus);
}

DEFINE_MAIN_FUNCTION(run);