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