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