]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/machine/machinectl.c
Merge pull request #10892 from mbiebl/revert-systemctl-runtime-unmask-breakage
[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(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 ret = 0, 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 sd_event_get_exit_code(event, &ret);
1359 return ret;
1360 }
1361
1362 static int parse_machine_uid(const char *spec, const char **machine, char **uid) {
1363 /*
1364 * Whatever is specified in the spec takes priority over global arguments.
1365 */
1366 char *_uid = NULL;
1367 const char *_machine = NULL;
1368
1369 if (spec) {
1370 const char *at;
1371
1372 at = strchr(spec, '@');
1373 if (at) {
1374 if (at == spec)
1375 /* Do the same as ssh and refuse "@host". */
1376 return -EINVAL;
1377
1378 _machine = at + 1;
1379 _uid = strndup(spec, at - spec);
1380 if (!_uid)
1381 return -ENOMEM;
1382 } else
1383 _machine = spec;
1384 };
1385
1386 if (arg_uid && !_uid) {
1387 _uid = strdup(arg_uid);
1388 if (!_uid)
1389 return -ENOMEM;
1390 }
1391
1392 *uid = _uid;
1393 *machine = isempty(_machine) ? ".host" : _machine;
1394 return 0;
1395 }
1396
1397 static int login_machine(int argc, char *argv[], void *userdata) {
1398 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1399 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1400 _cleanup_(pty_forward_freep) PTYForward *forward = NULL;
1401 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1402 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1403 int master = -1, r;
1404 sd_bus *bus = userdata;
1405 const char *match, *machine;
1406
1407 assert(bus);
1408
1409 if (!strv_isempty(arg_setenv) || arg_uid) {
1410 log_error("--setenv= and --uid= are not supported for 'login'. Use 'shell' instead.");
1411 return -EINVAL;
1412 }
1413
1414 if (!IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_MACHINE)) {
1415 log_error("Login only supported on local machines.");
1416 return -EOPNOTSUPP;
1417 }
1418
1419 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1420
1421 r = sd_event_default(&event);
1422 if (r < 0)
1423 return log_error_errno(r, "Failed to get event loop: %m");
1424
1425 r = sd_bus_attach_event(bus, event, 0);
1426 if (r < 0)
1427 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1428
1429 machine = argc < 2 || isempty(argv[1]) ? ".host" : argv[1];
1430
1431 match = strjoina("type='signal',"
1432 "sender='org.freedesktop.machine1',"
1433 "path='/org/freedesktop/machine1',",
1434 "interface='org.freedesktop.machine1.Manager',"
1435 "member='MachineRemoved',"
1436 "arg0='", machine, "'");
1437
1438 r = sd_bus_add_match_async(bus, &slot, match, on_machine_removed, NULL, &forward);
1439 if (r < 0)
1440 return log_error_errno(r, "Failed to request machine removal match: %m");
1441
1442 r = sd_bus_call_method(
1443 bus,
1444 "org.freedesktop.machine1",
1445 "/org/freedesktop/machine1",
1446 "org.freedesktop.machine1.Manager",
1447 "OpenMachineLogin",
1448 &error,
1449 &reply,
1450 "s", machine);
1451 if (r < 0)
1452 return log_error_errno(r, "Failed to get login PTY: %s", bus_error_message(&error, -r));
1453
1454 r = sd_bus_message_read(reply, "hs", &master, NULL);
1455 if (r < 0)
1456 return bus_log_parse_error(r);
1457
1458 return process_forward(event, &forward, master, PTY_FORWARD_IGNORE_VHANGUP, machine);
1459 }
1460
1461 static int shell_machine(int argc, char *argv[], void *userdata) {
1462 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
1463 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1464 _cleanup_(pty_forward_freep) PTYForward *forward = NULL;
1465 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1466 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1467 int master = -1, r;
1468 sd_bus *bus = userdata;
1469 const char *match, *machine, *path;
1470 _cleanup_free_ char *uid = NULL;
1471
1472 assert(bus);
1473
1474 if (!IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_MACHINE)) {
1475 log_error("Shell only supported on local machines.");
1476 return -EOPNOTSUPP;
1477 }
1478
1479 /* Pass $TERM to shell session, if not explicitly specified. */
1480 if (!strv_find_prefix(arg_setenv, "TERM=")) {
1481 const char *t;
1482
1483 t = strv_find_prefix(environ, "TERM=");
1484 if (t) {
1485 if (strv_extend(&arg_setenv, t) < 0)
1486 return log_oom();
1487 }
1488 }
1489
1490 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1491
1492 r = sd_event_default(&event);
1493 if (r < 0)
1494 return log_error_errno(r, "Failed to get event loop: %m");
1495
1496 r = sd_bus_attach_event(bus, event, 0);
1497 if (r < 0)
1498 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1499
1500 r = parse_machine_uid(argc >= 2 ? argv[1] : NULL, &machine, &uid);
1501 if (r < 0)
1502 return log_error_errno(r, "Failed to parse machine specification: %m");
1503
1504 match = strjoina("type='signal',"
1505 "sender='org.freedesktop.machine1',"
1506 "path='/org/freedesktop/machine1',",
1507 "interface='org.freedesktop.machine1.Manager',"
1508 "member='MachineRemoved',"
1509 "arg0='", machine, "'");
1510
1511 r = sd_bus_add_match_async(bus, &slot, match, on_machine_removed, NULL, &forward);
1512 if (r < 0)
1513 return log_error_errno(r, "Failed to request machine removal match: %m");
1514
1515 r = sd_bus_message_new_method_call(
1516 bus,
1517 &m,
1518 "org.freedesktop.machine1",
1519 "/org/freedesktop/machine1",
1520 "org.freedesktop.machine1.Manager",
1521 "OpenMachineShell");
1522 if (r < 0)
1523 return bus_log_create_error(r);
1524
1525 path = argc < 3 || isempty(argv[2]) ? NULL : argv[2];
1526
1527 r = sd_bus_message_append(m, "sss", machine, uid, path);
1528 if (r < 0)
1529 return bus_log_create_error(r);
1530
1531 r = sd_bus_message_append_strv(m, strv_length(argv) <= 3 ? NULL : argv + 2);
1532 if (r < 0)
1533 return bus_log_create_error(r);
1534
1535 r = sd_bus_message_append_strv(m, arg_setenv);
1536 if (r < 0)
1537 return bus_log_create_error(r);
1538
1539 r = sd_bus_call(bus, m, 0, &error, &reply);
1540 if (r < 0)
1541 return log_error_errno(r, "Failed to get shell PTY: %s", bus_error_message(&error, -r));
1542
1543 r = sd_bus_message_read(reply, "hs", &master, NULL);
1544 if (r < 0)
1545 return bus_log_parse_error(r);
1546
1547 return process_forward(event, &forward, master, 0, machine);
1548 }
1549
1550 static int remove_image(int argc, char *argv[], void *userdata) {
1551 sd_bus *bus = userdata;
1552 int r, i;
1553
1554 assert(bus);
1555
1556 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1557
1558 for (i = 1; i < argc; i++) {
1559 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1560 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1561
1562 r = sd_bus_message_new_method_call(
1563 bus,
1564 &m,
1565 "org.freedesktop.machine1",
1566 "/org/freedesktop/machine1",
1567 "org.freedesktop.machine1.Manager",
1568 "RemoveImage");
1569 if (r < 0)
1570 return bus_log_create_error(r);
1571
1572 r = sd_bus_message_append(m, "s", argv[i]);
1573 if (r < 0)
1574 return bus_log_create_error(r);
1575
1576 /* This is a slow operation, hence turn off any method call timeouts */
1577 r = sd_bus_call(bus, m, USEC_INFINITY, &error, NULL);
1578 if (r < 0)
1579 return log_error_errno(r, "Could not remove image: %s", bus_error_message(&error, r));
1580 }
1581
1582 return 0;
1583 }
1584
1585 static int rename_image(int argc, char *argv[], void *userdata) {
1586 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1587 sd_bus *bus = userdata;
1588 int r;
1589
1590 assert(bus);
1591
1592 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1593
1594 r = sd_bus_call_method(
1595 bus,
1596 "org.freedesktop.machine1",
1597 "/org/freedesktop/machine1",
1598 "org.freedesktop.machine1.Manager",
1599 "RenameImage",
1600 &error,
1601 NULL,
1602 "ss", argv[1], argv[2]);
1603 if (r < 0)
1604 return log_error_errno(r, "Could not rename image: %s", bus_error_message(&error, -r));
1605
1606 return 0;
1607 }
1608
1609 static int clone_image(int argc, char *argv[], void *userdata) {
1610 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1611 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1612 sd_bus *bus = userdata;
1613 int r;
1614
1615 assert(bus);
1616
1617 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1618
1619 r = sd_bus_message_new_method_call(
1620 bus,
1621 &m,
1622 "org.freedesktop.machine1",
1623 "/org/freedesktop/machine1",
1624 "org.freedesktop.machine1.Manager",
1625 "CloneImage");
1626 if (r < 0)
1627 return bus_log_create_error(r);
1628
1629 r = sd_bus_message_append(m, "ssb", argv[1], argv[2], arg_read_only);
1630 if (r < 0)
1631 return bus_log_create_error(r);
1632
1633 /* This is a slow operation, hence turn off any method call timeouts */
1634 r = sd_bus_call(bus, m, USEC_INFINITY, &error, NULL);
1635 if (r < 0)
1636 return log_error_errno(r, "Could not clone image: %s", bus_error_message(&error, r));
1637
1638 return 0;
1639 }
1640
1641 static int read_only_image(int argc, char *argv[], void *userdata) {
1642 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1643 sd_bus *bus = userdata;
1644 int b = true, r;
1645
1646 assert(bus);
1647
1648 if (argc > 2) {
1649 b = parse_boolean(argv[2]);
1650 if (b < 0) {
1651 log_error("Failed to parse boolean argument: %s", argv[2]);
1652 return -EINVAL;
1653 }
1654 }
1655
1656 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1657
1658 r = sd_bus_call_method(
1659 bus,
1660 "org.freedesktop.machine1",
1661 "/org/freedesktop/machine1",
1662 "org.freedesktop.machine1.Manager",
1663 "MarkImageReadOnly",
1664 &error,
1665 NULL,
1666 "sb", argv[1], b);
1667 if (r < 0)
1668 return log_error_errno(r, "Could not mark image read-only: %s", bus_error_message(&error, -r));
1669
1670 return 0;
1671 }
1672
1673 static int image_exists(sd_bus *bus, const char *name) {
1674 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1675 int r;
1676
1677 assert(bus);
1678 assert(name);
1679
1680 r = sd_bus_call_method(
1681 bus,
1682 "org.freedesktop.machine1",
1683 "/org/freedesktop/machine1",
1684 "org.freedesktop.machine1.Manager",
1685 "GetImage",
1686 &error,
1687 NULL,
1688 "s", name);
1689 if (r < 0) {
1690 if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_IMAGE))
1691 return 0;
1692
1693 return log_error_errno(r, "Failed to check whether image %s exists: %s", name, bus_error_message(&error, -r));
1694 }
1695
1696 return 1;
1697 }
1698
1699 static int make_service_name(const char *name, char **ret) {
1700 int r;
1701
1702 assert(name);
1703 assert(ret);
1704
1705 if (!machine_name_is_valid(name))
1706 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1707 "Invalid machine name %s.", name);
1708
1709 r = unit_name_build("systemd-nspawn", name, ".service", ret);
1710 if (r < 0)
1711 return log_error_errno(r, "Failed to build unit name: %m");
1712
1713 return 0;
1714 }
1715
1716 static int start_machine(int argc, char *argv[], void *userdata) {
1717 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1718 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
1719 sd_bus *bus = userdata;
1720 int r, i;
1721
1722 assert(bus);
1723
1724 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1725
1726 r = bus_wait_for_jobs_new(bus, &w);
1727 if (r < 0)
1728 return log_oom();
1729
1730 for (i = 1; i < argc; i++) {
1731 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1732 _cleanup_free_ char *unit = NULL;
1733 const char *object;
1734
1735 r = make_service_name(argv[i], &unit);
1736 if (r < 0)
1737 return r;
1738
1739 r = image_exists(bus, argv[i]);
1740 if (r < 0)
1741 return r;
1742 if (r == 0) {
1743 log_error("Machine image '%s' does not exist.", argv[1]);
1744 return -ENXIO;
1745 }
1746
1747 r = sd_bus_call_method(
1748 bus,
1749 "org.freedesktop.systemd1",
1750 "/org/freedesktop/systemd1",
1751 "org.freedesktop.systemd1.Manager",
1752 "StartUnit",
1753 &error,
1754 &reply,
1755 "ss", unit, "fail");
1756 if (r < 0)
1757 return log_error_errno(r, "Failed to start unit: %s", bus_error_message(&error, -r));
1758
1759 r = sd_bus_message_read(reply, "o", &object);
1760 if (r < 0)
1761 return bus_log_parse_error(r);
1762
1763 r = bus_wait_for_jobs_add(w, object);
1764 if (r < 0)
1765 return log_oom();
1766 }
1767
1768 r = bus_wait_for_jobs(w, arg_quiet, NULL);
1769 if (r < 0)
1770 return r;
1771
1772 return 0;
1773 }
1774
1775 static int enable_machine(int argc, char *argv[], void *userdata) {
1776 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
1777 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1778 UnitFileChange *changes = NULL;
1779 size_t n_changes = 0;
1780 const char *method = NULL;
1781 sd_bus *bus = userdata;
1782 int r, i;
1783
1784 assert(bus);
1785
1786 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1787
1788 method = streq(argv[0], "enable") ? "EnableUnitFiles" : "DisableUnitFiles";
1789
1790 r = sd_bus_message_new_method_call(
1791 bus,
1792 &m,
1793 "org.freedesktop.systemd1",
1794 "/org/freedesktop/systemd1",
1795 "org.freedesktop.systemd1.Manager",
1796 method);
1797 if (r < 0)
1798 return bus_log_create_error(r);
1799
1800 r = sd_bus_message_open_container(m, 'a', "s");
1801 if (r < 0)
1802 return bus_log_create_error(r);
1803
1804 for (i = 1; i < argc; i++) {
1805 _cleanup_free_ char *unit = NULL;
1806
1807 r = make_service_name(argv[i], &unit);
1808 if (r < 0)
1809 return r;
1810
1811 r = image_exists(bus, argv[i]);
1812 if (r < 0)
1813 return r;
1814 if (r == 0) {
1815 log_error("Machine image '%s' does not exist.", argv[1]);
1816 return -ENXIO;
1817 }
1818
1819 r = sd_bus_message_append(m, "s", unit);
1820 if (r < 0)
1821 return bus_log_create_error(r);
1822 }
1823
1824 r = sd_bus_message_close_container(m);
1825 if (r < 0)
1826 return bus_log_create_error(r);
1827
1828 if (streq(argv[0], "enable"))
1829 r = sd_bus_message_append(m, "bb", false, false);
1830 else
1831 r = sd_bus_message_append(m, "b", false);
1832 if (r < 0)
1833 return bus_log_create_error(r);
1834
1835 r = sd_bus_call(bus, m, 0, &error, &reply);
1836 if (r < 0)
1837 return log_error_errno(r, "Failed to enable or disable unit: %s", bus_error_message(&error, -r));
1838
1839 if (streq(argv[0], "enable")) {
1840 r = sd_bus_message_read(reply, "b", NULL);
1841 if (r < 0)
1842 return bus_log_parse_error(r);
1843 }
1844
1845 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
1846 if (r < 0)
1847 goto finish;
1848
1849 r = sd_bus_call_method(
1850 bus,
1851 "org.freedesktop.systemd1",
1852 "/org/freedesktop/systemd1",
1853 "org.freedesktop.systemd1.Manager",
1854 "Reload",
1855 &error,
1856 NULL,
1857 NULL);
1858 if (r < 0) {
1859 log_error("Failed to reload daemon: %s", bus_error_message(&error, -r));
1860 goto finish;
1861 }
1862
1863 r = 0;
1864
1865 finish:
1866 unit_file_changes_free(changes, n_changes);
1867
1868 return r;
1869 }
1870
1871 static int match_log_message(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1872 const char **our_path = userdata, *line;
1873 unsigned priority;
1874 int r;
1875
1876 assert(m);
1877 assert(our_path);
1878
1879 r = sd_bus_message_read(m, "us", &priority, &line);
1880 if (r < 0) {
1881 bus_log_parse_error(r);
1882 return 0;
1883 }
1884
1885 if (!streq_ptr(*our_path, sd_bus_message_get_path(m)))
1886 return 0;
1887
1888 if (arg_quiet && LOG_PRI(priority) >= LOG_INFO)
1889 return 0;
1890
1891 log_full(priority, "%s", line);
1892 return 0;
1893 }
1894
1895 static int match_transfer_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1896 const char **our_path = userdata, *path, *result;
1897 uint32_t id;
1898 int r;
1899
1900 assert(m);
1901 assert(our_path);
1902
1903 r = sd_bus_message_read(m, "uos", &id, &path, &result);
1904 if (r < 0) {
1905 bus_log_parse_error(r);
1906 return 0;
1907 }
1908
1909 if (!streq_ptr(*our_path, path))
1910 return 0;
1911
1912 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), !streq_ptr(result, "done"));
1913 return 0;
1914 }
1915
1916 static int transfer_signal_handler(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1917 assert(s);
1918 assert(si);
1919
1920 if (!arg_quiet)
1921 log_info("Continuing download in the background. Use \"machinectl cancel-transfer %" PRIu32 "\" to abort transfer.", PTR_TO_UINT32(userdata));
1922
1923 sd_event_exit(sd_event_source_get_event(s), EINTR);
1924 return 0;
1925 }
1926
1927 static int transfer_image_common(sd_bus *bus, sd_bus_message *m) {
1928 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot_job_removed = NULL, *slot_log_message = NULL;
1929 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1930 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1931 _cleanup_(sd_event_unrefp) sd_event* event = NULL;
1932 const char *path = NULL;
1933 uint32_t id;
1934 int r;
1935
1936 assert(bus);
1937 assert(m);
1938
1939 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1940
1941 r = sd_event_default(&event);
1942 if (r < 0)
1943 return log_error_errno(r, "Failed to get event loop: %m");
1944
1945 r = sd_bus_attach_event(bus, event, 0);
1946 if (r < 0)
1947 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1948
1949 r = sd_bus_match_signal_async(
1950 bus,
1951 &slot_job_removed,
1952 "org.freedesktop.import1",
1953 "/org/freedesktop/import1",
1954 "org.freedesktop.import1.Manager",
1955 "TransferRemoved",
1956 match_transfer_removed, NULL, &path);
1957 if (r < 0)
1958 return log_error_errno(r, "Failed to request match: %m");
1959
1960 r = sd_bus_match_signal_async(
1961 bus,
1962 &slot_log_message,
1963 "org.freedesktop.import1",
1964 NULL,
1965 "org.freedesktop.import1.Transfer",
1966 "LogMessage",
1967 match_log_message, NULL, &path);
1968 if (r < 0)
1969 return log_error_errno(r, "Failed to request match: %m");
1970
1971 r = sd_bus_call(bus, m, 0, &error, &reply);
1972 if (r < 0)
1973 return log_error_errno(r, "Failed to transfer image: %s", bus_error_message(&error, -r));
1974
1975 r = sd_bus_message_read(reply, "uo", &id, &path);
1976 if (r < 0)
1977 return bus_log_parse_error(r);
1978
1979 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0);
1980
1981 if (!arg_quiet)
1982 log_info("Enqueued transfer job %u. Press C-c to continue download in background.", id);
1983
1984 (void) sd_event_add_signal(event, NULL, SIGINT, transfer_signal_handler, UINT32_TO_PTR(id));
1985 (void) sd_event_add_signal(event, NULL, SIGTERM, transfer_signal_handler, UINT32_TO_PTR(id));
1986
1987 r = sd_event_loop(event);
1988 if (r < 0)
1989 return log_error_errno(r, "Failed to run event loop: %m");
1990
1991 return -r;
1992 }
1993
1994 static const char *nullify_dash(const char *p) {
1995 if (isempty(p))
1996 return NULL;
1997
1998 if (streq(p, "-"))
1999 return NULL;
2000
2001 return p;
2002 }
2003
2004 static int import_tar(int argc, char *argv[], void *userdata) {
2005 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2006 _cleanup_free_ char *ll = NULL, *fn = NULL;
2007 const char *local = NULL, *path = NULL;
2008 _cleanup_close_ int fd = -1;
2009 sd_bus *bus = userdata;
2010 int r;
2011
2012 assert(bus);
2013
2014 if (argc >= 2)
2015 path = nullify_dash(argv[1]);
2016
2017 if (argc >= 3)
2018 local = nullify_dash(argv[2]);
2019 else if (path) {
2020 r = path_extract_filename(path, &fn);
2021 if (r < 0)
2022 return log_error_errno(r, "Cannot extract container name from filename: %m");
2023
2024 local = fn;
2025 }
2026 if (!local) {
2027 log_error("Need either path or local name.");
2028 return -EINVAL;
2029 }
2030
2031 r = tar_strip_suffixes(local, &ll);
2032 if (r < 0)
2033 return log_oom();
2034
2035 local = ll;
2036
2037 if (!machine_name_is_valid(local)) {
2038 log_error("Local name %s is not a suitable machine name.", local);
2039 return -EINVAL;
2040 }
2041
2042 if (path) {
2043 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
2044 if (fd < 0)
2045 return log_error_errno(errno, "Failed to open %s: %m", path);
2046 }
2047
2048 r = sd_bus_message_new_method_call(
2049 bus,
2050 &m,
2051 "org.freedesktop.import1",
2052 "/org/freedesktop/import1",
2053 "org.freedesktop.import1.Manager",
2054 "ImportTar");
2055 if (r < 0)
2056 return bus_log_create_error(r);
2057
2058 r = sd_bus_message_append(
2059 m,
2060 "hsbb",
2061 fd >= 0 ? fd : STDIN_FILENO,
2062 local,
2063 arg_force,
2064 arg_read_only);
2065 if (r < 0)
2066 return bus_log_create_error(r);
2067
2068 return transfer_image_common(bus, m);
2069 }
2070
2071 static int import_raw(int argc, char *argv[], void *userdata) {
2072 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2073 _cleanup_free_ char *ll = NULL, *fn = NULL;
2074 const char *local = NULL, *path = NULL;
2075 _cleanup_close_ int fd = -1;
2076 sd_bus *bus = userdata;
2077 int r;
2078
2079 assert(bus);
2080
2081 if (argc >= 2)
2082 path = nullify_dash(argv[1]);
2083
2084 if (argc >= 3)
2085 local = nullify_dash(argv[2]);
2086 else if (path) {
2087 r = path_extract_filename(path, &fn);
2088 if (r < 0)
2089 return log_error_errno(r, "Cannot extract container name from filename: %m");
2090
2091 local = fn;
2092 }
2093 if (!local) {
2094 log_error("Need either path or local name.");
2095 return -EINVAL;
2096 }
2097
2098 r = raw_strip_suffixes(local, &ll);
2099 if (r < 0)
2100 return log_oom();
2101
2102 local = ll;
2103
2104 if (!machine_name_is_valid(local)) {
2105 log_error("Local name %s is not a suitable machine name.", local);
2106 return -EINVAL;
2107 }
2108
2109 if (path) {
2110 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
2111 if (fd < 0)
2112 return log_error_errno(errno, "Failed to open %s: %m", path);
2113 }
2114
2115 r = sd_bus_message_new_method_call(
2116 bus,
2117 &m,
2118 "org.freedesktop.import1",
2119 "/org/freedesktop/import1",
2120 "org.freedesktop.import1.Manager",
2121 "ImportRaw");
2122 if (r < 0)
2123 return bus_log_create_error(r);
2124
2125 r = sd_bus_message_append(
2126 m,
2127 "hsbb",
2128 fd >= 0 ? fd : STDIN_FILENO,
2129 local,
2130 arg_force,
2131 arg_read_only);
2132 if (r < 0)
2133 return bus_log_create_error(r);
2134
2135 return transfer_image_common(bus, m);
2136 }
2137
2138 static int import_fs(int argc, char *argv[], void *userdata) {
2139 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2140 const char *local = NULL, *path = NULL;
2141 _cleanup_free_ char *fn = NULL;
2142 _cleanup_close_ int fd = -1;
2143 sd_bus *bus = userdata;
2144 int r;
2145
2146 assert(bus);
2147
2148 if (argc >= 2)
2149 path = nullify_dash(argv[1]);
2150
2151 if (argc >= 3)
2152 local = nullify_dash(argv[2]);
2153 else if (path) {
2154 r = path_extract_filename(path, &fn);
2155 if (r < 0)
2156 return log_error_errno(r, "Cannot extract container name from filename: %m");
2157
2158 local = fn;
2159 }
2160 if (!local) {
2161 log_error("Need either path or local name.");
2162 return -EINVAL;
2163 }
2164
2165 if (!machine_name_is_valid(local)) {
2166 log_error("Local name %s is not a suitable machine name.", local);
2167 return -EINVAL;
2168 }
2169
2170 if (path) {
2171 fd = open(path, O_DIRECTORY|O_RDONLY|O_CLOEXEC);
2172 if (fd < 0)
2173 return log_error_errno(errno, "Failed to open directory '%s': %m", path);
2174 }
2175
2176 r = sd_bus_message_new_method_call(
2177 bus,
2178 &m,
2179 "org.freedesktop.import1",
2180 "/org/freedesktop/import1",
2181 "org.freedesktop.import1.Manager",
2182 "ImportFileSystem");
2183 if (r < 0)
2184 return bus_log_create_error(r);
2185
2186 r = sd_bus_message_append(
2187 m,
2188 "hsbb",
2189 fd >= 0 ? fd : STDIN_FILENO,
2190 local,
2191 arg_force,
2192 arg_read_only);
2193 if (r < 0)
2194 return bus_log_create_error(r);
2195
2196 return transfer_image_common(bus, m);
2197 }
2198
2199 static void determine_compression_from_filename(const char *p) {
2200 if (arg_format)
2201 return;
2202
2203 if (!p)
2204 return;
2205
2206 if (endswith(p, ".xz"))
2207 arg_format = "xz";
2208 else if (endswith(p, ".gz"))
2209 arg_format = "gzip";
2210 else if (endswith(p, ".bz2"))
2211 arg_format = "bzip2";
2212 }
2213
2214 static int export_tar(int argc, char *argv[], void *userdata) {
2215 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2216 _cleanup_close_ int fd = -1;
2217 const char *local = NULL, *path = NULL;
2218 sd_bus *bus = userdata;
2219 int r;
2220
2221 assert(bus);
2222
2223 local = argv[1];
2224 if (!machine_name_is_valid(local)) {
2225 log_error("Machine name %s is not valid.", local);
2226 return -EINVAL;
2227 }
2228
2229 if (argc >= 3)
2230 path = argv[2];
2231 if (isempty(path) || streq(path, "-"))
2232 path = NULL;
2233
2234 if (path) {
2235 determine_compression_from_filename(path);
2236
2237 fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC|O_NOCTTY, 0666);
2238 if (fd < 0)
2239 return log_error_errno(errno, "Failed to open %s: %m", path);
2240 }
2241
2242 r = sd_bus_message_new_method_call(
2243 bus,
2244 &m,
2245 "org.freedesktop.import1",
2246 "/org/freedesktop/import1",
2247 "org.freedesktop.import1.Manager",
2248 "ExportTar");
2249 if (r < 0)
2250 return bus_log_create_error(r);
2251
2252 r = sd_bus_message_append(
2253 m,
2254 "shs",
2255 local,
2256 fd >= 0 ? fd : STDOUT_FILENO,
2257 arg_format);
2258 if (r < 0)
2259 return bus_log_create_error(r);
2260
2261 return transfer_image_common(bus, m);
2262 }
2263
2264 static int export_raw(int argc, char *argv[], void *userdata) {
2265 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2266 _cleanup_close_ int fd = -1;
2267 const char *local = NULL, *path = NULL;
2268 sd_bus *bus = userdata;
2269 int r;
2270
2271 assert(bus);
2272
2273 local = argv[1];
2274 if (!machine_name_is_valid(local)) {
2275 log_error("Machine name %s is not valid.", local);
2276 return -EINVAL;
2277 }
2278
2279 if (argc >= 3)
2280 path = argv[2];
2281 if (isempty(path) || streq(path, "-"))
2282 path = NULL;
2283
2284 if (path) {
2285 determine_compression_from_filename(path);
2286
2287 fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC|O_NOCTTY, 0666);
2288 if (fd < 0)
2289 return log_error_errno(errno, "Failed to open %s: %m", path);
2290 }
2291
2292 r = sd_bus_message_new_method_call(
2293 bus,
2294 &m,
2295 "org.freedesktop.import1",
2296 "/org/freedesktop/import1",
2297 "org.freedesktop.import1.Manager",
2298 "ExportRaw");
2299 if (r < 0)
2300 return bus_log_create_error(r);
2301
2302 r = sd_bus_message_append(
2303 m,
2304 "shs",
2305 local,
2306 fd >= 0 ? fd : STDOUT_FILENO,
2307 arg_format);
2308 if (r < 0)
2309 return bus_log_create_error(r);
2310
2311 return transfer_image_common(bus, m);
2312 }
2313
2314 static int pull_tar(int argc, char *argv[], void *userdata) {
2315 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2316 _cleanup_free_ char *l = NULL, *ll = NULL;
2317 const char *local, *remote;
2318 sd_bus *bus = userdata;
2319 int r;
2320
2321 assert(bus);
2322
2323 remote = argv[1];
2324 if (!http_url_is_valid(remote)) {
2325 log_error("URL '%s' is not valid.", remote);
2326 return -EINVAL;
2327 }
2328
2329 if (argc >= 3)
2330 local = argv[2];
2331 else {
2332 r = import_url_last_component(remote, &l);
2333 if (r < 0)
2334 return log_error_errno(r, "Failed to get final component of URL: %m");
2335
2336 local = l;
2337 }
2338
2339 if (isempty(local) || streq(local, "-"))
2340 local = NULL;
2341
2342 if (local) {
2343 r = tar_strip_suffixes(local, &ll);
2344 if (r < 0)
2345 return log_oom();
2346
2347 local = ll;
2348
2349 if (!machine_name_is_valid(local)) {
2350 log_error("Local name %s is not a suitable machine name.", local);
2351 return -EINVAL;
2352 }
2353 }
2354
2355 r = sd_bus_message_new_method_call(
2356 bus,
2357 &m,
2358 "org.freedesktop.import1",
2359 "/org/freedesktop/import1",
2360 "org.freedesktop.import1.Manager",
2361 "PullTar");
2362 if (r < 0)
2363 return bus_log_create_error(r);
2364
2365 r = sd_bus_message_append(
2366 m,
2367 "sssb",
2368 remote,
2369 local,
2370 import_verify_to_string(arg_verify),
2371 arg_force);
2372 if (r < 0)
2373 return bus_log_create_error(r);
2374
2375 return transfer_image_common(bus, m);
2376 }
2377
2378 static int pull_raw(int argc, char *argv[], void *userdata) {
2379 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2380 _cleanup_free_ char *l = NULL, *ll = NULL;
2381 const char *local, *remote;
2382 sd_bus *bus = userdata;
2383 int r;
2384
2385 assert(bus);
2386
2387 remote = argv[1];
2388 if (!http_url_is_valid(remote)) {
2389 log_error("URL '%s' is not valid.", remote);
2390 return -EINVAL;
2391 }
2392
2393 if (argc >= 3)
2394 local = argv[2];
2395 else {
2396 r = import_url_last_component(remote, &l);
2397 if (r < 0)
2398 return log_error_errno(r, "Failed to get final component of URL: %m");
2399
2400 local = l;
2401 }
2402
2403 if (isempty(local) || streq(local, "-"))
2404 local = NULL;
2405
2406 if (local) {
2407 r = raw_strip_suffixes(local, &ll);
2408 if (r < 0)
2409 return log_oom();
2410
2411 local = ll;
2412
2413 if (!machine_name_is_valid(local)) {
2414 log_error("Local name %s is not a suitable machine name.", local);
2415 return -EINVAL;
2416 }
2417 }
2418
2419 r = sd_bus_message_new_method_call(
2420 bus,
2421 &m,
2422 "org.freedesktop.import1",
2423 "/org/freedesktop/import1",
2424 "org.freedesktop.import1.Manager",
2425 "PullRaw");
2426 if (r < 0)
2427 return bus_log_create_error(r);
2428
2429 r = sd_bus_message_append(
2430 m,
2431 "sssb",
2432 remote,
2433 local,
2434 import_verify_to_string(arg_verify),
2435 arg_force);
2436 if (r < 0)
2437 return bus_log_create_error(r);
2438
2439 return transfer_image_common(bus, m);
2440 }
2441
2442 typedef struct TransferInfo {
2443 uint32_t id;
2444 const char *type;
2445 const char *remote;
2446 const char *local;
2447 double progress;
2448 } TransferInfo;
2449
2450 static int compare_transfer_info(const TransferInfo *a, const TransferInfo *b) {
2451 return strcmp(a->local, b->local);
2452 }
2453
2454 static int list_transfers(int argc, char *argv[], void *userdata) {
2455 size_t max_type = STRLEN("TYPE"), max_local = STRLEN("LOCAL"), max_remote = STRLEN("REMOTE");
2456 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2457 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2458 _cleanup_free_ TransferInfo *transfers = NULL;
2459 size_t n_transfers = 0, n_allocated = 0, j;
2460 const char *type, *remote, *local;
2461 sd_bus *bus = userdata;
2462 uint32_t id, max_id = 0;
2463 double progress;
2464 int r;
2465
2466 (void) pager_open(arg_pager_flags);
2467
2468 r = sd_bus_call_method(bus,
2469 "org.freedesktop.import1",
2470 "/org/freedesktop/import1",
2471 "org.freedesktop.import1.Manager",
2472 "ListTransfers",
2473 &error,
2474 &reply,
2475 NULL);
2476 if (r < 0)
2477 return log_error_errno(r, "Could not get transfers: %s", bus_error_message(&error, -r));
2478
2479 r = sd_bus_message_enter_container(reply, 'a', "(usssdo)");
2480 if (r < 0)
2481 return bus_log_parse_error(r);
2482
2483 while ((r = sd_bus_message_read(reply, "(usssdo)", &id, &type, &remote, &local, &progress, NULL)) > 0) {
2484 size_t l;
2485
2486 if (!GREEDY_REALLOC(transfers, n_allocated, n_transfers + 1))
2487 return log_oom();
2488
2489 transfers[n_transfers].id = id;
2490 transfers[n_transfers].type = type;
2491 transfers[n_transfers].remote = remote;
2492 transfers[n_transfers].local = local;
2493 transfers[n_transfers].progress = progress;
2494
2495 l = strlen(type);
2496 if (l > max_type)
2497 max_type = l;
2498
2499 l = strlen(remote);
2500 if (l > max_remote)
2501 max_remote = l;
2502
2503 l = strlen(local);
2504 if (l > max_local)
2505 max_local = l;
2506
2507 if (id > max_id)
2508 max_id = id;
2509
2510 n_transfers++;
2511 }
2512 if (r < 0)
2513 return bus_log_parse_error(r);
2514
2515 r = sd_bus_message_exit_container(reply);
2516 if (r < 0)
2517 return bus_log_parse_error(r);
2518
2519 typesafe_qsort(transfers, n_transfers, compare_transfer_info);
2520
2521 if (arg_legend && n_transfers > 0)
2522 printf("%-*s %-*s %-*s %-*s %-*s\n",
2523 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id)), "ID",
2524 (int) 7, "PERCENT",
2525 (int) max_type, "TYPE",
2526 (int) max_local, "LOCAL",
2527 (int) max_remote, "REMOTE");
2528
2529 for (j = 0; j < n_transfers; j++)
2530
2531 if (transfers[j].progress < 0)
2532 printf("%*" PRIu32 " %*s %-*s %-*s %-*s\n",
2533 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id)), transfers[j].id,
2534 (int) 7, "n/a",
2535 (int) max_type, transfers[j].type,
2536 (int) max_local, transfers[j].local,
2537 (int) max_remote, transfers[j].remote);
2538 else
2539 printf("%*" PRIu32 " %*u%% %-*s %-*s %-*s\n",
2540 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id)), transfers[j].id,
2541 (int) 6, (unsigned) (transfers[j].progress * 100),
2542 (int) max_type, transfers[j].type,
2543 (int) max_local, transfers[j].local,
2544 (int) max_remote, transfers[j].remote);
2545
2546 if (arg_legend) {
2547 if (n_transfers > 0)
2548 printf("\n%zu transfers listed.\n", n_transfers);
2549 else
2550 printf("No transfers.\n");
2551 }
2552
2553 return 0;
2554 }
2555
2556 static int cancel_transfer(int argc, char *argv[], void *userdata) {
2557 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2558 sd_bus *bus = userdata;
2559 int r, i;
2560
2561 assert(bus);
2562
2563 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2564
2565 for (i = 1; i < argc; i++) {
2566 uint32_t id;
2567
2568 r = safe_atou32(argv[i], &id);
2569 if (r < 0)
2570 return log_error_errno(r, "Failed to parse transfer id: %s", argv[i]);
2571
2572 r = sd_bus_call_method(
2573 bus,
2574 "org.freedesktop.import1",
2575 "/org/freedesktop/import1",
2576 "org.freedesktop.import1.Manager",
2577 "CancelTransfer",
2578 &error,
2579 NULL,
2580 "u", id);
2581 if (r < 0)
2582 return log_error_errno(r, "Could not cancel transfer: %s", bus_error_message(&error, -r));
2583 }
2584
2585 return 0;
2586 }
2587
2588 static int set_limit(int argc, char *argv[], void *userdata) {
2589 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2590 sd_bus *bus = userdata;
2591 uint64_t limit;
2592 int r;
2593
2594 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2595
2596 if (STR_IN_SET(argv[argc-1], "-", "none", "infinity"))
2597 limit = (uint64_t) -1;
2598 else {
2599 r = parse_size(argv[argc-1], 1024, &limit);
2600 if (r < 0)
2601 return log_error_errno(r, "Failed to parse size: %s", argv[argc-1]);
2602 }
2603
2604 if (argc > 2)
2605 /* With two arguments changes the quota limit of the
2606 * specified image */
2607 r = sd_bus_call_method(
2608 bus,
2609 "org.freedesktop.machine1",
2610 "/org/freedesktop/machine1",
2611 "org.freedesktop.machine1.Manager",
2612 "SetImageLimit",
2613 &error,
2614 NULL,
2615 "st", argv[1], limit);
2616 else
2617 /* With one argument changes the pool quota limit */
2618 r = sd_bus_call_method(
2619 bus,
2620 "org.freedesktop.machine1",
2621 "/org/freedesktop/machine1",
2622 "org.freedesktop.machine1.Manager",
2623 "SetPoolLimit",
2624 &error,
2625 NULL,
2626 "t", limit);
2627
2628 if (r < 0)
2629 return log_error_errno(r, "Could not set limit: %s", bus_error_message(&error, r));
2630
2631 return 0;
2632 }
2633
2634 static int clean_images(int argc, char *argv[], void *userdata) {
2635 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
2636 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2637 uint64_t usage, total = 0;
2638 char fb[FORMAT_BYTES_MAX];
2639 sd_bus *bus = userdata;
2640 const char *name;
2641 unsigned c = 0;
2642 int r;
2643
2644 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2645
2646 r = sd_bus_message_new_method_call(
2647 bus,
2648 &m,
2649 "org.freedesktop.machine1",
2650 "/org/freedesktop/machine1",
2651 "org.freedesktop.machine1.Manager",
2652 "CleanPool");
2653 if (r < 0)
2654 return bus_log_create_error(r);
2655
2656 r = sd_bus_message_append(m, "s", arg_all ? "all" : "hidden");
2657 if (r < 0)
2658 return bus_log_create_error(r);
2659
2660 /* This is a slow operation, hence permit a longer time for completion. */
2661 r = sd_bus_call(bus, m, USEC_INFINITY, &error, &reply);
2662 if (r < 0)
2663 return log_error_errno(r, "Could not clean pool: %s", bus_error_message(&error, r));
2664
2665 r = sd_bus_message_enter_container(reply, 'a', "(st)");
2666 if (r < 0)
2667 return bus_log_parse_error(r);
2668
2669 while ((r = sd_bus_message_read(reply, "(st)", &name, &usage)) > 0) {
2670 log_info("Removed image '%s'. Freed exclusive disk space: %s",
2671 name, format_bytes(fb, sizeof(fb), usage));
2672
2673 total += usage;
2674 c++;
2675 }
2676
2677 r = sd_bus_message_exit_container(reply);
2678 if (r < 0)
2679 return bus_log_parse_error(r);
2680
2681 log_info("Removed %u images in total. Total freed exclusive disk space %s.",
2682 c, format_bytes(fb, sizeof(fb), total));
2683
2684 return 0;
2685 }
2686
2687 static int help(int argc, char *argv[], void *userdata) {
2688 _cleanup_free_ char *link = NULL;
2689 int r;
2690
2691 (void) pager_open(arg_pager_flags);
2692
2693 r = terminal_urlify_man("machinectl", "1", &link);
2694 if (r < 0)
2695 return log_oom();
2696
2697 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
2698 "Send control commands to or query the virtual machine and container\n"
2699 "registration manager.\n\n"
2700 " -h --help Show this help\n"
2701 " --version Show package version\n"
2702 " --no-pager Do not pipe output into a pager\n"
2703 " --no-legend Do not show the headers and footers\n"
2704 " --no-ask-password Do not ask for system passwords\n"
2705 " -H --host=[USER@]HOST Operate on remote host\n"
2706 " -M --machine=CONTAINER Operate on local container\n"
2707 " -p --property=NAME Show only properties by this name\n"
2708 " -q --quiet Suppress output\n"
2709 " -a --all Show all properties, including empty ones\n"
2710 " --value When showing properties, only print the value\n"
2711 " -l --full Do not ellipsize output\n"
2712 " --kill-who=WHO Who to send signal to\n"
2713 " -s --signal=SIGNAL Which signal to send\n"
2714 " --uid=USER Specify user ID to invoke shell as\n"
2715 " -E --setenv=VAR=VALUE Add an environment variable for shell\n"
2716 " --read-only Create read-only bind mount\n"
2717 " --mkdir Create directory before bind mounting, if missing\n"
2718 " -n --lines=INTEGER Number of journal entries to show\n"
2719 " --max-addresses=INTEGER Number of internet addresses to show at most\n"
2720 " -o --output=STRING Change journal output mode (short, short-precise,\n"
2721 " short-iso, short-iso-precise, short-full,\n"
2722 " short-monotonic, short-unix, verbose, export,\n"
2723 " json, json-pretty, json-sse, json-seq, cat,\n"
2724 " with-unit)\n"
2725 " --verify=MODE Verification mode for downloaded images (no,\n"
2726 " checksum, signature)\n"
2727 " --force Download image even if already exists\n\n"
2728 "Machine Commands:\n"
2729 " list List running VMs and containers\n"
2730 " status NAME... Show VM/container details\n"
2731 " show [NAME...] Show properties of one or more VMs/containers\n"
2732 " start NAME... Start container as a service\n"
2733 " login [NAME] Get a login prompt in a container or on the\n"
2734 " local host\n"
2735 " shell [[USER@]NAME [COMMAND...]]\n"
2736 " Invoke a shell (or other command) in a container\n"
2737 " or on the local host\n"
2738 " enable NAME... Enable automatic container start at boot\n"
2739 " disable NAME... Disable automatic container start at boot\n"
2740 " poweroff NAME... Power off one or more containers\n"
2741 " reboot NAME... Reboot one or more containers\n"
2742 " terminate NAME... Terminate one or more VMs/containers\n"
2743 " kill NAME... Send signal to processes of a VM/container\n"
2744 " copy-to NAME PATH [PATH] Copy files from the host to a container\n"
2745 " copy-from NAME PATH [PATH] Copy files from a container to the host\n"
2746 " bind NAME PATH [PATH] Bind mount a path from the host into a container\n\n"
2747 "Image Commands:\n"
2748 " list-images Show available container and VM images\n"
2749 " image-status [NAME...] Show image details\n"
2750 " show-image [NAME...] Show properties of image\n"
2751 " clone NAME NAME Clone an image\n"
2752 " rename NAME NAME Rename an image\n"
2753 " read-only NAME [BOOL] Mark or unmark image read-only\n"
2754 " remove NAME... Remove an image\n"
2755 " set-limit [NAME] BYTES Set image or pool size limit (disk quota)\n"
2756 " clean Remove hidden (or all) images\n\n"
2757 "Image Transfer Commands:\n"
2758 " pull-tar URL [NAME] Download a TAR container image\n"
2759 " pull-raw URL [NAME] Download a RAW container or VM image\n"
2760 " import-tar FILE [NAME] Import a local TAR container image\n"
2761 " import-raw FILE [NAME] Import a local RAW container or VM image\n"
2762 " import-fs DIRECTORY [NAME] Import a local directory container image\n"
2763 " export-tar NAME [FILE] Export a TAR container image locally\n"
2764 " export-raw NAME [FILE] Export a RAW container or VM image locally\n"
2765 " list-transfers Show list of downloads in progress\n"
2766 " cancel-transfer Cancel a download\n"
2767 "\nSee the %s for details.\n"
2768 , program_invocation_short_name
2769 , link
2770 );
2771
2772 return 0;
2773 }
2774
2775 static int parse_argv(int argc, char *argv[]) {
2776
2777 enum {
2778 ARG_VERSION = 0x100,
2779 ARG_NO_PAGER,
2780 ARG_NO_LEGEND,
2781 ARG_VALUE,
2782 ARG_KILL_WHO,
2783 ARG_READ_ONLY,
2784 ARG_MKDIR,
2785 ARG_NO_ASK_PASSWORD,
2786 ARG_VERIFY,
2787 ARG_FORCE,
2788 ARG_FORMAT,
2789 ARG_UID,
2790 ARG_NUMBER_IPS,
2791 };
2792
2793 static const struct option options[] = {
2794 { "help", no_argument, NULL, 'h' },
2795 { "version", no_argument, NULL, ARG_VERSION },
2796 { "property", required_argument, NULL, 'p' },
2797 { "all", no_argument, NULL, 'a' },
2798 { "value", no_argument, NULL, ARG_VALUE },
2799 { "full", no_argument, NULL, 'l' },
2800 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
2801 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
2802 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
2803 { "signal", required_argument, NULL, 's' },
2804 { "host", required_argument, NULL, 'H' },
2805 { "machine", required_argument, NULL, 'M' },
2806 { "read-only", no_argument, NULL, ARG_READ_ONLY },
2807 { "mkdir", no_argument, NULL, ARG_MKDIR },
2808 { "quiet", no_argument, NULL, 'q' },
2809 { "lines", required_argument, NULL, 'n' },
2810 { "output", required_argument, NULL, 'o' },
2811 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
2812 { "verify", required_argument, NULL, ARG_VERIFY },
2813 { "force", no_argument, NULL, ARG_FORCE },
2814 { "format", required_argument, NULL, ARG_FORMAT },
2815 { "uid", required_argument, NULL, ARG_UID },
2816 { "setenv", required_argument, NULL, 'E' },
2817 { "max-addresses", required_argument, NULL, ARG_NUMBER_IPS },
2818 {}
2819 };
2820
2821 bool reorder = false;
2822 int c, r, shell = -1;
2823
2824 assert(argc >= 0);
2825 assert(argv);
2826
2827 for (;;) {
2828 static const char option_string[] = "-hp:als:H:M:qn:o:E:";
2829
2830 c = getopt_long(argc, argv, option_string + reorder, options, NULL);
2831 if (c < 0)
2832 break;
2833
2834 switch (c) {
2835
2836 case 1: /* getopt_long() returns 1 if "-" was the first character of the option string, and a
2837 * non-option argument was discovered. */
2838
2839 assert(!reorder);
2840
2841 /* We generally are fine with the fact that getopt_long() reorders the command line, and looks
2842 * for switches after the main verb. However, for "shell" we really don't want that, since we
2843 * want that switches specified after the machine name are passed to the program to execute,
2844 * and not processed by us. To make this possible, we'll first invoke getopt_long() with
2845 * reordering disabled (i.e. with the "-" prefix in the option string), looking for the first
2846 * non-option parameter. If it's the verb "shell" we remember its position and continue
2847 * processing options. In this case, as soon as we hit the next non-option argument we found
2848 * the machine name, and stop further processing. If the first non-option argument is any other
2849 * verb than "shell" we switch to normal reordering mode and continue processing arguments
2850 * normally. */
2851
2852 if (shell >= 0) {
2853 /* If we already found the "shell" verb on the command line, and now found the next
2854 * non-option argument, then this is the machine name and we should stop processing
2855 * further arguments. */
2856 optind --; /* don't process this argument, go one step back */
2857 goto done;
2858 }
2859 if (streq(optarg, "shell"))
2860 /* Remember the position of the "shell" verb, and continue processing normally. */
2861 shell = optind - 1;
2862 else {
2863 int saved_optind;
2864
2865 /* OK, this is some other verb. In this case, turn on reordering again, and continue
2866 * processing normally. */
2867 reorder = true;
2868
2869 /* We changed the option string. getopt_long() only looks at it again if we invoke it
2870 * at least once with a reset option index. Hence, let's reset the option index here,
2871 * then invoke getopt_long() again (ignoring what it has to say, after all we most
2872 * likely already processed it), and the bump the option index so that we read the
2873 * intended argument again. */
2874 saved_optind = optind;
2875 optind = 0;
2876 (void) getopt_long(argc, argv, option_string + reorder, options, NULL);
2877 optind = saved_optind - 1; /* go one step back, process this argument again */
2878 }
2879
2880 break;
2881
2882 case 'h':
2883 return help(0, NULL, NULL);
2884
2885 case ARG_VERSION:
2886 return version();
2887
2888 case 'p':
2889 r = strv_extend(&arg_property, optarg);
2890 if (r < 0)
2891 return log_oom();
2892
2893 /* If the user asked for a particular
2894 * property, show it to him, even if it is
2895 * empty. */
2896 arg_all = true;
2897 break;
2898
2899 case 'a':
2900 arg_all = true;
2901 break;
2902
2903 case ARG_VALUE:
2904 arg_value = true;
2905 break;
2906
2907 case 'l':
2908 arg_full = true;
2909 break;
2910
2911 case 'n':
2912 if (safe_atou(optarg, &arg_lines) < 0)
2913 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2914 "Failed to parse lines '%s'", optarg);
2915 break;
2916
2917 case 'o':
2918 if (streq(optarg, "help")) {
2919 DUMP_STRING_TABLE(output_mode, OutputMode, _OUTPUT_MODE_MAX);
2920 return 0;
2921 }
2922
2923 arg_output = output_mode_from_string(optarg);
2924 if (arg_output < 0)
2925 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2926 "Unknown output '%s'.", optarg);
2927
2928 if (OUTPUT_MODE_IS_JSON(arg_output))
2929 arg_legend = false;
2930 break;
2931
2932 case ARG_NO_PAGER:
2933 arg_pager_flags |= PAGER_DISABLE;
2934 break;
2935
2936 case ARG_NO_LEGEND:
2937 arg_legend = false;
2938 break;
2939
2940 case ARG_KILL_WHO:
2941 arg_kill_who = optarg;
2942 break;
2943
2944 case 's':
2945 if (streq(optarg, "help")) {
2946 DUMP_STRING_TABLE(signal, int, _NSIG);
2947 return 0;
2948 }
2949
2950 arg_signal = signal_from_string(optarg);
2951 if (arg_signal < 0)
2952 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2953 "Failed to parse signal string %s.", optarg);
2954 break;
2955
2956 case ARG_NO_ASK_PASSWORD:
2957 arg_ask_password = false;
2958 break;
2959
2960 case 'H':
2961 arg_transport = BUS_TRANSPORT_REMOTE;
2962 arg_host = optarg;
2963 break;
2964
2965 case 'M':
2966 arg_transport = BUS_TRANSPORT_MACHINE;
2967 arg_host = optarg;
2968 break;
2969
2970 case ARG_READ_ONLY:
2971 arg_read_only = true;
2972 break;
2973
2974 case ARG_MKDIR:
2975 arg_mkdir = true;
2976 break;
2977
2978 case 'q':
2979 arg_quiet = true;
2980 break;
2981
2982 case ARG_VERIFY:
2983 if (streq(optarg, "help")) {
2984 DUMP_STRING_TABLE(import_verify, ImportVerify, _IMPORT_VERIFY_MAX);
2985 return 0;
2986 }
2987
2988 arg_verify = import_verify_from_string(optarg);
2989 if (arg_verify < 0)
2990 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2991 "Failed to parse --verify= setting: %s", optarg);
2992 break;
2993
2994 case ARG_FORCE:
2995 arg_force = true;
2996 break;
2997
2998 case ARG_FORMAT:
2999 if (!STR_IN_SET(optarg, "uncompressed", "xz", "gzip", "bzip2"))
3000 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3001 "Unknown format: %s", optarg);
3002
3003 arg_format = optarg;
3004 break;
3005
3006 case ARG_UID:
3007 arg_uid = optarg;
3008 break;
3009
3010 case 'E':
3011 if (!env_assignment_is_valid(optarg))
3012 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3013 "Environment assignment invalid: %s", optarg);
3014
3015 r = strv_extend(&arg_setenv, optarg);
3016 if (r < 0)
3017 return log_oom();
3018 break;
3019
3020 case ARG_NUMBER_IPS:
3021 if (streq(optarg, "all"))
3022 arg_addrs = ALL_IP_ADDRESSES;
3023 else if (safe_atoi(optarg, &arg_addrs) < 0)
3024 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3025 "Invalid number of IPs");
3026 else if (arg_addrs < 0)
3027 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3028 "Number of IPs cannot be negative");
3029 break;
3030
3031 case '?':
3032 return -EINVAL;
3033
3034 default:
3035 assert_not_reached("Unhandled option");
3036 }
3037 }
3038
3039 done:
3040 if (shell >= 0) {
3041 char *t;
3042 int i;
3043
3044 /* We found the "shell" verb while processing the argument list. Since we turned off reordering of the
3045 * argument list initially let's readjust it now, and move the "shell" verb to the back. */
3046
3047 optind -= 1; /* place the option index where the "shell" verb will be placed */
3048
3049 t = argv[shell];
3050 for (i = shell; i < optind; i++)
3051 argv[i] = argv[i+1];
3052 argv[optind] = t;
3053 }
3054
3055 return 1;
3056 }
3057
3058 static int machinectl_main(int argc, char *argv[], sd_bus *bus) {
3059
3060 static const Verb verbs[] = {
3061 { "help", VERB_ANY, VERB_ANY, 0, help },
3062 { "list", VERB_ANY, 1, VERB_DEFAULT, list_machines },
3063 { "list-images", VERB_ANY, 1, 0, list_images },
3064 { "status", 2, VERB_ANY, 0, show_machine },
3065 { "image-status", VERB_ANY, VERB_ANY, 0, show_image },
3066 { "show", VERB_ANY, VERB_ANY, 0, show_machine },
3067 { "show-image", VERB_ANY, VERB_ANY, 0, show_image },
3068 { "terminate", 2, VERB_ANY, 0, terminate_machine },
3069 { "reboot", 2, VERB_ANY, 0, reboot_machine },
3070 { "poweroff", 2, VERB_ANY, 0, poweroff_machine },
3071 { "stop", 2, VERB_ANY, 0, poweroff_machine }, /* Convenience alias */
3072 { "kill", 2, VERB_ANY, 0, kill_machine },
3073 { "login", VERB_ANY, 2, 0, login_machine },
3074 { "shell", VERB_ANY, VERB_ANY, 0, shell_machine },
3075 { "bind", 3, 4, 0, bind_mount },
3076 { "copy-to", 3, 4, 0, copy_files },
3077 { "copy-from", 3, 4, 0, copy_files },
3078 { "remove", 2, VERB_ANY, 0, remove_image },
3079 { "rename", 3, 3, 0, rename_image },
3080 { "clone", 3, 3, 0, clone_image },
3081 { "read-only", 2, 3, 0, read_only_image },
3082 { "start", 2, VERB_ANY, 0, start_machine },
3083 { "enable", 2, VERB_ANY, 0, enable_machine },
3084 { "disable", 2, VERB_ANY, 0, enable_machine },
3085 { "import-tar", 2, 3, 0, import_tar },
3086 { "import-raw", 2, 3, 0, import_raw },
3087 { "import-fs", 2, 3, 0, import_fs },
3088 { "export-tar", 2, 3, 0, export_tar },
3089 { "export-raw", 2, 3, 0, export_raw },
3090 { "pull-tar", 2, 3, 0, pull_tar },
3091 { "pull-raw", 2, 3, 0, pull_raw },
3092 { "list-transfers", VERB_ANY, 1, 0, list_transfers },
3093 { "cancel-transfer", 2, VERB_ANY, 0, cancel_transfer },
3094 { "set-limit", 2, 3, 0, set_limit },
3095 { "clean", VERB_ANY, 1, 0, clean_images },
3096 {}
3097 };
3098
3099 return dispatch_verb(argc, argv, verbs, bus);
3100 }
3101
3102 static int run(int argc, char *argv[]) {
3103 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
3104 int r;
3105
3106 setlocale(LC_ALL, "");
3107 log_parse_environment();
3108 log_open();
3109
3110 /* The journal merging logic potentially needs a lot of fds. */
3111 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
3112
3113 sigbus_install();
3114
3115 r = parse_argv(argc, argv);
3116 if (r <= 0)
3117 return r;
3118
3119 r = bus_connect_transport(arg_transport, arg_host, false, &bus);
3120 if (r < 0)
3121 return log_error_errno(r, "Failed to create bus connection: %m");
3122
3123 (void) sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);
3124
3125 return machinectl_main(argc, argv, bus);
3126 }
3127
3128 DEFINE_MAIN_FUNCTION(run);