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