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