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