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