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