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