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