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