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