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