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