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