]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/machine/machinectl.c
47ccb352bf2549c6439e857c7bf24b797787aeb3
[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 return log_error_errno(r, "Could not get path to machine: %s", bus_error_message(&error, -r));
778
779 r = sd_bus_message_read(reply, "o", &path);
780 if (r < 0)
781 return bus_log_parse_error(r);
782
783 if (properties)
784 r = show_machine_properties(bus, path, &new_line);
785 else
786 r = show_machine_info(argv[0], bus, path, &new_line);
787 }
788
789 return r;
790 }
791
792 static int print_image_hostname(sd_bus *bus, const char *name) {
793 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
794 const char *hn;
795 int r;
796
797 r = sd_bus_call_method(
798 bus,
799 "org.freedesktop.machine1",
800 "/org/freedesktop/machine1",
801 "org.freedesktop.machine1.Manager",
802 "GetImageHostname",
803 NULL, &reply, "s", name);
804 if (r < 0)
805 return r;
806
807 r = sd_bus_message_read(reply, "s", &hn);
808 if (r < 0)
809 return r;
810
811 if (!isempty(hn))
812 printf("\tHostname: %s\n", hn);
813
814 return 0;
815 }
816
817 static int print_image_machine_id(sd_bus *bus, const char *name) {
818 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
819 sd_id128_t id = SD_ID128_NULL;
820 const void *p;
821 size_t size;
822 int r;
823
824 r = sd_bus_call_method(
825 bus,
826 "org.freedesktop.machine1",
827 "/org/freedesktop/machine1",
828 "org.freedesktop.machine1.Manager",
829 "GetImageMachineID",
830 NULL, &reply, "s", name);
831 if (r < 0)
832 return r;
833
834 r = sd_bus_message_read_array(reply, 'y', &p, &size);
835 if (r < 0)
836 return r;
837
838 if (size == sizeof(sd_id128_t))
839 memcpy(&id, p, size);
840
841 if (!sd_id128_is_null(id))
842 printf(" Machine ID: " SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(id));
843
844 return 0;
845 }
846
847 static int print_image_machine_info(sd_bus *bus, const char *name) {
848 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
849 int r;
850
851 r = sd_bus_call_method(
852 bus,
853 "org.freedesktop.machine1",
854 "/org/freedesktop/machine1",
855 "org.freedesktop.machine1.Manager",
856 "GetImageMachineInfo",
857 NULL, &reply, "s", name);
858 if (r < 0)
859 return r;
860
861 r = sd_bus_message_enter_container(reply, 'a', "{ss}");
862 if (r < 0)
863 return r;
864
865 for (;;) {
866 const char *p, *q;
867
868 r = sd_bus_message_read(reply, "{ss}", &p, &q);
869 if (r < 0)
870 return r;
871 if (r == 0)
872 break;
873
874 if (streq(p, "DEPLOYMENT"))
875 printf(" Deployment: %s\n", q);
876 }
877
878 r = sd_bus_message_exit_container(reply);
879 if (r < 0)
880 return r;
881
882 return 0;
883 }
884
885 typedef struct ImageStatusInfo {
886 const char *name;
887 const char *path;
888 const char *type;
889 bool read_only;
890 usec_t crtime;
891 usec_t mtime;
892 uint64_t usage;
893 uint64_t limit;
894 uint64_t usage_exclusive;
895 uint64_t limit_exclusive;
896 } ImageStatusInfo;
897
898 static void print_image_status_info(sd_bus *bus, ImageStatusInfo *i) {
899 char ts_relative[FORMAT_TIMESTAMP_RELATIVE_MAX];
900 char ts_absolute[FORMAT_TIMESTAMP_MAX];
901 char bs[FORMAT_BYTES_MAX];
902 char bs_exclusive[FORMAT_BYTES_MAX];
903 const char *s1, *s2, *s3, *s4;
904
905 assert(bus);
906 assert(i);
907
908 if (i->name) {
909 fputs(i->name, stdout);
910 putchar('\n');
911 }
912
913 if (i->type)
914 printf("\t Type: %s\n", i->type);
915
916 if (i->path)
917 printf("\t Path: %s\n", i->path);
918
919 (void) print_image_hostname(bus, i->name);
920 (void) print_image_machine_id(bus, i->name);
921 (void) print_image_machine_info(bus, i->name);
922
923 print_os_release(bus, "GetImageOSRelease", i->name, "\t OS: ");
924
925 printf("\t RO: %s%s%s\n",
926 i->read_only ? ansi_highlight_red() : "",
927 i->read_only ? "read-only" : "writable",
928 i->read_only ? ansi_normal() : "");
929
930 s1 = format_timestamp_relative(ts_relative, sizeof(ts_relative), i->crtime);
931 s2 = format_timestamp(ts_absolute, sizeof(ts_absolute), i->crtime);
932 if (s1 && s2)
933 printf("\t Created: %s; %s\n", s2, s1);
934 else if (s2)
935 printf("\t Created: %s\n", s2);
936
937 s1 = format_timestamp_relative(ts_relative, sizeof(ts_relative), i->mtime);
938 s2 = format_timestamp(ts_absolute, sizeof(ts_absolute), i->mtime);
939 if (s1 && s2)
940 printf("\tModified: %s; %s\n", s2, s1);
941 else if (s2)
942 printf("\tModified: %s\n", s2);
943
944 s3 = format_bytes(bs, sizeof(bs), i->usage);
945 s4 = i->usage_exclusive != i->usage ? format_bytes(bs_exclusive, sizeof(bs_exclusive), i->usage_exclusive) : NULL;
946 if (s3 && s4)
947 printf("\t Usage: %s (exclusive: %s)\n", s3, s4);
948 else if (s3)
949 printf("\t Usage: %s\n", s3);
950
951 s3 = format_bytes(bs, sizeof(bs), i->limit);
952 s4 = i->limit_exclusive != i->limit ? format_bytes(bs_exclusive, sizeof(bs_exclusive), i->limit_exclusive) : NULL;
953 if (s3 && s4)
954 printf("\t Limit: %s (exclusive: %s)\n", s3, s4);
955 else if (s3)
956 printf("\t Limit: %s\n", s3);
957 }
958
959 static int show_image_info(sd_bus *bus, const char *path, bool *new_line) {
960
961 static const struct bus_properties_map map[] = {
962 { "Name", "s", NULL, offsetof(ImageStatusInfo, name) },
963 { "Path", "s", NULL, offsetof(ImageStatusInfo, path) },
964 { "Type", "s", NULL, offsetof(ImageStatusInfo, type) },
965 { "ReadOnly", "b", NULL, offsetof(ImageStatusInfo, read_only) },
966 { "CreationTimestamp", "t", NULL, offsetof(ImageStatusInfo, crtime) },
967 { "ModificationTimestamp", "t", NULL, offsetof(ImageStatusInfo, mtime) },
968 { "Usage", "t", NULL, offsetof(ImageStatusInfo, usage) },
969 { "Limit", "t", NULL, offsetof(ImageStatusInfo, limit) },
970 { "UsageExclusive", "t", NULL, offsetof(ImageStatusInfo, usage_exclusive) },
971 { "LimitExclusive", "t", NULL, offsetof(ImageStatusInfo, limit_exclusive) },
972 {}
973 };
974
975 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
976 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
977 ImageStatusInfo info = {};
978 int r;
979
980 assert(bus);
981 assert(path);
982 assert(new_line);
983
984 r = bus_map_all_properties(bus,
985 "org.freedesktop.machine1",
986 path,
987 map,
988 BUS_MAP_BOOLEAN_AS_BOOL,
989 &error,
990 &m,
991 &info);
992 if (r < 0)
993 return log_error_errno(r, "Could not get properties: %s", bus_error_message(&error, r));
994
995 if (*new_line)
996 printf("\n");
997 *new_line = true;
998
999 print_image_status_info(bus, &info);
1000
1001 return r;
1002 }
1003
1004 typedef struct PoolStatusInfo {
1005 const char *path;
1006 uint64_t usage;
1007 uint64_t limit;
1008 } PoolStatusInfo;
1009
1010 static void print_pool_status_info(sd_bus *bus, PoolStatusInfo *i) {
1011 char bs[FORMAT_BYTES_MAX], *s;
1012
1013 if (i->path)
1014 printf("\t Path: %s\n", i->path);
1015
1016 s = format_bytes(bs, sizeof(bs), i->usage);
1017 if (s)
1018 printf("\t Usage: %s\n", s);
1019
1020 s = format_bytes(bs, sizeof(bs), i->limit);
1021 if (s)
1022 printf("\t Limit: %s\n", s);
1023 }
1024
1025 static int show_pool_info(sd_bus *bus) {
1026
1027 static const struct bus_properties_map map[] = {
1028 { "PoolPath", "s", NULL, offsetof(PoolStatusInfo, path) },
1029 { "PoolUsage", "t", NULL, offsetof(PoolStatusInfo, usage) },
1030 { "PoolLimit", "t", NULL, offsetof(PoolStatusInfo, limit) },
1031 {}
1032 };
1033
1034 PoolStatusInfo info = {
1035 .usage = (uint64_t) -1,
1036 .limit = (uint64_t) -1,
1037 };
1038
1039 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1040 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1041 int r;
1042
1043 assert(bus);
1044
1045 r = bus_map_all_properties(bus,
1046 "org.freedesktop.machine1",
1047 "/org/freedesktop/machine1",
1048 map,
1049 0,
1050 &error,
1051 &m,
1052 &info);
1053 if (r < 0)
1054 return log_error_errno(r, "Could not get properties: %s", bus_error_message(&error, r));
1055
1056 print_pool_status_info(bus, &info);
1057
1058 return 0;
1059 }
1060
1061 static int show_image_properties(sd_bus *bus, const char *path, bool *new_line) {
1062 int r;
1063
1064 assert(bus);
1065 assert(path);
1066 assert(new_line);
1067
1068 if (*new_line)
1069 printf("\n");
1070
1071 *new_line = true;
1072
1073 r = bus_print_all_properties(bus, "org.freedesktop.machine1", path, NULL, arg_property, arg_value, arg_all, NULL);
1074 if (r < 0)
1075 log_error_errno(r, "Could not get properties: %m");
1076
1077 return r;
1078 }
1079
1080 static int show_image(int argc, char *argv[], void *userdata) {
1081
1082 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1083 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1084 bool properties, new_line = false;
1085 sd_bus *bus = userdata;
1086 int r = 0, i;
1087
1088 assert(bus);
1089
1090 properties = !strstr(argv[0], "status");
1091
1092 (void) pager_open(arg_no_pager, false);
1093
1094 if (argc <= 1) {
1095
1096 /* If no argument is specified, inspect the manager
1097 * itself */
1098
1099 if (properties)
1100 r = show_image_properties(bus, "/org/freedesktop/machine1", &new_line);
1101 else
1102 r = show_pool_info(bus);
1103 if (r < 0)
1104 return r;
1105 }
1106
1107 for (i = 1; i < argc; i++) {
1108 const char *path = NULL;
1109
1110 r = sd_bus_call_method(
1111 bus,
1112 "org.freedesktop.machine1",
1113 "/org/freedesktop/machine1",
1114 "org.freedesktop.machine1.Manager",
1115 "GetImage",
1116 &error,
1117 &reply,
1118 "s", argv[i]);
1119 if (r < 0)
1120 return log_error_errno(r, "Could not get path to image: %s", bus_error_message(&error, -r));
1121
1122 r = sd_bus_message_read(reply, "o", &path);
1123 if (r < 0)
1124 return bus_log_parse_error(r);
1125
1126 if (properties)
1127 r = show_image_properties(bus, path, &new_line);
1128 else
1129 r = show_image_info(bus, path, &new_line);
1130 }
1131
1132 return r;
1133 }
1134
1135 static int kill_machine(int argc, char *argv[], void *userdata) {
1136 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1137 sd_bus *bus = userdata;
1138 int r, i;
1139
1140 assert(bus);
1141
1142 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1143
1144 if (!arg_kill_who)
1145 arg_kill_who = "all";
1146
1147 for (i = 1; i < argc; i++) {
1148 r = sd_bus_call_method(
1149 bus,
1150 "org.freedesktop.machine1",
1151 "/org/freedesktop/machine1",
1152 "org.freedesktop.machine1.Manager",
1153 "KillMachine",
1154 &error,
1155 NULL,
1156 "ssi", argv[i], arg_kill_who, arg_signal);
1157 if (r < 0)
1158 return log_error_errno(r, "Could not kill machine: %s", bus_error_message(&error, -r));
1159 }
1160
1161 return 0;
1162 }
1163
1164 static int reboot_machine(int argc, char *argv[], void *userdata) {
1165 arg_kill_who = "leader";
1166 arg_signal = SIGINT; /* sysvinit + systemd */
1167
1168 return kill_machine(argc, argv, userdata);
1169 }
1170
1171 static int poweroff_machine(int argc, char *argv[], void *userdata) {
1172 arg_kill_who = "leader";
1173 arg_signal = SIGRTMIN+4; /* only systemd */
1174
1175 return kill_machine(argc, argv, userdata);
1176 }
1177
1178 static int terminate_machine(int argc, char *argv[], void *userdata) {
1179 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1180 sd_bus *bus = userdata;
1181 int r, i;
1182
1183 assert(bus);
1184
1185 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1186
1187 for (i = 1; i < argc; i++) {
1188 r = sd_bus_call_method(
1189 bus,
1190 "org.freedesktop.machine1",
1191 "/org/freedesktop/machine1",
1192 "org.freedesktop.machine1.Manager",
1193 "TerminateMachine",
1194 &error,
1195 NULL,
1196 "s", argv[i]);
1197 if (r < 0)
1198 return log_error_errno(r, "Could not terminate machine: %s", bus_error_message(&error, -r));
1199 }
1200
1201 return 0;
1202 }
1203
1204 static int copy_files(int argc, char *argv[], void *userdata) {
1205 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1206 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1207 _cleanup_free_ char *abs_host_path = NULL;
1208 char *dest, *host_path, *container_path;
1209 sd_bus *bus = userdata;
1210 bool copy_from;
1211 int r;
1212
1213 assert(bus);
1214
1215 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1216
1217 copy_from = streq(argv[0], "copy-from");
1218 dest = argv[3] ?: argv[2];
1219 host_path = copy_from ? dest : argv[2];
1220 container_path = copy_from ? argv[2] : dest;
1221
1222 if (!path_is_absolute(host_path)) {
1223 r = path_make_absolute_cwd(host_path, &abs_host_path);
1224 if (r < 0)
1225 return log_error_errno(r, "Failed to make path absolute: %m");
1226
1227 host_path = abs_host_path;
1228 }
1229
1230 r = sd_bus_message_new_method_call(
1231 bus,
1232 &m,
1233 "org.freedesktop.machine1",
1234 "/org/freedesktop/machine1",
1235 "org.freedesktop.machine1.Manager",
1236 copy_from ? "CopyFromMachine" : "CopyToMachine");
1237 if (r < 0)
1238 return bus_log_create_error(r);
1239
1240 r = sd_bus_message_append(
1241 m,
1242 "sss",
1243 argv[1],
1244 copy_from ? container_path : host_path,
1245 copy_from ? host_path : container_path);
1246 if (r < 0)
1247 return bus_log_create_error(r);
1248
1249 /* This is a slow operation, hence turn off any method call timeouts */
1250 r = sd_bus_call(bus, m, USEC_INFINITY, &error, NULL);
1251 if (r < 0)
1252 return log_error_errno(r, "Failed to copy: %s", bus_error_message(&error, r));
1253
1254 return 0;
1255 }
1256
1257 static int bind_mount(int argc, char *argv[], void *userdata) {
1258 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1259 sd_bus *bus = userdata;
1260 int r;
1261
1262 assert(bus);
1263
1264 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1265
1266 r = sd_bus_call_method(
1267 bus,
1268 "org.freedesktop.machine1",
1269 "/org/freedesktop/machine1",
1270 "org.freedesktop.machine1.Manager",
1271 "BindMountMachine",
1272 &error,
1273 NULL,
1274 "sssbb",
1275 argv[1],
1276 argv[2],
1277 argv[3],
1278 arg_read_only,
1279 arg_mkdir);
1280 if (r < 0)
1281 return log_error_errno(r, "Failed to bind mount: %s", bus_error_message(&error, -r));
1282
1283 return 0;
1284 }
1285
1286 static int on_machine_removed(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1287 PTYForward ** forward = (PTYForward**) userdata;
1288 int r;
1289
1290 assert(m);
1291 assert(forward);
1292
1293 if (*forward) {
1294 /* If the forwarder is already initialized, tell it to
1295 * exit on the next vhangup(), so that we still flush
1296 * out what might be queued and exit then. */
1297
1298 r = pty_forward_set_ignore_vhangup(*forward, false);
1299 if (r >= 0)
1300 return 0;
1301
1302 log_error_errno(r, "Failed to set ignore_vhangup flag: %m");
1303 }
1304
1305 /* On error, or when the forwarder is not initialized yet, quit immediately */
1306 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), EXIT_FAILURE);
1307 return 0;
1308 }
1309
1310 static int process_forward(sd_event *event, PTYForward **forward, int master, PTYForwardFlags flags, const char *name) {
1311 char last_char = 0;
1312 bool machine_died;
1313 int ret = 0, r;
1314
1315 assert(event);
1316 assert(master >= 0);
1317 assert(name);
1318
1319 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGWINCH, SIGTERM, SIGINT, -1) >= 0);
1320
1321 if (!arg_quiet) {
1322 if (streq(name, ".host"))
1323 log_info("Connected to the local host. Press ^] three times within 1s to exit session.");
1324 else
1325 log_info("Connected to machine %s. Press ^] three times within 1s to exit session.", name);
1326 }
1327
1328 sd_event_add_signal(event, NULL, SIGINT, NULL, NULL);
1329 sd_event_add_signal(event, NULL, SIGTERM, NULL, NULL);
1330
1331 r = pty_forward_new(event, master, flags, forward);
1332 if (r < 0)
1333 return log_error_errno(r, "Failed to create PTY forwarder: %m");
1334
1335 r = sd_event_loop(event);
1336 if (r < 0)
1337 return log_error_errno(r, "Failed to run event loop: %m");
1338
1339 pty_forward_get_last_char(*forward, &last_char);
1340
1341 machine_died =
1342 (flags & PTY_FORWARD_IGNORE_VHANGUP) &&
1343 pty_forward_get_ignore_vhangup(*forward) == 0;
1344
1345 *forward = pty_forward_free(*forward);
1346
1347 if (last_char != '\n')
1348 fputc('\n', stdout);
1349
1350 if (!arg_quiet) {
1351 if (machine_died)
1352 log_info("Machine %s terminated.", name);
1353 else if (streq(name, ".host"))
1354 log_info("Connection to the local host terminated.");
1355 else
1356 log_info("Connection to machine %s terminated.", name);
1357 }
1358
1359 sd_event_get_exit_code(event, &ret);
1360 return ret;
1361 }
1362
1363 static int parse_machine_uid(const char *spec, const char **machine, char **uid) {
1364 /*
1365 * Whatever is specified in the spec takes priority over global arguments.
1366 */
1367 char *_uid = NULL;
1368 const char *_machine = NULL;
1369
1370 if (spec) {
1371 const char *at;
1372
1373 at = strchr(spec, '@');
1374 if (at) {
1375 if (at == spec)
1376 /* Do the same as ssh and refuse "@host". */
1377 return -EINVAL;
1378
1379 _machine = at + 1;
1380 _uid = strndup(spec, at - spec);
1381 if (!_uid)
1382 return -ENOMEM;
1383 } else
1384 _machine = spec;
1385 };
1386
1387 if (arg_uid && !_uid) {
1388 _uid = strdup(arg_uid);
1389 if (!_uid)
1390 return -ENOMEM;
1391 }
1392
1393 *uid = _uid;
1394 *machine = isempty(_machine) ? ".host" : _machine;
1395 return 0;
1396 }
1397
1398 static int login_machine(int argc, char *argv[], void *userdata) {
1399 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1400 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1401 _cleanup_(pty_forward_freep) PTYForward *forward = NULL;
1402 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1403 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1404 int master = -1, r;
1405 sd_bus *bus = userdata;
1406 const char *match, *machine;
1407
1408 assert(bus);
1409
1410 if (!strv_isempty(arg_setenv) || arg_uid) {
1411 log_error("--setenv= and --uid= are not supported for 'login'. Use 'shell' instead.");
1412 return -EINVAL;
1413 }
1414
1415 if (!IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_MACHINE)) {
1416 log_error("Login only supported on local machines.");
1417 return -EOPNOTSUPP;
1418 }
1419
1420 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1421
1422 r = sd_event_default(&event);
1423 if (r < 0)
1424 return log_error_errno(r, "Failed to get event loop: %m");
1425
1426 r = sd_bus_attach_event(bus, event, 0);
1427 if (r < 0)
1428 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1429
1430 machine = argc < 2 || isempty(argv[1]) ? ".host" : argv[1];
1431
1432 match = strjoina("type='signal',"
1433 "sender='org.freedesktop.machine1',"
1434 "path='/org/freedesktop/machine1',",
1435 "interface='org.freedesktop.machine1.Manager',"
1436 "member='MachineRemoved',"
1437 "arg0='", machine, "'");
1438
1439 r = sd_bus_add_match_async(bus, &slot, match, on_machine_removed, NULL, &forward);
1440 if (r < 0)
1441 return log_error_errno(r, "Failed to request machine removal match: %m");
1442
1443 r = sd_bus_call_method(
1444 bus,
1445 "org.freedesktop.machine1",
1446 "/org/freedesktop/machine1",
1447 "org.freedesktop.machine1.Manager",
1448 "OpenMachineLogin",
1449 &error,
1450 &reply,
1451 "s", machine);
1452 if (r < 0)
1453 return log_error_errno(r, "Failed to get login PTY: %s", bus_error_message(&error, -r));
1454
1455 r = sd_bus_message_read(reply, "hs", &master, NULL);
1456 if (r < 0)
1457 return bus_log_parse_error(r);
1458
1459 return process_forward(event, &forward, master, PTY_FORWARD_IGNORE_VHANGUP, machine);
1460 }
1461
1462 static int shell_machine(int argc, char *argv[], void *userdata) {
1463 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
1464 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1465 _cleanup_(pty_forward_freep) PTYForward *forward = NULL;
1466 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1467 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1468 int master = -1, r;
1469 sd_bus *bus = userdata;
1470 const char *match, *machine, *path;
1471 _cleanup_free_ char *uid = NULL;
1472
1473 assert(bus);
1474
1475 if (!IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_MACHINE)) {
1476 log_error("Shell only supported on local machines.");
1477 return -EOPNOTSUPP;
1478 }
1479
1480 /* Pass $TERM to shell session, if not explicitly specified. */
1481 if (!strv_find_prefix(arg_setenv, "TERM=")) {
1482 const char *t;
1483
1484 t = strv_find_prefix(environ, "TERM=");
1485 if (t) {
1486 if (strv_extend(&arg_setenv, t) < 0)
1487 return log_oom();
1488 }
1489 }
1490
1491 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1492
1493 r = sd_event_default(&event);
1494 if (r < 0)
1495 return log_error_errno(r, "Failed to get event loop: %m");
1496
1497 r = sd_bus_attach_event(bus, event, 0);
1498 if (r < 0)
1499 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1500
1501 r = parse_machine_uid(argc >= 2 ? argv[1] : NULL, &machine, &uid);
1502 if (r < 0)
1503 return log_error_errno(r, "Failed to parse machine specification: %m");
1504
1505 match = strjoina("type='signal',"
1506 "sender='org.freedesktop.machine1',"
1507 "path='/org/freedesktop/machine1',",
1508 "interface='org.freedesktop.machine1.Manager',"
1509 "member='MachineRemoved',"
1510 "arg0='", machine, "'");
1511
1512 r = sd_bus_add_match_async(bus, &slot, match, on_machine_removed, NULL, &forward);
1513 if (r < 0)
1514 return log_error_errno(r, "Failed to request machine removal match: %m");
1515
1516 r = sd_bus_message_new_method_call(
1517 bus,
1518 &m,
1519 "org.freedesktop.machine1",
1520 "/org/freedesktop/machine1",
1521 "org.freedesktop.machine1.Manager",
1522 "OpenMachineShell");
1523 if (r < 0)
1524 return bus_log_create_error(r);
1525
1526 path = argc < 3 || isempty(argv[2]) ? NULL : argv[2];
1527
1528 r = sd_bus_message_append(m, "sss", machine, uid, path);
1529 if (r < 0)
1530 return bus_log_create_error(r);
1531
1532 r = sd_bus_message_append_strv(m, strv_length(argv) <= 3 ? NULL : argv + 2);
1533 if (r < 0)
1534 return bus_log_create_error(r);
1535
1536 r = sd_bus_message_append_strv(m, arg_setenv);
1537 if (r < 0)
1538 return bus_log_create_error(r);
1539
1540 r = sd_bus_call(bus, m, 0, &error, &reply);
1541 if (r < 0)
1542 return log_error_errno(r, "Failed to get shell PTY: %s", bus_error_message(&error, -r));
1543
1544 r = sd_bus_message_read(reply, "hs", &master, NULL);
1545 if (r < 0)
1546 return bus_log_parse_error(r);
1547
1548 return process_forward(event, &forward, master, 0, machine);
1549 }
1550
1551 static int remove_image(int argc, char *argv[], void *userdata) {
1552 sd_bus *bus = userdata;
1553 int r, i;
1554
1555 assert(bus);
1556
1557 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1558
1559 for (i = 1; i < argc; i++) {
1560 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1561 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1562
1563 r = sd_bus_message_new_method_call(
1564 bus,
1565 &m,
1566 "org.freedesktop.machine1",
1567 "/org/freedesktop/machine1",
1568 "org.freedesktop.machine1.Manager",
1569 "RemoveImage");
1570 if (r < 0)
1571 return bus_log_create_error(r);
1572
1573 r = sd_bus_message_append(m, "s", argv[i]);
1574 if (r < 0)
1575 return bus_log_create_error(r);
1576
1577 /* This is a slow operation, hence turn off any method call timeouts */
1578 r = sd_bus_call(bus, m, USEC_INFINITY, &error, NULL);
1579 if (r < 0)
1580 return log_error_errno(r, "Could not remove image: %s", bus_error_message(&error, r));
1581 }
1582
1583 return 0;
1584 }
1585
1586 static int rename_image(int argc, char *argv[], void *userdata) {
1587 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1588 sd_bus *bus = userdata;
1589 int r;
1590
1591 assert(bus);
1592
1593 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1594
1595 r = sd_bus_call_method(
1596 bus,
1597 "org.freedesktop.machine1",
1598 "/org/freedesktop/machine1",
1599 "org.freedesktop.machine1.Manager",
1600 "RenameImage",
1601 &error,
1602 NULL,
1603 "ss", argv[1], argv[2]);
1604 if (r < 0)
1605 return log_error_errno(r, "Could not rename image: %s", bus_error_message(&error, -r));
1606
1607 return 0;
1608 }
1609
1610 static int clone_image(int argc, char *argv[], void *userdata) {
1611 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1612 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1613 sd_bus *bus = userdata;
1614 int r;
1615
1616 assert(bus);
1617
1618 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1619
1620 r = sd_bus_message_new_method_call(
1621 bus,
1622 &m,
1623 "org.freedesktop.machine1",
1624 "/org/freedesktop/machine1",
1625 "org.freedesktop.machine1.Manager",
1626 "CloneImage");
1627 if (r < 0)
1628 return bus_log_create_error(r);
1629
1630 r = sd_bus_message_append(m, "ssb", argv[1], argv[2], arg_read_only);
1631 if (r < 0)
1632 return bus_log_create_error(r);
1633
1634 /* This is a slow operation, hence turn off any method call timeouts */
1635 r = sd_bus_call(bus, m, USEC_INFINITY, &error, NULL);
1636 if (r < 0)
1637 return log_error_errno(r, "Could not clone image: %s", bus_error_message(&error, r));
1638
1639 return 0;
1640 }
1641
1642 static int read_only_image(int argc, char *argv[], void *userdata) {
1643 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1644 sd_bus *bus = userdata;
1645 int b = true, r;
1646
1647 assert(bus);
1648
1649 if (argc > 2) {
1650 b = parse_boolean(argv[2]);
1651 if (b < 0) {
1652 log_error("Failed to parse boolean argument: %s", argv[2]);
1653 return -EINVAL;
1654 }
1655 }
1656
1657 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1658
1659 r = sd_bus_call_method(
1660 bus,
1661 "org.freedesktop.machine1",
1662 "/org/freedesktop/machine1",
1663 "org.freedesktop.machine1.Manager",
1664 "MarkImageReadOnly",
1665 &error,
1666 NULL,
1667 "sb", argv[1], b);
1668 if (r < 0)
1669 return log_error_errno(r, "Could not mark image read-only: %s", bus_error_message(&error, -r));
1670
1671 return 0;
1672 }
1673
1674 static int image_exists(sd_bus *bus, const char *name) {
1675 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1676 int r;
1677
1678 assert(bus);
1679 assert(name);
1680
1681 r = sd_bus_call_method(
1682 bus,
1683 "org.freedesktop.machine1",
1684 "/org/freedesktop/machine1",
1685 "org.freedesktop.machine1.Manager",
1686 "GetImage",
1687 &error,
1688 NULL,
1689 "s", name);
1690 if (r < 0) {
1691 if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_IMAGE))
1692 return 0;
1693
1694 return log_error_errno(r, "Failed to check whether image %s exists: %s", name, bus_error_message(&error, -r));
1695 }
1696
1697 return 1;
1698 }
1699
1700 static int make_service_name(const char *name, char **ret) {
1701 int r;
1702
1703 assert(name);
1704 assert(ret);
1705
1706 if (!machine_name_is_valid(name)) {
1707 log_error("Invalid machine name %s.", name);
1708 return -EINVAL;
1709 }
1710
1711 r = unit_name_build("systemd-nspawn", name, ".service", ret);
1712 if (r < 0)
1713 return log_error_errno(r, "Failed to build unit name: %m");
1714
1715 return 0;
1716 }
1717
1718 static int start_machine(int argc, char *argv[], void *userdata) {
1719 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1720 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
1721 sd_bus *bus = userdata;
1722 int r, i;
1723
1724 assert(bus);
1725
1726 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1727
1728 r = bus_wait_for_jobs_new(bus, &w);
1729 if (r < 0)
1730 return log_oom();
1731
1732 for (i = 1; i < argc; i++) {
1733 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1734 _cleanup_free_ char *unit = NULL;
1735 const char *object;
1736
1737 r = make_service_name(argv[i], &unit);
1738 if (r < 0)
1739 return r;
1740
1741 r = image_exists(bus, argv[i]);
1742 if (r < 0)
1743 return r;
1744 if (r == 0) {
1745 log_error("Machine image '%s' does not exist.", argv[1]);
1746 return -ENXIO;
1747 }
1748
1749 r = sd_bus_call_method(
1750 bus,
1751 "org.freedesktop.systemd1",
1752 "/org/freedesktop/systemd1",
1753 "org.freedesktop.systemd1.Manager",
1754 "StartUnit",
1755 &error,
1756 &reply,
1757 "ss", unit, "fail");
1758 if (r < 0)
1759 return log_error_errno(r, "Failed to start unit: %s", bus_error_message(&error, -r));
1760
1761 r = sd_bus_message_read(reply, "o", &object);
1762 if (r < 0)
1763 return bus_log_parse_error(r);
1764
1765 r = bus_wait_for_jobs_add(w, object);
1766 if (r < 0)
1767 return log_oom();
1768 }
1769
1770 r = bus_wait_for_jobs(w, arg_quiet, NULL);
1771 if (r < 0)
1772 return r;
1773
1774 return 0;
1775 }
1776
1777 static int enable_machine(int argc, char *argv[], void *userdata) {
1778 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
1779 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1780 UnitFileChange *changes = NULL;
1781 size_t n_changes = 0;
1782 const char *method = NULL;
1783 sd_bus *bus = userdata;
1784 int r, i;
1785
1786 assert(bus);
1787
1788 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1789
1790 method = streq(argv[0], "enable") ? "EnableUnitFiles" : "DisableUnitFiles";
1791
1792 r = sd_bus_message_new_method_call(
1793 bus,
1794 &m,
1795 "org.freedesktop.systemd1",
1796 "/org/freedesktop/systemd1",
1797 "org.freedesktop.systemd1.Manager",
1798 method);
1799 if (r < 0)
1800 return bus_log_create_error(r);
1801
1802 r = sd_bus_message_open_container(m, 'a', "s");
1803 if (r < 0)
1804 return bus_log_create_error(r);
1805
1806 for (i = 1; i < argc; i++) {
1807 _cleanup_free_ char *unit = NULL;
1808
1809 r = make_service_name(argv[i], &unit);
1810 if (r < 0)
1811 return r;
1812
1813 r = image_exists(bus, argv[i]);
1814 if (r < 0)
1815 return r;
1816 if (r == 0) {
1817 log_error("Machine image '%s' does not exist.", argv[1]);
1818 return -ENXIO;
1819 }
1820
1821 r = sd_bus_message_append(m, "s", unit);
1822 if (r < 0)
1823 return bus_log_create_error(r);
1824 }
1825
1826 r = sd_bus_message_close_container(m);
1827 if (r < 0)
1828 return bus_log_create_error(r);
1829
1830 if (streq(argv[0], "enable"))
1831 r = sd_bus_message_append(m, "bb", false, false);
1832 else
1833 r = sd_bus_message_append(m, "b", false);
1834 if (r < 0)
1835 return bus_log_create_error(r);
1836
1837 r = sd_bus_call(bus, m, 0, &error, &reply);
1838 if (r < 0)
1839 return log_error_errno(r, "Failed to enable or disable unit: %s", bus_error_message(&error, -r));
1840
1841 if (streq(argv[0], "enable")) {
1842 r = sd_bus_message_read(reply, "b", NULL);
1843 if (r < 0)
1844 return bus_log_parse_error(r);
1845 }
1846
1847 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
1848 if (r < 0)
1849 goto finish;
1850
1851 r = sd_bus_call_method(
1852 bus,
1853 "org.freedesktop.systemd1",
1854 "/org/freedesktop/systemd1",
1855 "org.freedesktop.systemd1.Manager",
1856 "Reload",
1857 &error,
1858 NULL,
1859 NULL);
1860 if (r < 0) {
1861 log_error("Failed to reload daemon: %s", bus_error_message(&error, -r));
1862 goto finish;
1863 }
1864
1865 r = 0;
1866
1867 finish:
1868 unit_file_changes_free(changes, n_changes);
1869
1870 return r;
1871 }
1872
1873 static int match_log_message(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1874 const char **our_path = userdata, *line;
1875 unsigned priority;
1876 int r;
1877
1878 assert(m);
1879 assert(our_path);
1880
1881 r = sd_bus_message_read(m, "us", &priority, &line);
1882 if (r < 0) {
1883 bus_log_parse_error(r);
1884 return 0;
1885 }
1886
1887 if (!streq_ptr(*our_path, sd_bus_message_get_path(m)))
1888 return 0;
1889
1890 if (arg_quiet && LOG_PRI(priority) >= LOG_INFO)
1891 return 0;
1892
1893 log_full(priority, "%s", line);
1894 return 0;
1895 }
1896
1897 static int match_transfer_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1898 const char **our_path = userdata, *path, *result;
1899 uint32_t id;
1900 int r;
1901
1902 assert(m);
1903 assert(our_path);
1904
1905 r = sd_bus_message_read(m, "uos", &id, &path, &result);
1906 if (r < 0) {
1907 bus_log_parse_error(r);
1908 return 0;
1909 }
1910
1911 if (!streq_ptr(*our_path, path))
1912 return 0;
1913
1914 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), !streq_ptr(result, "done"));
1915 return 0;
1916 }
1917
1918 static int transfer_signal_handler(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1919 assert(s);
1920 assert(si);
1921
1922 if (!arg_quiet)
1923 log_info("Continuing download in the background. Use \"machinectl cancel-transfer %" PRIu32 "\" to abort transfer.", PTR_TO_UINT32(userdata));
1924
1925 sd_event_exit(sd_event_source_get_event(s), EINTR);
1926 return 0;
1927 }
1928
1929 static int transfer_image_common(sd_bus *bus, sd_bus_message *m) {
1930 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot_job_removed = NULL, *slot_log_message = NULL;
1931 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1932 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1933 _cleanup_(sd_event_unrefp) sd_event* event = NULL;
1934 const char *path = NULL;
1935 uint32_t id;
1936 int r;
1937
1938 assert(bus);
1939 assert(m);
1940
1941 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1942
1943 r = sd_event_default(&event);
1944 if (r < 0)
1945 return log_error_errno(r, "Failed to get event loop: %m");
1946
1947 r = sd_bus_attach_event(bus, event, 0);
1948 if (r < 0)
1949 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1950
1951 r = sd_bus_match_signal_async(
1952 bus,
1953 &slot_job_removed,
1954 "org.freedesktop.import1",
1955 "/org/freedesktop/import1",
1956 "org.freedesktop.import1.Manager",
1957 "TransferRemoved",
1958 match_transfer_removed, NULL, &path);
1959 if (r < 0)
1960 return log_error_errno(r, "Failed to request match: %m");
1961
1962 r = sd_bus_match_signal_async(
1963 bus,
1964 &slot_log_message,
1965 "org.freedesktop.import1",
1966 NULL,
1967 "org.freedesktop.import1.Transfer",
1968 "LogMessage",
1969 match_log_message, NULL, &path);
1970 if (r < 0)
1971 return log_error_errno(r, "Failed to request match: %m");
1972
1973 r = sd_bus_call(bus, m, 0, &error, &reply);
1974 if (r < 0)
1975 return log_error_errno(r, "Failed to transfer image: %s", bus_error_message(&error, -r));
1976
1977 r = sd_bus_message_read(reply, "uo", &id, &path);
1978 if (r < 0)
1979 return bus_log_parse_error(r);
1980
1981 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0);
1982
1983 if (!arg_quiet)
1984 log_info("Enqueued transfer job %u. Press C-c to continue download in background.", id);
1985
1986 sd_event_add_signal(event, NULL, SIGINT, transfer_signal_handler, UINT32_TO_PTR(id));
1987 sd_event_add_signal(event, NULL, SIGTERM, transfer_signal_handler, UINT32_TO_PTR(id));
1988
1989 r = sd_event_loop(event);
1990 if (r < 0)
1991 return log_error_errno(r, "Failed to run event loop: %m");
1992
1993 return -r;
1994 }
1995
1996 static int import_tar(int argc, char *argv[], void *userdata) {
1997 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1998 _cleanup_free_ char *ll = NULL;
1999 _cleanup_close_ int fd = -1;
2000 const char *local = NULL, *path = NULL;
2001 sd_bus *bus = userdata;
2002 int r;
2003
2004 assert(bus);
2005
2006 if (argc >= 2)
2007 path = argv[1];
2008 if (isempty(path) || streq(path, "-"))
2009 path = NULL;
2010
2011 if (argc >= 3)
2012 local = argv[2];
2013 else if (path)
2014 local = basename(path);
2015 if (isempty(local) || streq(local, "-"))
2016 local = NULL;
2017
2018 if (!local) {
2019 log_error("Need either path or local name.");
2020 return -EINVAL;
2021 }
2022
2023 r = tar_strip_suffixes(local, &ll);
2024 if (r < 0)
2025 return log_oom();
2026
2027 local = ll;
2028
2029 if (!machine_name_is_valid(local)) {
2030 log_error("Local name %s is not a suitable machine name.", local);
2031 return -EINVAL;
2032 }
2033
2034 if (path) {
2035 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
2036 if (fd < 0)
2037 return log_error_errno(errno, "Failed to open %s: %m", path);
2038 }
2039
2040 r = sd_bus_message_new_method_call(
2041 bus,
2042 &m,
2043 "org.freedesktop.import1",
2044 "/org/freedesktop/import1",
2045 "org.freedesktop.import1.Manager",
2046 "ImportTar");
2047 if (r < 0)
2048 return bus_log_create_error(r);
2049
2050 r = sd_bus_message_append(
2051 m,
2052 "hsbb",
2053 fd >= 0 ? fd : STDIN_FILENO,
2054 local,
2055 arg_force,
2056 arg_read_only);
2057 if (r < 0)
2058 return bus_log_create_error(r);
2059
2060 return transfer_image_common(bus, m);
2061 }
2062
2063 static int import_raw(int argc, char *argv[], void *userdata) {
2064 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2065 _cleanup_free_ char *ll = NULL;
2066 _cleanup_close_ int fd = -1;
2067 const char *local = NULL, *path = NULL;
2068 sd_bus *bus = userdata;
2069 int r;
2070
2071 assert(bus);
2072
2073 if (argc >= 2)
2074 path = argv[1];
2075 if (isempty(path) || streq(path, "-"))
2076 path = NULL;
2077
2078 if (argc >= 3)
2079 local = argv[2];
2080 else if (path)
2081 local = basename(path);
2082 if (isempty(local) || streq(local, "-"))
2083 local = NULL;
2084
2085 if (!local) {
2086 log_error("Need either path or local name.");
2087 return -EINVAL;
2088 }
2089
2090 r = raw_strip_suffixes(local, &ll);
2091 if (r < 0)
2092 return log_oom();
2093
2094 local = ll;
2095
2096 if (!machine_name_is_valid(local)) {
2097 log_error("Local name %s is not a suitable machine name.", local);
2098 return -EINVAL;
2099 }
2100
2101 if (path) {
2102 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
2103 if (fd < 0)
2104 return log_error_errno(errno, "Failed to open %s: %m", path);
2105 }
2106
2107 r = sd_bus_message_new_method_call(
2108 bus,
2109 &m,
2110 "org.freedesktop.import1",
2111 "/org/freedesktop/import1",
2112 "org.freedesktop.import1.Manager",
2113 "ImportRaw");
2114 if (r < 0)
2115 return bus_log_create_error(r);
2116
2117 r = sd_bus_message_append(
2118 m,
2119 "hsbb",
2120 fd >= 0 ? fd : STDIN_FILENO,
2121 local,
2122 arg_force,
2123 arg_read_only);
2124 if (r < 0)
2125 return bus_log_create_error(r);
2126
2127 return transfer_image_common(bus, m);
2128 }
2129
2130 static void determine_compression_from_filename(const char *p) {
2131 if (arg_format)
2132 return;
2133
2134 if (!p)
2135 return;
2136
2137 if (endswith(p, ".xz"))
2138 arg_format = "xz";
2139 else if (endswith(p, ".gz"))
2140 arg_format = "gzip";
2141 else if (endswith(p, ".bz2"))
2142 arg_format = "bzip2";
2143 }
2144
2145 static int export_tar(int argc, char *argv[], void *userdata) {
2146 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2147 _cleanup_close_ int fd = -1;
2148 const char *local = NULL, *path = NULL;
2149 sd_bus *bus = userdata;
2150 int r;
2151
2152 assert(bus);
2153
2154 local = argv[1];
2155 if (!machine_name_is_valid(local)) {
2156 log_error("Machine name %s is not valid.", local);
2157 return -EINVAL;
2158 }
2159
2160 if (argc >= 3)
2161 path = argv[2];
2162 if (isempty(path) || streq(path, "-"))
2163 path = NULL;
2164
2165 if (path) {
2166 determine_compression_from_filename(path);
2167
2168 fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC|O_NOCTTY, 0666);
2169 if (fd < 0)
2170 return log_error_errno(errno, "Failed to open %s: %m", path);
2171 }
2172
2173 r = sd_bus_message_new_method_call(
2174 bus,
2175 &m,
2176 "org.freedesktop.import1",
2177 "/org/freedesktop/import1",
2178 "org.freedesktop.import1.Manager",
2179 "ExportTar");
2180 if (r < 0)
2181 return bus_log_create_error(r);
2182
2183 r = sd_bus_message_append(
2184 m,
2185 "shs",
2186 local,
2187 fd >= 0 ? fd : STDOUT_FILENO,
2188 arg_format);
2189 if (r < 0)
2190 return bus_log_create_error(r);
2191
2192 return transfer_image_common(bus, m);
2193 }
2194
2195 static int export_raw(int argc, char *argv[], void *userdata) {
2196 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2197 _cleanup_close_ int fd = -1;
2198 const char *local = NULL, *path = NULL;
2199 sd_bus *bus = userdata;
2200 int r;
2201
2202 assert(bus);
2203
2204 local = argv[1];
2205 if (!machine_name_is_valid(local)) {
2206 log_error("Machine name %s is not valid.", local);
2207 return -EINVAL;
2208 }
2209
2210 if (argc >= 3)
2211 path = argv[2];
2212 if (isempty(path) || streq(path, "-"))
2213 path = NULL;
2214
2215 if (path) {
2216 determine_compression_from_filename(path);
2217
2218 fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC|O_NOCTTY, 0666);
2219 if (fd < 0)
2220 return log_error_errno(errno, "Failed to open %s: %m", path);
2221 }
2222
2223 r = sd_bus_message_new_method_call(
2224 bus,
2225 &m,
2226 "org.freedesktop.import1",
2227 "/org/freedesktop/import1",
2228 "org.freedesktop.import1.Manager",
2229 "ExportRaw");
2230 if (r < 0)
2231 return bus_log_create_error(r);
2232
2233 r = sd_bus_message_append(
2234 m,
2235 "shs",
2236 local,
2237 fd >= 0 ? fd : STDOUT_FILENO,
2238 arg_format);
2239 if (r < 0)
2240 return bus_log_create_error(r);
2241
2242 return transfer_image_common(bus, m);
2243 }
2244
2245 static int pull_tar(int argc, char *argv[], void *userdata) {
2246 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2247 _cleanup_free_ char *l = NULL, *ll = NULL;
2248 const char *local, *remote;
2249 sd_bus *bus = userdata;
2250 int r;
2251
2252 assert(bus);
2253
2254 remote = argv[1];
2255 if (!http_url_is_valid(remote)) {
2256 log_error("URL '%s' is not valid.", remote);
2257 return -EINVAL;
2258 }
2259
2260 if (argc >= 3)
2261 local = argv[2];
2262 else {
2263 r = import_url_last_component(remote, &l);
2264 if (r < 0)
2265 return log_error_errno(r, "Failed to get final component of URL: %m");
2266
2267 local = l;
2268 }
2269
2270 if (isempty(local) || streq(local, "-"))
2271 local = NULL;
2272
2273 if (local) {
2274 r = tar_strip_suffixes(local, &ll);
2275 if (r < 0)
2276 return log_oom();
2277
2278 local = ll;
2279
2280 if (!machine_name_is_valid(local)) {
2281 log_error("Local name %s is not a suitable machine name.", local);
2282 return -EINVAL;
2283 }
2284 }
2285
2286 r = sd_bus_message_new_method_call(
2287 bus,
2288 &m,
2289 "org.freedesktop.import1",
2290 "/org/freedesktop/import1",
2291 "org.freedesktop.import1.Manager",
2292 "PullTar");
2293 if (r < 0)
2294 return bus_log_create_error(r);
2295
2296 r = sd_bus_message_append(
2297 m,
2298 "sssb",
2299 remote,
2300 local,
2301 import_verify_to_string(arg_verify),
2302 arg_force);
2303 if (r < 0)
2304 return bus_log_create_error(r);
2305
2306 return transfer_image_common(bus, m);
2307 }
2308
2309 static int pull_raw(int argc, char *argv[], void *userdata) {
2310 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2311 _cleanup_free_ char *l = NULL, *ll = NULL;
2312 const char *local, *remote;
2313 sd_bus *bus = userdata;
2314 int r;
2315
2316 assert(bus);
2317
2318 remote = argv[1];
2319 if (!http_url_is_valid(remote)) {
2320 log_error("URL '%s' is not valid.", remote);
2321 return -EINVAL;
2322 }
2323
2324 if (argc >= 3)
2325 local = argv[2];
2326 else {
2327 r = import_url_last_component(remote, &l);
2328 if (r < 0)
2329 return log_error_errno(r, "Failed to get final component of URL: %m");
2330
2331 local = l;
2332 }
2333
2334 if (isempty(local) || streq(local, "-"))
2335 local = NULL;
2336
2337 if (local) {
2338 r = raw_strip_suffixes(local, &ll);
2339 if (r < 0)
2340 return log_oom();
2341
2342 local = ll;
2343
2344 if (!machine_name_is_valid(local)) {
2345 log_error("Local name %s is not a suitable machine name.", local);
2346 return -EINVAL;
2347 }
2348 }
2349
2350 r = sd_bus_message_new_method_call(
2351 bus,
2352 &m,
2353 "org.freedesktop.import1",
2354 "/org/freedesktop/import1",
2355 "org.freedesktop.import1.Manager",
2356 "PullRaw");
2357 if (r < 0)
2358 return bus_log_create_error(r);
2359
2360 r = sd_bus_message_append(
2361 m,
2362 "sssb",
2363 remote,
2364 local,
2365 import_verify_to_string(arg_verify),
2366 arg_force);
2367 if (r < 0)
2368 return bus_log_create_error(r);
2369
2370 return transfer_image_common(bus, m);
2371 }
2372
2373 typedef struct TransferInfo {
2374 uint32_t id;
2375 const char *type;
2376 const char *remote;
2377 const char *local;
2378 double progress;
2379 } TransferInfo;
2380
2381 static int compare_transfer_info(const TransferInfo *a, const TransferInfo *b) {
2382 return strcmp(a->local, b->local);
2383 }
2384
2385 static int list_transfers(int argc, char *argv[], void *userdata) {
2386 size_t max_type = STRLEN("TYPE"), max_local = STRLEN("LOCAL"), max_remote = STRLEN("REMOTE");
2387 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2388 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2389 _cleanup_free_ TransferInfo *transfers = NULL;
2390 size_t n_transfers = 0, n_allocated = 0, j;
2391 const char *type, *remote, *local;
2392 sd_bus *bus = userdata;
2393 uint32_t id, max_id = 0;
2394 double progress;
2395 int r;
2396
2397 (void) pager_open(arg_no_pager, false);
2398
2399 r = sd_bus_call_method(bus,
2400 "org.freedesktop.import1",
2401 "/org/freedesktop/import1",
2402 "org.freedesktop.import1.Manager",
2403 "ListTransfers",
2404 &error,
2405 &reply,
2406 NULL);
2407 if (r < 0)
2408 return log_error_errno(r, "Could not get transfers: %s", bus_error_message(&error, -r));
2409
2410 r = sd_bus_message_enter_container(reply, 'a', "(usssdo)");
2411 if (r < 0)
2412 return bus_log_parse_error(r);
2413
2414 while ((r = sd_bus_message_read(reply, "(usssdo)", &id, &type, &remote, &local, &progress, NULL)) > 0) {
2415 size_t l;
2416
2417 if (!GREEDY_REALLOC(transfers, n_allocated, n_transfers + 1))
2418 return log_oom();
2419
2420 transfers[n_transfers].id = id;
2421 transfers[n_transfers].type = type;
2422 transfers[n_transfers].remote = remote;
2423 transfers[n_transfers].local = local;
2424 transfers[n_transfers].progress = progress;
2425
2426 l = strlen(type);
2427 if (l > max_type)
2428 max_type = l;
2429
2430 l = strlen(remote);
2431 if (l > max_remote)
2432 max_remote = l;
2433
2434 l = strlen(local);
2435 if (l > max_local)
2436 max_local = l;
2437
2438 if (id > max_id)
2439 max_id = id;
2440
2441 n_transfers++;
2442 }
2443 if (r < 0)
2444 return bus_log_parse_error(r);
2445
2446 r = sd_bus_message_exit_container(reply);
2447 if (r < 0)
2448 return bus_log_parse_error(r);
2449
2450 typesafe_qsort(transfers, n_transfers, compare_transfer_info);
2451
2452 if (arg_legend && n_transfers > 0)
2453 printf("%-*s %-*s %-*s %-*s %-*s\n",
2454 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id)), "ID",
2455 (int) 7, "PERCENT",
2456 (int) max_type, "TYPE",
2457 (int) max_local, "LOCAL",
2458 (int) max_remote, "REMOTE");
2459
2460 for (j = 0; j < n_transfers; j++)
2461 printf("%*" PRIu32 " %*u%% %-*s %-*s %-*s\n",
2462 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id)), transfers[j].id,
2463 (int) 6, (unsigned) (transfers[j].progress * 100),
2464 (int) max_type, transfers[j].type,
2465 (int) max_local, transfers[j].local,
2466 (int) max_remote, transfers[j].remote);
2467
2468 if (arg_legend) {
2469 if (n_transfers > 0)
2470 printf("\n%zu transfers listed.\n", n_transfers);
2471 else
2472 printf("No transfers.\n");
2473 }
2474
2475 return 0;
2476 }
2477
2478 static int cancel_transfer(int argc, char *argv[], void *userdata) {
2479 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2480 sd_bus *bus = userdata;
2481 int r, i;
2482
2483 assert(bus);
2484
2485 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2486
2487 for (i = 1; i < argc; i++) {
2488 uint32_t id;
2489
2490 r = safe_atou32(argv[i], &id);
2491 if (r < 0)
2492 return log_error_errno(r, "Failed to parse transfer id: %s", argv[i]);
2493
2494 r = sd_bus_call_method(
2495 bus,
2496 "org.freedesktop.import1",
2497 "/org/freedesktop/import1",
2498 "org.freedesktop.import1.Manager",
2499 "CancelTransfer",
2500 &error,
2501 NULL,
2502 "u", id);
2503 if (r < 0)
2504 return log_error_errno(r, "Could not cancel transfer: %s", bus_error_message(&error, -r));
2505 }
2506
2507 return 0;
2508 }
2509
2510 static int set_limit(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 uint64_t limit;
2514 int r;
2515
2516 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2517
2518 if (STR_IN_SET(argv[argc-1], "-", "none", "infinity"))
2519 limit = (uint64_t) -1;
2520 else {
2521 r = parse_size(argv[argc-1], 1024, &limit);
2522 if (r < 0)
2523 return log_error_errno(r, "Failed to parse size: %s", argv[argc-1]);
2524 }
2525
2526 if (argc > 2)
2527 /* With two arguments changes the quota limit of the
2528 * specified image */
2529 r = sd_bus_call_method(
2530 bus,
2531 "org.freedesktop.machine1",
2532 "/org/freedesktop/machine1",
2533 "org.freedesktop.machine1.Manager",
2534 "SetImageLimit",
2535 &error,
2536 NULL,
2537 "st", argv[1], limit);
2538 else
2539 /* With one argument changes the pool quota limit */
2540 r = sd_bus_call_method(
2541 bus,
2542 "org.freedesktop.machine1",
2543 "/org/freedesktop/machine1",
2544 "org.freedesktop.machine1.Manager",
2545 "SetPoolLimit",
2546 &error,
2547 NULL,
2548 "t", limit);
2549
2550 if (r < 0)
2551 return log_error_errno(r, "Could not set limit: %s", bus_error_message(&error, r));
2552
2553 return 0;
2554 }
2555
2556 static int clean_images(int argc, char *argv[], void *userdata) {
2557 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
2558 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2559 uint64_t usage, total = 0;
2560 char fb[FORMAT_BYTES_MAX];
2561 sd_bus *bus = userdata;
2562 const char *name;
2563 unsigned c = 0;
2564 int r;
2565
2566 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2567
2568 r = sd_bus_message_new_method_call(
2569 bus,
2570 &m,
2571 "org.freedesktop.machine1",
2572 "/org/freedesktop/machine1",
2573 "org.freedesktop.machine1.Manager",
2574 "CleanPool");
2575 if (r < 0)
2576 return bus_log_create_error(r);
2577
2578 r = sd_bus_message_append(m, "s", arg_all ? "all" : "hidden");
2579 if (r < 0)
2580 return bus_log_create_error(r);
2581
2582 /* This is a slow operation, hence permit a longer time for completion. */
2583 r = sd_bus_call(bus, m, USEC_INFINITY, &error, &reply);
2584 if (r < 0)
2585 return log_error_errno(r, "Could not clean pool: %s", bus_error_message(&error, r));
2586
2587 r = sd_bus_message_enter_container(reply, 'a', "(st)");
2588 if (r < 0)
2589 return bus_log_parse_error(r);
2590
2591 while ((r = sd_bus_message_read(reply, "(st)", &name, &usage)) > 0) {
2592 log_info("Removed image '%s'. Freed exclusive disk space: %s",
2593 name, format_bytes(fb, sizeof(fb), usage));
2594
2595 total += usage;
2596 c++;
2597 }
2598
2599 r = sd_bus_message_exit_container(reply);
2600 if (r < 0)
2601 return bus_log_parse_error(r);
2602
2603 log_info("Removed %u images in total. Total freed exclusive disk space %s.",
2604 c, format_bytes(fb, sizeof(fb), total));
2605
2606 return 0;
2607 }
2608
2609 static int help(int argc, char *argv[], void *userdata) {
2610 _cleanup_free_ char *link = NULL;
2611 int r;
2612
2613 (void) pager_open(arg_no_pager, false);
2614
2615 r = terminal_urlify_man("machinectl", "1", &link);
2616 if (r < 0)
2617 return log_oom();
2618
2619 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
2620 "Send control commands to or query the virtual machine and container\n"
2621 "registration manager.\n\n"
2622 " -h --help Show this help\n"
2623 " --version Show package version\n"
2624 " --no-pager Do not pipe output into a pager\n"
2625 " --no-legend Do not show the headers and footers\n"
2626 " --no-ask-password Do not ask for system passwords\n"
2627 " -H --host=[USER@]HOST Operate on remote host\n"
2628 " -M --machine=CONTAINER Operate on local container\n"
2629 " -p --property=NAME Show only properties by this name\n"
2630 " -q --quiet Suppress output\n"
2631 " -a --all Show all properties, including empty ones\n"
2632 " --value When showing properties, only print the value\n"
2633 " -l --full Do not ellipsize output\n"
2634 " --kill-who=WHO Who to send signal to\n"
2635 " -s --signal=SIGNAL Which signal to send\n"
2636 " --uid=USER Specify user ID to invoke shell as\n"
2637 " -E --setenv=VAR=VALUE Add an environment variable for shell\n"
2638 " --read-only Create read-only bind mount\n"
2639 " --mkdir Create directory before bind mounting, if missing\n"
2640 " -n --lines=INTEGER Number of journal entries to show\n"
2641 " --max-addresses=INTEGER Number of internet addresses to show at most\n"
2642 " -o --output=STRING Change journal output mode (short, short-precise,\n"
2643 " short-iso, short-iso-precise, short-full,\n"
2644 " short-monotonic, short-unix, verbose, export,\n"
2645 " json, json-pretty, json-sse, cat)\n"
2646 " --verify=MODE Verification mode for downloaded images (no,\n"
2647 " checksum, signature)\n"
2648 " --force Download image even if already exists\n\n"
2649 "Machine Commands:\n"
2650 " list List running VMs and containers\n"
2651 " status NAME... Show VM/container details\n"
2652 " show [NAME...] Show properties of one or more VMs/containers\n"
2653 " start NAME... Start container as a service\n"
2654 " login [NAME] Get a login prompt in a container or on the\n"
2655 " local host\n"
2656 " shell [[USER@]NAME [COMMAND...]]\n"
2657 " Invoke a shell (or other command) in a container\n"
2658 " or on the local host\n"
2659 " enable NAME... Enable automatic container start at boot\n"
2660 " disable NAME... Disable automatic container start at boot\n"
2661 " poweroff NAME... Power off one or more containers\n"
2662 " reboot NAME... Reboot one or more containers\n"
2663 " terminate NAME... Terminate one or more VMs/containers\n"
2664 " kill NAME... Send signal to processes of a VM/container\n"
2665 " copy-to NAME PATH [PATH] Copy files from the host to a container\n"
2666 " copy-from NAME PATH [PATH] Copy files from a container to the host\n"
2667 " bind NAME PATH [PATH] Bind mount a path from the host into a container\n\n"
2668 "Image Commands:\n"
2669 " list-images Show available container and VM images\n"
2670 " image-status [NAME...] Show image details\n"
2671 " show-image [NAME...] Show properties of image\n"
2672 " clone NAME NAME Clone an image\n"
2673 " rename NAME NAME Rename an image\n"
2674 " read-only NAME [BOOL] Mark or unmark image read-only\n"
2675 " remove NAME... Remove an image\n"
2676 " set-limit [NAME] BYTES Set image or pool size limit (disk quota)\n"
2677 " clean Remove hidden (or all) images\n\n"
2678 "Image Transfer Commands:\n"
2679 " pull-tar URL [NAME] Download a TAR container image\n"
2680 " pull-raw URL [NAME] Download a RAW container or VM image\n"
2681 " import-tar FILE [NAME] Import a local TAR container image\n"
2682 " import-raw FILE [NAME] Import a local RAW container or VM image\n"
2683 " export-tar NAME [FILE] Export a TAR container image locally\n"
2684 " export-raw NAME [FILE] Export a RAW container or VM image locally\n"
2685 " list-transfers Show list of downloads in progress\n"
2686 " cancel-transfer Cancel a download\n"
2687 "\nSee the %s for details.\n"
2688 , program_invocation_short_name
2689 , link
2690 );
2691
2692 return 0;
2693 }
2694
2695 static int parse_argv(int argc, char *argv[]) {
2696
2697 enum {
2698 ARG_VERSION = 0x100,
2699 ARG_NO_PAGER,
2700 ARG_NO_LEGEND,
2701 ARG_VALUE,
2702 ARG_KILL_WHO,
2703 ARG_READ_ONLY,
2704 ARG_MKDIR,
2705 ARG_NO_ASK_PASSWORD,
2706 ARG_VERIFY,
2707 ARG_FORCE,
2708 ARG_FORMAT,
2709 ARG_UID,
2710 ARG_NUMBER_IPS,
2711 };
2712
2713 static const struct option options[] = {
2714 { "help", no_argument, NULL, 'h' },
2715 { "version", no_argument, NULL, ARG_VERSION },
2716 { "property", required_argument, NULL, 'p' },
2717 { "all", no_argument, NULL, 'a' },
2718 { "value", no_argument, NULL, ARG_VALUE },
2719 { "full", no_argument, NULL, 'l' },
2720 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
2721 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
2722 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
2723 { "signal", required_argument, NULL, 's' },
2724 { "host", required_argument, NULL, 'H' },
2725 { "machine", required_argument, NULL, 'M' },
2726 { "read-only", no_argument, NULL, ARG_READ_ONLY },
2727 { "mkdir", no_argument, NULL, ARG_MKDIR },
2728 { "quiet", no_argument, NULL, 'q' },
2729 { "lines", required_argument, NULL, 'n' },
2730 { "output", required_argument, NULL, 'o' },
2731 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
2732 { "verify", required_argument, NULL, ARG_VERIFY },
2733 { "force", no_argument, NULL, ARG_FORCE },
2734 { "format", required_argument, NULL, ARG_FORMAT },
2735 { "uid", required_argument, NULL, ARG_UID },
2736 { "setenv", required_argument, NULL, 'E' },
2737 { "max-addresses", required_argument, NULL, ARG_NUMBER_IPS },
2738 {}
2739 };
2740
2741 bool reorder = false;
2742 int c, r, shell = -1;
2743
2744 assert(argc >= 0);
2745 assert(argv);
2746
2747 for (;;) {
2748 static const char option_string[] = "-hp:als:H:M:qn:o:E:";
2749
2750 c = getopt_long(argc, argv, option_string + reorder, options, NULL);
2751 if (c < 0)
2752 break;
2753
2754 switch (c) {
2755
2756 case 1: /* getopt_long() returns 1 if "-" was the first character of the option string, and a
2757 * non-option argument was discovered. */
2758
2759 assert(!reorder);
2760
2761 /* We generally are fine with the fact that getopt_long() reorders the command line, and looks
2762 * for switches after the main verb. However, for "shell" we really don't want that, since we
2763 * want that switches specified after the machine name are passed to the program to execute,
2764 * and not processed by us. To make this possible, we'll first invoke getopt_long() with
2765 * reordering disabled (i.e. with the "-" prefix in the option string), looking for the first
2766 * non-option parameter. If it's the verb "shell" we remember its position and continue
2767 * processing options. In this case, as soon as we hit the next non-option argument we found
2768 * the machine name, and stop further processing. If the first non-option argument is any other
2769 * verb than "shell" we switch to normal reordering mode and continue processing arguments
2770 * normally. */
2771
2772 if (shell >= 0) {
2773 /* If we already found the "shell" verb on the command line, and now found the next
2774 * non-option argument, then this is the machine name and we should stop processing
2775 * further arguments. */
2776 optind --; /* don't process this argument, go one step back */
2777 goto done;
2778 }
2779 if (streq(optarg, "shell"))
2780 /* Remember the position of the "shell" verb, and continue processing normally. */
2781 shell = optind - 1;
2782 else {
2783 int saved_optind;
2784
2785 /* OK, this is some other verb. In this case, turn on reordering again, and continue
2786 * processing normally. */
2787 reorder = true;
2788
2789 /* We changed the option string. getopt_long() only looks at it again if we invoke it
2790 * at least once with a reset option index. Hence, let's reset the option index here,
2791 * then invoke getopt_long() again (ignoring what it has to say, after all we most
2792 * likely already processed it), and the bump the option index so that we read the
2793 * intended argument again. */
2794 saved_optind = optind;
2795 optind = 0;
2796 (void) getopt_long(argc, argv, option_string + reorder, options, NULL);
2797 optind = saved_optind - 1; /* go one step back, process this argument again */
2798 }
2799
2800 break;
2801
2802 case 'h':
2803 return help(0, NULL, NULL);
2804
2805 case ARG_VERSION:
2806 return version();
2807
2808 case 'p':
2809 r = strv_extend(&arg_property, optarg);
2810 if (r < 0)
2811 return log_oom();
2812
2813 /* If the user asked for a particular
2814 * property, show it to him, even if it is
2815 * empty. */
2816 arg_all = true;
2817 break;
2818
2819 case 'a':
2820 arg_all = true;
2821 break;
2822
2823 case ARG_VALUE:
2824 arg_value = true;
2825 break;
2826
2827 case 'l':
2828 arg_full = true;
2829 break;
2830
2831 case 'n':
2832 if (safe_atou(optarg, &arg_lines) < 0) {
2833 log_error("Failed to parse lines '%s'", optarg);
2834 return -EINVAL;
2835 }
2836 break;
2837
2838 case 'o':
2839 if (streq(optarg, "help")) {
2840 DUMP_STRING_TABLE(output_mode, OutputMode, _OUTPUT_MODE_MAX);
2841 return 0;
2842 }
2843
2844 arg_output = output_mode_from_string(optarg);
2845 if (arg_output < 0) {
2846 log_error("Unknown output '%s'.", optarg);
2847 return -EINVAL;
2848 }
2849 break;
2850
2851 case ARG_NO_PAGER:
2852 arg_no_pager = true;
2853 break;
2854
2855 case ARG_NO_LEGEND:
2856 arg_legend = false;
2857 break;
2858
2859 case ARG_KILL_WHO:
2860 arg_kill_who = optarg;
2861 break;
2862
2863 case 's':
2864 if (streq(optarg, "help")) {
2865 DUMP_STRING_TABLE(signal, int, _NSIG);
2866 return 0;
2867 }
2868
2869 arg_signal = signal_from_string(optarg);
2870 if (arg_signal < 0) {
2871 log_error("Failed to parse signal string %s.", optarg);
2872 return -EINVAL;
2873 }
2874 break;
2875
2876 case ARG_NO_ASK_PASSWORD:
2877 arg_ask_password = false;
2878 break;
2879
2880 case 'H':
2881 arg_transport = BUS_TRANSPORT_REMOTE;
2882 arg_host = optarg;
2883 break;
2884
2885 case 'M':
2886 arg_transport = BUS_TRANSPORT_MACHINE;
2887 arg_host = optarg;
2888 break;
2889
2890 case ARG_READ_ONLY:
2891 arg_read_only = true;
2892 break;
2893
2894 case ARG_MKDIR:
2895 arg_mkdir = true;
2896 break;
2897
2898 case 'q':
2899 arg_quiet = true;
2900 break;
2901
2902 case ARG_VERIFY:
2903 if (streq(optarg, "help")) {
2904 DUMP_STRING_TABLE(import_verify, ImportVerify, _IMPORT_VERIFY_MAX);
2905 return 0;
2906 }
2907
2908 arg_verify = import_verify_from_string(optarg);
2909 if (arg_verify < 0) {
2910 log_error("Failed to parse --verify= setting: %s", optarg);
2911 return -EINVAL;
2912 }
2913 break;
2914
2915 case ARG_FORCE:
2916 arg_force = true;
2917 break;
2918
2919 case ARG_FORMAT:
2920 if (!STR_IN_SET(optarg, "uncompressed", "xz", "gzip", "bzip2")) {
2921 log_error("Unknown format: %s", optarg);
2922 return -EINVAL;
2923 }
2924
2925 arg_format = optarg;
2926 break;
2927
2928 case ARG_UID:
2929 arg_uid = optarg;
2930 break;
2931
2932 case 'E':
2933 if (!env_assignment_is_valid(optarg)) {
2934 log_error("Environment assignment invalid: %s", optarg);
2935 return -EINVAL;
2936 }
2937
2938 r = strv_extend(&arg_setenv, optarg);
2939 if (r < 0)
2940 return log_oom();
2941 break;
2942
2943 case ARG_NUMBER_IPS:
2944 if (streq(optarg, "all"))
2945 arg_addrs = ALL_IP_ADDRESSES;
2946 else if (safe_atoi(optarg, &arg_addrs) < 0) {
2947 log_error("Invalid number of IPs");
2948 return -EINVAL;
2949 } else if (arg_addrs < 0) {
2950 log_error("Number of IPs cannot be negative");
2951 return -EINVAL;
2952 }
2953 break;
2954
2955 case '?':
2956 return -EINVAL;
2957
2958 default:
2959 assert_not_reached("Unhandled option");
2960 }
2961 }
2962
2963 done:
2964 if (shell >= 0) {
2965 char *t;
2966 int i;
2967
2968 /* We found the "shell" verb while processing the argument list. Since we turned off reordering of the
2969 * argument list initially let's readjust it now, and move the "shell" verb to the back. */
2970
2971 optind -= 1; /* place the option index where the "shell" verb will be placed */
2972
2973 t = argv[shell];
2974 for (i = shell; i < optind; i++)
2975 argv[i] = argv[i+1];
2976 argv[optind] = t;
2977 }
2978
2979 return 1;
2980 }
2981
2982 static int machinectl_main(int argc, char *argv[], sd_bus *bus) {
2983
2984 static const Verb verbs[] = {
2985 { "help", VERB_ANY, VERB_ANY, 0, help },
2986 { "list", VERB_ANY, 1, VERB_DEFAULT, list_machines },
2987 { "list-images", VERB_ANY, 1, 0, list_images },
2988 { "status", 2, VERB_ANY, 0, show_machine },
2989 { "image-status", VERB_ANY, VERB_ANY, 0, show_image },
2990 { "show", VERB_ANY, VERB_ANY, 0, show_machine },
2991 { "show-image", VERB_ANY, VERB_ANY, 0, show_image },
2992 { "terminate", 2, VERB_ANY, 0, terminate_machine },
2993 { "reboot", 2, VERB_ANY, 0, reboot_machine },
2994 { "poweroff", 2, VERB_ANY, 0, poweroff_machine },
2995 { "stop", 2, VERB_ANY, 0, poweroff_machine }, /* Convenience alias */
2996 { "kill", 2, VERB_ANY, 0, kill_machine },
2997 { "login", VERB_ANY, 2, 0, login_machine },
2998 { "shell", VERB_ANY, VERB_ANY, 0, shell_machine },
2999 { "bind", 3, 4, 0, bind_mount },
3000 { "copy-to", 3, 4, 0, copy_files },
3001 { "copy-from", 3, 4, 0, copy_files },
3002 { "remove", 2, VERB_ANY, 0, remove_image },
3003 { "rename", 3, 3, 0, rename_image },
3004 { "clone", 3, 3, 0, clone_image },
3005 { "read-only", 2, 3, 0, read_only_image },
3006 { "start", 2, VERB_ANY, 0, start_machine },
3007 { "enable", 2, VERB_ANY, 0, enable_machine },
3008 { "disable", 2, VERB_ANY, 0, enable_machine },
3009 { "import-tar", 2, 3, 0, import_tar },
3010 { "import-raw", 2, 3, 0, import_raw },
3011 { "export-tar", 2, 3, 0, export_tar },
3012 { "export-raw", 2, 3, 0, export_raw },
3013 { "pull-tar", 2, 3, 0, pull_tar },
3014 { "pull-raw", 2, 3, 0, pull_raw },
3015 { "list-transfers", VERB_ANY, 1, 0, list_transfers },
3016 { "cancel-transfer", 2, VERB_ANY, 0, cancel_transfer },
3017 { "set-limit", 2, 3, 0, set_limit },
3018 { "clean", VERB_ANY, 1, 0, clean_images },
3019 {}
3020 };
3021
3022 return dispatch_verb(argc, argv, verbs, bus);
3023 }
3024
3025 int main(int argc, char*argv[]) {
3026 sd_bus *bus = NULL;
3027 int r;
3028
3029 setlocale(LC_ALL, "");
3030 log_parse_environment();
3031 log_open();
3032 sigbus_install();
3033
3034 r = parse_argv(argc, argv);
3035 if (r <= 0)
3036 goto finish;
3037
3038 r = bus_connect_transport(arg_transport, arg_host, false, &bus);
3039 if (r < 0) {
3040 log_error_errno(r, "Failed to create bus connection: %m");
3041 goto finish;
3042 }
3043
3044 (void) sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);
3045
3046 r = machinectl_main(argc, argv, bus);
3047
3048 finish:
3049 /* make sure we terminate the bus connection first, and then close the
3050 * pager, see issue #3543 for the details. */
3051 sd_bus_flush_close_unref(bus);
3052 pager_close();
3053 polkit_agent_close();
3054
3055 strv_free(arg_property);
3056 strv_free(arg_setenv);
3057
3058 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
3059 }