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