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