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