]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/machine/machinectl.c
Merge pull request #23654 from keszybz/gcc-warnings
[thirdparty/systemd.git] / src / machine / machinectl.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <arpa/inet.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <getopt.h>
7 #include <math.h>
8 #include <net/if.h>
9 #include <netinet/in.h>
10 #include <sys/mount.h>
11 #include <sys/socket.h>
12 #include <unistd.h>
13
14 #include "sd-bus.h"
15
16 #include "alloc-util.h"
17 #include "bus-common-errors.h"
18 #include "bus-error.h"
19 #include "bus-locator.h"
20 #include "bus-map-properties.h"
21 #include "bus-print-properties.h"
22 #include "bus-unit-procs.h"
23 #include "bus-unit-util.h"
24 #include "bus-wait-for-jobs.h"
25 #include "cgroup-show.h"
26 #include "cgroup-util.h"
27 #include "copy.h"
28 #include "def.h"
29 #include "env-util.h"
30 #include "fd-util.h"
31 #include "format-table.h"
32 #include "hostname-util.h"
33 #include "import-util.h"
34 #include "locale-util.h"
35 #include "log.h"
36 #include "logs-show.h"
37 #include "macro.h"
38 #include "main-func.h"
39 #include "mkdir.h"
40 #include "nulstr-util.h"
41 #include "pager.h"
42 #include "parse-argument.h"
43 #include "parse-util.h"
44 #include "path-util.h"
45 #include "pretty-print.h"
46 #include "process-util.h"
47 #include "ptyfwd.h"
48 #include "rlimit-util.h"
49 #include "sigbus.h"
50 #include "signal-util.h"
51 #include "sort-util.h"
52 #include "spawn-ask-password-agent.h"
53 #include "spawn-polkit-agent.h"
54 #include "stdio-util.h"
55 #include "string-table.h"
56 #include "strv.h"
57 #include "terminal-util.h"
58 #include "unit-name.h"
59 #include "verbs.h"
60 #include "web-util.h"
61
62 #define ALL_ADDRESSES -1
63
64 static char **arg_property = NULL;
65 static bool arg_all = false;
66 static BusPrintPropertyFlags arg_print_flags = 0;
67 static bool arg_full = false;
68 static PagerFlags arg_pager_flags = 0;
69 static bool arg_legend = true;
70 static const char *arg_kill_who = NULL;
71 static int arg_signal = SIGTERM;
72 static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
73 static const char *arg_host = NULL;
74 static bool arg_read_only = false;
75 static bool arg_mkdir = false;
76 static bool arg_quiet = false;
77 static bool arg_ask_password = true;
78 static unsigned arg_lines = 10;
79 static OutputMode arg_output = OUTPUT_SHORT;
80 static bool arg_force = false;
81 static ImportVerify arg_verify = IMPORT_VERIFY_SIGNATURE;
82 static const char* arg_format = NULL;
83 static const char *arg_uid = NULL;
84 static char **arg_setenv = NULL;
85 static int arg_max_addresses = 1;
86
87 STATIC_DESTRUCTOR_REGISTER(arg_property, strv_freep);
88 STATIC_DESTRUCTOR_REGISTER(arg_setenv, strv_freep);
89
90 static OutputFlags get_output_flags(void) {
91 return
92 FLAGS_SET(arg_print_flags, BUS_PRINT_PROPERTY_SHOW_EMPTY) * OUTPUT_SHOW_ALL |
93 (arg_full || !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
94 colors_enabled() * OUTPUT_COLOR |
95 !arg_quiet * OUTPUT_WARN_CUTOFF;
96 }
97
98 static int call_get_os_release(sd_bus *bus, const char *method, const char *name, const char *query, ...) {
99 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
100 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
101 const char *k, *v, *iter, **query_res = NULL;
102 size_t count = 0, awaited_args = 0;
103 va_list ap;
104 int r;
105
106 assert(bus);
107 assert(name);
108 assert(query);
109
110 NULSTR_FOREACH(iter, query)
111 awaited_args++;
112 query_res = newa0(const char *, awaited_args);
113
114 r = bus_call_method(bus, bus_machine_mgr, method, &error, &reply, "s", name);
115 if (r < 0)
116 return log_debug_errno(r, "Failed to call '%s()': %s", method, bus_error_message(&error, r));
117
118 r = sd_bus_message_enter_container(reply, 'a', "{ss}");
119 if (r < 0)
120 return bus_log_parse_error(r);
121
122 while ((r = sd_bus_message_read(reply, "{ss}", &k, &v)) > 0) {
123 count = 0;
124 NULSTR_FOREACH(iter, query) {
125 if (streq(k, iter)) {
126 query_res[count] = v;
127 break;
128 }
129 count++;
130 }
131 }
132 if (r < 0)
133 return bus_log_parse_error(r);
134
135 r = sd_bus_message_exit_container(reply);
136 if (r < 0)
137 return bus_log_parse_error(r);
138
139 va_start(ap, query);
140 for (count = 0; count < awaited_args; count++) {
141 char *val, **out;
142
143 out = va_arg(ap, char **);
144 assert(out);
145 if (query_res[count]) {
146 val = strdup(query_res[count]);
147 if (!val) {
148 va_end(ap);
149 return -ENOMEM;
150 }
151 *out = val;
152 }
153 }
154 va_end(ap);
155
156 return 0;
157 }
158
159 static int call_get_addresses(
160 sd_bus *bus,
161 const char *name,
162 int ifi,
163 const char *prefix,
164 const char *prefix2,
165 char **ret) {
166
167 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
168 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
169 _cleanup_free_ char *addresses = NULL;
170 unsigned n = 0;
171 int r;
172
173 assert(bus);
174 assert(name);
175 assert(prefix);
176 assert(prefix2);
177
178 r = bus_call_method(bus, bus_machine_mgr, "GetMachineAddresses", NULL, &reply, "s", name);
179 if (r < 0)
180 return log_debug_errno(r, "Could not get addresses: %s", bus_error_message(&error, r));
181
182 addresses = strdup(prefix);
183 if (!addresses)
184 return log_oom();
185 prefix = "";
186
187 r = sd_bus_message_enter_container(reply, 'a', "(iay)");
188 if (r < 0)
189 return bus_log_parse_error(r);
190
191 while ((r = sd_bus_message_enter_container(reply, 'r', "iay")) > 0) {
192 int family;
193 const void *a;
194 size_t sz;
195 char buf_ifi[1 + DECIMAL_STR_MAX(int)] = "";
196
197 r = sd_bus_message_read(reply, "i", &family);
198 if (r < 0)
199 return bus_log_parse_error(r);
200
201 r = sd_bus_message_read_array(reply, 'y', &a, &sz);
202 if (r < 0)
203 return bus_log_parse_error(r);
204
205 if (family == AF_INET6 && ifi > 0)
206 xsprintf(buf_ifi, "%%%i", ifi);
207
208 if (!strextend(&addresses, prefix, IN_ADDR_TO_STRING(family, a), buf_ifi))
209 return log_oom();
210
211 r = sd_bus_message_exit_container(reply);
212 if (r < 0)
213 return bus_log_parse_error(r);
214
215 prefix = prefix2;
216
217 n++;
218 }
219 if (r < 0)
220 return bus_log_parse_error(r);
221
222 r = sd_bus_message_exit_container(reply);
223 if (r < 0)
224 return bus_log_parse_error(r);
225
226 *ret = TAKE_PTR(addresses);
227 return (int) n;
228 }
229
230 static int show_table(Table *table, const char *word) {
231 int r;
232
233 assert(table);
234 assert(word);
235
236 if (table_get_rows(table) > 1 || OUTPUT_MODE_IS_JSON(arg_output)) {
237 r = table_set_sort(table, (size_t) 0);
238 if (r < 0)
239 return table_log_sort_error(r);
240
241 table_set_header(table, arg_legend);
242
243 if (OUTPUT_MODE_IS_JSON(arg_output))
244 r = table_print_json(table, NULL, output_mode_to_json_format_flags(arg_output) | JSON_FORMAT_COLOR_AUTO);
245 else
246 r = table_print(table, NULL);
247 if (r < 0)
248 return table_log_print_error(r);
249 }
250
251 if (arg_legend) {
252 if (table_get_rows(table) > 1)
253 printf("\n%zu %s listed.\n", table_get_rows(table) - 1, word);
254 else
255 printf("No %s.\n", word);
256 }
257
258 return 0;
259 }
260
261 static int list_machines(int argc, char *argv[], void *userdata) {
262
263 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
264 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
265 _cleanup_(table_unrefp) Table *table = NULL;
266 sd_bus *bus = userdata;
267 int r;
268
269 assert(bus);
270
271 pager_open(arg_pager_flags);
272
273 r = bus_call_method(bus, bus_machine_mgr, "ListMachines", &error, &reply, NULL);
274 if (r < 0)
275 return log_error_errno(r, "Could not get machines: %s", bus_error_message(&error, r));
276
277 table = table_new("machine", "class", "service", "os", "version", "addresses");
278 if (!table)
279 return log_oom();
280
281 table_set_empty_string(table, "-");
282 if (!arg_full && arg_max_addresses != ALL_ADDRESSES)
283 table_set_cell_height_max(table, arg_max_addresses);
284
285 if (arg_full)
286 table_set_width(table, 0);
287
288 r = sd_bus_message_enter_container(reply, 'a', "(ssso)");
289 if (r < 0)
290 return bus_log_parse_error(r);
291
292 for (;;) {
293 _cleanup_free_ char *os = NULL, *version_id = NULL, *addresses = NULL;
294 const char *name, *class, *service;
295
296 r = sd_bus_message_read(reply, "(ssso)", &name, &class, &service, NULL);
297 if (r < 0)
298 return bus_log_parse_error(r);
299 if (r == 0)
300 break;
301
302 if (name[0] == '.' && !arg_all)
303 continue;
304
305 (void) call_get_os_release(
306 bus,
307 "GetMachineOSRelease",
308 name,
309 "ID\0"
310 "VERSION_ID\0",
311 &os,
312 &version_id);
313
314 (void) call_get_addresses(
315 bus,
316 name,
317 0,
318 "",
319 "\n",
320 &addresses);
321
322 r = table_add_many(table,
323 TABLE_STRING, empty_to_null(name),
324 TABLE_STRING, empty_to_null(class),
325 TABLE_STRING, empty_to_null(service),
326 TABLE_STRING, empty_to_null(os),
327 TABLE_STRING, empty_to_null(version_id),
328 TABLE_STRING, empty_to_null(addresses));
329 if (r < 0)
330 return table_log_add_error(r);
331 }
332
333 r = sd_bus_message_exit_container(reply);
334 if (r < 0)
335 return bus_log_parse_error(r);
336
337 return show_table(table, "machines");
338 }
339
340 static int list_images(int argc, char *argv[], void *userdata) {
341
342 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
343 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
344 _cleanup_(table_unrefp) Table *table = NULL;
345 sd_bus *bus = userdata;
346 int r;
347
348 assert(bus);
349
350 pager_open(arg_pager_flags);
351
352 r = bus_call_method(bus, bus_machine_mgr, "ListImages", &error, &reply, NULL);
353 if (r < 0)
354 return log_error_errno(r, "Could not get images: %s", bus_error_message(&error, r));
355
356 table = table_new("name", "type", "ro", "usage", "created", "modified");
357 if (!table)
358 return log_oom();
359
360 if (arg_full)
361 table_set_width(table, 0);
362
363 (void) table_set_align_percent(table, TABLE_HEADER_CELL(3), 100);
364
365 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssbttto)");
366 if (r < 0)
367 return bus_log_parse_error(r);
368
369 for (;;) {
370 uint64_t crtime, mtime, size;
371 const char *name, *type;
372 int ro_int;
373
374 r = sd_bus_message_read(reply, "(ssbttto)", &name, &type, &ro_int, &crtime, &mtime, &size, NULL);
375 if (r < 0)
376 return bus_log_parse_error(r);
377 if (r == 0)
378 break;
379
380 if (name[0] == '.' && !arg_all)
381 continue;
382
383 r = table_add_many(table,
384 TABLE_STRING, name,
385 TABLE_STRING, type,
386 TABLE_BOOLEAN, ro_int,
387 TABLE_SET_COLOR, ro_int ? ansi_highlight_red() : NULL,
388 TABLE_SIZE, size,
389 TABLE_TIMESTAMP, crtime,
390 TABLE_TIMESTAMP, mtime);
391 if (r < 0)
392 return table_log_add_error(r);
393 }
394
395 r = sd_bus_message_exit_container(reply);
396 if (r < 0)
397 return bus_log_parse_error(r);
398
399 return show_table(table, "images");
400 }
401
402 static int show_unit_cgroup(sd_bus *bus, const char *unit, pid_t leader) {
403 _cleanup_free_ char *cgroup = NULL;
404 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
405 int r;
406 unsigned c;
407
408 assert(bus);
409 assert(unit);
410
411 r = show_cgroup_get_unit_path_and_warn(bus, unit, &cgroup);
412 if (r < 0)
413 return r;
414
415 if (isempty(cgroup))
416 return 0;
417
418 c = columns();
419 if (c > 18)
420 c -= 18;
421 else
422 c = 0;
423
424 r = unit_show_processes(bus, unit, cgroup, "\t\t ", c, get_output_flags(), &error);
425 if (r == -EBADR) {
426
427 if (arg_transport == BUS_TRANSPORT_REMOTE)
428 return 0;
429
430 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
431
432 if (cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, cgroup) != 0 && leader <= 0)
433 return 0;
434
435 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER, cgroup, "\t\t ", c, &leader, leader > 0, get_output_flags());
436 } else if (r < 0)
437 return log_error_errno(r, "Failed to dump process list: %s", bus_error_message(&error, r));
438
439 return 0;
440 }
441
442 static int print_os_release(sd_bus *bus, const char *method, const char *name, const char *prefix) {
443 _cleanup_free_ char *pretty = NULL;
444 int r;
445
446 assert(bus);
447 assert(name);
448 assert(prefix);
449
450 r = call_get_os_release(bus, method, name, "PRETTY_NAME\0", &pretty, NULL);
451 if (r < 0)
452 return r;
453
454 if (pretty)
455 printf("%s%s\n", prefix, pretty);
456
457 return 0;
458 }
459
460 static int print_uid_shift(sd_bus *bus, const char *name) {
461 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
462 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
463 uint32_t shift;
464 int r;
465
466 assert(bus);
467 assert(name);
468
469 r = bus_call_method(bus, bus_machine_mgr, "GetMachineUIDShift", &error, &reply, "s", name);
470 if (r < 0)
471 return log_debug_errno(r, "Failed to query UID/GID shift: %s", bus_error_message(&error, r));
472
473 r = sd_bus_message_read(reply, "u", &shift);
474 if (r < 0)
475 return r;
476
477 if (shift == 0) /* Don't show trivial mappings */
478 return 0;
479
480 printf(" UID Shift: %" PRIu32 "\n", shift);
481 return 0;
482 }
483
484 typedef struct MachineStatusInfo {
485 const char *name;
486 sd_id128_t id;
487 const char *class;
488 const char *service;
489 const char *unit;
490 const char *root_directory;
491 pid_t leader;
492 struct dual_timestamp timestamp;
493 int *netif;
494 size_t n_netif;
495 } MachineStatusInfo;
496
497 static void machine_status_info_clear(MachineStatusInfo *info) {
498 if (info) {
499 free(info->netif);
500 zero(*info);
501 }
502 }
503
504 static void print_machine_status_info(sd_bus *bus, MachineStatusInfo *i) {
505 _cleanup_free_ char *addresses = NULL, *s1 = NULL, *s2 = NULL;
506 int ifi = -1;
507
508 assert(bus);
509 assert(i);
510
511 fputs(strna(i->name), stdout);
512
513 if (!sd_id128_is_null(i->id))
514 printf("(" SD_ID128_FORMAT_STR ")\n", SD_ID128_FORMAT_VAL(i->id));
515 else
516 putchar('\n');
517
518 s1 = strdup(strempty(FORMAT_TIMESTAMP_RELATIVE(i->timestamp.realtime)));
519 s2 = strdup(strempty(FORMAT_TIMESTAMP(i->timestamp.realtime)));
520
521 if (!isempty(s1))
522 printf("\t Since: %s; %s\n", strna(s2), s1);
523 else if (!isempty(s2))
524 printf("\t Since: %s\n", s2);
525
526 if (i->leader > 0) {
527 _cleanup_free_ char *t = NULL;
528
529 printf("\t Leader: %u", (unsigned) i->leader);
530
531 (void) get_process_comm(i->leader, &t);
532 if (t)
533 printf(" (%s)", t);
534
535 putchar('\n');
536 }
537
538 if (i->service) {
539 printf("\t Service: %s", i->service);
540
541 if (i->class)
542 printf("; class %s", i->class);
543
544 putchar('\n');
545 } else if (i->class)
546 printf("\t Class: %s\n", i->class);
547
548 if (i->root_directory)
549 printf("\t Root: %s\n", i->root_directory);
550
551 if (i->n_netif > 0) {
552 fputs("\t Iface:", stdout);
553
554 for (size_t c = 0; c < i->n_netif; c++) {
555 char name[IF_NAMESIZE];
556
557 if (format_ifname(i->netif[c], name) >= 0) {
558 fputc(' ', stdout);
559 fputs(name, stdout);
560
561 if (ifi < 0)
562 ifi = i->netif[c];
563 else
564 ifi = 0;
565 } else
566 printf(" %i", i->netif[c]);
567 }
568
569 fputc('\n', stdout);
570 }
571
572 if (call_get_addresses(bus, i->name, ifi,
573 "\t Address: ", "\n\t ",
574 &addresses) > 0) {
575 fputs(addresses, stdout);
576 fputc('\n', stdout);
577 }
578
579 print_os_release(bus, "GetMachineOSRelease", i->name, "\t OS: ");
580
581 print_uid_shift(bus, i->name);
582
583 if (i->unit) {
584 printf("\t Unit: %s\n", i->unit);
585 show_unit_cgroup(bus, i->unit, i->leader);
586
587 if (arg_transport == BUS_TRANSPORT_LOCAL)
588
589 show_journal_by_unit(
590 stdout,
591 i->unit,
592 NULL,
593 arg_output,
594 0,
595 i->timestamp.monotonic,
596 arg_lines,
597 0,
598 get_output_flags() | OUTPUT_BEGIN_NEWLINE,
599 SD_JOURNAL_LOCAL_ONLY,
600 true,
601 NULL);
602 }
603 }
604
605 static int map_netif(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
606 MachineStatusInfo *i = userdata;
607 size_t l;
608 const void *v;
609 int r;
610
611 assert_cc(sizeof(int32_t) == sizeof(int));
612 r = sd_bus_message_read_array(m, SD_BUS_TYPE_INT32, &v, &l);
613 if (r < 0)
614 return r;
615 if (r == 0)
616 return -EBADMSG;
617
618 i->n_netif = l / sizeof(int32_t);
619 i->netif = memdup(v, l);
620 if (!i->netif)
621 return -ENOMEM;
622
623 return 0;
624 }
625
626 static int show_machine_info(const char *verb, sd_bus *bus, const char *path, bool *new_line) {
627
628 static const struct bus_properties_map map[] = {
629 { "Name", "s", NULL, offsetof(MachineStatusInfo, name) },
630 { "Class", "s", NULL, offsetof(MachineStatusInfo, class) },
631 { "Service", "s", NULL, offsetof(MachineStatusInfo, service) },
632 { "Unit", "s", NULL, offsetof(MachineStatusInfo, unit) },
633 { "RootDirectory", "s", NULL, offsetof(MachineStatusInfo, root_directory) },
634 { "Leader", "u", NULL, offsetof(MachineStatusInfo, leader) },
635 { "Timestamp", "t", NULL, offsetof(MachineStatusInfo, timestamp.realtime) },
636 { "TimestampMonotonic", "t", NULL, offsetof(MachineStatusInfo, timestamp.monotonic) },
637 { "Id", "ay", bus_map_id128, offsetof(MachineStatusInfo, id) },
638 { "NetworkInterfaces", "ai", map_netif, 0 },
639 {}
640 };
641
642 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
643 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
644 _cleanup_(machine_status_info_clear) MachineStatusInfo info = {};
645 int r;
646
647 assert(verb);
648 assert(bus);
649 assert(path);
650 assert(new_line);
651
652 r = bus_map_all_properties(bus,
653 "org.freedesktop.machine1",
654 path,
655 map,
656 0,
657 &error,
658 &m,
659 &info);
660 if (r < 0)
661 return log_error_errno(r, "Could not get properties: %s", bus_error_message(&error, r));
662
663 if (*new_line)
664 printf("\n");
665 *new_line = true;
666
667 print_machine_status_info(bus, &info);
668
669 return r;
670 }
671
672 static int show_machine_properties(sd_bus *bus, const char *path, bool *new_line) {
673 int r;
674
675 assert(bus);
676 assert(path);
677 assert(new_line);
678
679 if (*new_line)
680 printf("\n");
681
682 *new_line = true;
683
684 r = bus_print_all_properties(bus, "org.freedesktop.machine1", path, NULL, arg_property, arg_print_flags, NULL);
685 if (r < 0)
686 log_error_errno(r, "Could not get properties: %m");
687
688 return r;
689 }
690
691 static int show_machine(int argc, char *argv[], void *userdata) {
692
693 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
694 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
695 bool properties, new_line = false;
696 sd_bus *bus = userdata;
697 int r = 0;
698
699 assert(bus);
700
701 properties = !strstr(argv[0], "status");
702
703 pager_open(arg_pager_flags);
704
705 if (properties && argc <= 1) {
706
707 /* If no argument is specified, inspect the manager
708 * itself */
709 r = show_machine_properties(bus, "/org/freedesktop/machine1", &new_line);
710 if (r < 0)
711 return r;
712 }
713
714 for (int i = 1; i < argc; i++) {
715 const char *path = NULL;
716
717 r = bus_call_method(bus, bus_machine_mgr, "GetMachine", &error, &reply, "s", argv[i]);
718 if (r < 0)
719 return log_error_errno(r, "Could not get path to machine: %s", bus_error_message(&error, r));
720
721 r = sd_bus_message_read(reply, "o", &path);
722 if (r < 0)
723 return bus_log_parse_error(r);
724
725 if (properties)
726 r = show_machine_properties(bus, path, &new_line);
727 else
728 r = show_machine_info(argv[0], bus, path, &new_line);
729 }
730
731 return r;
732 }
733
734 static int print_image_hostname(sd_bus *bus, const char *name) {
735 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
736 const char *hn;
737 int r;
738
739 r = bus_call_method(bus, bus_machine_mgr, "GetImageHostname", NULL, &reply, "s", name);
740 if (r < 0)
741 return r;
742
743 r = sd_bus_message_read(reply, "s", &hn);
744 if (r < 0)
745 return r;
746
747 if (!isempty(hn))
748 printf("\tHostname: %s\n", hn);
749
750 return 0;
751 }
752
753 static int print_image_machine_id(sd_bus *bus, const char *name) {
754 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
755 sd_id128_t id = SD_ID128_NULL;
756 const void *p;
757 size_t size;
758 int r;
759
760 r = bus_call_method(bus, bus_machine_mgr, "GetImageMachineID", NULL, &reply, "s", name);
761 if (r < 0)
762 return r;
763
764 r = sd_bus_message_read_array(reply, 'y', &p, &size);
765 if (r < 0)
766 return r;
767
768 if (size == sizeof(sd_id128_t))
769 memcpy(&id, p, size);
770
771 if (!sd_id128_is_null(id))
772 printf(" Machine ID: " SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(id));
773
774 return 0;
775 }
776
777 static int print_image_machine_info(sd_bus *bus, const char *name) {
778 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
779 int r;
780
781 r = bus_call_method(bus, bus_machine_mgr, "GetImageMachineInfo", NULL, &reply, "s", name);
782 if (r < 0)
783 return r;
784
785 r = sd_bus_message_enter_container(reply, 'a', "{ss}");
786 if (r < 0)
787 return r;
788
789 for (;;) {
790 const char *p, *q;
791
792 r = sd_bus_message_read(reply, "{ss}", &p, &q);
793 if (r < 0)
794 return r;
795 if (r == 0)
796 break;
797
798 if (streq(p, "DEPLOYMENT"))
799 printf(" Deployment: %s\n", q);
800 }
801
802 r = sd_bus_message_exit_container(reply);
803 if (r < 0)
804 return r;
805
806 return 0;
807 }
808
809 typedef struct ImageStatusInfo {
810 const char *name;
811 const char *path;
812 const char *type;
813 bool read_only;
814 usec_t crtime;
815 usec_t mtime;
816 uint64_t usage;
817 uint64_t limit;
818 uint64_t usage_exclusive;
819 uint64_t limit_exclusive;
820 } ImageStatusInfo;
821
822 static void print_image_status_info(sd_bus *bus, ImageStatusInfo *i) {
823 assert(bus);
824 assert(i);
825
826 if (i->name) {
827 fputs(i->name, stdout);
828 putchar('\n');
829 }
830
831 if (i->type)
832 printf("\t Type: %s\n", i->type);
833
834 if (i->path)
835 printf("\t Path: %s\n", i->path);
836
837 (void) print_image_hostname(bus, i->name);
838 (void) print_image_machine_id(bus, i->name);
839 (void) print_image_machine_info(bus, i->name);
840
841 print_os_release(bus, "GetImageOSRelease", i->name, "\t OS: ");
842
843 printf("\t RO: %s%s%s\n",
844 i->read_only ? ansi_highlight_red() : "",
845 i->read_only ? "read-only" : "writable",
846 i->read_only ? ansi_normal() : "");
847
848 if (timestamp_is_set(i->crtime))
849 printf("\t Created: %s; %s\n",
850 FORMAT_TIMESTAMP(i->crtime), FORMAT_TIMESTAMP_RELATIVE(i->crtime));
851
852 if (timestamp_is_set(i->mtime))
853 printf("\tModified: %s; %s\n",
854 FORMAT_TIMESTAMP(i->mtime), FORMAT_TIMESTAMP_RELATIVE(i->mtime));
855
856 if (i->usage != UINT64_MAX) {
857 if (i->usage_exclusive != i->usage && i->usage_exclusive != UINT64_MAX)
858 printf("\t Usage: %s (exclusive: %s)\n",
859 FORMAT_BYTES(i->usage), FORMAT_BYTES(i->usage_exclusive));
860 else
861 printf("\t Usage: %s\n", FORMAT_BYTES(i->usage));
862 }
863
864 if (i->limit != UINT64_MAX) {
865 if (i->limit_exclusive != i->limit && i->limit_exclusive != UINT64_MAX)
866 printf("\t Limit: %s (exclusive: %s)\n",
867 FORMAT_BYTES(i->limit), FORMAT_BYTES(i->limit_exclusive));
868 else
869 printf("\t Limit: %s\n", FORMAT_BYTES(i->limit));
870 }
871 }
872
873 static int show_image_info(sd_bus *bus, const char *path, bool *new_line) {
874
875 static const struct bus_properties_map map[] = {
876 { "Name", "s", NULL, offsetof(ImageStatusInfo, name) },
877 { "Path", "s", NULL, offsetof(ImageStatusInfo, path) },
878 { "Type", "s", NULL, offsetof(ImageStatusInfo, type) },
879 { "ReadOnly", "b", NULL, offsetof(ImageStatusInfo, read_only) },
880 { "CreationTimestamp", "t", NULL, offsetof(ImageStatusInfo, crtime) },
881 { "ModificationTimestamp", "t", NULL, offsetof(ImageStatusInfo, mtime) },
882 { "Usage", "t", NULL, offsetof(ImageStatusInfo, usage) },
883 { "Limit", "t", NULL, offsetof(ImageStatusInfo, limit) },
884 { "UsageExclusive", "t", NULL, offsetof(ImageStatusInfo, usage_exclusive) },
885 { "LimitExclusive", "t", NULL, offsetof(ImageStatusInfo, limit_exclusive) },
886 {}
887 };
888
889 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
890 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
891 ImageStatusInfo info = {};
892 int r;
893
894 assert(bus);
895 assert(path);
896 assert(new_line);
897
898 r = bus_map_all_properties(bus,
899 "org.freedesktop.machine1",
900 path,
901 map,
902 BUS_MAP_BOOLEAN_AS_BOOL,
903 &error,
904 &m,
905 &info);
906 if (r < 0)
907 return log_error_errno(r, "Could not get properties: %s", bus_error_message(&error, r));
908
909 if (*new_line)
910 printf("\n");
911 *new_line = true;
912
913 print_image_status_info(bus, &info);
914
915 return r;
916 }
917
918 typedef struct PoolStatusInfo {
919 const char *path;
920 uint64_t usage;
921 uint64_t limit;
922 } PoolStatusInfo;
923
924 static void print_pool_status_info(sd_bus *bus, PoolStatusInfo *i) {
925 if (i->path)
926 printf("\t Path: %s\n", i->path);
927
928 if (i->usage != UINT64_MAX)
929 printf("\t Usage: %s\n", FORMAT_BYTES(i->usage));
930
931 if (i->limit != UINT64_MAX)
932 printf("\t Limit: %s\n", FORMAT_BYTES(i->limit));
933 }
934
935 static int show_pool_info(sd_bus *bus) {
936
937 static const struct bus_properties_map map[] = {
938 { "PoolPath", "s", NULL, offsetof(PoolStatusInfo, path) },
939 { "PoolUsage", "t", NULL, offsetof(PoolStatusInfo, usage) },
940 { "PoolLimit", "t", NULL, offsetof(PoolStatusInfo, limit) },
941 {}
942 };
943
944 PoolStatusInfo info = {
945 .usage = UINT64_MAX,
946 .limit = UINT64_MAX,
947 };
948
949 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
950 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
951 int r;
952
953 assert(bus);
954
955 r = bus_map_all_properties(bus,
956 "org.freedesktop.machine1",
957 "/org/freedesktop/machine1",
958 map,
959 0,
960 &error,
961 &m,
962 &info);
963 if (r < 0)
964 return log_error_errno(r, "Could not get properties: %s", bus_error_message(&error, r));
965
966 print_pool_status_info(bus, &info);
967
968 return 0;
969 }
970
971 static int show_image_properties(sd_bus *bus, const char *path, bool *new_line) {
972 int r;
973
974 assert(bus);
975 assert(path);
976 assert(new_line);
977
978 if (*new_line)
979 printf("\n");
980
981 *new_line = true;
982
983 r = bus_print_all_properties(bus, "org.freedesktop.machine1", path, NULL, arg_property, arg_print_flags, NULL);
984 if (r < 0)
985 log_error_errno(r, "Could not get properties: %m");
986
987 return r;
988 }
989
990 static int show_image(int argc, char *argv[], void *userdata) {
991
992 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
993 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
994 bool properties, new_line = false;
995 sd_bus *bus = userdata;
996 int r = 0;
997
998 assert(bus);
999
1000 properties = !strstr(argv[0], "status");
1001
1002 pager_open(arg_pager_flags);
1003
1004 if (argc <= 1) {
1005
1006 /* If no argument is specified, inspect the manager
1007 * itself */
1008
1009 if (properties)
1010 r = show_image_properties(bus, "/org/freedesktop/machine1", &new_line);
1011 else
1012 r = show_pool_info(bus);
1013 if (r < 0)
1014 return r;
1015 }
1016
1017 for (int i = 1; i < argc; i++) {
1018 const char *path = NULL;
1019
1020 r = bus_call_method(bus, bus_machine_mgr, "GetImage", &error, &reply, "s", argv[i]);
1021 if (r < 0)
1022 return log_error_errno(r, "Could not get path to image: %s", bus_error_message(&error, r));
1023
1024 r = sd_bus_message_read(reply, "o", &path);
1025 if (r < 0)
1026 return bus_log_parse_error(r);
1027
1028 if (properties)
1029 r = show_image_properties(bus, path, &new_line);
1030 else
1031 r = show_image_info(bus, path, &new_line);
1032 }
1033
1034 return r;
1035 }
1036
1037 static int kill_machine(int argc, char *argv[], void *userdata) {
1038 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1039 sd_bus *bus = userdata;
1040 int r;
1041
1042 assert(bus);
1043
1044 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1045
1046 if (!arg_kill_who)
1047 arg_kill_who = "all";
1048
1049 for (int i = 1; i < argc; i++) {
1050 r = bus_call_method(
1051 bus,
1052 bus_machine_mgr,
1053 "KillMachine",
1054 &error,
1055 NULL,
1056 "ssi", argv[i], arg_kill_who, arg_signal);
1057 if (r < 0)
1058 return log_error_errno(r, "Could not kill machine: %s", bus_error_message(&error, r));
1059 }
1060
1061 return 0;
1062 }
1063
1064 static int reboot_machine(int argc, char *argv[], void *userdata) {
1065 arg_kill_who = "leader";
1066 arg_signal = SIGINT; /* sysvinit + systemd */
1067
1068 return kill_machine(argc, argv, userdata);
1069 }
1070
1071 static int poweroff_machine(int argc, char *argv[], void *userdata) {
1072 arg_kill_who = "leader";
1073 arg_signal = SIGRTMIN+4; /* only systemd */
1074
1075 return kill_machine(argc, argv, userdata);
1076 }
1077
1078 static int terminate_machine(int argc, char *argv[], void *userdata) {
1079 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1080 sd_bus *bus = userdata;
1081 int r;
1082
1083 assert(bus);
1084
1085 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1086
1087 for (int i = 1; i < argc; i++) {
1088 r = bus_call_method(bus, bus_machine_mgr, "TerminateMachine", &error, NULL, "s", argv[i]);
1089 if (r < 0)
1090 return log_error_errno(r, "Could not terminate machine: %s", bus_error_message(&error, r));
1091 }
1092
1093 return 0;
1094 }
1095
1096 static int copy_files(int argc, char *argv[], void *userdata) {
1097 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1098 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1099 _cleanup_free_ char *abs_host_path = NULL;
1100 char *dest, *host_path, *container_path;
1101 sd_bus *bus = userdata;
1102 bool copy_from;
1103 int r;
1104
1105 assert(bus);
1106
1107 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1108
1109 copy_from = streq(argv[0], "copy-from");
1110 dest = argv[3] ?: argv[2];
1111 host_path = copy_from ? dest : argv[2];
1112 container_path = copy_from ? argv[2] : dest;
1113
1114 if (!path_is_absolute(host_path)) {
1115 r = path_make_absolute_cwd(host_path, &abs_host_path);
1116 if (r < 0)
1117 return log_error_errno(r, "Failed to make path absolute: %m");
1118
1119 host_path = abs_host_path;
1120 }
1121
1122 r = bus_message_new_method_call(
1123 bus,
1124 &m,
1125 bus_machine_mgr,
1126 copy_from ? "CopyFromMachine" : "CopyToMachine");
1127 if (r < 0)
1128 return bus_log_create_error(r);
1129
1130 r = sd_bus_message_append(
1131 m,
1132 "sss",
1133 argv[1],
1134 copy_from ? container_path : host_path,
1135 copy_from ? host_path : container_path);
1136 if (r < 0)
1137 return bus_log_create_error(r);
1138
1139 /* This is a slow operation, hence turn off any method call timeouts */
1140 r = sd_bus_call(bus, m, USEC_INFINITY, &error, NULL);
1141 if (r < 0)
1142 return log_error_errno(r, "Failed to copy: %s", bus_error_message(&error, r));
1143
1144 return 0;
1145 }
1146
1147 static int bind_mount(int argc, char *argv[], void *userdata) {
1148 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1149 sd_bus *bus = userdata;
1150 int r;
1151
1152 assert(bus);
1153
1154 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1155
1156 r = bus_call_method(
1157 bus,
1158 bus_machine_mgr,
1159 "BindMountMachine",
1160 &error,
1161 NULL,
1162 "sssbb",
1163 argv[1],
1164 argv[2],
1165 argv[3],
1166 arg_read_only,
1167 arg_mkdir);
1168 if (r < 0)
1169 return log_error_errno(r, "Failed to bind mount: %s", bus_error_message(&error, r));
1170
1171 return 0;
1172 }
1173
1174 static int on_machine_removed(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1175 PTYForward ** forward = (PTYForward**) userdata;
1176 int r;
1177
1178 assert(m);
1179 assert(forward);
1180
1181 if (*forward) {
1182 /* If the forwarder is already initialized, tell it to
1183 * exit on the next vhangup(), so that we still flush
1184 * out what might be queued and exit then. */
1185
1186 r = pty_forward_set_ignore_vhangup(*forward, false);
1187 if (r >= 0)
1188 return 0;
1189
1190 log_error_errno(r, "Failed to set ignore_vhangup flag: %m");
1191 }
1192
1193 /* On error, or when the forwarder is not initialized yet, quit immediately */
1194 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), EXIT_FAILURE);
1195 return 0;
1196 }
1197
1198 static int process_forward(sd_event *event, PTYForward **forward, int master, PTYForwardFlags flags, const char *name) {
1199 char last_char = 0;
1200 bool machine_died;
1201 int r;
1202
1203 assert(event);
1204 assert(master >= 0);
1205 assert(name);
1206
1207 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGWINCH, SIGTERM, SIGINT, -1) >= 0);
1208
1209 if (!arg_quiet) {
1210 if (streq(name, ".host"))
1211 log_info("Connected to the local host. Press ^] three times within 1s to exit session.");
1212 else
1213 log_info("Connected to machine %s. Press ^] three times within 1s to exit session.", name);
1214 }
1215
1216 (void) sd_event_add_signal(event, NULL, SIGINT, NULL, NULL);
1217 (void) sd_event_add_signal(event, NULL, SIGTERM, NULL, NULL);
1218
1219 r = pty_forward_new(event, master, flags, forward);
1220 if (r < 0)
1221 return log_error_errno(r, "Failed to create PTY forwarder: %m");
1222
1223 r = sd_event_loop(event);
1224 if (r < 0)
1225 return log_error_errno(r, "Failed to run event loop: %m");
1226
1227 pty_forward_get_last_char(*forward, &last_char);
1228
1229 machine_died =
1230 (flags & PTY_FORWARD_IGNORE_VHANGUP) &&
1231 pty_forward_get_ignore_vhangup(*forward) == 0;
1232
1233 *forward = pty_forward_free(*forward);
1234
1235 if (last_char != '\n')
1236 fputc('\n', stdout);
1237
1238 if (!arg_quiet) {
1239 if (machine_died)
1240 log_info("Machine %s terminated.", name);
1241 else if (streq(name, ".host"))
1242 log_info("Connection to the local host terminated.");
1243 else
1244 log_info("Connection to machine %s terminated.", name);
1245 }
1246
1247 return 0;
1248 }
1249
1250 static int parse_machine_uid(const char *spec, const char **machine, char **uid) {
1251 /*
1252 * Whatever is specified in the spec takes priority over global arguments.
1253 */
1254 char *_uid = NULL;
1255 const char *_machine = NULL;
1256
1257 if (spec) {
1258 const char *at;
1259
1260 at = strchr(spec, '@');
1261 if (at) {
1262 if (at == spec)
1263 /* Do the same as ssh and refuse "@host". */
1264 return -EINVAL;
1265
1266 _machine = at + 1;
1267 _uid = strndup(spec, at - spec);
1268 if (!_uid)
1269 return -ENOMEM;
1270 } else
1271 _machine = spec;
1272 };
1273
1274 if (arg_uid && !_uid) {
1275 _uid = strdup(arg_uid);
1276 if (!_uid)
1277 return -ENOMEM;
1278 }
1279
1280 *uid = _uid;
1281 *machine = isempty(_machine) ? ".host" : _machine;
1282 return 0;
1283 }
1284
1285 static int login_machine(int argc, char *argv[], void *userdata) {
1286 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1287 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1288 _cleanup_(pty_forward_freep) PTYForward *forward = NULL;
1289 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1290 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1291 int master = -1, r;
1292 sd_bus *bus = userdata;
1293 const char *match, *machine;
1294
1295 assert(bus);
1296
1297 if (!strv_isempty(arg_setenv) || arg_uid)
1298 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1299 "--setenv= and --uid= are not supported for 'login'. Use 'shell' instead.");
1300
1301 if (!IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_MACHINE))
1302 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1303 "Login only supported on local machines.");
1304
1305 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1306
1307 r = sd_event_default(&event);
1308 if (r < 0)
1309 return log_error_errno(r, "Failed to get event loop: %m");
1310
1311 r = sd_bus_attach_event(bus, event, 0);
1312 if (r < 0)
1313 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1314
1315 machine = argc < 2 || isempty(argv[1]) ? ".host" : argv[1];
1316
1317 match = strjoina("type='signal',"
1318 "sender='org.freedesktop.machine1',"
1319 "path='/org/freedesktop/machine1',",
1320 "interface='org.freedesktop.machine1.Manager',"
1321 "member='MachineRemoved',"
1322 "arg0='", machine, "'");
1323
1324 r = sd_bus_add_match_async(bus, &slot, match, on_machine_removed, NULL, &forward);
1325 if (r < 0)
1326 return log_error_errno(r, "Failed to request machine removal match: %m");
1327
1328 r = bus_call_method(bus, bus_machine_mgr, "OpenMachineLogin", &error, &reply, "s", machine);
1329 if (r < 0)
1330 return log_error_errno(r, "Failed to get login PTY: %s", bus_error_message(&error, r));
1331
1332 r = sd_bus_message_read(reply, "hs", &master, NULL);
1333 if (r < 0)
1334 return bus_log_parse_error(r);
1335
1336 return process_forward(event, &forward, master, PTY_FORWARD_IGNORE_VHANGUP, machine);
1337 }
1338
1339 static int shell_machine(int argc, char *argv[], void *userdata) {
1340 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
1341 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1342 _cleanup_(pty_forward_freep) PTYForward *forward = NULL;
1343 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1344 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1345 int master = -1, r;
1346 sd_bus *bus = userdata;
1347 const char *match, *machine, *path;
1348 _cleanup_free_ char *uid = NULL;
1349
1350 assert(bus);
1351
1352 if (!IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_MACHINE))
1353 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1354 "Shell only supported on local machines.");
1355
1356 /* Pass $TERM to shell session, if not explicitly specified. */
1357 if (!strv_find_prefix(arg_setenv, "TERM=")) {
1358 const char *t;
1359
1360 t = strv_find_prefix(environ, "TERM=");
1361 if (t) {
1362 if (strv_extend(&arg_setenv, t) < 0)
1363 return log_oom();
1364 }
1365 }
1366
1367 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1368
1369 r = sd_event_default(&event);
1370 if (r < 0)
1371 return log_error_errno(r, "Failed to get event loop: %m");
1372
1373 r = sd_bus_attach_event(bus, event, 0);
1374 if (r < 0)
1375 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1376
1377 r = parse_machine_uid(argc >= 2 ? argv[1] : NULL, &machine, &uid);
1378 if (r < 0)
1379 return log_error_errno(r, "Failed to parse machine specification: %m");
1380
1381 match = strjoina("type='signal',"
1382 "sender='org.freedesktop.machine1',"
1383 "path='/org/freedesktop/machine1',",
1384 "interface='org.freedesktop.machine1.Manager',"
1385 "member='MachineRemoved',"
1386 "arg0='", machine, "'");
1387
1388 r = sd_bus_add_match_async(bus, &slot, match, on_machine_removed, NULL, &forward);
1389 if (r < 0)
1390 return log_error_errno(r, "Failed to request machine removal match: %m");
1391
1392 r = bus_message_new_method_call(bus, &m, bus_machine_mgr, "OpenMachineShell");
1393 if (r < 0)
1394 return bus_log_create_error(r);
1395
1396 path = argc < 3 || isempty(argv[2]) ? NULL : argv[2];
1397
1398 r = sd_bus_message_append(m, "sss", machine, uid, path);
1399 if (r < 0)
1400 return bus_log_create_error(r);
1401
1402 r = sd_bus_message_append_strv(m, strv_length(argv) <= 3 ? NULL : argv + 2);
1403 if (r < 0)
1404 return bus_log_create_error(r);
1405
1406 r = sd_bus_message_append_strv(m, arg_setenv);
1407 if (r < 0)
1408 return bus_log_create_error(r);
1409
1410 r = sd_bus_call(bus, m, 0, &error, &reply);
1411 if (r < 0)
1412 return log_error_errno(r, "Failed to get shell PTY: %s", bus_error_message(&error, r));
1413
1414 r = sd_bus_message_read(reply, "hs", &master, NULL);
1415 if (r < 0)
1416 return bus_log_parse_error(r);
1417
1418 return process_forward(event, &forward, master, 0, machine);
1419 }
1420
1421 static int remove_image(int argc, char *argv[], void *userdata) {
1422 sd_bus *bus = userdata;
1423 int r;
1424
1425 assert(bus);
1426
1427 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1428
1429 for (int i = 1; i < argc; i++) {
1430 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1431 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1432
1433 r = bus_message_new_method_call(bus, &m, bus_machine_mgr, "RemoveImage");
1434 if (r < 0)
1435 return bus_log_create_error(r);
1436
1437 r = sd_bus_message_append(m, "s", argv[i]);
1438 if (r < 0)
1439 return bus_log_create_error(r);
1440
1441 /* This is a slow operation, hence turn off any method call timeouts */
1442 r = sd_bus_call(bus, m, USEC_INFINITY, &error, NULL);
1443 if (r < 0)
1444 return log_error_errno(r, "Could not remove image: %s", bus_error_message(&error, r));
1445 }
1446
1447 return 0;
1448 }
1449
1450 static int rename_image(int argc, char *argv[], void *userdata) {
1451 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1452 sd_bus *bus = userdata;
1453 int r;
1454
1455 assert(bus);
1456
1457 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1458
1459 r = bus_call_method(
1460 bus,
1461 bus_machine_mgr,
1462 "RenameImage",
1463 &error,
1464 NULL,
1465 "ss", argv[1], argv[2]);
1466 if (r < 0)
1467 return log_error_errno(r, "Could not rename image: %s", bus_error_message(&error, r));
1468
1469 return 0;
1470 }
1471
1472 static int clone_image(int argc, char *argv[], void *userdata) {
1473 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1474 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1475 sd_bus *bus = userdata;
1476 int r;
1477
1478 assert(bus);
1479
1480 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1481
1482 r = bus_message_new_method_call(bus, &m, bus_machine_mgr, "CloneImage");
1483 if (r < 0)
1484 return bus_log_create_error(r);
1485
1486 r = sd_bus_message_append(m, "ssb", argv[1], argv[2], arg_read_only);
1487 if (r < 0)
1488 return bus_log_create_error(r);
1489
1490 /* This is a slow operation, hence turn off any method call timeouts */
1491 r = sd_bus_call(bus, m, USEC_INFINITY, &error, NULL);
1492 if (r < 0)
1493 return log_error_errno(r, "Could not clone image: %s", bus_error_message(&error, r));
1494
1495 return 0;
1496 }
1497
1498 static int read_only_image(int argc, char *argv[], void *userdata) {
1499 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1500 sd_bus *bus = userdata;
1501 int b = true, r;
1502
1503 assert(bus);
1504
1505 if (argc > 2) {
1506 b = parse_boolean(argv[2]);
1507 if (b < 0)
1508 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1509 "Failed to parse boolean argument: %s",
1510 argv[2]);
1511 }
1512
1513 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1514
1515 r = bus_call_method(bus, bus_machine_mgr, "MarkImageReadOnly", &error, NULL, "sb", argv[1], b);
1516 if (r < 0)
1517 return log_error_errno(r, "Could not mark image read-only: %s", bus_error_message(&error, r));
1518
1519 return 0;
1520 }
1521
1522 static int image_exists(sd_bus *bus, const char *name) {
1523 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1524 int r;
1525
1526 assert(bus);
1527 assert(name);
1528
1529 r = bus_call_method(bus, bus_machine_mgr, "GetImage", &error, NULL, "s", name);
1530 if (r < 0) {
1531 if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_IMAGE))
1532 return 0;
1533
1534 return log_error_errno(r, "Failed to check whether image %s exists: %s", name, bus_error_message(&error, r));
1535 }
1536
1537 return 1;
1538 }
1539
1540 static int make_service_name(const char *name, char **ret) {
1541 int r;
1542
1543 assert(name);
1544 assert(ret);
1545
1546 if (!hostname_is_valid(name, 0))
1547 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1548 "Invalid machine name %s.", name);
1549
1550 r = unit_name_build("systemd-nspawn", name, ".service", ret);
1551 if (r < 0)
1552 return log_error_errno(r, "Failed to build unit name: %m");
1553
1554 return 0;
1555 }
1556
1557 static int start_machine(int argc, char *argv[], void *userdata) {
1558 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1559 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
1560 sd_bus *bus = userdata;
1561 int r;
1562
1563 assert(bus);
1564
1565 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1566 ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
1567
1568 r = bus_wait_for_jobs_new(bus, &w);
1569 if (r < 0)
1570 return log_oom();
1571
1572 for (int i = 1; i < argc; i++) {
1573 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1574 _cleanup_free_ char *unit = NULL;
1575 const char *object;
1576
1577 r = make_service_name(argv[i], &unit);
1578 if (r < 0)
1579 return r;
1580
1581 r = image_exists(bus, argv[i]);
1582 if (r < 0)
1583 return r;
1584 if (r == 0)
1585 return log_error_errno(SYNTHETIC_ERRNO(ENXIO),
1586 "Machine image '%s' does not exist.",
1587 argv[i]);
1588
1589 r = sd_bus_call_method(
1590 bus,
1591 "org.freedesktop.systemd1",
1592 "/org/freedesktop/systemd1",
1593 "org.freedesktop.systemd1.Manager",
1594 "StartUnit",
1595 &error,
1596 &reply,
1597 "ss", unit, "fail");
1598 if (r < 0)
1599 return log_error_errno(r, "Failed to start unit: %s", bus_error_message(&error, r));
1600
1601 r = sd_bus_message_read(reply, "o", &object);
1602 if (r < 0)
1603 return bus_log_parse_error(r);
1604
1605 r = bus_wait_for_jobs_add(w, object);
1606 if (r < 0)
1607 return log_oom();
1608 }
1609
1610 r = bus_wait_for_jobs(w, arg_quiet, NULL);
1611 if (r < 0)
1612 return r;
1613
1614 return 0;
1615 }
1616
1617 static int enable_machine(int argc, char *argv[], void *userdata) {
1618 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
1619 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1620 UnitFileChange *changes = NULL;
1621 size_t n_changes = 0;
1622 const char *method = NULL;
1623 sd_bus *bus = userdata;
1624 int r;
1625
1626 assert(bus);
1627
1628 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1629
1630 method = streq(argv[0], "enable") ? "EnableUnitFiles" : "DisableUnitFiles";
1631
1632 r = sd_bus_message_new_method_call(
1633 bus,
1634 &m,
1635 "org.freedesktop.systemd1",
1636 "/org/freedesktop/systemd1",
1637 "org.freedesktop.systemd1.Manager",
1638 method);
1639 if (r < 0)
1640 return bus_log_create_error(r);
1641
1642 r = sd_bus_message_open_container(m, 'a', "s");
1643 if (r < 0)
1644 return bus_log_create_error(r);
1645
1646 for (int i = 1; i < argc; i++) {
1647 _cleanup_free_ char *unit = NULL;
1648
1649 r = make_service_name(argv[i], &unit);
1650 if (r < 0)
1651 return r;
1652
1653 r = image_exists(bus, argv[i]);
1654 if (r < 0)
1655 return r;
1656 if (r == 0)
1657 return log_error_errno(SYNTHETIC_ERRNO(ENXIO),
1658 "Machine image '%s' does not exist.",
1659 argv[i]);
1660
1661 r = sd_bus_message_append(m, "s", unit);
1662 if (r < 0)
1663 return bus_log_create_error(r);
1664 }
1665
1666 r = sd_bus_message_close_container(m);
1667 if (r < 0)
1668 return bus_log_create_error(r);
1669
1670 if (streq(argv[0], "enable"))
1671 r = sd_bus_message_append(m, "bb", false, false);
1672 else
1673 r = sd_bus_message_append(m, "b", false);
1674 if (r < 0)
1675 return bus_log_create_error(r);
1676
1677 r = sd_bus_call(bus, m, 0, &error, &reply);
1678 if (r < 0)
1679 return log_error_errno(r, "Failed to enable or disable unit: %s", bus_error_message(&error, r));
1680
1681 if (streq(argv[0], "enable")) {
1682 r = sd_bus_message_read(reply, "b", NULL);
1683 if (r < 0)
1684 return bus_log_parse_error(r);
1685 }
1686
1687 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
1688 if (r < 0)
1689 goto finish;
1690
1691 r = sd_bus_call_method(
1692 bus,
1693 "org.freedesktop.systemd1",
1694 "/org/freedesktop/systemd1",
1695 "org.freedesktop.systemd1.Manager",
1696 "Reload",
1697 &error,
1698 NULL,
1699 NULL);
1700 if (r < 0) {
1701 log_error("Failed to reload daemon: %s", bus_error_message(&error, r));
1702 goto finish;
1703 }
1704
1705 r = 0;
1706
1707 finish:
1708 unit_file_changes_free(changes, n_changes);
1709
1710 return r;
1711 }
1712
1713 static int match_log_message(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1714 const char **our_path = userdata, *line;
1715 unsigned priority;
1716 int r;
1717
1718 assert(m);
1719 assert(our_path);
1720
1721 r = sd_bus_message_read(m, "us", &priority, &line);
1722 if (r < 0) {
1723 bus_log_parse_error(r);
1724 return 0;
1725 }
1726
1727 if (!streq_ptr(*our_path, sd_bus_message_get_path(m)))
1728 return 0;
1729
1730 if (arg_quiet && LOG_PRI(priority) >= LOG_INFO)
1731 return 0;
1732
1733 log_full(priority, "%s", line);
1734 return 0;
1735 }
1736
1737 static int match_transfer_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1738 const char **our_path = userdata, *path, *result;
1739 uint32_t id;
1740 int r;
1741
1742 assert(m);
1743 assert(our_path);
1744
1745 r = sd_bus_message_read(m, "uos", &id, &path, &result);
1746 if (r < 0) {
1747 bus_log_parse_error(r);
1748 return 0;
1749 }
1750
1751 if (!streq_ptr(*our_path, path))
1752 return 0;
1753
1754 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), !streq_ptr(result, "done"));
1755 return 0;
1756 }
1757
1758 static int transfer_signal_handler(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1759 assert(s);
1760 assert(si);
1761
1762 if (!arg_quiet)
1763 log_info("Continuing download in the background. Use \"machinectl cancel-transfer %" PRIu32 "\" to abort transfer.", PTR_TO_UINT32(userdata));
1764
1765 sd_event_exit(sd_event_source_get_event(s), EINTR);
1766 return 0;
1767 }
1768
1769 static int transfer_image_common(sd_bus *bus, sd_bus_message *m) {
1770 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot_job_removed = NULL, *slot_log_message = NULL;
1771 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1772 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1773 _cleanup_(sd_event_unrefp) sd_event* event = NULL;
1774 const char *path = NULL;
1775 uint32_t id;
1776 int r;
1777
1778 assert(bus);
1779 assert(m);
1780
1781 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1782
1783 r = sd_event_default(&event);
1784 if (r < 0)
1785 return log_error_errno(r, "Failed to get event loop: %m");
1786
1787 r = sd_bus_attach_event(bus, event, 0);
1788 if (r < 0)
1789 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1790
1791 r = bus_match_signal_async(
1792 bus,
1793 &slot_job_removed,
1794 bus_import_mgr,
1795 "TransferRemoved",
1796 match_transfer_removed, NULL, &path);
1797 if (r < 0)
1798 return log_error_errno(r, "Failed to request match: %m");
1799
1800 r = sd_bus_match_signal_async(
1801 bus,
1802 &slot_log_message,
1803 "org.freedesktop.import1",
1804 NULL,
1805 "org.freedesktop.import1.Transfer",
1806 "LogMessage",
1807 match_log_message, NULL, &path);
1808 if (r < 0)
1809 return log_error_errno(r, "Failed to request match: %m");
1810
1811 r = sd_bus_call(bus, m, 0, &error, &reply);
1812 if (r < 0)
1813 return log_error_errno(r, "Failed to transfer image: %s", bus_error_message(&error, r));
1814
1815 r = sd_bus_message_read(reply, "uo", &id, &path);
1816 if (r < 0)
1817 return bus_log_parse_error(r);
1818
1819 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0);
1820
1821 if (!arg_quiet)
1822 log_info("Enqueued transfer job %u. Press C-c to continue download in background.", id);
1823
1824 (void) sd_event_add_signal(event, NULL, SIGINT, transfer_signal_handler, UINT32_TO_PTR(id));
1825 (void) sd_event_add_signal(event, NULL, SIGTERM, transfer_signal_handler, UINT32_TO_PTR(id));
1826
1827 r = sd_event_loop(event);
1828 if (r < 0)
1829 return log_error_errno(r, "Failed to run event loop: %m");
1830
1831 return -r;
1832 }
1833
1834 static int import_tar(int argc, char *argv[], void *userdata) {
1835 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1836 _cleanup_free_ char *ll = NULL, *fn = NULL;
1837 const char *local = NULL, *path = NULL;
1838 _cleanup_close_ int fd = -1;
1839 sd_bus *bus = userdata;
1840 int r;
1841
1842 assert(bus);
1843
1844 if (argc >= 2)
1845 path = empty_or_dash_to_null(argv[1]);
1846
1847 if (argc >= 3)
1848 local = empty_or_dash_to_null(argv[2]);
1849 else if (path) {
1850 r = path_extract_filename(path, &fn);
1851 if (r < 0)
1852 return log_error_errno(r, "Cannot extract container name from filename: %m");
1853 if (r == O_DIRECTORY)
1854 return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
1855 "Path '%s' refers to directory, but we need a regular file: %m", path);
1856
1857 local = fn;
1858 }
1859 if (!local)
1860 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1861 "Need either path or local name.");
1862
1863 r = tar_strip_suffixes(local, &ll);
1864 if (r < 0)
1865 return log_oom();
1866
1867 local = ll;
1868
1869 if (!hostname_is_valid(local, 0))
1870 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1871 "Local name %s is not a suitable machine name.",
1872 local);
1873
1874 if (path) {
1875 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
1876 if (fd < 0)
1877 return log_error_errno(errno, "Failed to open %s: %m", path);
1878 }
1879
1880 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportTar");
1881 if (r < 0)
1882 return bus_log_create_error(r);
1883
1884 r = sd_bus_message_append(
1885 m,
1886 "hsbb",
1887 fd >= 0 ? fd : STDIN_FILENO,
1888 local,
1889 arg_force,
1890 arg_read_only);
1891 if (r < 0)
1892 return bus_log_create_error(r);
1893
1894 return transfer_image_common(bus, m);
1895 }
1896
1897 static int import_raw(int argc, char *argv[], void *userdata) {
1898 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1899 _cleanup_free_ char *ll = NULL, *fn = NULL;
1900 const char *local = NULL, *path = NULL;
1901 _cleanup_close_ int fd = -1;
1902 sd_bus *bus = userdata;
1903 int r;
1904
1905 assert(bus);
1906
1907 if (argc >= 2)
1908 path = empty_or_dash_to_null(argv[1]);
1909
1910 if (argc >= 3)
1911 local = empty_or_dash_to_null(argv[2]);
1912 else if (path) {
1913 r = path_extract_filename(path, &fn);
1914 if (r < 0)
1915 return log_error_errno(r, "Cannot extract container name from filename: %m");
1916 if (r == O_DIRECTORY)
1917 return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
1918 "Path '%s' refers to directory, but we need a regular file: %m", path);
1919
1920 local = fn;
1921 }
1922 if (!local)
1923 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1924 "Need either path or local name.");
1925
1926 r = raw_strip_suffixes(local, &ll);
1927 if (r < 0)
1928 return log_oom();
1929
1930 local = ll;
1931
1932 if (!hostname_is_valid(local, 0))
1933 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1934 "Local name %s is not a suitable machine name.",
1935 local);
1936
1937 if (path) {
1938 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
1939 if (fd < 0)
1940 return log_error_errno(errno, "Failed to open %s: %m", path);
1941 }
1942
1943 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportRaw");
1944 if (r < 0)
1945 return bus_log_create_error(r);
1946
1947 r = sd_bus_message_append(
1948 m,
1949 "hsbb",
1950 fd >= 0 ? fd : STDIN_FILENO,
1951 local,
1952 arg_force,
1953 arg_read_only);
1954 if (r < 0)
1955 return bus_log_create_error(r);
1956
1957 return transfer_image_common(bus, m);
1958 }
1959
1960 static int import_fs(int argc, char *argv[], void *userdata) {
1961 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1962 const char *local = NULL, *path = NULL;
1963 _cleanup_free_ char *fn = NULL;
1964 _cleanup_close_ int fd = -1;
1965 sd_bus *bus = userdata;
1966 int r;
1967
1968 assert(bus);
1969
1970 if (argc >= 2)
1971 path = empty_or_dash_to_null(argv[1]);
1972
1973 if (argc >= 3)
1974 local = empty_or_dash_to_null(argv[2]);
1975 else if (path) {
1976 r = path_extract_filename(path, &fn);
1977 if (r < 0)
1978 return log_error_errno(r, "Cannot extract container name from filename: %m");
1979
1980 local = fn;
1981 }
1982 if (!local)
1983 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1984 "Need either path or local name.");
1985
1986 if (!hostname_is_valid(local, 0))
1987 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1988 "Local name %s is not a suitable machine name.",
1989 local);
1990
1991 if (path) {
1992 fd = open(path, O_DIRECTORY|O_RDONLY|O_CLOEXEC);
1993 if (fd < 0)
1994 return log_error_errno(errno, "Failed to open directory '%s': %m", path);
1995 }
1996
1997 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportFileSystem");
1998 if (r < 0)
1999 return bus_log_create_error(r);
2000
2001 r = sd_bus_message_append(
2002 m,
2003 "hsbb",
2004 fd >= 0 ? fd : STDIN_FILENO,
2005 local,
2006 arg_force,
2007 arg_read_only);
2008 if (r < 0)
2009 return bus_log_create_error(r);
2010
2011 return transfer_image_common(bus, m);
2012 }
2013
2014 static void determine_compression_from_filename(const char *p) {
2015 if (arg_format)
2016 return;
2017
2018 if (!p)
2019 return;
2020
2021 if (endswith(p, ".xz"))
2022 arg_format = "xz";
2023 else if (endswith(p, ".gz"))
2024 arg_format = "gzip";
2025 else if (endswith(p, ".bz2"))
2026 arg_format = "bzip2";
2027 }
2028
2029 static int export_tar(int argc, char *argv[], void *userdata) {
2030 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2031 _cleanup_close_ int fd = -1;
2032 const char *local = NULL, *path = NULL;
2033 sd_bus *bus = userdata;
2034 int r;
2035
2036 assert(bus);
2037
2038 local = argv[1];
2039 if (!hostname_is_valid(local, 0))
2040 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2041 "Machine name %s is not valid.", local);
2042
2043 if (argc >= 3)
2044 path = argv[2];
2045 path = empty_or_dash_to_null(path);
2046
2047 if (path) {
2048 determine_compression_from_filename(path);
2049
2050 fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC|O_NOCTTY, 0666);
2051 if (fd < 0)
2052 return log_error_errno(errno, "Failed to open %s: %m", path);
2053 }
2054
2055 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ExportTar");
2056 if (r < 0)
2057 return bus_log_create_error(r);
2058
2059 r = sd_bus_message_append(
2060 m,
2061 "shs",
2062 local,
2063 fd >= 0 ? fd : STDOUT_FILENO,
2064 arg_format);
2065 if (r < 0)
2066 return bus_log_create_error(r);
2067
2068 return transfer_image_common(bus, m);
2069 }
2070
2071 static int export_raw(int argc, char *argv[], void *userdata) {
2072 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2073 _cleanup_close_ int fd = -1;
2074 const char *local = NULL, *path = NULL;
2075 sd_bus *bus = userdata;
2076 int r;
2077
2078 assert(bus);
2079
2080 local = argv[1];
2081 if (!hostname_is_valid(local, 0))
2082 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2083 "Machine name %s is not valid.", local);
2084
2085 if (argc >= 3)
2086 path = argv[2];
2087 path = empty_or_dash_to_null(path);
2088
2089 if (path) {
2090 determine_compression_from_filename(path);
2091
2092 fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC|O_NOCTTY, 0666);
2093 if (fd < 0)
2094 return log_error_errno(errno, "Failed to open %s: %m", path);
2095 }
2096
2097 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ExportRaw");
2098 if (r < 0)
2099 return bus_log_create_error(r);
2100
2101 r = sd_bus_message_append(
2102 m,
2103 "shs",
2104 local,
2105 fd >= 0 ? fd : STDOUT_FILENO,
2106 arg_format);
2107 if (r < 0)
2108 return bus_log_create_error(r);
2109
2110 return transfer_image_common(bus, m);
2111 }
2112
2113 static int pull_tar(int argc, char *argv[], void *userdata) {
2114 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2115 _cleanup_free_ char *l = NULL, *ll = NULL;
2116 const char *local, *remote;
2117 sd_bus *bus = userdata;
2118 int r;
2119
2120 assert(bus);
2121
2122 remote = argv[1];
2123 if (!http_url_is_valid(remote) && !file_url_is_valid(remote))
2124 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2125 "URL '%s' is not valid.", remote);
2126
2127 if (argc >= 3)
2128 local = argv[2];
2129 else {
2130 r = import_url_last_component(remote, &l);
2131 if (r < 0)
2132 return log_error_errno(r, "Failed to get final component of URL: %m");
2133
2134 local = l;
2135 }
2136
2137 local = empty_or_dash_to_null(local);
2138
2139 if (local) {
2140 r = tar_strip_suffixes(local, &ll);
2141 if (r < 0)
2142 return log_oom();
2143
2144 local = ll;
2145
2146 if (!hostname_is_valid(local, 0))
2147 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2148 "Local name %s is not a suitable machine name.",
2149 local);
2150 }
2151
2152 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "PullTar");
2153 if (r < 0)
2154 return bus_log_create_error(r);
2155
2156 r = sd_bus_message_append(
2157 m,
2158 "sssb",
2159 remote,
2160 local,
2161 import_verify_to_string(arg_verify),
2162 arg_force);
2163 if (r < 0)
2164 return bus_log_create_error(r);
2165
2166 return transfer_image_common(bus, m);
2167 }
2168
2169 static int pull_raw(int argc, char *argv[], void *userdata) {
2170 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2171 _cleanup_free_ char *l = NULL, *ll = NULL;
2172 const char *local, *remote;
2173 sd_bus *bus = userdata;
2174 int r;
2175
2176 assert(bus);
2177
2178 remote = argv[1];
2179 if (!http_url_is_valid(remote) && !file_url_is_valid(remote))
2180 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2181 "URL '%s' is not valid.", remote);
2182
2183 if (argc >= 3)
2184 local = argv[2];
2185 else {
2186 r = import_url_last_component(remote, &l);
2187 if (r < 0)
2188 return log_error_errno(r, "Failed to get final component of URL: %m");
2189
2190 local = l;
2191 }
2192
2193 local = empty_or_dash_to_null(local);
2194
2195 if (local) {
2196 r = raw_strip_suffixes(local, &ll);
2197 if (r < 0)
2198 return log_oom();
2199
2200 local = ll;
2201
2202 if (!hostname_is_valid(local, 0))
2203 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2204 "Local name %s is not a suitable machine name.",
2205 local);
2206 }
2207
2208 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "PullRaw");
2209 if (r < 0)
2210 return bus_log_create_error(r);
2211
2212 r = sd_bus_message_append(
2213 m,
2214 "sssb",
2215 remote,
2216 local,
2217 import_verify_to_string(arg_verify),
2218 arg_force);
2219 if (r < 0)
2220 return bus_log_create_error(r);
2221
2222 return transfer_image_common(bus, m);
2223 }
2224
2225 typedef struct TransferInfo {
2226 uint32_t id;
2227 const char *type;
2228 const char *remote;
2229 const char *local;
2230 double progress;
2231 } TransferInfo;
2232
2233 static int compare_transfer_info(const TransferInfo *a, const TransferInfo *b) {
2234 return strcmp(a->local, b->local);
2235 }
2236
2237 static int list_transfers(int argc, char *argv[], void *userdata) {
2238 size_t max_type = STRLEN("TYPE"), max_local = STRLEN("LOCAL"), max_remote = STRLEN("REMOTE");
2239 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2240 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2241 _cleanup_free_ TransferInfo *transfers = NULL;
2242 const char *type, *remote, *local;
2243 sd_bus *bus = userdata;
2244 uint32_t id, max_id = 0;
2245 size_t n_transfers = 0;
2246 double progress;
2247 int r;
2248
2249 pager_open(arg_pager_flags);
2250
2251 r = bus_call_method(bus, bus_import_mgr, "ListTransfers", &error, &reply, NULL);
2252 if (r < 0)
2253 return log_error_errno(r, "Could not get transfers: %s", bus_error_message(&error, r));
2254
2255 r = sd_bus_message_enter_container(reply, 'a', "(usssdo)");
2256 if (r < 0)
2257 return bus_log_parse_error(r);
2258
2259 while ((r = sd_bus_message_read(reply, "(usssdo)", &id, &type, &remote, &local, &progress, NULL)) > 0) {
2260 size_t l;
2261
2262 if (!GREEDY_REALLOC(transfers, n_transfers + 1))
2263 return log_oom();
2264
2265 transfers[n_transfers].id = id;
2266 transfers[n_transfers].type = type;
2267 transfers[n_transfers].remote = remote;
2268 transfers[n_transfers].local = local;
2269 transfers[n_transfers].progress = progress;
2270
2271 l = strlen(type);
2272 if (l > max_type)
2273 max_type = l;
2274
2275 l = strlen(remote);
2276 if (l > max_remote)
2277 max_remote = l;
2278
2279 l = strlen(local);
2280 if (l > max_local)
2281 max_local = l;
2282
2283 if (id > max_id)
2284 max_id = id;
2285
2286 n_transfers++;
2287 }
2288 if (r < 0)
2289 return bus_log_parse_error(r);
2290
2291 r = sd_bus_message_exit_container(reply);
2292 if (r < 0)
2293 return bus_log_parse_error(r);
2294
2295 typesafe_qsort(transfers, n_transfers, compare_transfer_info);
2296
2297 if (arg_legend && n_transfers > 0)
2298 printf("%-*s %-*s %-*s %-*s %-*s\n",
2299 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id)), "ID",
2300 (int) 7, "PERCENT",
2301 (int) max_type, "TYPE",
2302 (int) max_local, "LOCAL",
2303 (int) max_remote, "REMOTE");
2304
2305 for (size_t j = 0; j < n_transfers; j++)
2306
2307 if (transfers[j].progress < 0)
2308 printf("%*" PRIu32 " %*s %-*s %-*s %-*s\n",
2309 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id)), transfers[j].id,
2310 (int) 7, "n/a",
2311 (int) max_type, transfers[j].type,
2312 (int) max_local, transfers[j].local,
2313 (int) max_remote, transfers[j].remote);
2314 else
2315 printf("%*" PRIu32 " %*u%% %-*s %-*s %-*s\n",
2316 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id)), transfers[j].id,
2317 (int) 6, (unsigned) (transfers[j].progress * 100),
2318 (int) max_type, transfers[j].type,
2319 (int) max_local, transfers[j].local,
2320 (int) max_remote, transfers[j].remote);
2321
2322 if (arg_legend) {
2323 if (n_transfers > 0)
2324 printf("\n%zu transfers listed.\n", n_transfers);
2325 else
2326 printf("No transfers.\n");
2327 }
2328
2329 return 0;
2330 }
2331
2332 static int cancel_transfer(int argc, char *argv[], void *userdata) {
2333 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2334 sd_bus *bus = userdata;
2335 int r;
2336
2337 assert(bus);
2338
2339 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2340
2341 for (int i = 1; i < argc; i++) {
2342 uint32_t id;
2343
2344 r = safe_atou32(argv[i], &id);
2345 if (r < 0)
2346 return log_error_errno(r, "Failed to parse transfer id: %s", argv[i]);
2347
2348 r = bus_call_method(bus, bus_import_mgr, "CancelTransfer", &error, NULL, "u", id);
2349 if (r < 0)
2350 return log_error_errno(r, "Could not cancel transfer: %s", bus_error_message(&error, r));
2351 }
2352
2353 return 0;
2354 }
2355
2356 static int set_limit(int argc, char *argv[], void *userdata) {
2357 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2358 sd_bus *bus = userdata;
2359 uint64_t limit;
2360 int r;
2361
2362 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2363
2364 if (STR_IN_SET(argv[argc-1], "-", "none", "infinity"))
2365 limit = UINT64_MAX;
2366 else {
2367 r = parse_size(argv[argc-1], 1024, &limit);
2368 if (r < 0)
2369 return log_error_errno(r, "Failed to parse size: %s", argv[argc-1]);
2370 }
2371
2372 if (argc > 2)
2373 /* With two arguments changes the quota limit of the
2374 * specified image */
2375 r = bus_call_method(bus, bus_machine_mgr, "SetImageLimit", &error, NULL, "st", argv[1], limit);
2376 else
2377 /* With one argument changes the pool quota limit */
2378 r = bus_call_method(bus, bus_machine_mgr, "SetPoolLimit", &error, NULL, "t", limit);
2379
2380 if (r < 0)
2381 return log_error_errno(r, "Could not set limit: %s", bus_error_message(&error, r));
2382
2383 return 0;
2384 }
2385
2386 static int clean_images(int argc, char *argv[], void *userdata) {
2387 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
2388 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2389 uint64_t usage, total = 0;
2390 sd_bus *bus = userdata;
2391 const char *name;
2392 unsigned c = 0;
2393 int r;
2394
2395 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2396
2397 r = bus_message_new_method_call(bus, &m, bus_machine_mgr, "CleanPool");
2398 if (r < 0)
2399 return bus_log_create_error(r);
2400
2401 r = sd_bus_message_append(m, "s", arg_all ? "all" : "hidden");
2402 if (r < 0)
2403 return bus_log_create_error(r);
2404
2405 /* This is a slow operation, hence permit a longer time for completion. */
2406 r = sd_bus_call(bus, m, USEC_INFINITY, &error, &reply);
2407 if (r < 0)
2408 return log_error_errno(r, "Could not clean pool: %s", bus_error_message(&error, r));
2409
2410 r = sd_bus_message_enter_container(reply, 'a', "(st)");
2411 if (r < 0)
2412 return bus_log_parse_error(r);
2413
2414 while ((r = sd_bus_message_read(reply, "(st)", &name, &usage)) > 0) {
2415 if (usage == UINT64_MAX) {
2416 log_info("Removed image '%s'", name);
2417 total = UINT64_MAX;
2418 } else {
2419 log_info("Removed image '%s'. Freed exclusive disk space: %s",
2420 name, FORMAT_BYTES(usage));
2421 if (total != UINT64_MAX)
2422 total += usage;
2423 }
2424 c++;
2425 }
2426
2427 r = sd_bus_message_exit_container(reply);
2428 if (r < 0)
2429 return bus_log_parse_error(r);
2430
2431 if (total == UINT64_MAX)
2432 log_info("Removed %u images in total.", c);
2433 else
2434 log_info("Removed %u images in total. Total freed exclusive disk space: %s.",
2435 c, FORMAT_BYTES(total));
2436
2437 return 0;
2438 }
2439
2440 static int help(int argc, char *argv[], void *userdata) {
2441 _cleanup_free_ char *link = NULL;
2442 int r;
2443
2444 pager_open(arg_pager_flags);
2445
2446 r = terminal_urlify_man("machinectl", "1", &link);
2447 if (r < 0)
2448 return log_oom();
2449
2450 printf("%s [OPTIONS...] COMMAND ...\n\n"
2451 "%sSend control commands to or query the virtual machine and container%s\n"
2452 "%sregistration manager.%s\n"
2453 "\nMachine Commands:\n"
2454 " list List running VMs and containers\n"
2455 " status NAME... Show VM/container details\n"
2456 " show [NAME...] Show properties of one or more VMs/containers\n"
2457 " start NAME... Start container as a service\n"
2458 " login [NAME] Get a login prompt in a container or on the\n"
2459 " local host\n"
2460 " shell [[USER@]NAME [COMMAND...]]\n"
2461 " Invoke a shell (or other command) in a container\n"
2462 " or on the local host\n"
2463 " enable NAME... Enable automatic container start at boot\n"
2464 " disable NAME... Disable automatic container start at boot\n"
2465 " poweroff NAME... Power off one or more containers\n"
2466 " reboot NAME... Reboot one or more containers\n"
2467 " terminate NAME... Terminate one or more VMs/containers\n"
2468 " kill NAME... Send signal to processes of a VM/container\n"
2469 " copy-to NAME PATH [PATH] Copy files from the host to a container\n"
2470 " copy-from NAME PATH [PATH] Copy files from a container to the host\n"
2471 " bind NAME PATH [PATH] Bind mount a path from the host into a container\n\n"
2472 "Image Commands:\n"
2473 " list-images Show available container and VM images\n"
2474 " image-status [NAME...] Show image details\n"
2475 " show-image [NAME...] Show properties of image\n"
2476 " clone NAME NAME Clone an image\n"
2477 " rename NAME NAME Rename an image\n"
2478 " read-only NAME [BOOL] Mark or unmark image read-only\n"
2479 " remove NAME... Remove an image\n"
2480 " set-limit [NAME] BYTES Set image or pool size limit (disk quota)\n"
2481 " clean Remove hidden (or all) images\n\n"
2482 "Image Transfer Commands:\n"
2483 " pull-tar URL [NAME] Download a TAR container image\n"
2484 " pull-raw URL [NAME] Download a RAW container or VM image\n"
2485 " import-tar FILE [NAME] Import a local TAR container image\n"
2486 " import-raw FILE [NAME] Import a local RAW container or VM image\n"
2487 " import-fs DIRECTORY [NAME] Import a local directory container image\n"
2488 " export-tar NAME [FILE] Export a TAR container image locally\n"
2489 " export-raw NAME [FILE] Export a RAW container or VM image locally\n"
2490 " list-transfers Show list of downloads in progress\n"
2491 " cancel-transfer Cancel a download\n"
2492 "\nOptions:\n"
2493 " -h --help Show this help\n"
2494 " --version Show package version\n"
2495 " --no-pager Do not pipe output into a pager\n"
2496 " --no-legend Do not show the headers and footers\n"
2497 " --no-ask-password Do not ask for system passwords\n"
2498 " -H --host=[USER@]HOST Operate on remote host\n"
2499 " -M --machine=CONTAINER Operate on local container\n"
2500 " -p --property=NAME Show only properties by this name\n"
2501 " -q --quiet Suppress output\n"
2502 " -a --all Show all properties, including empty ones\n"
2503 " --value When showing properties, only print the value\n"
2504 " -l --full Do not ellipsize output\n"
2505 " --kill-who=WHO Who to send signal to\n"
2506 " -s --signal=SIGNAL Which signal to send\n"
2507 " --uid=USER Specify user ID to invoke shell as\n"
2508 " -E --setenv=VAR[=VALUE] Add an environment variable for shell\n"
2509 " --read-only Create read-only bind mount\n"
2510 " --mkdir Create directory before bind mounting, if missing\n"
2511 " -n --lines=INTEGER Number of journal entries to show\n"
2512 " --max-addresses=INTEGER Number of internet addresses to show at most\n"
2513 " -o --output=STRING Change journal output mode (short, short-precise,\n"
2514 " short-iso, short-iso-precise, short-full,\n"
2515 " short-monotonic, short-unix, verbose, export,\n"
2516 " json, json-pretty, json-sse, json-seq, cat,\n"
2517 " with-unit)\n"
2518 " --verify=MODE Verification mode for downloaded images (no,\n"
2519 " checksum, signature)\n"
2520 " --force Download image even if already exists\n"
2521 "\nSee the %s for details.\n",
2522 program_invocation_short_name,
2523 ansi_highlight(),
2524 ansi_normal(),
2525 ansi_highlight(),
2526 ansi_normal(),
2527 link);
2528
2529 return 0;
2530 }
2531
2532 static int parse_argv(int argc, char *argv[]) {
2533
2534 enum {
2535 ARG_VERSION = 0x100,
2536 ARG_NO_PAGER,
2537 ARG_NO_LEGEND,
2538 ARG_VALUE,
2539 ARG_KILL_WHO,
2540 ARG_READ_ONLY,
2541 ARG_MKDIR,
2542 ARG_NO_ASK_PASSWORD,
2543 ARG_VERIFY,
2544 ARG_FORCE,
2545 ARG_FORMAT,
2546 ARG_UID,
2547 ARG_MAX_ADDRESSES,
2548 };
2549
2550 static const struct option options[] = {
2551 { "help", no_argument, NULL, 'h' },
2552 { "version", no_argument, NULL, ARG_VERSION },
2553 { "property", required_argument, NULL, 'p' },
2554 { "all", no_argument, NULL, 'a' },
2555 { "value", no_argument, NULL, ARG_VALUE },
2556 { "full", no_argument, NULL, 'l' },
2557 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
2558 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
2559 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
2560 { "signal", required_argument, NULL, 's' },
2561 { "host", required_argument, NULL, 'H' },
2562 { "machine", required_argument, NULL, 'M' },
2563 { "read-only", no_argument, NULL, ARG_READ_ONLY },
2564 { "mkdir", no_argument, NULL, ARG_MKDIR },
2565 { "quiet", no_argument, NULL, 'q' },
2566 { "lines", required_argument, NULL, 'n' },
2567 { "output", required_argument, NULL, 'o' },
2568 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
2569 { "verify", required_argument, NULL, ARG_VERIFY },
2570 { "force", no_argument, NULL, ARG_FORCE },
2571 { "format", required_argument, NULL, ARG_FORMAT },
2572 { "uid", required_argument, NULL, ARG_UID },
2573 { "setenv", required_argument, NULL, 'E' },
2574 { "max-addresses", required_argument, NULL, ARG_MAX_ADDRESSES },
2575 {}
2576 };
2577
2578 bool reorder = false;
2579 int c, r, shell = -1;
2580
2581 assert(argc >= 0);
2582 assert(argv);
2583
2584 for (;;) {
2585 static const char option_string[] = "-hp:als:H:M:qn:o:E:";
2586
2587 c = getopt_long(argc, argv, option_string + reorder, options, NULL);
2588 if (c < 0)
2589 break;
2590
2591 switch (c) {
2592
2593 case 1: /* getopt_long() returns 1 if "-" was the first character of the option string, and a
2594 * non-option argument was discovered. */
2595
2596 assert(!reorder);
2597
2598 /* We generally are fine with the fact that getopt_long() reorders the command line, and looks
2599 * for switches after the main verb. However, for "shell" we really don't want that, since we
2600 * want that switches specified after the machine name are passed to the program to execute,
2601 * and not processed by us. To make this possible, we'll first invoke getopt_long() with
2602 * reordering disabled (i.e. with the "-" prefix in the option string), looking for the first
2603 * non-option parameter. If it's the verb "shell" we remember its position and continue
2604 * processing options. In this case, as soon as we hit the next non-option argument we found
2605 * the machine name, and stop further processing. If the first non-option argument is any other
2606 * verb than "shell" we switch to normal reordering mode and continue processing arguments
2607 * normally. */
2608
2609 if (shell >= 0) {
2610 /* If we already found the "shell" verb on the command line, and now found the next
2611 * non-option argument, then this is the machine name and we should stop processing
2612 * further arguments. */
2613 optind --; /* don't process this argument, go one step back */
2614 goto done;
2615 }
2616 if (streq(optarg, "shell"))
2617 /* Remember the position of the "shell" verb, and continue processing normally. */
2618 shell = optind - 1;
2619 else {
2620 int saved_optind;
2621
2622 /* OK, this is some other verb. In this case, turn on reordering again, and continue
2623 * processing normally. */
2624 reorder = true;
2625
2626 /* We changed the option string. getopt_long() only looks at it again if we invoke it
2627 * at least once with a reset option index. Hence, let's reset the option index here,
2628 * then invoke getopt_long() again (ignoring what it has to say, after all we most
2629 * likely already processed it), and the bump the option index so that we read the
2630 * intended argument again. */
2631 saved_optind = optind;
2632 optind = 0;
2633 (void) getopt_long(argc, argv, option_string + reorder, options, NULL);
2634 optind = saved_optind - 1; /* go one step back, process this argument again */
2635 }
2636
2637 break;
2638
2639 case 'h':
2640 return help(0, NULL, NULL);
2641
2642 case ARG_VERSION:
2643 return version();
2644
2645 case 'p':
2646 r = strv_extend(&arg_property, optarg);
2647 if (r < 0)
2648 return log_oom();
2649
2650 /* If the user asked for a particular
2651 * property, show it to them, even if it is
2652 * empty. */
2653 SET_FLAG(arg_print_flags, BUS_PRINT_PROPERTY_SHOW_EMPTY, true);
2654 break;
2655
2656 case 'a':
2657 SET_FLAG(arg_print_flags, BUS_PRINT_PROPERTY_SHOW_EMPTY, true);
2658 arg_all = true;
2659 break;
2660
2661 case ARG_VALUE:
2662 SET_FLAG(arg_print_flags, BUS_PRINT_PROPERTY_ONLY_VALUE, true);
2663 break;
2664
2665 case 'l':
2666 arg_full = true;
2667 break;
2668
2669 case 'n':
2670 if (safe_atou(optarg, &arg_lines) < 0)
2671 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2672 "Failed to parse lines '%s'", optarg);
2673 break;
2674
2675 case 'o':
2676 if (streq(optarg, "help")) {
2677 DUMP_STRING_TABLE(output_mode, OutputMode, _OUTPUT_MODE_MAX);
2678 return 0;
2679 }
2680
2681 r = output_mode_from_string(optarg);
2682 if (r < 0)
2683 return log_error_errno(r, "Unknown output '%s'.", optarg);
2684 arg_output = r;
2685
2686 if (OUTPUT_MODE_IS_JSON(arg_output))
2687 arg_legend = false;
2688 break;
2689
2690 case ARG_NO_PAGER:
2691 arg_pager_flags |= PAGER_DISABLE;
2692 break;
2693
2694 case ARG_NO_LEGEND:
2695 arg_legend = false;
2696 break;
2697
2698 case ARG_KILL_WHO:
2699 arg_kill_who = optarg;
2700 break;
2701
2702 case 's':
2703 r = parse_signal_argument(optarg, &arg_signal);
2704 if (r <= 0)
2705 return r;
2706 break;
2707
2708 case ARG_NO_ASK_PASSWORD:
2709 arg_ask_password = false;
2710 break;
2711
2712 case 'H':
2713 arg_transport = BUS_TRANSPORT_REMOTE;
2714 arg_host = optarg;
2715 break;
2716
2717 case 'M':
2718 arg_transport = BUS_TRANSPORT_MACHINE;
2719 arg_host = optarg;
2720 break;
2721
2722 case ARG_READ_ONLY:
2723 arg_read_only = true;
2724 break;
2725
2726 case ARG_MKDIR:
2727 arg_mkdir = true;
2728 break;
2729
2730 case 'q':
2731 arg_quiet = true;
2732 break;
2733
2734 case ARG_VERIFY:
2735 if (streq(optarg, "help")) {
2736 DUMP_STRING_TABLE(import_verify, ImportVerify, _IMPORT_VERIFY_MAX);
2737 return 0;
2738 }
2739
2740 r = import_verify_from_string(optarg);
2741 if (r < 0)
2742 return log_error_errno(r, "Failed to parse --verify= setting: %s", optarg);
2743 arg_verify = r;
2744 break;
2745
2746 case ARG_FORCE:
2747 arg_force = true;
2748 break;
2749
2750 case ARG_FORMAT:
2751 if (!STR_IN_SET(optarg, "uncompressed", "xz", "gzip", "bzip2"))
2752 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2753 "Unknown format: %s", optarg);
2754
2755 arg_format = optarg;
2756 break;
2757
2758 case ARG_UID:
2759 arg_uid = optarg;
2760 break;
2761
2762 case 'E':
2763 r = strv_env_replace_strdup_passthrough(&arg_setenv, optarg);
2764 if (r < 0)
2765 return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg);
2766 break;
2767
2768 case ARG_MAX_ADDRESSES:
2769 if (streq(optarg, "all"))
2770 arg_max_addresses = ALL_ADDRESSES;
2771 else if (safe_atoi(optarg, &arg_max_addresses) < 0)
2772 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2773 "Invalid number of addresses: %s", optarg);
2774 else if (arg_max_addresses <= 0)
2775 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2776 "Number of IPs cannot be negative or zero: %s", optarg);
2777 break;
2778
2779 case '?':
2780 return -EINVAL;
2781
2782 default:
2783 assert_not_reached();
2784 }
2785 }
2786
2787 done:
2788 if (shell >= 0) {
2789 char *t;
2790
2791 /* We found the "shell" verb while processing the argument list. Since we turned off reordering of the
2792 * argument list initially let's readjust it now, and move the "shell" verb to the back. */
2793
2794 optind -= 1; /* place the option index where the "shell" verb will be placed */
2795
2796 t = argv[shell];
2797 for (int i = shell; i < optind; i++)
2798 argv[i] = argv[i+1];
2799 argv[optind] = t;
2800 }
2801
2802 return 1;
2803 }
2804
2805 static int machinectl_main(int argc, char *argv[], sd_bus *bus) {
2806
2807 static const Verb verbs[] = {
2808 { "help", VERB_ANY, VERB_ANY, 0, help },
2809 { "list", VERB_ANY, 1, VERB_DEFAULT, list_machines },
2810 { "list-images", VERB_ANY, 1, 0, list_images },
2811 { "status", 2, VERB_ANY, 0, show_machine },
2812 { "image-status", VERB_ANY, VERB_ANY, 0, show_image },
2813 { "show", VERB_ANY, VERB_ANY, 0, show_machine },
2814 { "show-image", VERB_ANY, VERB_ANY, 0, show_image },
2815 { "terminate", 2, VERB_ANY, 0, terminate_machine },
2816 { "reboot", 2, VERB_ANY, 0, reboot_machine },
2817 { "poweroff", 2, VERB_ANY, 0, poweroff_machine },
2818 { "stop", 2, VERB_ANY, 0, poweroff_machine }, /* Convenience alias */
2819 { "kill", 2, VERB_ANY, 0, kill_machine },
2820 { "login", VERB_ANY, 2, 0, login_machine },
2821 { "shell", VERB_ANY, VERB_ANY, 0, shell_machine },
2822 { "bind", 3, 4, 0, bind_mount },
2823 { "copy-to", 3, 4, 0, copy_files },
2824 { "copy-from", 3, 4, 0, copy_files },
2825 { "remove", 2, VERB_ANY, 0, remove_image },
2826 { "rename", 3, 3, 0, rename_image },
2827 { "clone", 3, 3, 0, clone_image },
2828 { "read-only", 2, 3, 0, read_only_image },
2829 { "start", 2, VERB_ANY, 0, start_machine },
2830 { "enable", 2, VERB_ANY, 0, enable_machine },
2831 { "disable", 2, VERB_ANY, 0, enable_machine },
2832 { "import-tar", 2, 3, 0, import_tar },
2833 { "import-raw", 2, 3, 0, import_raw },
2834 { "import-fs", 2, 3, 0, import_fs },
2835 { "export-tar", 2, 3, 0, export_tar },
2836 { "export-raw", 2, 3, 0, export_raw },
2837 { "pull-tar", 2, 3, 0, pull_tar },
2838 { "pull-raw", 2, 3, 0, pull_raw },
2839 { "list-transfers", VERB_ANY, 1, 0, list_transfers },
2840 { "cancel-transfer", 2, VERB_ANY, 0, cancel_transfer },
2841 { "set-limit", 2, 3, 0, set_limit },
2842 { "clean", VERB_ANY, 1, 0, clean_images },
2843 {}
2844 };
2845
2846 return dispatch_verb(argc, argv, verbs, bus);
2847 }
2848
2849 static int run(int argc, char *argv[]) {
2850 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
2851 int r;
2852
2853 setlocale(LC_ALL, "");
2854 log_setup();
2855
2856 /* The journal merging logic potentially needs a lot of fds. */
2857 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
2858
2859 sigbus_install();
2860
2861 r = parse_argv(argc, argv);
2862 if (r <= 0)
2863 return r;
2864
2865 r = bus_connect_transport(arg_transport, arg_host, false, &bus);
2866 if (r < 0)
2867 return bus_log_connect_error(r, arg_transport);
2868
2869 (void) sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);
2870
2871 return machinectl_main(argc, argv, bus);
2872 }
2873
2874 DEFINE_MAIN_FUNCTION(run);