]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/machine/machinectl.c
Merge pull request #25608 from poettering/dissect-moar
[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) get_process_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
691 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
692 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
693 bool properties, new_line = false;
694 sd_bus *bus = ASSERT_PTR(userdata);
695 int r = 0;
696
697 properties = !strstr(argv[0], "status");
698
699 pager_open(arg_pager_flags);
700
701 if (properties && argc <= 1) {
702
703 /* If no argument is specified, inspect the manager
704 * itself */
705 r = show_machine_properties(bus, "/org/freedesktop/machine1", &new_line);
706 if (r < 0)
707 return r;
708 }
709
710 for (int i = 1; i < argc; i++) {
711 const char *path = NULL;
712
713 r = bus_call_method(bus, bus_machine_mgr, "GetMachine", &error, &reply, "s", argv[i]);
714 if (r < 0)
715 return log_error_errno(r, "Could not get path to machine: %s", bus_error_message(&error, r));
716
717 r = sd_bus_message_read(reply, "o", &path);
718 if (r < 0)
719 return bus_log_parse_error(r);
720
721 if (properties)
722 r = show_machine_properties(bus, path, &new_line);
723 else
724 r = show_machine_info(argv[0], bus, path, &new_line);
725 }
726
727 return r;
728 }
729
730 static int print_image_hostname(sd_bus *bus, const char *name) {
731 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
732 const char *hn;
733 int r;
734
735 r = bus_call_method(bus, bus_machine_mgr, "GetImageHostname", NULL, &reply, "s", name);
736 if (r < 0)
737 return r;
738
739 r = sd_bus_message_read(reply, "s", &hn);
740 if (r < 0)
741 return r;
742
743 if (!isempty(hn))
744 printf("\tHostname: %s\n", hn);
745
746 return 0;
747 }
748
749 static int print_image_machine_id(sd_bus *bus, const char *name) {
750 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
751 sd_id128_t id = SD_ID128_NULL;
752 const void *p;
753 size_t size;
754 int r;
755
756 r = bus_call_method(bus, bus_machine_mgr, "GetImageMachineID", NULL, &reply, "s", name);
757 if (r < 0)
758 return r;
759
760 r = sd_bus_message_read_array(reply, 'y', &p, &size);
761 if (r < 0)
762 return r;
763
764 if (size == sizeof(sd_id128_t))
765 memcpy(&id, p, size);
766
767 if (!sd_id128_is_null(id))
768 printf(" Machine ID: " SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(id));
769
770 return 0;
771 }
772
773 static int print_image_machine_info(sd_bus *bus, const char *name) {
774 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
775 int r;
776
777 r = bus_call_method(bus, bus_machine_mgr, "GetImageMachineInfo", NULL, &reply, "s", name);
778 if (r < 0)
779 return r;
780
781 r = sd_bus_message_enter_container(reply, 'a', "{ss}");
782 if (r < 0)
783 return r;
784
785 for (;;) {
786 const char *p, *q;
787
788 r = sd_bus_message_read(reply, "{ss}", &p, &q);
789 if (r < 0)
790 return r;
791 if (r == 0)
792 break;
793
794 if (streq(p, "DEPLOYMENT"))
795 printf(" Deployment: %s\n", q);
796 }
797
798 r = sd_bus_message_exit_container(reply);
799 if (r < 0)
800 return r;
801
802 return 0;
803 }
804
805 typedef struct ImageStatusInfo {
806 const char *name;
807 const char *path;
808 const char *type;
809 bool read_only;
810 usec_t crtime;
811 usec_t mtime;
812 uint64_t usage;
813 uint64_t limit;
814 uint64_t usage_exclusive;
815 uint64_t limit_exclusive;
816 } ImageStatusInfo;
817
818 static void print_image_status_info(sd_bus *bus, ImageStatusInfo *i) {
819 assert(bus);
820 assert(i);
821
822 if (i->name) {
823 fputs(i->name, stdout);
824 putchar('\n');
825 }
826
827 if (i->type)
828 printf("\t Type: %s\n", i->type);
829
830 if (i->path)
831 printf("\t Path: %s\n", i->path);
832
833 (void) print_image_hostname(bus, i->name);
834 (void) print_image_machine_id(bus, i->name);
835 (void) print_image_machine_info(bus, i->name);
836
837 print_os_release(bus, "GetImageOSRelease", i->name, "\t OS: ");
838
839 printf("\t RO: %s%s%s\n",
840 i->read_only ? ansi_highlight_red() : "",
841 i->read_only ? "read-only" : "writable",
842 i->read_only ? ansi_normal() : "");
843
844 if (timestamp_is_set(i->crtime))
845 printf("\t Created: %s; %s\n",
846 FORMAT_TIMESTAMP(i->crtime), FORMAT_TIMESTAMP_RELATIVE(i->crtime));
847
848 if (timestamp_is_set(i->mtime))
849 printf("\tModified: %s; %s\n",
850 FORMAT_TIMESTAMP(i->mtime), FORMAT_TIMESTAMP_RELATIVE(i->mtime));
851
852 if (i->usage != UINT64_MAX) {
853 if (i->usage_exclusive != i->usage && i->usage_exclusive != UINT64_MAX)
854 printf("\t Usage: %s (exclusive: %s)\n",
855 FORMAT_BYTES(i->usage), FORMAT_BYTES(i->usage_exclusive));
856 else
857 printf("\t Usage: %s\n", FORMAT_BYTES(i->usage));
858 }
859
860 if (i->limit != UINT64_MAX) {
861 if (i->limit_exclusive != i->limit && i->limit_exclusive != UINT64_MAX)
862 printf("\t Limit: %s (exclusive: %s)\n",
863 FORMAT_BYTES(i->limit), FORMAT_BYTES(i->limit_exclusive));
864 else
865 printf("\t Limit: %s\n", FORMAT_BYTES(i->limit));
866 }
867 }
868
869 static int show_image_info(sd_bus *bus, const char *path, bool *new_line) {
870
871 static const struct bus_properties_map map[] = {
872 { "Name", "s", NULL, offsetof(ImageStatusInfo, name) },
873 { "Path", "s", NULL, offsetof(ImageStatusInfo, path) },
874 { "Type", "s", NULL, offsetof(ImageStatusInfo, type) },
875 { "ReadOnly", "b", NULL, offsetof(ImageStatusInfo, read_only) },
876 { "CreationTimestamp", "t", NULL, offsetof(ImageStatusInfo, crtime) },
877 { "ModificationTimestamp", "t", NULL, offsetof(ImageStatusInfo, mtime) },
878 { "Usage", "t", NULL, offsetof(ImageStatusInfo, usage) },
879 { "Limit", "t", NULL, offsetof(ImageStatusInfo, limit) },
880 { "UsageExclusive", "t", NULL, offsetof(ImageStatusInfo, usage_exclusive) },
881 { "LimitExclusive", "t", NULL, offsetof(ImageStatusInfo, limit_exclusive) },
882 {}
883 };
884
885 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
886 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
887 ImageStatusInfo info = {};
888 int r;
889
890 assert(bus);
891 assert(path);
892 assert(new_line);
893
894 r = bus_map_all_properties(bus,
895 "org.freedesktop.machine1",
896 path,
897 map,
898 BUS_MAP_BOOLEAN_AS_BOOL,
899 &error,
900 &m,
901 &info);
902 if (r < 0)
903 return log_error_errno(r, "Could not get properties: %s", bus_error_message(&error, r));
904
905 if (*new_line)
906 printf("\n");
907 *new_line = true;
908
909 print_image_status_info(bus, &info);
910
911 return r;
912 }
913
914 typedef struct PoolStatusInfo {
915 const char *path;
916 uint64_t usage;
917 uint64_t limit;
918 } PoolStatusInfo;
919
920 static void print_pool_status_info(sd_bus *bus, PoolStatusInfo *i) {
921 if (i->path)
922 printf("\t Path: %s\n", i->path);
923
924 if (i->usage != UINT64_MAX)
925 printf("\t Usage: %s\n", FORMAT_BYTES(i->usage));
926
927 if (i->limit != UINT64_MAX)
928 printf("\t Limit: %s\n", FORMAT_BYTES(i->limit));
929 }
930
931 static int show_pool_info(sd_bus *bus) {
932
933 static const struct bus_properties_map map[] = {
934 { "PoolPath", "s", NULL, offsetof(PoolStatusInfo, path) },
935 { "PoolUsage", "t", NULL, offsetof(PoolStatusInfo, usage) },
936 { "PoolLimit", "t", NULL, offsetof(PoolStatusInfo, limit) },
937 {}
938 };
939
940 PoolStatusInfo info = {
941 .usage = UINT64_MAX,
942 .limit = UINT64_MAX,
943 };
944
945 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
946 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
947 int r;
948
949 assert(bus);
950
951 r = bus_map_all_properties(bus,
952 "org.freedesktop.machine1",
953 "/org/freedesktop/machine1",
954 map,
955 0,
956 &error,
957 &m,
958 &info);
959 if (r < 0)
960 return log_error_errno(r, "Could not get properties: %s", bus_error_message(&error, r));
961
962 print_pool_status_info(bus, &info);
963
964 return 0;
965 }
966
967 static int show_image_properties(sd_bus *bus, const char *path, bool *new_line) {
968 int r;
969
970 assert(bus);
971 assert(path);
972 assert(new_line);
973
974 if (*new_line)
975 printf("\n");
976
977 *new_line = true;
978
979 r = bus_print_all_properties(bus, "org.freedesktop.machine1", path, NULL, arg_property, arg_print_flags, NULL);
980 if (r < 0)
981 log_error_errno(r, "Could not get properties: %m");
982
983 return r;
984 }
985
986 static int show_image(int argc, char *argv[], void *userdata) {
987
988 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
989 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
990 bool properties, new_line = false;
991 sd_bus *bus = ASSERT_PTR(userdata);
992 int r = 0;
993
994 properties = !strstr(argv[0], "status");
995
996 pager_open(arg_pager_flags);
997
998 if (argc <= 1) {
999
1000 /* If no argument is specified, inspect the manager
1001 * itself */
1002
1003 if (properties)
1004 r = show_image_properties(bus, "/org/freedesktop/machine1", &new_line);
1005 else
1006 r = show_pool_info(bus);
1007 if (r < 0)
1008 return r;
1009 }
1010
1011 for (int i = 1; i < argc; i++) {
1012 const char *path = NULL;
1013
1014 r = bus_call_method(bus, bus_machine_mgr, "GetImage", &error, &reply, "s", argv[i]);
1015 if (r < 0)
1016 return log_error_errno(r, "Could not get path to image: %s", bus_error_message(&error, r));
1017
1018 r = sd_bus_message_read(reply, "o", &path);
1019 if (r < 0)
1020 return bus_log_parse_error(r);
1021
1022 if (properties)
1023 r = show_image_properties(bus, path, &new_line);
1024 else
1025 r = show_image_info(bus, path, &new_line);
1026 }
1027
1028 return r;
1029 }
1030
1031 static int kill_machine(int argc, char *argv[], void *userdata) {
1032 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1033 sd_bus *bus = ASSERT_PTR(userdata);
1034 int r;
1035
1036 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1037
1038 if (!arg_kill_whom)
1039 arg_kill_whom = "all";
1040
1041 for (int i = 1; i < argc; i++) {
1042 r = bus_call_method(
1043 bus,
1044 bus_machine_mgr,
1045 "KillMachine",
1046 &error,
1047 NULL,
1048 "ssi", argv[i], arg_kill_whom, arg_signal);
1049 if (r < 0)
1050 return log_error_errno(r, "Could not kill machine: %s", bus_error_message(&error, r));
1051 }
1052
1053 return 0;
1054 }
1055
1056 static int reboot_machine(int argc, char *argv[], void *userdata) {
1057 arg_kill_whom = "leader";
1058 arg_signal = SIGINT; /* sysvinit + systemd */
1059
1060 return kill_machine(argc, argv, userdata);
1061 }
1062
1063 static int poweroff_machine(int argc, char *argv[], void *userdata) {
1064 arg_kill_whom = "leader";
1065 arg_signal = SIGRTMIN+4; /* only systemd */
1066
1067 return kill_machine(argc, argv, userdata);
1068 }
1069
1070 static int terminate_machine(int argc, char *argv[], void *userdata) {
1071 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1072 sd_bus *bus = ASSERT_PTR(userdata);
1073 int r;
1074
1075 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1076
1077 for (int i = 1; i < argc; i++) {
1078 r = bus_call_method(bus, bus_machine_mgr, "TerminateMachine", &error, NULL, "s", argv[i]);
1079 if (r < 0)
1080 return log_error_errno(r, "Could not terminate machine: %s", bus_error_message(&error, r));
1081 }
1082
1083 return 0;
1084 }
1085
1086 static const char *select_copy_method(bool copy_from, bool force) {
1087 if (force)
1088 return copy_from ? "CopyFromMachineWithFlags" : "CopyToMachineWithFlags";
1089 else
1090 return copy_from ? "CopyFromMachine" : "CopyToMachine";
1091 }
1092
1093 static int copy_files(int argc, char *argv[], void *userdata) {
1094 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1095 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1096 _cleanup_free_ char *abs_host_path = NULL;
1097 char *dest, *host_path, *container_path;
1098 sd_bus *bus = ASSERT_PTR(userdata);
1099 bool copy_from;
1100 int r;
1101
1102 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1103
1104 copy_from = streq(argv[0], "copy-from");
1105 dest = argv[3] ?: argv[2];
1106 host_path = copy_from ? dest : argv[2];
1107 container_path = copy_from ? argv[2] : dest;
1108
1109 if (!path_is_absolute(host_path)) {
1110 r = path_make_absolute_cwd(host_path, &abs_host_path);
1111 if (r < 0)
1112 return log_error_errno(r, "Failed to make path absolute: %m");
1113
1114 host_path = abs_host_path;
1115 }
1116
1117 r = bus_message_new_method_call(
1118 bus,
1119 &m,
1120 bus_machine_mgr,
1121 select_copy_method(copy_from, arg_force));
1122 if (r < 0)
1123 return bus_log_create_error(r);
1124
1125 r = sd_bus_message_append(
1126 m,
1127 "sss",
1128 argv[1],
1129 copy_from ? container_path : host_path,
1130 copy_from ? host_path : container_path);
1131 if (r < 0)
1132 return bus_log_create_error(r);
1133
1134 if (arg_force) {
1135 r = sd_bus_message_append(m, "t", MACHINE_COPY_REPLACE);
1136 if (r < 0)
1137 return bus_log_create_error(r);
1138 }
1139
1140 /* This is a slow operation, hence turn off any method call timeouts */
1141 r = sd_bus_call(bus, m, USEC_INFINITY, &error, NULL);
1142 if (r < 0)
1143 return log_error_errno(r, "Failed to copy: %s", bus_error_message(&error, r));
1144
1145 return 0;
1146 }
1147
1148 static int bind_mount(int argc, char *argv[], void *userdata) {
1149 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1150 sd_bus *bus = ASSERT_PTR(userdata);
1151 int r;
1152
1153 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1154
1155 r = bus_call_method(
1156 bus,
1157 bus_machine_mgr,
1158 "BindMountMachine",
1159 &error,
1160 NULL,
1161 "sssbb",
1162 argv[1],
1163 argv[2],
1164 argv[3],
1165 arg_read_only,
1166 arg_mkdir);
1167 if (r < 0)
1168 return log_error_errno(r, "Failed to bind mount: %s", bus_error_message(&error, r));
1169
1170 return 0;
1171 }
1172
1173 static int on_machine_removed(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1174 PTYForward ** forward = (PTYForward**) userdata;
1175 int r;
1176
1177 assert(m);
1178 assert(forward);
1179
1180 if (*forward) {
1181 /* If the forwarder is already initialized, tell it to
1182 * exit on the next vhangup(), so that we still flush
1183 * out what might be queued and exit then. */
1184
1185 r = pty_forward_set_ignore_vhangup(*forward, false);
1186 if (r >= 0)
1187 return 0;
1188
1189 log_error_errno(r, "Failed to set ignore_vhangup flag: %m");
1190 }
1191
1192 /* On error, or when the forwarder is not initialized yet, quit immediately */
1193 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), EXIT_FAILURE);
1194 return 0;
1195 }
1196
1197 static int process_forward(sd_event *event, PTYForward **forward, int master, PTYForwardFlags flags, const char *name) {
1198 char last_char = 0;
1199 bool machine_died;
1200 int r;
1201
1202 assert(event);
1203 assert(master >= 0);
1204 assert(name);
1205
1206 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGWINCH, SIGTERM, SIGINT, -1) >= 0);
1207
1208 if (!arg_quiet) {
1209 if (streq(name, ".host"))
1210 log_info("Connected to the local host. Press ^] three times within 1s to exit session.");
1211 else
1212 log_info("Connected to machine %s. Press ^] three times within 1s to exit session.", name);
1213 }
1214
1215 (void) sd_event_add_signal(event, NULL, SIGINT, NULL, NULL);
1216 (void) sd_event_add_signal(event, NULL, SIGTERM, NULL, NULL);
1217
1218 r = pty_forward_new(event, master, flags, forward);
1219 if (r < 0)
1220 return log_error_errno(r, "Failed to create PTY forwarder: %m");
1221
1222 r = sd_event_loop(event);
1223 if (r < 0)
1224 return log_error_errno(r, "Failed to run event loop: %m");
1225
1226 pty_forward_get_last_char(*forward, &last_char);
1227
1228 machine_died =
1229 (flags & PTY_FORWARD_IGNORE_VHANGUP) &&
1230 pty_forward_get_ignore_vhangup(*forward) == 0;
1231
1232 *forward = pty_forward_free(*forward);
1233
1234 if (last_char != '\n')
1235 fputc('\n', stdout);
1236
1237 if (!arg_quiet) {
1238 if (machine_died)
1239 log_info("Machine %s terminated.", name);
1240 else if (streq(name, ".host"))
1241 log_info("Connection to the local host terminated.");
1242 else
1243 log_info("Connection to machine %s terminated.", name);
1244 }
1245
1246 return 0;
1247 }
1248
1249 static int parse_machine_uid(const char *spec, const char **machine, char **uid) {
1250 /*
1251 * Whatever is specified in the spec takes priority over global arguments.
1252 */
1253 char *_uid = NULL;
1254 const char *_machine = NULL;
1255
1256 if (spec) {
1257 const char *at;
1258
1259 at = strchr(spec, '@');
1260 if (at) {
1261 if (at == spec)
1262 /* Do the same as ssh and refuse "@host". */
1263 return -EINVAL;
1264
1265 _machine = at + 1;
1266 _uid = strndup(spec, at - spec);
1267 if (!_uid)
1268 return -ENOMEM;
1269 } else
1270 _machine = spec;
1271 };
1272
1273 if (arg_uid && !_uid) {
1274 _uid = strdup(arg_uid);
1275 if (!_uid)
1276 return -ENOMEM;
1277 }
1278
1279 *uid = _uid;
1280 *machine = isempty(_machine) ? ".host" : _machine;
1281 return 0;
1282 }
1283
1284 static int login_machine(int argc, char *argv[], void *userdata) {
1285 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1286 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1287 _cleanup_(pty_forward_freep) PTYForward *forward = NULL;
1288 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1289 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1290 int master = -1, r;
1291 sd_bus *bus = ASSERT_PTR(userdata);
1292 const char *match, *machine;
1293
1294 if (!strv_isempty(arg_setenv) || arg_uid)
1295 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1296 "--setenv= and --uid= are not supported for 'login'. Use 'shell' instead.");
1297
1298 if (!IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_MACHINE))
1299 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1300 "Login only supported on local machines.");
1301
1302 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1303
1304 r = sd_event_default(&event);
1305 if (r < 0)
1306 return log_error_errno(r, "Failed to get event loop: %m");
1307
1308 r = sd_bus_attach_event(bus, event, 0);
1309 if (r < 0)
1310 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1311
1312 machine = argc < 2 || isempty(argv[1]) ? ".host" : argv[1];
1313
1314 match = strjoina("type='signal',"
1315 "sender='org.freedesktop.machine1',"
1316 "path='/org/freedesktop/machine1',",
1317 "interface='org.freedesktop.machine1.Manager',"
1318 "member='MachineRemoved',"
1319 "arg0='", machine, "'");
1320
1321 r = sd_bus_add_match_async(bus, &slot, match, on_machine_removed, NULL, &forward);
1322 if (r < 0)
1323 return log_error_errno(r, "Failed to request machine removal match: %m");
1324
1325 r = bus_call_method(bus, bus_machine_mgr, "OpenMachineLogin", &error, &reply, "s", machine);
1326 if (r < 0)
1327 return log_error_errno(r, "Failed to get login PTY: %s", bus_error_message(&error, r));
1328
1329 r = sd_bus_message_read(reply, "hs", &master, NULL);
1330 if (r < 0)
1331 return bus_log_parse_error(r);
1332
1333 return process_forward(event, &forward, master, PTY_FORWARD_IGNORE_VHANGUP, machine);
1334 }
1335
1336 static int shell_machine(int argc, char *argv[], void *userdata) {
1337 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
1338 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1339 _cleanup_(pty_forward_freep) PTYForward *forward = NULL;
1340 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1341 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1342 int master = -1, r;
1343 sd_bus *bus = ASSERT_PTR(userdata);
1344 const char *match, *machine, *path;
1345 _cleanup_free_ char *uid = NULL;
1346
1347 if (!IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_MACHINE))
1348 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1349 "Shell only supported on local machines.");
1350
1351 /* Pass $TERM to shell session, if not explicitly specified. */
1352 if (!strv_find_prefix(arg_setenv, "TERM=")) {
1353 const char *t;
1354
1355 t = strv_find_prefix(environ, "TERM=");
1356 if (t) {
1357 if (strv_extend(&arg_setenv, t) < 0)
1358 return log_oom();
1359 }
1360 }
1361
1362 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1363
1364 r = sd_event_default(&event);
1365 if (r < 0)
1366 return log_error_errno(r, "Failed to get event loop: %m");
1367
1368 r = sd_bus_attach_event(bus, event, 0);
1369 if (r < 0)
1370 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1371
1372 r = parse_machine_uid(argc >= 2 ? argv[1] : NULL, &machine, &uid);
1373 if (r < 0)
1374 return log_error_errno(r, "Failed to parse machine specification: %m");
1375
1376 match = strjoina("type='signal',"
1377 "sender='org.freedesktop.machine1',"
1378 "path='/org/freedesktop/machine1',",
1379 "interface='org.freedesktop.machine1.Manager',"
1380 "member='MachineRemoved',"
1381 "arg0='", machine, "'");
1382
1383 r = sd_bus_add_match_async(bus, &slot, match, on_machine_removed, NULL, &forward);
1384 if (r < 0)
1385 return log_error_errno(r, "Failed to request machine removal match: %m");
1386
1387 r = bus_message_new_method_call(bus, &m, bus_machine_mgr, "OpenMachineShell");
1388 if (r < 0)
1389 return bus_log_create_error(r);
1390
1391 path = argc < 3 || isempty(argv[2]) ? NULL : argv[2];
1392
1393 r = sd_bus_message_append(m, "sss", machine, uid, path);
1394 if (r < 0)
1395 return bus_log_create_error(r);
1396
1397 r = sd_bus_message_append_strv(m, strv_length(argv) <= 3 ? NULL : argv + 2);
1398 if (r < 0)
1399 return bus_log_create_error(r);
1400
1401 r = sd_bus_message_append_strv(m, arg_setenv);
1402 if (r < 0)
1403 return bus_log_create_error(r);
1404
1405 r = sd_bus_call(bus, m, 0, &error, &reply);
1406 if (r < 0)
1407 return log_error_errno(r, "Failed to get shell PTY: %s", bus_error_message(&error, r));
1408
1409 r = sd_bus_message_read(reply, "hs", &master, NULL);
1410 if (r < 0)
1411 return bus_log_parse_error(r);
1412
1413 return process_forward(event, &forward, master, 0, machine);
1414 }
1415
1416 static int normalize_nspawn_filename(const char *name, char **ret_file) {
1417 _cleanup_free_ char *file = NULL;
1418
1419 assert(name);
1420 assert(ret_file);
1421
1422 if (!endswith(name, ".nspawn"))
1423 file = strjoin(name, ".nspawn");
1424 else
1425 file = strdup(name);
1426 if (!file)
1427 return log_oom();
1428
1429 if (!filename_is_valid(file))
1430 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid settings file name '%s'.", file);
1431
1432 *ret_file = TAKE_PTR(file);
1433 return 0;
1434 }
1435
1436 static int get_settings_path(const char *name, char **ret_path) {
1437 assert(name);
1438 assert(ret_path);
1439
1440 FOREACH_STRING(i, "/etc/systemd/nspawn", "/run/systemd/nspawn", "/var/lib/machines") {
1441 _cleanup_free_ char *path = NULL;
1442
1443 path = path_join(i, name);
1444 if (!path)
1445 return -ENOMEM;
1446
1447 if (access(path, F_OK) >= 0) {
1448 *ret_path = TAKE_PTR(path);
1449 return 0;
1450 }
1451 }
1452
1453 return -ENOENT;
1454 }
1455
1456 static int edit_settings(int argc, char *argv[], void *userdata) {
1457 _cleanup_(edit_file_context_done) EditFileContext context = {};
1458 int r;
1459
1460 if (!on_tty())
1461 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot edit machine settings if not on a tty.");
1462
1463 if (arg_transport != BUS_TRANSPORT_LOCAL)
1464 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1465 "Edit is only supported on the host machine.");
1466
1467 r = mac_selinux_init();
1468 if (r < 0)
1469 return r;
1470
1471 STRV_FOREACH(name, strv_skip(argv, 1)) {
1472 _cleanup_free_ char *file = NULL, *path = NULL;
1473
1474 if (path_is_absolute(*name)) {
1475 if (!path_is_safe(*name))
1476 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1477 "Invalid settings file path '%s'.",
1478 *name);
1479
1480 r = edit_files_add(&context, *name, NULL, NULL);
1481 if (r < 0)
1482 return r;
1483 continue;
1484 }
1485
1486 r = normalize_nspawn_filename(*name, &file);
1487 if (r < 0)
1488 return r;
1489
1490 r = get_settings_path(file, &path);
1491 if (r == -ENOENT) {
1492 log_debug("No existing settings file for machine '%s' found, creating a new file.", *name);
1493
1494 path = path_join("/etc/systemd/nspawn", file);
1495 if (!path)
1496 return log_oom();
1497
1498 r = edit_files_add(&context, path, NULL, NULL);
1499 if (r < 0)
1500 return r;
1501 continue;
1502 }
1503 if (r < 0)
1504 return log_error_errno(r, "Failed to get the path of the settings file: %m");
1505
1506 if (path_startswith(path, "/var/lib/machines")) {
1507 _cleanup_free_ char *new_path = NULL;
1508
1509 new_path = path_join("/etc/systemd/nspawn", file);
1510 if (!new_path)
1511 return log_oom();
1512
1513 r = edit_files_add(&context, new_path, path, NULL);
1514 } else
1515 r = edit_files_add(&context, path, NULL, NULL);
1516 if (r < 0)
1517 return r;
1518 }
1519
1520 return do_edit_files_and_install(&context);
1521 }
1522
1523 static int cat_settings(int argc, char *argv[], void *userdata) {
1524 int r = 0;
1525
1526 if (arg_transport != BUS_TRANSPORT_LOCAL)
1527 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1528 "Cat is only supported on the host machine.");
1529
1530 pager_open(arg_pager_flags);
1531
1532 STRV_FOREACH(name, strv_skip(argv, 1)) {
1533 _cleanup_free_ char *file = NULL, *path = NULL;
1534 int q;
1535
1536 if (path_is_absolute(*name)) {
1537 if (!path_is_safe(*name))
1538 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1539 "Invalid settings file path '%s'.",
1540 *name);
1541
1542 q = cat_files(*name, /* dropins = */ NULL, /* flags = */ 0);
1543 if (q < 0)
1544 return r < 0 ? r : q;
1545 continue;
1546 }
1547
1548 q = normalize_nspawn_filename(*name, &file);
1549 if (q < 0)
1550 return r < 0 ? r : q;
1551
1552 q = get_settings_path(file, &path);
1553 if (q == -ENOENT) {
1554 log_error_errno(q, "No settings file found for machine '%s'.", *name);
1555 r = r < 0 ? r : q;
1556 continue;
1557 }
1558 if (q < 0) {
1559 log_error_errno(q, "Failed to get the path of the settings file: %m");
1560 return r < 0 ? r : q;
1561 }
1562
1563 q = cat_files(path, /* dropins = */ NULL, /* flags = */ 0);
1564 if (q < 0)
1565 return r < 0 ? r : q;
1566 }
1567
1568 return r;
1569 }
1570
1571 static int remove_image(int argc, char *argv[], void *userdata) {
1572 sd_bus *bus = ASSERT_PTR(userdata);
1573 int r;
1574
1575 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1576
1577 for (int i = 1; i < argc; i++) {
1578 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1579 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1580
1581 r = bus_message_new_method_call(bus, &m, bus_machine_mgr, "RemoveImage");
1582 if (r < 0)
1583 return bus_log_create_error(r);
1584
1585 r = sd_bus_message_append(m, "s", argv[i]);
1586 if (r < 0)
1587 return bus_log_create_error(r);
1588
1589 /* This is a slow operation, hence turn off any method call timeouts */
1590 r = sd_bus_call(bus, m, USEC_INFINITY, &error, NULL);
1591 if (r < 0)
1592 return log_error_errno(r, "Could not remove image: %s", bus_error_message(&error, r));
1593 }
1594
1595 return 0;
1596 }
1597
1598 static int rename_image(int argc, char *argv[], void *userdata) {
1599 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1600 sd_bus *bus = ASSERT_PTR(userdata);
1601 int r;
1602
1603 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1604
1605 r = bus_call_method(
1606 bus,
1607 bus_machine_mgr,
1608 "RenameImage",
1609 &error,
1610 NULL,
1611 "ss", argv[1], argv[2]);
1612 if (r < 0)
1613 return log_error_errno(r, "Could not rename image: %s", bus_error_message(&error, r));
1614
1615 return 0;
1616 }
1617
1618 static int clone_image(int argc, char *argv[], void *userdata) {
1619 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1620 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1621 sd_bus *bus = ASSERT_PTR(userdata);
1622 int r;
1623
1624 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1625
1626 r = bus_message_new_method_call(bus, &m, bus_machine_mgr, "CloneImage");
1627 if (r < 0)
1628 return bus_log_create_error(r);
1629
1630 r = sd_bus_message_append(m, "ssb", argv[1], argv[2], arg_read_only);
1631 if (r < 0)
1632 return bus_log_create_error(r);
1633
1634 /* This is a slow operation, hence turn off any method call timeouts */
1635 r = sd_bus_call(bus, m, USEC_INFINITY, &error, NULL);
1636 if (r < 0)
1637 return log_error_errno(r, "Could not clone image: %s", bus_error_message(&error, r));
1638
1639 return 0;
1640 }
1641
1642 static int read_only_image(int argc, char *argv[], void *userdata) {
1643 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1644 sd_bus *bus = ASSERT_PTR(userdata);
1645 int b = true, r;
1646
1647 if (argc > 2) {
1648 b = parse_boolean(argv[2]);
1649 if (b < 0)
1650 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1651 "Failed to parse boolean argument: %s",
1652 argv[2]);
1653 }
1654
1655 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1656
1657 r = bus_call_method(bus, bus_machine_mgr, "MarkImageReadOnly", &error, NULL, "sb", argv[1], b);
1658 if (r < 0)
1659 return log_error_errno(r, "Could not mark image read-only: %s", bus_error_message(&error, r));
1660
1661 return 0;
1662 }
1663
1664 static int image_exists(sd_bus *bus, const char *name) {
1665 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1666 int r;
1667
1668 assert(bus);
1669 assert(name);
1670
1671 r = bus_call_method(bus, bus_machine_mgr, "GetImage", &error, NULL, "s", name);
1672 if (r < 0) {
1673 if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_IMAGE))
1674 return 0;
1675
1676 return log_error_errno(r, "Failed to check whether image %s exists: %s", name, bus_error_message(&error, r));
1677 }
1678
1679 return 1;
1680 }
1681
1682 static int make_service_name(const char *name, char **ret) {
1683 int r;
1684
1685 assert(name);
1686 assert(ret);
1687
1688 if (!hostname_is_valid(name, 0))
1689 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1690 "Invalid machine name %s.", name);
1691
1692 r = unit_name_build("systemd-nspawn", name, ".service", ret);
1693 if (r < 0)
1694 return log_error_errno(r, "Failed to build unit name: %m");
1695
1696 return 0;
1697 }
1698
1699 static int start_machine(int argc, char *argv[], void *userdata) {
1700 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1701 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
1702 sd_bus *bus = ASSERT_PTR(userdata);
1703 int r;
1704
1705 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1706 ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
1707
1708 r = bus_wait_for_jobs_new(bus, &w);
1709 if (r < 0)
1710 return log_oom();
1711
1712 for (int i = 1; i < argc; i++) {
1713 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1714 _cleanup_free_ char *unit = NULL;
1715 const char *object;
1716
1717 r = make_service_name(argv[i], &unit);
1718 if (r < 0)
1719 return r;
1720
1721 r = image_exists(bus, argv[i]);
1722 if (r < 0)
1723 return r;
1724 if (r == 0)
1725 return log_error_errno(SYNTHETIC_ERRNO(ENXIO),
1726 "Machine image '%s' does not exist.",
1727 argv[i]);
1728
1729 r = bus_call_method(
1730 bus,
1731 bus_systemd_mgr,
1732 "StartUnit",
1733 &error,
1734 &reply,
1735 "ss", unit, "fail");
1736 if (r < 0)
1737 return log_error_errno(r, "Failed to start unit: %s", bus_error_message(&error, r));
1738
1739 r = sd_bus_message_read(reply, "o", &object);
1740 if (r < 0)
1741 return bus_log_parse_error(r);
1742
1743 r = bus_wait_for_jobs_add(w, object);
1744 if (r < 0)
1745 return log_oom();
1746 }
1747
1748 r = bus_wait_for_jobs(w, arg_quiet, NULL);
1749 if (r < 0)
1750 return r;
1751
1752 return 0;
1753 }
1754
1755 static int enable_machine(int argc, char *argv[], void *userdata) {
1756 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
1757 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1758 const char *method;
1759 sd_bus *bus = ASSERT_PTR(userdata);
1760 int r;
1761 bool enable;
1762
1763 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1764
1765 enable = streq(argv[0], "enable");
1766 method = enable ? "EnableUnitFiles" : "DisableUnitFiles";
1767
1768 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, method);
1769 if (r < 0)
1770 return bus_log_create_error(r);
1771
1772 r = sd_bus_message_open_container(m, 'a', "s");
1773 if (r < 0)
1774 return bus_log_create_error(r);
1775
1776 if (enable) {
1777 r = sd_bus_message_append(m, "s", "machines.target");
1778 if (r < 0)
1779 return bus_log_create_error(r);
1780 }
1781
1782 for (int i = 1; i < argc; i++) {
1783 _cleanup_free_ char *unit = NULL;
1784
1785 r = make_service_name(argv[i], &unit);
1786 if (r < 0)
1787 return r;
1788
1789 r = image_exists(bus, argv[i]);
1790 if (r < 0)
1791 return r;
1792 if (r == 0)
1793 return log_error_errno(SYNTHETIC_ERRNO(ENXIO),
1794 "Machine image '%s' does not exist.",
1795 argv[i]);
1796
1797 r = sd_bus_message_append(m, "s", unit);
1798 if (r < 0)
1799 return bus_log_create_error(r);
1800 }
1801
1802 r = sd_bus_message_close_container(m);
1803 if (r < 0)
1804 return bus_log_create_error(r);
1805
1806 if (enable)
1807 r = sd_bus_message_append(m, "bb", false, false);
1808 else
1809 r = sd_bus_message_append(m, "b", false);
1810 if (r < 0)
1811 return bus_log_create_error(r);
1812
1813 r = sd_bus_call(bus, m, 0, &error, &reply);
1814 if (r < 0)
1815 return log_error_errno(r, "Failed to enable or disable unit: %s", bus_error_message(&error, r));
1816
1817 if (enable) {
1818 r = sd_bus_message_read(reply, "b", NULL);
1819 if (r < 0)
1820 return bus_log_parse_error(r);
1821 }
1822
1823 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet);
1824 if (r < 0)
1825 return r;
1826
1827 r = bus_call_method(bus, bus_systemd_mgr, "Reload", &error, NULL, NULL);
1828 if (r < 0)
1829 return log_error_errno(r, "Failed to reload daemon: %s", bus_error_message(&error, r));
1830
1831 if (arg_now) {
1832 _cleanup_strv_free_ char **new_args = NULL;
1833
1834 new_args = strv_new(enable ? "start" : "poweroff");
1835 if (!new_args)
1836 return log_oom();
1837
1838 r = strv_extend_strv(&new_args, argv + 1, /* filter_duplicates = */ false);
1839 if (r < 0)
1840 return log_oom();
1841
1842 if (enable)
1843 return start_machine(strv_length(new_args), new_args, userdata);
1844
1845 return poweroff_machine(strv_length(new_args), new_args, userdata);
1846 }
1847
1848 return 0;
1849 }
1850
1851 static int match_log_message(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1852 const char **our_path = userdata, *line;
1853 unsigned priority;
1854 int r;
1855
1856 assert(m);
1857 assert(our_path);
1858
1859 r = sd_bus_message_read(m, "us", &priority, &line);
1860 if (r < 0) {
1861 bus_log_parse_error(r);
1862 return 0;
1863 }
1864
1865 if (!streq_ptr(*our_path, sd_bus_message_get_path(m)))
1866 return 0;
1867
1868 if (arg_quiet && LOG_PRI(priority) >= LOG_INFO)
1869 return 0;
1870
1871 log_full(priority, "%s", line);
1872 return 0;
1873 }
1874
1875 static int match_transfer_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1876 const char **our_path = userdata, *path, *result;
1877 uint32_t id;
1878 int r;
1879
1880 assert(m);
1881 assert(our_path);
1882
1883 r = sd_bus_message_read(m, "uos", &id, &path, &result);
1884 if (r < 0) {
1885 bus_log_parse_error(r);
1886 return 0;
1887 }
1888
1889 if (!streq_ptr(*our_path, path))
1890 return 0;
1891
1892 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), !streq_ptr(result, "done"));
1893 return 0;
1894 }
1895
1896 static int transfer_signal_handler(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1897 assert(s);
1898 assert(si);
1899
1900 if (!arg_quiet)
1901 log_info("Continuing download in the background. Use \"machinectl cancel-transfer %" PRIu32 "\" to abort transfer.", PTR_TO_UINT32(userdata));
1902
1903 sd_event_exit(sd_event_source_get_event(s), EINTR);
1904 return 0;
1905 }
1906
1907 static int transfer_image_common(sd_bus *bus, sd_bus_message *m) {
1908 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot_job_removed = NULL, *slot_log_message = NULL;
1909 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1910 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1911 _cleanup_(sd_event_unrefp) sd_event* event = NULL;
1912 const char *path = NULL;
1913 uint32_t id;
1914 int r;
1915
1916 assert(bus);
1917 assert(m);
1918
1919 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1920
1921 r = sd_event_default(&event);
1922 if (r < 0)
1923 return log_error_errno(r, "Failed to get event loop: %m");
1924
1925 r = sd_bus_attach_event(bus, event, 0);
1926 if (r < 0)
1927 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1928
1929 r = bus_match_signal_async(
1930 bus,
1931 &slot_job_removed,
1932 bus_import_mgr,
1933 "TransferRemoved",
1934 match_transfer_removed, NULL, &path);
1935 if (r < 0)
1936 return log_error_errno(r, "Failed to request match: %m");
1937
1938 r = sd_bus_match_signal_async(
1939 bus,
1940 &slot_log_message,
1941 "org.freedesktop.import1",
1942 NULL,
1943 "org.freedesktop.import1.Transfer",
1944 "LogMessage",
1945 match_log_message, NULL, &path);
1946 if (r < 0)
1947 return log_error_errno(r, "Failed to request match: %m");
1948
1949 r = sd_bus_call(bus, m, 0, &error, &reply);
1950 if (r < 0)
1951 return log_error_errno(r, "Failed to transfer image: %s", bus_error_message(&error, r));
1952
1953 r = sd_bus_message_read(reply, "uo", &id, &path);
1954 if (r < 0)
1955 return bus_log_parse_error(r);
1956
1957 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0);
1958
1959 if (!arg_quiet)
1960 log_info("Enqueued transfer job %u. Press C-c to continue download in background.", id);
1961
1962 (void) sd_event_add_signal(event, NULL, SIGINT, transfer_signal_handler, UINT32_TO_PTR(id));
1963 (void) sd_event_add_signal(event, NULL, SIGTERM, transfer_signal_handler, UINT32_TO_PTR(id));
1964
1965 r = sd_event_loop(event);
1966 if (r < 0)
1967 return log_error_errno(r, "Failed to run event loop: %m");
1968
1969 return -r;
1970 }
1971
1972 static int import_tar(int argc, char *argv[], void *userdata) {
1973 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1974 _cleanup_free_ char *ll = NULL, *fn = NULL;
1975 const char *local = NULL, *path = NULL;
1976 _cleanup_close_ int fd = -EBADF;
1977 sd_bus *bus = ASSERT_PTR(userdata);
1978 int r;
1979
1980 if (argc >= 2)
1981 path = empty_or_dash_to_null(argv[1]);
1982
1983 if (argc >= 3)
1984 local = empty_or_dash_to_null(argv[2]);
1985 else if (path) {
1986 r = path_extract_filename(path, &fn);
1987 if (r < 0)
1988 return log_error_errno(r, "Cannot extract container name from filename: %m");
1989 if (r == O_DIRECTORY)
1990 return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
1991 "Path '%s' refers to directory, but we need a regular file: %m", path);
1992
1993 local = fn;
1994 }
1995 if (!local)
1996 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1997 "Need either path or local name.");
1998
1999 r = tar_strip_suffixes(local, &ll);
2000 if (r < 0)
2001 return log_oom();
2002
2003 local = ll;
2004
2005 if (!hostname_is_valid(local, 0))
2006 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2007 "Local name %s is not a suitable machine name.",
2008 local);
2009
2010 if (path) {
2011 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
2012 if (fd < 0)
2013 return log_error_errno(errno, "Failed to open %s: %m", path);
2014 }
2015
2016 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportTar");
2017 if (r < 0)
2018 return bus_log_create_error(r);
2019
2020 r = sd_bus_message_append(
2021 m,
2022 "hsbb",
2023 fd >= 0 ? fd : STDIN_FILENO,
2024 local,
2025 arg_force,
2026 arg_read_only);
2027 if (r < 0)
2028 return bus_log_create_error(r);
2029
2030 return transfer_image_common(bus, m);
2031 }
2032
2033 static int import_raw(int argc, char *argv[], void *userdata) {
2034 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2035 _cleanup_free_ char *ll = NULL, *fn = NULL;
2036 const char *local = NULL, *path = NULL;
2037 _cleanup_close_ int fd = -EBADF;
2038 sd_bus *bus = ASSERT_PTR(userdata);
2039 int r;
2040
2041 if (argc >= 2)
2042 path = empty_or_dash_to_null(argv[1]);
2043
2044 if (argc >= 3)
2045 local = empty_or_dash_to_null(argv[2]);
2046 else if (path) {
2047 r = path_extract_filename(path, &fn);
2048 if (r < 0)
2049 return log_error_errno(r, "Cannot extract container name from filename: %m");
2050 if (r == O_DIRECTORY)
2051 return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
2052 "Path '%s' refers to directory, but we need a regular file: %m", path);
2053
2054 local = fn;
2055 }
2056 if (!local)
2057 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2058 "Need either path or local name.");
2059
2060 r = raw_strip_suffixes(local, &ll);
2061 if (r < 0)
2062 return log_oom();
2063
2064 local = ll;
2065
2066 if (!hostname_is_valid(local, 0))
2067 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2068 "Local name %s is not a suitable machine name.",
2069 local);
2070
2071 if (path) {
2072 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
2073 if (fd < 0)
2074 return log_error_errno(errno, "Failed to open %s: %m", path);
2075 }
2076
2077 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportRaw");
2078 if (r < 0)
2079 return bus_log_create_error(r);
2080
2081 r = sd_bus_message_append(
2082 m,
2083 "hsbb",
2084 fd >= 0 ? fd : STDIN_FILENO,
2085 local,
2086 arg_force,
2087 arg_read_only);
2088 if (r < 0)
2089 return bus_log_create_error(r);
2090
2091 return transfer_image_common(bus, m);
2092 }
2093
2094 static int import_fs(int argc, char *argv[], void *userdata) {
2095 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2096 const char *local = NULL, *path = NULL;
2097 _cleanup_free_ char *fn = NULL;
2098 _cleanup_close_ int fd = -EBADF;
2099 sd_bus *bus = ASSERT_PTR(userdata);
2100 int r;
2101
2102 if (argc >= 2)
2103 path = empty_or_dash_to_null(argv[1]);
2104
2105 if (argc >= 3)
2106 local = empty_or_dash_to_null(argv[2]);
2107 else if (path) {
2108 r = path_extract_filename(path, &fn);
2109 if (r < 0)
2110 return log_error_errno(r, "Cannot extract container name from filename: %m");
2111
2112 local = fn;
2113 }
2114 if (!local)
2115 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2116 "Need either path or local name.");
2117
2118 if (!hostname_is_valid(local, 0))
2119 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2120 "Local name %s is not a suitable machine name.",
2121 local);
2122
2123 if (path) {
2124 fd = open(path, O_DIRECTORY|O_RDONLY|O_CLOEXEC);
2125 if (fd < 0)
2126 return log_error_errno(errno, "Failed to open directory '%s': %m", path);
2127 }
2128
2129 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ImportFileSystem");
2130 if (r < 0)
2131 return bus_log_create_error(r);
2132
2133 r = sd_bus_message_append(
2134 m,
2135 "hsbb",
2136 fd >= 0 ? fd : STDIN_FILENO,
2137 local,
2138 arg_force,
2139 arg_read_only);
2140 if (r < 0)
2141 return bus_log_create_error(r);
2142
2143 return transfer_image_common(bus, m);
2144 }
2145
2146 static void determine_compression_from_filename(const char *p) {
2147 if (arg_format)
2148 return;
2149
2150 if (!p)
2151 return;
2152
2153 if (endswith(p, ".xz"))
2154 arg_format = "xz";
2155 else if (endswith(p, ".gz"))
2156 arg_format = "gzip";
2157 else if (endswith(p, ".bz2"))
2158 arg_format = "bzip2";
2159 }
2160
2161 static int export_tar(int argc, char *argv[], void *userdata) {
2162 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2163 _cleanup_close_ int fd = -EBADF;
2164 const char *local = NULL, *path = NULL;
2165 sd_bus *bus = ASSERT_PTR(userdata);
2166 int r;
2167
2168 local = argv[1];
2169 if (!hostname_is_valid(local, 0))
2170 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2171 "Machine name %s is not valid.", local);
2172
2173 if (argc >= 3)
2174 path = argv[2];
2175 path = empty_or_dash_to_null(path);
2176
2177 if (path) {
2178 determine_compression_from_filename(path);
2179
2180 fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC|O_NOCTTY, 0666);
2181 if (fd < 0)
2182 return log_error_errno(errno, "Failed to open %s: %m", path);
2183 }
2184
2185 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ExportTar");
2186 if (r < 0)
2187 return bus_log_create_error(r);
2188
2189 r = sd_bus_message_append(
2190 m,
2191 "shs",
2192 local,
2193 fd >= 0 ? fd : STDOUT_FILENO,
2194 arg_format);
2195 if (r < 0)
2196 return bus_log_create_error(r);
2197
2198 return transfer_image_common(bus, m);
2199 }
2200
2201 static int export_raw(int argc, char *argv[], void *userdata) {
2202 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2203 _cleanup_close_ int fd = -EBADF;
2204 const char *local = NULL, *path = NULL;
2205 sd_bus *bus = ASSERT_PTR(userdata);
2206 int r;
2207
2208 local = argv[1];
2209 if (!hostname_is_valid(local, 0))
2210 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2211 "Machine name %s is not valid.", local);
2212
2213 if (argc >= 3)
2214 path = argv[2];
2215 path = empty_or_dash_to_null(path);
2216
2217 if (path) {
2218 determine_compression_from_filename(path);
2219
2220 fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC|O_NOCTTY, 0666);
2221 if (fd < 0)
2222 return log_error_errno(errno, "Failed to open %s: %m", path);
2223 }
2224
2225 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "ExportRaw");
2226 if (r < 0)
2227 return bus_log_create_error(r);
2228
2229 r = sd_bus_message_append(
2230 m,
2231 "shs",
2232 local,
2233 fd >= 0 ? fd : STDOUT_FILENO,
2234 arg_format);
2235 if (r < 0)
2236 return bus_log_create_error(r);
2237
2238 return transfer_image_common(bus, m);
2239 }
2240
2241 static int pull_tar(int argc, char *argv[], void *userdata) {
2242 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2243 _cleanup_free_ char *l = NULL, *ll = NULL;
2244 const char *local, *remote;
2245 sd_bus *bus = ASSERT_PTR(userdata);
2246 int r;
2247
2248 remote = argv[1];
2249 if (!http_url_is_valid(remote) && !file_url_is_valid(remote))
2250 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2251 "URL '%s' is not valid.", remote);
2252
2253 if (argc >= 3)
2254 local = argv[2];
2255 else {
2256 r = import_url_last_component(remote, &l);
2257 if (r < 0)
2258 return log_error_errno(r, "Failed to get final component of URL: %m");
2259
2260 local = l;
2261 }
2262
2263 local = empty_or_dash_to_null(local);
2264
2265 if (local) {
2266 r = tar_strip_suffixes(local, &ll);
2267 if (r < 0)
2268 return log_oom();
2269
2270 local = ll;
2271
2272 if (!hostname_is_valid(local, 0))
2273 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2274 "Local name %s is not a suitable machine name.",
2275 local);
2276 }
2277
2278 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "PullTar");
2279 if (r < 0)
2280 return bus_log_create_error(r);
2281
2282 r = sd_bus_message_append(
2283 m,
2284 "sssb",
2285 remote,
2286 local,
2287 import_verify_to_string(arg_verify),
2288 arg_force);
2289 if (r < 0)
2290 return bus_log_create_error(r);
2291
2292 return transfer_image_common(bus, m);
2293 }
2294
2295 static int pull_raw(int argc, char *argv[], void *userdata) {
2296 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2297 _cleanup_free_ char *l = NULL, *ll = NULL;
2298 const char *local, *remote;
2299 sd_bus *bus = ASSERT_PTR(userdata);
2300 int r;
2301
2302 remote = argv[1];
2303 if (!http_url_is_valid(remote) && !file_url_is_valid(remote))
2304 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2305 "URL '%s' is not valid.", remote);
2306
2307 if (argc >= 3)
2308 local = argv[2];
2309 else {
2310 r = import_url_last_component(remote, &l);
2311 if (r < 0)
2312 return log_error_errno(r, "Failed to get final component of URL: %m");
2313
2314 local = l;
2315 }
2316
2317 local = empty_or_dash_to_null(local);
2318
2319 if (local) {
2320 r = raw_strip_suffixes(local, &ll);
2321 if (r < 0)
2322 return log_oom();
2323
2324 local = ll;
2325
2326 if (!hostname_is_valid(local, 0))
2327 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2328 "Local name %s is not a suitable machine name.",
2329 local);
2330 }
2331
2332 r = bus_message_new_method_call(bus, &m, bus_import_mgr, "PullRaw");
2333 if (r < 0)
2334 return bus_log_create_error(r);
2335
2336 r = sd_bus_message_append(
2337 m,
2338 "sssb",
2339 remote,
2340 local,
2341 import_verify_to_string(arg_verify),
2342 arg_force);
2343 if (r < 0)
2344 return bus_log_create_error(r);
2345
2346 return transfer_image_common(bus, m);
2347 }
2348
2349 typedef struct TransferInfo {
2350 uint32_t id;
2351 const char *type;
2352 const char *remote;
2353 const char *local;
2354 double progress;
2355 } TransferInfo;
2356
2357 static int compare_transfer_info(const TransferInfo *a, const TransferInfo *b) {
2358 return strcmp(a->local, b->local);
2359 }
2360
2361 static int list_transfers(int argc, char *argv[], void *userdata) {
2362 size_t max_type = STRLEN("TYPE"), max_local = STRLEN("LOCAL"), max_remote = STRLEN("REMOTE");
2363 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2364 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2365 _cleanup_free_ TransferInfo *transfers = NULL;
2366 const char *type, *remote, *local;
2367 sd_bus *bus = userdata;
2368 uint32_t id, max_id = 0;
2369 size_t n_transfers = 0;
2370 double progress;
2371 int r;
2372
2373 pager_open(arg_pager_flags);
2374
2375 r = bus_call_method(bus, bus_import_mgr, "ListTransfers", &error, &reply, NULL);
2376 if (r < 0)
2377 return log_error_errno(r, "Could not get transfers: %s", bus_error_message(&error, r));
2378
2379 r = sd_bus_message_enter_container(reply, 'a', "(usssdo)");
2380 if (r < 0)
2381 return bus_log_parse_error(r);
2382
2383 while ((r = sd_bus_message_read(reply, "(usssdo)", &id, &type, &remote, &local, &progress, NULL)) > 0) {
2384 size_t l;
2385
2386 if (!GREEDY_REALLOC(transfers, n_transfers + 1))
2387 return log_oom();
2388
2389 transfers[n_transfers].id = id;
2390 transfers[n_transfers].type = type;
2391 transfers[n_transfers].remote = remote;
2392 transfers[n_transfers].local = local;
2393 transfers[n_transfers].progress = progress;
2394
2395 l = strlen(type);
2396 if (l > max_type)
2397 max_type = l;
2398
2399 l = strlen(remote);
2400 if (l > max_remote)
2401 max_remote = l;
2402
2403 l = strlen(local);
2404 if (l > max_local)
2405 max_local = l;
2406
2407 if (id > max_id)
2408 max_id = id;
2409
2410 n_transfers++;
2411 }
2412 if (r < 0)
2413 return bus_log_parse_error(r);
2414
2415 r = sd_bus_message_exit_container(reply);
2416 if (r < 0)
2417 return bus_log_parse_error(r);
2418
2419 typesafe_qsort(transfers, n_transfers, compare_transfer_info);
2420
2421 if (arg_legend && n_transfers > 0)
2422 printf("%-*s %-*s %-*s %-*s %-*s\n",
2423 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id)), "ID",
2424 (int) 7, "PERCENT",
2425 (int) max_type, "TYPE",
2426 (int) max_local, "LOCAL",
2427 (int) max_remote, "REMOTE");
2428
2429 for (size_t j = 0; j < n_transfers; j++)
2430
2431 if (transfers[j].progress < 0)
2432 printf("%*" PRIu32 " %*s %-*s %-*s %-*s\n",
2433 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id)), transfers[j].id,
2434 (int) 7, "n/a",
2435 (int) max_type, transfers[j].type,
2436 (int) max_local, transfers[j].local,
2437 (int) max_remote, transfers[j].remote);
2438 else
2439 printf("%*" PRIu32 " %*u%% %-*s %-*s %-*s\n",
2440 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id)), transfers[j].id,
2441 (int) 6, (unsigned) (transfers[j].progress * 100),
2442 (int) max_type, transfers[j].type,
2443 (int) max_local, transfers[j].local,
2444 (int) max_remote, transfers[j].remote);
2445
2446 if (arg_legend) {
2447 if (n_transfers > 0)
2448 printf("\n%zu transfers listed.\n", n_transfers);
2449 else
2450 printf("No transfers.\n");
2451 }
2452
2453 return 0;
2454 }
2455
2456 static int cancel_transfer(int argc, char *argv[], void *userdata) {
2457 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2458 sd_bus *bus = ASSERT_PTR(userdata);
2459 int r;
2460
2461 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2462
2463 for (int i = 1; i < argc; i++) {
2464 uint32_t id;
2465
2466 r = safe_atou32(argv[i], &id);
2467 if (r < 0)
2468 return log_error_errno(r, "Failed to parse transfer id: %s", argv[i]);
2469
2470 r = bus_call_method(bus, bus_import_mgr, "CancelTransfer", &error, NULL, "u", id);
2471 if (r < 0)
2472 return log_error_errno(r, "Could not cancel transfer: %s", bus_error_message(&error, r));
2473 }
2474
2475 return 0;
2476 }
2477
2478 static int set_limit(int argc, char *argv[], void *userdata) {
2479 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2480 sd_bus *bus = userdata;
2481 uint64_t limit;
2482 int r;
2483
2484 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2485
2486 if (STR_IN_SET(argv[argc-1], "-", "none", "infinity"))
2487 limit = UINT64_MAX;
2488 else {
2489 r = parse_size(argv[argc-1], 1024, &limit);
2490 if (r < 0)
2491 return log_error_errno(r, "Failed to parse size: %s", argv[argc-1]);
2492 }
2493
2494 if (argc > 2)
2495 /* With two arguments changes the quota limit of the
2496 * specified image */
2497 r = bus_call_method(bus, bus_machine_mgr, "SetImageLimit", &error, NULL, "st", argv[1], limit);
2498 else
2499 /* With one argument changes the pool quota limit */
2500 r = bus_call_method(bus, bus_machine_mgr, "SetPoolLimit", &error, NULL, "t", limit);
2501
2502 if (r < 0)
2503 return log_error_errno(r, "Could not set limit: %s", bus_error_message(&error, r));
2504
2505 return 0;
2506 }
2507
2508 static int clean_images(int argc, char *argv[], void *userdata) {
2509 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
2510 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2511 uint64_t usage, total = 0;
2512 sd_bus *bus = userdata;
2513 const char *name;
2514 unsigned c = 0;
2515 int r;
2516
2517 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2518
2519 r = bus_message_new_method_call(bus, &m, bus_machine_mgr, "CleanPool");
2520 if (r < 0)
2521 return bus_log_create_error(r);
2522
2523 r = sd_bus_message_append(m, "s", arg_all ? "all" : "hidden");
2524 if (r < 0)
2525 return bus_log_create_error(r);
2526
2527 /* This is a slow operation, hence permit a longer time for completion. */
2528 r = sd_bus_call(bus, m, USEC_INFINITY, &error, &reply);
2529 if (r < 0)
2530 return log_error_errno(r, "Could not clean pool: %s", bus_error_message(&error, r));
2531
2532 r = sd_bus_message_enter_container(reply, 'a', "(st)");
2533 if (r < 0)
2534 return bus_log_parse_error(r);
2535
2536 while ((r = sd_bus_message_read(reply, "(st)", &name, &usage)) > 0) {
2537 if (usage == UINT64_MAX) {
2538 log_info("Removed image '%s'", name);
2539 total = UINT64_MAX;
2540 } else {
2541 log_info("Removed image '%s'. Freed exclusive disk space: %s",
2542 name, FORMAT_BYTES(usage));
2543 if (total != UINT64_MAX)
2544 total += usage;
2545 }
2546 c++;
2547 }
2548
2549 r = sd_bus_message_exit_container(reply);
2550 if (r < 0)
2551 return bus_log_parse_error(r);
2552
2553 if (total == UINT64_MAX)
2554 log_info("Removed %u images in total.", c);
2555 else
2556 log_info("Removed %u images in total. Total freed exclusive disk space: %s.",
2557 c, FORMAT_BYTES(total));
2558
2559 return 0;
2560 }
2561
2562 static int help(int argc, char *argv[], void *userdata) {
2563 _cleanup_free_ char *link = NULL;
2564 int r;
2565
2566 pager_open(arg_pager_flags);
2567
2568 r = terminal_urlify_man("machinectl", "1", &link);
2569 if (r < 0)
2570 return log_oom();
2571
2572 printf("%s [OPTIONS...] COMMAND ...\n\n"
2573 "%sSend control commands to or query the virtual machine and container%s\n"
2574 "%sregistration manager.%s\n"
2575 "\nMachine Commands:\n"
2576 " list List running VMs and containers\n"
2577 " status NAME... Show VM/container details\n"
2578 " show [NAME...] Show properties of one or more VMs/containers\n"
2579 " start NAME... Start container as a service\n"
2580 " login [NAME] Get a login prompt in a container or on the\n"
2581 " local host\n"
2582 " shell [[USER@]NAME [COMMAND...]]\n"
2583 " Invoke a shell (or other command) in a container\n"
2584 " or on the local host\n"
2585 " enable NAME... Enable automatic container start at boot\n"
2586 " disable NAME... Disable automatic container start at boot\n"
2587 " poweroff NAME... Power off one or more containers\n"
2588 " reboot NAME... Reboot one or more containers\n"
2589 " terminate NAME... Terminate one or more VMs/containers\n"
2590 " kill NAME... Send signal to processes of a VM/container\n"
2591 " copy-to NAME PATH [PATH] Copy files from the host to a container\n"
2592 " copy-from NAME PATH [PATH] Copy files from a container to the host\n"
2593 " bind NAME PATH [PATH] Bind mount a path from the host into a container\n"
2594 "\nImage Commands:\n"
2595 " list-images Show available container and VM images\n"
2596 " image-status [NAME...] Show image details\n"
2597 " show-image [NAME...] Show properties of image\n"
2598 " edit NAME|FILE... Edit settings of one or more VMs/containers\n"
2599 " cat NAME|FILE... Show settings of one or more VMs/containers\n"
2600 " clone NAME NAME Clone an image\n"
2601 " rename NAME NAME Rename an image\n"
2602 " read-only NAME [BOOL] Mark or unmark image read-only\n"
2603 " remove NAME... Remove an image\n"
2604 " set-limit [NAME] BYTES Set image or pool size limit (disk quota)\n"
2605 " clean Remove hidden (or all) images\n"
2606 "\nImage Transfer Commands:\n"
2607 " pull-tar URL [NAME] Download a TAR container image\n"
2608 " pull-raw URL [NAME] Download a RAW container or VM image\n"
2609 " import-tar FILE [NAME] Import a local TAR container image\n"
2610 " import-raw FILE [NAME] Import a local RAW container or VM image\n"
2611 " import-fs DIRECTORY [NAME] Import a local directory container image\n"
2612 " export-tar NAME [FILE] Export a TAR container image locally\n"
2613 " export-raw NAME [FILE] Export a RAW container or VM image locally\n"
2614 " list-transfers Show list of downloads in progress\n"
2615 " cancel-transfer Cancel a download\n"
2616 "\nOptions:\n"
2617 " -h --help Show this help\n"
2618 " --version Show package version\n"
2619 " --no-pager Do not pipe output into a pager\n"
2620 " --no-legend Do not show the headers and footers\n"
2621 " --no-ask-password Do not ask for system passwords\n"
2622 " -H --host=[USER@]HOST Operate on remote host\n"
2623 " -M --machine=CONTAINER Operate on local container\n"
2624 " -p --property=NAME Show only properties by this name\n"
2625 " -q --quiet Suppress output\n"
2626 " -a --all Show all properties, including empty ones\n"
2627 " --value When showing properties, only print the value\n"
2628 " -l --full Do not ellipsize output\n"
2629 " --kill-whom=WHOM Whom to send signal to\n"
2630 " -s --signal=SIGNAL Which signal to send\n"
2631 " --uid=USER Specify user ID to invoke shell as\n"
2632 " -E --setenv=VAR[=VALUE] Add an environment variable for shell\n"
2633 " --read-only Create read-only bind mount\n"
2634 " --mkdir Create directory before bind mounting, if missing\n"
2635 " -n --lines=INTEGER Number of journal entries to show\n"
2636 " --max-addresses=INTEGER Number of internet addresses to show at most\n"
2637 " -o --output=STRING Change journal output mode (short, short-precise,\n"
2638 " short-iso, short-iso-precise, short-full,\n"
2639 " short-monotonic, short-unix, short-delta,\n"
2640 " json, json-pretty, json-sse, json-seq, cat,\n"
2641 " verbose, export, with-unit)\n"
2642 " --verify=MODE Verification mode for downloaded images (no,\n"
2643 " checksum, signature)\n"
2644 " --force Download image even if already exists\n"
2645 " --now Start or power off container after enabling or\n"
2646 " disabling it\n"
2647 "\nSee the %s for details.\n",
2648 program_invocation_short_name,
2649 ansi_highlight(),
2650 ansi_normal(),
2651 ansi_highlight(),
2652 ansi_normal(),
2653 link);
2654
2655 return 0;
2656 }
2657
2658 static int parse_argv(int argc, char *argv[]) {
2659
2660 enum {
2661 ARG_VERSION = 0x100,
2662 ARG_NO_PAGER,
2663 ARG_NO_LEGEND,
2664 ARG_VALUE,
2665 ARG_KILL_WHOM,
2666 ARG_READ_ONLY,
2667 ARG_MKDIR,
2668 ARG_NO_ASK_PASSWORD,
2669 ARG_VERIFY,
2670 ARG_NOW,
2671 ARG_FORCE,
2672 ARG_FORMAT,
2673 ARG_UID,
2674 ARG_MAX_ADDRESSES,
2675 };
2676
2677 static const struct option options[] = {
2678 { "help", no_argument, NULL, 'h' },
2679 { "version", no_argument, NULL, ARG_VERSION },
2680 { "property", required_argument, NULL, 'p' },
2681 { "all", no_argument, NULL, 'a' },
2682 { "value", no_argument, NULL, ARG_VALUE },
2683 { "full", no_argument, NULL, 'l' },
2684 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
2685 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
2686 { "kill-whom", required_argument, NULL, ARG_KILL_WHOM },
2687 { "signal", required_argument, NULL, 's' },
2688 { "host", required_argument, NULL, 'H' },
2689 { "machine", required_argument, NULL, 'M' },
2690 { "read-only", no_argument, NULL, ARG_READ_ONLY },
2691 { "mkdir", no_argument, NULL, ARG_MKDIR },
2692 { "quiet", no_argument, NULL, 'q' },
2693 { "lines", required_argument, NULL, 'n' },
2694 { "output", required_argument, NULL, 'o' },
2695 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
2696 { "verify", required_argument, NULL, ARG_VERIFY },
2697 { "now", no_argument, NULL, ARG_NOW },
2698 { "force", no_argument, NULL, ARG_FORCE },
2699 { "format", required_argument, NULL, ARG_FORMAT },
2700 { "uid", required_argument, NULL, ARG_UID },
2701 { "setenv", required_argument, NULL, 'E' },
2702 { "max-addresses", required_argument, NULL, ARG_MAX_ADDRESSES },
2703 {}
2704 };
2705
2706 bool reorder = false;
2707 int c, r, shell = -1;
2708
2709 assert(argc >= 0);
2710 assert(argv);
2711
2712 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
2713 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
2714 optind = 0;
2715
2716 for (;;) {
2717 static const char option_string[] = "-hp:als:H:M:qn:o:E:";
2718
2719 c = getopt_long(argc, argv, option_string + reorder, options, NULL);
2720 if (c < 0)
2721 break;
2722
2723 switch (c) {
2724
2725 case 1: /* getopt_long() returns 1 if "-" was the first character of the option string, and a
2726 * non-option argument was discovered. */
2727
2728 assert(!reorder);
2729
2730 /* We generally are fine with the fact that getopt_long() reorders the command line, and looks
2731 * for switches after the main verb. However, for "shell" we really don't want that, since we
2732 * want that switches specified after the machine name are passed to the program to execute,
2733 * and not processed by us. To make this possible, we'll first invoke getopt_long() with
2734 * reordering disabled (i.e. with the "-" prefix in the option string), looking for the first
2735 * non-option parameter. If it's the verb "shell" we remember its position and continue
2736 * processing options. In this case, as soon as we hit the next non-option argument we found
2737 * the machine name, and stop further processing. If the first non-option argument is any other
2738 * verb than "shell" we switch to normal reordering mode and continue processing arguments
2739 * normally. */
2740
2741 if (shell >= 0) {
2742 /* If we already found the "shell" verb on the command line, and now found the next
2743 * non-option argument, then this is the machine name and we should stop processing
2744 * further arguments. */
2745 optind --; /* don't process this argument, go one step back */
2746 goto done;
2747 }
2748 if (streq(optarg, "shell"))
2749 /* Remember the position of the "shell" verb, and continue processing normally. */
2750 shell = optind - 1;
2751 else {
2752 int saved_optind;
2753
2754 /* OK, this is some other verb. In this case, turn on reordering again, and continue
2755 * processing normally. */
2756 reorder = true;
2757
2758 /* We changed the option string. getopt_long() only looks at it again if we invoke it
2759 * at least once with a reset option index. Hence, let's reset the option index here,
2760 * then invoke getopt_long() again (ignoring what it has to say, after all we most
2761 * likely already processed it), and the bump the option index so that we read the
2762 * intended argument again. */
2763 saved_optind = optind;
2764 optind = 0;
2765 (void) getopt_long(argc, argv, option_string + reorder, options, NULL);
2766 optind = saved_optind - 1; /* go one step back, process this argument again */
2767 }
2768
2769 break;
2770
2771 case 'h':
2772 return help(0, NULL, NULL);
2773
2774 case ARG_VERSION:
2775 return version();
2776
2777 case 'p':
2778 r = strv_extend(&arg_property, optarg);
2779 if (r < 0)
2780 return log_oom();
2781
2782 /* If the user asked for a particular
2783 * property, show it to them, even if it is
2784 * empty. */
2785 SET_FLAG(arg_print_flags, BUS_PRINT_PROPERTY_SHOW_EMPTY, true);
2786 break;
2787
2788 case 'a':
2789 SET_FLAG(arg_print_flags, BUS_PRINT_PROPERTY_SHOW_EMPTY, true);
2790 arg_all = true;
2791 break;
2792
2793 case ARG_VALUE:
2794 SET_FLAG(arg_print_flags, BUS_PRINT_PROPERTY_ONLY_VALUE, true);
2795 break;
2796
2797 case 'l':
2798 arg_full = true;
2799 break;
2800
2801 case 'n':
2802 if (safe_atou(optarg, &arg_lines) < 0)
2803 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2804 "Failed to parse lines '%s'", optarg);
2805 break;
2806
2807 case 'o':
2808 if (streq(optarg, "help")) {
2809 DUMP_STRING_TABLE(output_mode, OutputMode, _OUTPUT_MODE_MAX);
2810 return 0;
2811 }
2812
2813 r = output_mode_from_string(optarg);
2814 if (r < 0)
2815 return log_error_errno(r, "Unknown output '%s'.", optarg);
2816 arg_output = r;
2817
2818 if (OUTPUT_MODE_IS_JSON(arg_output))
2819 arg_legend = false;
2820 break;
2821
2822 case ARG_NO_PAGER:
2823 arg_pager_flags |= PAGER_DISABLE;
2824 break;
2825
2826 case ARG_NO_LEGEND:
2827 arg_legend = false;
2828 break;
2829
2830 case ARG_KILL_WHOM:
2831 arg_kill_whom = optarg;
2832 break;
2833
2834 case 's':
2835 r = parse_signal_argument(optarg, &arg_signal);
2836 if (r <= 0)
2837 return r;
2838 break;
2839
2840 case ARG_NO_ASK_PASSWORD:
2841 arg_ask_password = false;
2842 break;
2843
2844 case 'H':
2845 arg_transport = BUS_TRANSPORT_REMOTE;
2846 arg_host = optarg;
2847 break;
2848
2849 case 'M':
2850 arg_transport = BUS_TRANSPORT_MACHINE;
2851 arg_host = optarg;
2852 break;
2853
2854 case ARG_READ_ONLY:
2855 arg_read_only = true;
2856 break;
2857
2858 case ARG_MKDIR:
2859 arg_mkdir = true;
2860 break;
2861
2862 case 'q':
2863 arg_quiet = true;
2864 break;
2865
2866 case ARG_VERIFY:
2867 if (streq(optarg, "help")) {
2868 DUMP_STRING_TABLE(import_verify, ImportVerify, _IMPORT_VERIFY_MAX);
2869 return 0;
2870 }
2871
2872 r = import_verify_from_string(optarg);
2873 if (r < 0)
2874 return log_error_errno(r, "Failed to parse --verify= setting: %s", optarg);
2875 arg_verify = r;
2876 break;
2877
2878 case ARG_NOW:
2879 arg_now = true;
2880 break;
2881
2882 case ARG_FORCE:
2883 arg_force = true;
2884 break;
2885
2886 case ARG_FORMAT:
2887 if (!STR_IN_SET(optarg, "uncompressed", "xz", "gzip", "bzip2"))
2888 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2889 "Unknown format: %s", optarg);
2890
2891 arg_format = optarg;
2892 break;
2893
2894 case ARG_UID:
2895 arg_uid = optarg;
2896 break;
2897
2898 case 'E':
2899 r = strv_env_replace_strdup_passthrough(&arg_setenv, optarg);
2900 if (r < 0)
2901 return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg);
2902 break;
2903
2904 case ARG_MAX_ADDRESSES:
2905 if (streq(optarg, "all"))
2906 arg_max_addresses = UINT_MAX;
2907 else if (safe_atou(optarg, &arg_max_addresses) < 0)
2908 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2909 "Invalid number of addresses: %s", optarg);
2910 break;
2911
2912 case '?':
2913 return -EINVAL;
2914
2915 default:
2916 assert_not_reached();
2917 }
2918 }
2919
2920 done:
2921 if (shell >= 0) {
2922 char *t;
2923
2924 /* We found the "shell" verb while processing the argument list. Since we turned off reordering of the
2925 * argument list initially let's readjust it now, and move the "shell" verb to the back. */
2926
2927 optind -= 1; /* place the option index where the "shell" verb will be placed */
2928
2929 t = argv[shell];
2930 for (int i = shell; i < optind; i++)
2931 argv[i] = argv[i+1];
2932 argv[optind] = t;
2933 }
2934
2935 return 1;
2936 }
2937
2938 static int machinectl_main(int argc, char *argv[], sd_bus *bus) {
2939
2940 static const Verb verbs[] = {
2941 { "help", VERB_ANY, VERB_ANY, 0, help },
2942 { "list", VERB_ANY, 1, VERB_DEFAULT, list_machines },
2943 { "list-images", VERB_ANY, 1, 0, list_images },
2944 { "status", 2, VERB_ANY, 0, show_machine },
2945 { "image-status", VERB_ANY, VERB_ANY, 0, show_image },
2946 { "show", VERB_ANY, VERB_ANY, 0, show_machine },
2947 { "show-image", VERB_ANY, VERB_ANY, 0, show_image },
2948 { "terminate", 2, VERB_ANY, 0, terminate_machine },
2949 { "reboot", 2, VERB_ANY, 0, reboot_machine },
2950 { "poweroff", 2, VERB_ANY, 0, poweroff_machine },
2951 { "stop", 2, VERB_ANY, 0, poweroff_machine }, /* Convenience alias */
2952 { "kill", 2, VERB_ANY, 0, kill_machine },
2953 { "login", VERB_ANY, 2, 0, login_machine },
2954 { "shell", VERB_ANY, VERB_ANY, 0, shell_machine },
2955 { "bind", 3, 4, 0, bind_mount },
2956 { "edit", 2, VERB_ANY, 0, edit_settings },
2957 { "cat", 2, VERB_ANY, 0, cat_settings },
2958 { "copy-to", 3, 4, 0, copy_files },
2959 { "copy-from", 3, 4, 0, copy_files },
2960 { "remove", 2, VERB_ANY, 0, remove_image },
2961 { "rename", 3, 3, 0, rename_image },
2962 { "clone", 3, 3, 0, clone_image },
2963 { "read-only", 2, 3, 0, read_only_image },
2964 { "start", 2, VERB_ANY, 0, start_machine },
2965 { "enable", 2, VERB_ANY, 0, enable_machine },
2966 { "disable", 2, VERB_ANY, 0, enable_machine },
2967 { "import-tar", 2, 3, 0, import_tar },
2968 { "import-raw", 2, 3, 0, import_raw },
2969 { "import-fs", 2, 3, 0, import_fs },
2970 { "export-tar", 2, 3, 0, export_tar },
2971 { "export-raw", 2, 3, 0, export_raw },
2972 { "pull-tar", 2, 3, 0, pull_tar },
2973 { "pull-raw", 2, 3, 0, pull_raw },
2974 { "list-transfers", VERB_ANY, 1, 0, list_transfers },
2975 { "cancel-transfer", 2, VERB_ANY, 0, cancel_transfer },
2976 { "set-limit", 2, 3, 0, set_limit },
2977 { "clean", VERB_ANY, 1, 0, clean_images },
2978 {}
2979 };
2980
2981 return dispatch_verb(argc, argv, verbs, bus);
2982 }
2983
2984 static int run(int argc, char *argv[]) {
2985 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
2986 int r;
2987
2988 setlocale(LC_ALL, "");
2989 log_setup();
2990
2991 /* The journal merging logic potentially needs a lot of fds. */
2992 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
2993
2994 sigbus_install();
2995
2996 r = parse_argv(argc, argv);
2997 if (r <= 0)
2998 return r;
2999
3000 r = bus_connect_transport(arg_transport, arg_host, RUNTIME_SCOPE_SYSTEM, &bus);
3001 if (r < 0)
3002 return bus_log_connect_error(r, arg_transport);
3003
3004 (void) sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);
3005
3006 return machinectl_main(argc, argv, bus);
3007 }
3008
3009 DEFINE_MAIN_FUNCTION(run);