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