]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/systemctl/systemctl.c
docs: Correct resource weight range
[thirdparty/systemd.git] / src / systemctl / systemctl.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
7e4249b9 2
03a7b521
LP
3#include <errno.h>
4#include <fcntl.h>
7e4249b9
LP
5#include <getopt.h>
6#include <stdbool.h>
03a7b521
LP
7#include <stddef.h>
8#include <stdio.h>
4c787df7 9#include <sys/mount.h>
4bb2e9d4 10#include <sys/prctl.h>
03a7b521 11#include <sys/reboot.h>
03a7b521 12#include <unistd.h>
81527be1 13
03a7b521 14#include "sd-bus.h"
f459b602 15#include "sd-daemon.h"
adb6cd9b 16#include "sd-event.h"
f459b602 17#include "sd-login.h"
03a7b521 18
b5efdb8a 19#include "alloc-util.h"
4bb2e9d4 20#include "bootspec.h"
03a7b521
LP
21#include "bus-common-errors.h"
22#include "bus-error.h"
23#include "bus-message.h"
25b1d72d 24#include "bus-unit-procs.h"
291d565a 25#include "bus-unit-util.h"
03a7b521 26#include "bus-util.h"
e45c81b8 27#include "bus-wait-for-jobs.h"
d81bc51f 28#include "bus-wait-for-units.h"
ab35fb1b 29#include "cgroup-show.h"
c6c18be3 30#include "cgroup-util.h"
cda134ab 31#include "copy.h"
a047f4f1 32#include "cpu-set-util.h"
e8630e69 33#include "dirent-util.h"
ad2a0358 34#include "dropin.h"
2fec5854 35#include "efi-loader.h"
5bdf2243 36#include "efivars.h"
03a7b521 37#include "env-util.h"
804ee07c 38#include "escape.h"
b3d59367 39#include "exec-util.h"
03a7b521 40#include "exit-status.h"
3ffd4af2 41#include "fd-util.h"
de9a8fe1 42#include "format-table.h"
f97b34a6 43#include "format-util.h"
f4f15635 44#include "fs-util.h"
7d50b32a 45#include "glob-util.h"
08f3be7a 46#include "hexdecoct.h"
c52a937b 47#include "hostname-util.h"
0a970718 48#include "in-addr-util.h"
03a7b521
LP
49#include "initreq.h"
50#include "install.h"
c004493c 51#include "io-util.h"
305a2850 52#include "journal-util.h"
03a7b521 53#include "list.h"
8752c575 54#include "locale-util.h"
03a7b521
LP
55#include "log.h"
56#include "logs-show.h"
57#include "macro.h"
d1405af3 58#include "main-func.h"
0a970718 59#include "memory-util.h"
03a7b521
LP
60#include "mkdir.h"
61#include "pager.h"
6bedfcbb 62#include "parse-util.h"
03a7b521
LP
63#include "path-lookup.h"
64#include "path-util.h"
294bf0c3 65#include "pretty-print.h"
01771226 66#include "proc-cmdline.h"
03a7b521 67#include "process-util.h"
e3631d1c 68#include "reboot-util.h"
78f22b97 69#include "rlimit-util.h"
03a7b521 70#include "set.h"
592705f2 71#include "sigbus.h"
24882e06 72#include "signal-util.h"
03a7b521 73#include "socket-util.h"
760877e9 74#include "sort-util.h"
03a7b521
LP
75#include "spawn-ask-password-agent.h"
76#include "spawn-polkit-agent.h"
77#include "special.h"
8fcde012 78#include "stat-util.h"
8559e61d 79#include "string-table.h"
03a7b521 80#include "strv.h"
63a3b3cb 81#include "sysv-compat.h"
03a7b521 82#include "terminal-util.h"
e4de7287 83#include "tmpfile-util.h"
89ada3ba 84#include "unit-def.h"
46ff70ca 85#include "unit-file.h"
03a7b521 86#include "unit-name.h"
b1d4f8e1 87#include "user-util.h"
305a2850 88#include "utf8.h"
03a7b521 89#include "utmp-wtmp.h"
e449de87 90#include "verbs.h"
7f4b3c5e 91#include "virt.h"
7e4249b9 92
20b3f379 93static char **arg_types = NULL;
9b9b3d36 94static char **arg_states = NULL;
20b3f379 95static char **arg_properties = NULL;
7e4249b9 96static bool arg_all = false;
afba4199
ZJS
97static enum dependency {
98 DEPENDENCY_FORWARD,
99 DEPENDENCY_REVERSE,
100 DEPENDENCY_AFTER,
101 DEPENDENCY_BEFORE,
071066a5 102 _DEPENDENCY_MAX
afba4199 103} arg_dependency = DEPENDENCY_FORWARD;
e67c3609 104static const char *arg_job_mode = "replace";
729e3769 105static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
93a08841 106static bool arg_wait = false;
ee5762e3 107static bool arg_no_block = false;
ebed32bf 108static bool arg_no_legend = false;
0221d68a 109static PagerFlags arg_pager_flags = 0;
e4b61340 110static bool arg_no_wtmp = false;
f3f054f0 111static bool arg_no_sync = false;
514f4ef5 112static bool arg_no_wall = false;
ee5762e3 113static bool arg_no_reload = false;
4f9a9105 114static bool arg_value = false;
991f2a39 115static bool arg_show_types = false;
b37844d3 116static bool arg_ignore_inhibitors = false;
1ae17672 117static bool arg_dry_run = false;
0183528f 118static bool arg_quiet = false;
ee5762e3 119static bool arg_full = false;
1238ee09 120static bool arg_recursive = false;
e9c387c8 121static bool arg_with_dependencies = false;
85d9b598 122static bool arg_show_transaction = false;
e606bb61 123static int arg_force = 0;
16f017fa 124static bool arg_ask_password = false;
729e3769 125static bool arg_runtime = false;
d309c1c3 126static UnitFilePresetMode arg_preset_mode = UNIT_FILE_PRESET_FULL;
e4b61340 127static char **arg_wall = NULL;
8a0867d6 128static const char *arg_kill_who = NULL;
8a0867d6 129static int arg_signal = SIGTERM;
0f03c2a4 130static char *arg_root = NULL;
f6144808 131static usec_t arg_when = 0;
4445a875 132static enum action {
e4b61340
LP
133 ACTION_SYSTEMCTL,
134 ACTION_HALT,
135 ACTION_POWEROFF,
136 ACTION_REBOOT,
20b09ca7
LP
137 ACTION_KEXEC,
138 ACTION_EXIT,
6edd7d0a
LP
139 ACTION_SUSPEND,
140 ACTION_HIBERNATE,
6524990f 141 ACTION_HYBRID_SLEEP,
e68c79db 142 ACTION_SUSPEND_THEN_HIBERNATE,
e4b61340
LP
143 ACTION_RUNLEVEL2,
144 ACTION_RUNLEVEL3,
145 ACTION_RUNLEVEL4,
146 ACTION_RUNLEVEL5,
147 ACTION_RESCUE,
514f4ef5
LP
148 ACTION_EMERGENCY,
149 ACTION_DEFAULT,
e4b61340
LP
150 ACTION_RELOAD,
151 ACTION_REEXEC,
152 ACTION_RUNLEVEL,
f6144808 153 ACTION_CANCEL_SHUTDOWN,
913c1916
AJ
154 _ACTION_MAX,
155 _ACTION_INVALID = -1
e4b61340 156} arg_action = ACTION_SYSTEMCTL;
f459b602 157static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
fc2ffaf1 158static const char *arg_host = NULL;
df50185b
LP
159static unsigned arg_lines = 10;
160static OutputMode arg_output = OUTPUT_SHORT;
5d0c05e5 161static bool arg_plain = false;
5bdf2243 162static bool arg_firmware_setup = false;
97af80c5
LP
163static usec_t arg_boot_loader_menu = USEC_INFINITY;
164static const char *arg_boot_loader_entry = NULL;
57ab2eab 165static bool arg_now = false;
82948f6c
LP
166static bool arg_jobs_before = false;
167static bool arg_jobs_after = false;
d81bc51f 168static char **arg_clean_what = NULL;
1238ee09 169
e8630e69
ZJS
170/* This is a global cache that will be constructed on first use. */
171static Hashmap *cached_id_map = NULL;
172static Hashmap *cached_name_map = NULL;
173
61ff45db
LP
174STATIC_DESTRUCTOR_REGISTER(arg_wall, strv_freep);
175STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
176STATIC_DESTRUCTOR_REGISTER(arg_types, strv_freep);
177STATIC_DESTRUCTOR_REGISTER(arg_states, strv_freep);
178STATIC_DESTRUCTOR_REGISTER(arg_properties, strv_freep);
d81bc51f 179STATIC_DESTRUCTOR_REGISTER(arg_clean_what, strv_freep);
e8630e69
ZJS
180STATIC_DESTRUCTOR_REGISTER(cached_id_map, hashmap_freep);
181STATIC_DESTRUCTOR_REGISTER(cached_name_map, hashmap_freep);
61ff45db 182
e449de87 183static int daemon_reload(int argc, char *argv[], void* userdata);
2853b60a 184static int trivial_method(int argc, char *argv[], void *userdata);
477def80 185static int halt_now(enum action a);
fa0d5878 186static int get_state_one_unit(sd_bus *bus, const char *name, UnitActiveState *active_state);
dbc2c080 187
4fbd7192
LP
188static bool original_stdout_is_tty;
189
190typedef enum BusFocus {
191 BUS_FULL, /* The full bus indicated via --system or --user */
192 BUS_MANAGER, /* The manager itself, possibly directly, possibly via the bus */
193 _BUS_FOCUS_MAX
194} BusFocus;
195
5238e957 196static sd_bus *buses[_BUS_FOCUS_MAX] = {};
4fbd7192 197
b3796dd8
JS
198static UnitFileFlags args_to_flags(void) {
199 return (arg_runtime ? UNIT_FILE_RUNTIME : 0) |
200 (arg_force ? UNIT_FILE_FORCE : 0);
201}
202
4fbd7192
LP
203static int acquire_bus(BusFocus focus, sd_bus **ret) {
204 int r;
205
206 assert(focus < _BUS_FOCUS_MAX);
207 assert(ret);
208
209 /* We only go directly to the manager, if we are using a local transport */
210 if (arg_transport != BUS_TRANSPORT_LOCAL)
211 focus = BUS_FULL;
212
d4015567
LP
213 if (getenv_bool("SYSTEMCTL_FORCE_BUS") > 0)
214 focus = BUS_FULL;
215
5238e957 216 if (!buses[focus]) {
4fbd7192
LP
217 bool user;
218
219 user = arg_scope != UNIT_FILE_SYSTEM;
220
221 if (focus == BUS_MANAGER)
5238e957 222 r = bus_connect_transport_systemd(arg_transport, arg_host, user, &buses[focus]);
4fbd7192 223 else
5238e957 224 r = bus_connect_transport(arg_transport, arg_host, user, &buses[focus]);
4fbd7192
LP
225 if (r < 0)
226 return log_error_errno(r, "Failed to connect to bus: %m");
227
5238e957 228 (void) sd_bus_set_allow_interactive_authorization(buses[focus], arg_ask_password);
4fbd7192
LP
229 }
230
5238e957 231 *ret = buses[focus];
4fbd7192
LP
232 return 0;
233}
234
235static void release_busses(void) {
236 BusFocus w;
237
238 for (w = 0; w < _BUS_FOCUS_MAX; w++)
5238e957 239 buses[w] = sd_bus_flush_close_unref(buses[w]);
4fbd7192
LP
240}
241
c59e2ec6 242static void ask_password_agent_open_maybe(void) {
729e3769 243 /* Open the password agent as a child process if necessary */
501fc174 244
1ae17672
ZJS
245 if (arg_dry_run)
246 return;
247
729e3769 248 if (arg_scope != UNIT_FILE_SYSTEM)
501fc174
LP
249 return;
250
c59e2ec6 251 ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
6bb92a16
LP
252}
253
8a4b13c5 254static void polkit_agent_open_maybe(void) {
6bb92a16
LP
255 /* Open the polkit agent as a child process if necessary */
256
6bb92a16
LP
257 if (arg_scope != UNIT_FILE_SYSTEM)
258 return;
259
8a4b13c5 260 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
501fc174
LP
261}
262
3c756001
LP
263static OutputFlags get_output_flags(void) {
264 return
265 arg_all * OUTPUT_SHOW_ALL |
459b9f9f 266 (arg_full || !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
40c9fe4c 267 colors_enabled() * OUTPUT_COLOR |
8b0cc9a3 268 !arg_quiet * OUTPUT_WARN_CUTOFF;
3c756001
LP
269}
270
f459b602 271static int translate_bus_error_to_exit_status(int r, const sd_bus_error *error) {
22f4096c
LP
272 assert(error);
273
f459b602 274 if (!sd_bus_error_is_set(error))
22f4096c
LP
275 return r;
276
f459b602
MAP
277 if (sd_bus_error_has_name(error, SD_BUS_ERROR_ACCESS_DENIED) ||
278 sd_bus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
279 sd_bus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
280 sd_bus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
22f4096c
LP
281 return EXIT_NOPERMISSION;
282
f459b602 283 if (sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
22f4096c
LP
284 return EXIT_NOTINSTALLED;
285
f459b602 286 if (sd_bus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
718db961 287 sd_bus_error_has_name(error, SD_BUS_ERROR_NOT_SUPPORTED))
22f4096c
LP
288 return EXIT_NOTIMPLEMENTED;
289
f459b602 290 if (sd_bus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
22f4096c
LP
291 return EXIT_NOTCONFIGURED;
292
293 if (r != 0)
294 return r;
295
296 return EXIT_FAILURE;
297}
298
4fbd7192 299static bool install_client_side(void) {
4fbd7192
LP
300 /* Decides when to execute enable/disable/... operations
301 * client-side rather than server-side. */
4f16c1f4 302
f38951a6 303 if (running_in_chroot_or_offline())
729e3769
LP
304 return true;
305
306 if (sd_booted() <= 0)
307 return true;
308
309 if (!isempty(arg_root))
310 return true;
311
312 if (arg_scope == UNIT_FILE_GLOBAL)
313 return true;
314
b41b9d2a
LP
315 /* Unsupported environment variable, mostly for debugging purposes */
316 if (getenv_bool("SYSTEMCTL_INSTALL_CLIENT_SIDE") > 0)
317 return true;
318
729e3769
LP
319 return false;
320}
321
93bab288 322static int compare_unit_info(const UnitInfo *a, const UnitInfo *b) {
36c32ba2 323 const char *d1, *d2;
1238ee09
LP
324 int r;
325
326 /* First, order by machine */
93bab288 327 if (!a->machine && b->machine)
1238ee09 328 return -1;
93bab288 329 if (a->machine && !b->machine)
1238ee09 330 return 1;
93bab288
YW
331 if (a->machine && b->machine) {
332 r = strcasecmp(a->machine, b->machine);
1238ee09
LP
333 if (r != 0)
334 return r;
335 }
36c32ba2 336
1238ee09 337 /* Second, order by unit type */
93bab288
YW
338 d1 = strrchr(a->id, '.');
339 d2 = strrchr(b->id, '.');
36c32ba2 340 if (d1 && d2) {
f84190d8
LP
341 r = strcasecmp(d1, d2);
342 if (r != 0)
36c32ba2
LP
343 return r;
344 }
345
1238ee09 346 /* Third, order by name */
93bab288 347 return strcasecmp(a->id, b->id);
36c32ba2
LP
348}
349
16484a8a
ZJS
350static const char* unit_type_suffix(const char *name) {
351 const char *dot;
352
353 dot = strrchr(name, '.');
354 if (!dot)
355 return "";
356
357 return dot + 1;
358}
359
d8fba7c6 360static bool output_show_unit(const UnitInfo *u, char **patterns) {
f8591ee1
LP
361 assert(u);
362
2404701e 363 if (!strv_fnmatch_or_empty(patterns, u->id, FNM_NOESCAPE))
d8fba7c6 364 return false;
d8fba7c6 365
16484a8a
ZJS
366 if (arg_types && !strv_find(arg_types, unit_type_suffix(u->id)))
367 return false;
6c71341a
ZJS
368
369 if (arg_all)
370 return true;
371
409472cb
FB
372 /* Note that '--all' is not purely a state filter, but also a
373 * filter that hides units that "follow" other units (which is
374 * used for device units that appear under different names). */
375 if (!isempty(u->following))
376 return false;
377
ebc96265
FB
378 if (!strv_isempty(arg_states))
379 return true;
380
381 /* By default show all units except the ones in inactive
382 * state and with no pending job */
6c71341a
ZJS
383 if (u->job_id > 0)
384 return true;
385
409472cb 386 if (streq(u->active_state, "inactive"))
6c71341a
ZJS
387 return false;
388
389 return true;
33330222
ZJS
390}
391
1238ee09 392static int output_units_list(const UnitInfo *unit_infos, unsigned c) {
de9a8fe1 393 _cleanup_(table_unrefp) Table *table = NULL;
f459b602 394 const UnitInfo *u;
b5d7f1bb 395 int job_count = 0;
de9a8fe1 396 int r;
cbc9fbd1 397
de9a8fe1
FS
398 table = table_new("", "unit", "load", "active", "sub", "job", "description");
399 if (!table)
400 return log_oom();
cbc9fbd1 401
de9a8fe1
FS
402 table_set_header(table, !arg_no_legend);
403 if (arg_full)
404 table_set_width(table, 0);
4deb3b93 405
b036fc00 406 for (u = unit_infos; u < unit_infos + c; u++) {
de9a8fe1
FS
407 _cleanup_free_ char *j = NULL;
408 const char *on_underline = "", *on_loaded = "", *on_active = "";
409 const char *on_circle = "", *id;
16484a8a 410 bool circle = false, underline = false;
b036fc00 411
16484a8a
ZJS
412 if (u + 1 < unit_infos + c &&
413 !streq(unit_type_suffix(u->id), unit_type_suffix((u + 1)->id))) {
414 on_underline = ansi_underline();
16484a8a
ZJS
415 underline = true;
416 }
417
c4555ad8 418 if (STR_IN_SET(u->load_state, "error", "not-found", "bad-setting", "masked") && !arg_plain) {
90c3f79d 419 on_circle = ansi_highlight_yellow();
90c3f79d 420 circle = true;
16484a8a 421 on_loaded = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
250ba664 422 } else if (streq(u->active_state, "failed") && !arg_plain) {
16484a8a 423 on_circle = ansi_highlight_red();
90c3f79d 424 circle = true;
16484a8a 425 on_active = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
de9a8fe1
FS
426 } else {
427 on_active = on_underline;
428 on_loaded = on_underline;
90c3f79d 429 }
eb68c413 430
1238ee09 431 if (u->machine) {
605405c6 432 j = strjoin(u->machine, ":", u->id);
1238ee09
LP
433 if (!j)
434 return log_oom();
435
436 id = j;
437 } else
438 id = u->id;
439
de9a8fe1
FS
440 r = table_add_many(table,
441 TABLE_STRING, circle ? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE) : " ",
442 TABLE_SET_COLOR, on_circle,
443 TABLE_STRING, id,
444 TABLE_SET_COLOR, on_active,
445 TABLE_STRING, u->load_state,
446 TABLE_SET_COLOR, on_loaded,
447 TABLE_STRING, u->active_state,
448 TABLE_SET_COLOR, on_active,
449 TABLE_STRING, u->sub_state,
450 TABLE_SET_COLOR, on_active,
451 TABLE_STRING, u->job_id ? u->job_type: "",
452 TABLE_SET_COLOR, u->job_id ? on_underline : "",
453 TABLE_STRING, u->description,
454 TABLE_SET_COLOR, on_underline);
455 if (r < 0)
456 return table_log_add_error(r);
1238ee09 457
de9a8fe1
FS
458 if (u->job_id != 0)
459 job_count++;
460 }
eb68c413 461
de9a8fe1
FS
462 if (job_count == 0) {
463 /* There's no data in the JOB column, so let's hide it */
464 /* Also, convert all number constants to size_t so va_arg()
465 * in table_set_display() fetches a correct number of bytes from
466 * the stack */
467 r = table_set_display(table, (size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 4, (size_t) 6, (size_t) -1);
468 if (r < 0)
469 return log_error_errno(r, "Failed to set columns to display: %m");
eb68c413
ZJS
470 }
471
de9a8fe1
FS
472 r = table_print(table, NULL);
473 if (r < 0)
474 return log_error_errno(r, "Failed to print the table: %m");
475
ebed32bf 476 if (!arg_no_legend) {
57f7ae4f 477 const char *on, *off;
de9a8fe1 478 size_t records = table_get_rows(table) - 1;
57f7ae4f 479
de9a8fe1 480 if (records > 0) {
90c3f79d
LP
481 puts("\n"
482 "LOAD = Reflects whether the unit definition was properly loaded.\n"
e3e0314b
ZJS
483 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
484 "SUB = The low-level unit activation state, values depend on unit type.");
485 puts(job_count ? "JOB = Pending job for the unit.\n" : "");
0b5a519c 486 on = ansi_highlight();
1fc464f6 487 off = ansi_normal();
57f7ae4f 488 } else {
0b5a519c 489 on = ansi_highlight_red();
1fc464f6 490 off = ansi_normal();
57f7ae4f 491 }
eb68c413 492
8eb0cafe 493 if (arg_all || strv_contains(arg_states, "inactive"))
de9a8fe1 494 printf("%s%zu loaded units listed.%s\n"
57f7ae4f 495 "To show all installed unit files use 'systemctl list-unit-files'.\n",
de9a8fe1 496 on, records, off);
8eb0cafe 497 else if (!arg_states)
de9a8fe1 498 printf("%s%zu loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
57f7ae4f 499 "To show all installed unit files use 'systemctl list-unit-files'.\n",
de9a8fe1 500 on, records, off);
8eb0cafe 501 else
de9a8fe1 502 printf("%zu loaded units listed.\n", records);
eb68c413 503 }
1238ee09
LP
504
505 return 0;
eb68c413
ZJS
506}
507
a00963a2 508static int get_unit_list(
f459b602 509 sd_bus *bus,
1238ee09
LP
510 const char *machine,
511 char **patterns,
512 UnitInfo **unit_infos,
513 int c,
514 sd_bus_message **_reply) {
a00963a2 515
4afd3348
LP
516 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
517 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
518 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
ca2d3784 519 size_t size = c;
1238ee09 520 int r;
f459b602 521 UnitInfo u;
313fe66f 522 bool fallback = false;
7e4249b9 523
265a7a2a 524 assert(bus);
1238ee09 525 assert(unit_infos);
f459b602 526 assert(_reply);
1238ee09 527
cdc06ed7 528 r = sd_bus_message_new_method_call(
f22f08cd 529 bus,
cdc06ed7 530 &m,
f22f08cd
SP
531 "org.freedesktop.systemd1",
532 "/org/freedesktop/systemd1",
533 "org.freedesktop.systemd1.Manager",
313fe66f 534 "ListUnitsByPatterns");
cdc06ed7
DS
535 if (r < 0)
536 return bus_log_create_error(r);
537
538 r = sd_bus_message_append_strv(m, arg_states);
539 if (r < 0)
540 return bus_log_create_error(r);
541
313fe66f 542 r = sd_bus_message_append_strv(m, patterns);
543 if (r < 0)
544 return bus_log_create_error(r);
545
cdc06ed7 546 r = sd_bus_call(bus, m, 0, &error, &reply);
33d52725
ZJS
547 if (r < 0 && (sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_METHOD) ||
548 sd_bus_error_has_name(&error, SD_BUS_ERROR_ACCESS_DENIED))) {
313fe66f 549 /* Fallback to legacy ListUnitsFiltered method */
550 fallback = true;
551 log_debug_errno(r, "Failed to list units: %s Falling back to ListUnitsFiltered method.", bus_error_message(&error, r));
552 m = sd_bus_message_unref(m);
553 sd_bus_error_free(&error);
554
555 r = sd_bus_message_new_method_call(
556 bus,
557 &m,
558 "org.freedesktop.systemd1",
559 "/org/freedesktop/systemd1",
560 "org.freedesktop.systemd1.Manager",
561 "ListUnitsFiltered");
562 if (r < 0)
563 return bus_log_create_error(r);
564
565 r = sd_bus_message_append_strv(m, arg_states);
566 if (r < 0)
567 return bus_log_create_error(r);
568
569 r = sd_bus_call(bus, m, 0, &error, &reply);
570 }
4c3e8e39
LP
571 if (r < 0)
572 return log_error_errno(r, "Failed to list units: %s", bus_error_message(&error, r));
7e4249b9 573
f459b602
MAP
574 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
575 if (r < 0)
576 return bus_log_parse_error(r);
7e4249b9 577
f459b602 578 while ((r = bus_parse_unit_info(reply, &u)) > 0) {
1238ee09
LP
579 u.machine = machine;
580
313fe66f 581 if (!output_show_unit(&u, fallback ? patterns : NULL))
8d5ba5a9 582 continue;
7e4249b9 583
1238ee09 584 if (!GREEDY_REALLOC(*unit_infos, size, c+1))
f459b602 585 return log_oom();
36c32ba2 586
1238ee09 587 (*unit_infos)[c++] = u;
991f2a39 588 }
f459b602
MAP
589 if (r < 0)
590 return bus_log_parse_error(r);
991f2a39 591
f459b602
MAP
592 r = sd_bus_message_exit_container(reply);
593 if (r < 0)
594 return bus_log_parse_error(r);
595
1cc6c93a 596 *_reply = TAKE_PTR(reply);
f459b602 597
1238ee09
LP
598 return c;
599}
600
601static void message_set_freep(Set **set) {
224b0e7a 602 set_free_with_destructor(*set, sd_bus_message_unref);
1238ee09
LP
603}
604
605static int get_unit_list_recursive(
606 sd_bus *bus,
607 char **patterns,
608 UnitInfo **_unit_infos,
609 Set **_replies,
610 char ***_machines) {
611
612 _cleanup_free_ UnitInfo *unit_infos = NULL;
613 _cleanup_(message_set_freep) Set *replies;
614 sd_bus_message *reply;
615 int c, r;
616
617 assert(bus);
618 assert(_replies);
619 assert(_unit_infos);
620 assert(_machines);
621
d5099efc 622 replies = set_new(NULL);
1238ee09
LP
623 if (!replies)
624 return log_oom();
625
626 c = get_unit_list(bus, NULL, patterns, &unit_infos, 0, &reply);
627 if (c < 0)
628 return c;
629
630 r = set_put(replies, reply);
631 if (r < 0) {
632 sd_bus_message_unref(reply);
4c3e8e39 633 return log_oom();
1238ee09
LP
634 }
635
636 if (arg_recursive) {
637 _cleanup_strv_free_ char **machines = NULL;
638 char **i;
639
640 r = sd_get_machine_names(&machines);
641 if (r < 0)
4c3e8e39 642 return log_error_errno(r, "Failed to get machine names: %m");
1238ee09
LP
643
644 STRV_FOREACH(i, machines) {
4afd3348 645 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *container = NULL;
1238ee09
LP
646 int k;
647
de33fc62 648 r = sd_bus_open_system_machine(&container, *i);
1238ee09 649 if (r < 0) {
4c3e8e39 650 log_warning_errno(r, "Failed to connect to container %s, ignoring: %m", *i);
1238ee09
LP
651 continue;
652 }
653
654 k = get_unit_list(container, *i, patterns, &unit_infos, c, &reply);
655 if (k < 0)
656 return k;
657
658 c = k;
659
660 r = set_put(replies, reply);
661 if (r < 0) {
662 sd_bus_message_unref(reply);
4c3e8e39 663 return log_oom();
1238ee09
LP
664 }
665 }
666
1cc6c93a 667 *_machines = TAKE_PTR(machines);
1238ee09
LP
668 } else
669 *_machines = NULL;
670
1cc6c93a 671 *_unit_infos = TAKE_PTR(unit_infos);
1cc6c93a 672 *_replies = TAKE_PTR(replies);
1238ee09 673
f459b602 674 return c;
991f2a39
ZJS
675}
676
1d56bc09 677static int expand_names(sd_bus *bus, char **names, const char* suffix, char ***ret, bool *ret_expanded) {
3a77f9fb
KK
678 _cleanup_strv_free_ char **mangled = NULL, **globs = NULL;
679 char **name;
680 int r, i;
681
682 assert(bus);
683 assert(ret);
684
685 STRV_FOREACH(name, names) {
686 char *t;
687 UnitNameMangle options = UNIT_NAME_MANGLE_GLOB | (arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN);
688
df7c4eb6 689 r = unit_name_mangle_with_suffix(*name, NULL, options, suffix ?: ".service", &t);
3a77f9fb
KK
690 if (r < 0)
691 return log_error_errno(r, "Failed to mangle name: %m");
692
693 if (string_is_glob(t))
694 r = strv_consume(&globs, t);
695 else
696 r = strv_consume(&mangled, t);
697 if (r < 0)
698 return log_oom();
699 }
700
701 /* Query the manager only if any of the names are a glob, since
702 * this is fairly expensive */
1d56bc09
ZJS
703 bool expanded = !strv_isempty(globs);
704 if (expanded) {
3a77f9fb
KK
705 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
706 _cleanup_free_ UnitInfo *unit_infos = NULL;
707 size_t allocated, n;
708
709 r = get_unit_list(bus, NULL, globs, &unit_infos, 0, &reply);
710 if (r < 0)
711 return r;
712
713 n = strv_length(mangled);
714 allocated = n + 1;
715
716 for (i = 0; i < r; i++) {
717 if (!GREEDY_REALLOC(mangled, allocated, n+2))
718 return log_oom();
719
720 mangled[n] = strdup(unit_infos[i].id);
721 if (!mangled[n])
722 return log_oom();
723
724 mangled[++n] = NULL;
725 }
726 }
727
1d56bc09
ZJS
728 if (ret_expanded)
729 *ret_expanded = expanded;
730
3a77f9fb
KK
731 *ret = TAKE_PTR(mangled);
732 return 0;
733}
734
e9c387c8
KK
735static int list_dependencies_get_dependencies(sd_bus *bus, const char *name, char ***ret) {
736 _cleanup_strv_free_ char **deps = NULL;
737
738 static const struct bus_properties_map map[_DEPENDENCY_MAX][6] = {
739 [DEPENDENCY_FORWARD] = {
740 { "Requires", "as", NULL, 0 },
741 { "Requisite", "as", NULL, 0 },
742 { "Wants", "as", NULL, 0 },
743 { "ConsistsOf", "as", NULL, 0 },
744 { "BindsTo", "as", NULL, 0 },
745 {}
746 },
747 [DEPENDENCY_REVERSE] = {
748 { "RequiredBy", "as", NULL, 0 },
749 { "RequisiteOf", "as", NULL, 0 },
750 { "WantedBy", "as", NULL, 0 },
751 { "PartOf", "as", NULL, 0 },
752 { "BoundBy", "as", NULL, 0 },
753 {}
754 },
755 [DEPENDENCY_AFTER] = {
756 { "After", "as", NULL, 0 },
757 {}
758 },
759 [DEPENDENCY_BEFORE] = {
760 { "Before", "as", NULL, 0 },
761 {}
762 },
763 };
764
765 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
766 _cleanup_free_ char *dbus_path = NULL;
767 int r;
768
769 assert(bus);
770 assert(name);
771 assert(ret);
772
773 dbus_path = unit_dbus_path_from_name(name);
774 if (!dbus_path)
775 return log_oom();
776
777 r = bus_map_all_properties(bus,
778 "org.freedesktop.systemd1",
779 dbus_path,
780 map[arg_dependency],
781 BUS_MAP_STRDUP,
782 &error,
783 NULL,
784 &deps);
785 if (r < 0)
786 return log_error_errno(r, "Failed to get properties of %s: %s", name, bus_error_message(&error, r));
787
788 *ret = TAKE_PTR(deps);
789
790 return 0;
791}
792
793static int append_unit_dependencies(sd_bus *bus, char **names, char ***ret) {
794 _cleanup_strv_free_ char **with_deps = NULL;
795 char **name;
796
797 assert(bus);
798 assert(ret);
799
800 STRV_FOREACH(name, names) {
801 _cleanup_strv_free_ char **deps = NULL;
802
803 if (strv_extend(&with_deps, *name) < 0)
804 return log_oom();
805
806 (void) list_dependencies_get_dependencies(bus, *name, &deps);
807
808 if (strv_extend_strv(&with_deps, deps, true) < 0)
809 return log_oom();
810 }
811
812 *ret = TAKE_PTR(with_deps);
813
814 return 0;
815}
816
817static int maybe_extend_with_unit_dependencies(sd_bus *bus, char ***list) {
818 assert(bus);
819 assert(list);
820
821 if (arg_with_dependencies) {
822 int r;
823 _cleanup_strv_free_ char **list_with_deps = NULL;
824
825 r = append_unit_dependencies(bus, *list, &list_with_deps);
826 if (r < 0)
827 return log_error_errno(r, "Failed to append unit dependencies: %m");
828
829 strv_free(*list);
830 *list = TAKE_PTR(list_with_deps);
831 }
832
833 return 0;
834}
835
e449de87 836static int list_units(int argc, char *argv[], void *userdata) {
f459b602 837 _cleanup_free_ UnitInfo *unit_infos = NULL;
1238ee09
LP
838 _cleanup_(message_set_freep) Set *replies = NULL;
839 _cleanup_strv_free_ char **machines = NULL;
4fbd7192 840 sd_bus *bus;
991f2a39
ZJS
841 int r;
842
4fbd7192
LP
843 r = acquire_bus(BUS_MANAGER, &bus);
844 if (r < 0)
845 return r;
846
0221d68a 847 (void) pager_open(arg_pager_flags);
d2ad7e1b 848
e9c387c8
KK
849 if (arg_with_dependencies) {
850 _cleanup_strv_free_ char **names = NULL;
851
852 r = append_unit_dependencies(bus, strv_skip(argv, 1), &names);
853 if (r < 0)
854 return r;
855
856 r = get_unit_list_recursive(bus, names, &unit_infos, &replies, &machines);
857 if (r < 0)
858 return r;
859 } else {
860 r = get_unit_list_recursive(bus, strv_skip(argv, 1), &unit_infos, &replies, &machines);
861 if (r < 0)
862 return r;
863 }
991f2a39 864
93bab288 865 typesafe_qsort(unit_infos, r, compare_unit_info);
1238ee09 866 return output_units_list(unit_infos, r);
991f2a39
ZJS
867}
868
a00963a2 869static int get_triggered_units(
f459b602
MAP
870 sd_bus *bus,
871 const char* path,
872 char*** ret) {
a00963a2 873
4afd3348 874 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
991f2a39
ZJS
875 int r;
876
4fbd7192
LP
877 assert(bus);
878 assert(path);
879 assert(ret);
880
f459b602
MAP
881 r = sd_bus_get_property_strv(
882 bus,
883 "org.freedesktop.systemd1",
884 path,
885 "org.freedesktop.systemd1.Unit",
886 "Triggers",
887 &error,
888 ret);
f459b602 889 if (r < 0)
691395d8 890 return log_error_errno(r, "Failed to determine triggers: %s", bus_error_message(&error, r));
991f2a39
ZJS
891
892 return 0;
893}
894
f459b602
MAP
895static int get_listening(
896 sd_bus *bus,
897 const char* unit_path,
cbb76c29 898 char*** listening) {
f459b602 899
4afd3348
LP
900 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
901 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602 902 const char *type, *path;
cbb76c29 903 int r, n = 0;
991f2a39 904
f459b602
MAP
905 r = sd_bus_get_property(
906 bus,
907 "org.freedesktop.systemd1",
908 unit_path,
909 "org.freedesktop.systemd1.Socket",
910 "Listen",
911 &error,
912 &reply,
913 "a(ss)");
691395d8
LP
914 if (r < 0)
915 return log_error_errno(r, "Failed to get list of listening sockets: %s", bus_error_message(&error, r));
991f2a39 916
f459b602
MAP
917 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ss)");
918 if (r < 0)
919 return bus_log_parse_error(r);
991f2a39 920
f459b602 921 while ((r = sd_bus_message_read(reply, "(ss)", &type, &path)) > 0) {
36c32ba2 922
0d95178e 923 r = strv_extend(listening, type);
f459b602
MAP
924 if (r < 0)
925 return log_oom();
991f2a39 926
0d95178e 927 r = strv_extend(listening, path);
f459b602
MAP
928 if (r < 0)
929 return log_oom();
7e4249b9 930
cbb76c29 931 n++;
36c32ba2 932 }
f459b602
MAP
933 if (r < 0)
934 return bus_log_parse_error(r);
935
936 r = sd_bus_message_exit_container(reply);
937 if (r < 0)
938 return bus_log_parse_error(r);
36c32ba2 939
cbb76c29 940 return n;
991f2a39
ZJS
941}
942
943struct socket_info {
0cfc3525 944 const char *machine;
991f2a39
ZJS
945 const char* id;
946
947 char* type;
948 char* path;
949
950 /* Note: triggered is a list here, although it almost certainly
951 * will always be one unit. Nevertheless, dbus API allows for multiple
f7340ab2 952 * values, so let's follow that. */
991f2a39
ZJS
953 char** triggered;
954
955 /* The strv above is shared. free is set only in the first one. */
956 bool own_triggered;
957};
958
cbb76c29 959static int socket_info_compare(const struct socket_info *a, const struct socket_info *b) {
93bab288 960 int r;
cbc9fbd1 961
cbb76c29
LP
962 assert(a);
963 assert(b);
964
0cfc3525
TA
965 if (!a->machine && b->machine)
966 return -1;
967 if (a->machine && !b->machine)
968 return 1;
969 if (a->machine && b->machine) {
93bab288
YW
970 r = strcasecmp(a->machine, b->machine);
971 if (r != 0)
972 return r;
0cfc3525
TA
973 }
974
93bab288
YW
975 r = strcmp(a->path, b->path);
976 if (r == 0)
977 r = strcmp(a->type, b->type);
cbc9fbd1 978
93bab288 979 return r;
991f2a39
ZJS
980}
981
982static int output_sockets_list(struct socket_info *socket_infos, unsigned cs) {
de9a8fe1 983 _cleanup_(table_unrefp) Table *table = NULL;
991f2a39 984 struct socket_info *s;
991f2a39 985 const char *on, *off;
de9a8fe1 986 int r;
991f2a39 987
de9a8fe1
FS
988 table = table_new("listen", "type", "units", "activates");
989 if (!table)
990 return log_oom();
991f2a39 991
de9a8fe1
FS
992 if (!arg_show_types) {
993 /* Hide the second (TYPE) column */
994 r = table_set_display(table, 0, 2, 3, (size_t) -1);
995 if (r < 0)
996 return log_error_errno(r, "Failed to set columns to display: %m");
991f2a39
ZJS
997 }
998
de9a8fe1
FS
999 table_set_header(table, !arg_no_legend);
1000 if (arg_full)
1001 table_set_width(table, 0);
991f2a39 1002
de9a8fe1 1003 if (cs) {
991f2a39 1004 for (s = socket_infos; s < socket_infos + cs; s++) {
de9a8fe1 1005 _cleanup_free_ char *j = NULL, *activates = NULL;
0cfc3525 1006 const char *path;
991f2a39 1007
0cfc3525 1008 if (s->machine) {
605405c6 1009 j = strjoin(s->machine, ":", s->path);
0cfc3525
TA
1010 if (!j)
1011 return log_oom();
1012 path = j;
1013 } else
1014 path = s->path;
1015
de9a8fe1
FS
1016 activates = strv_join(s->triggered, ", ");
1017 if (!activates)
1018 return log_oom();
1019
1020 r = table_add_many(table,
1021 TABLE_STRING, path,
1022 TABLE_STRING, s->type,
1023 TABLE_STRING, s->id,
1024 TABLE_STRING, activates);
1025 if (r < 0)
1026 return table_log_add_error(r);
991f2a39
ZJS
1027 }
1028
0b5a519c 1029 on = ansi_highlight();
1fc464f6 1030 off = ansi_normal();
991f2a39 1031 } else {
0b5a519c 1032 on = ansi_highlight_red();
1fc464f6 1033 off = ansi_normal();
991f2a39
ZJS
1034 }
1035
de9a8fe1
FS
1036 r = table_print(table, NULL);
1037 if (r < 0)
1038 return log_error_errno(r, "Failed to print the table: %m");
1039
571bfc6c 1040 if (!arg_no_legend) {
de9a8fe1 1041 printf("\n%s%u sockets listed.%s\n", on, cs, off);
571bfc6c
MM
1042 if (!arg_all)
1043 printf("Pass --all to see loaded but inactive sockets, too.\n");
1044 }
265a7a2a
ZJS
1045
1046 return 0;
1047}
1048
e449de87 1049static int list_sockets(int argc, char *argv[], void *userdata) {
0cfc3525
TA
1050 _cleanup_(message_set_freep) Set *replies = NULL;
1051 _cleanup_strv_free_ char **machines = NULL;
3a77f9fb 1052 _cleanup_strv_free_ char **sockets_with_suffix = NULL;
f459b602 1053 _cleanup_free_ UnitInfo *unit_infos = NULL;
8d5ba5a9 1054 _cleanup_free_ struct socket_info *socket_infos = NULL;
f459b602 1055 const UnitInfo *u;
991f2a39 1056 struct socket_info *s;
cbb76c29 1057 unsigned cs = 0;
991f2a39 1058 size_t size = 0;
ad83b4c4 1059 int r = 0, n;
4fbd7192 1060 sd_bus *bus;
265a7a2a 1061
4fbd7192
LP
1062 r = acquire_bus(BUS_MANAGER, &bus);
1063 if (r < 0)
1064 return r;
1065
0221d68a 1066 (void) pager_open(arg_pager_flags);
d2ad7e1b 1067
1d56bc09 1068 r = expand_names(bus, strv_skip(argv, 1), ".socket", &sockets_with_suffix, NULL);
3a77f9fb
KK
1069 if (r < 0)
1070 return r;
265a7a2a 1071
3a77f9fb
KK
1072 if (argc == 1 || sockets_with_suffix) {
1073 n = get_unit_list_recursive(bus, sockets_with_suffix, &unit_infos, &replies, &machines);
1074 if (n < 0)
1075 return n;
991f2a39 1076
3a77f9fb
KK
1077 for (u = unit_infos; u < unit_infos + n; u++) {
1078 _cleanup_strv_free_ char **listening = NULL, **triggered = NULL;
1079 int i, c;
991f2a39 1080
3a77f9fb
KK
1081 if (!endswith(u->id, ".socket"))
1082 continue;
991f2a39 1083
3a77f9fb
KK
1084 r = get_triggered_units(bus, u->unit_path, &triggered);
1085 if (r < 0)
1086 goto cleanup;
991f2a39 1087
3a77f9fb
KK
1088 c = get_listening(bus, u->unit_path, &listening);
1089 if (c < 0) {
1090 r = c;
1091 goto cleanup;
1092 }
991f2a39 1093
3a77f9fb
KK
1094 if (!GREEDY_REALLOC(socket_infos, size, cs + c)) {
1095 r = log_oom();
1096 goto cleanup;
1097 }
991f2a39 1098
3a77f9fb
KK
1099 for (i = 0; i < c; i++)
1100 socket_infos[cs + i] = (struct socket_info) {
1101 .machine = u->machine,
1102 .id = u->id,
1103 .type = listening[i*2],
1104 .path = listening[i*2 + 1],
1105 .triggered = triggered,
1106 .own_triggered = i==0,
1107 };
1108
1109 /* from this point on we will cleanup those socket_infos */
1110 cs += c;
1111 free(listening);
1112 listening = triggered = NULL; /* avoid cleanup */
1113 }
991f2a39 1114
3a77f9fb
KK
1115 typesafe_qsort(socket_infos, cs, socket_info_compare);
1116 }
991f2a39
ZJS
1117
1118 output_sockets_list(socket_infos, cs);
1119
1120 cleanup:
1121 assert(cs == 0 || socket_infos);
1122 for (s = socket_infos; s < socket_infos + cs; s++) {
1123 free(s->type);
1124 free(s->path);
1125 if (s->own_triggered)
1126 strv_free(s->triggered);
1127 }
4445a875 1128
872c8faa 1129 return r;
4445a875
LP
1130}
1131
cbb76c29
LP
1132static int get_next_elapse(
1133 sd_bus *bus,
1134 const char *path,
1135 dual_timestamp *next) {
1136
4afd3348 1137 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
cbb76c29
LP
1138 dual_timestamp t;
1139 int r;
1140
1141 assert(bus);
1142 assert(path);
1143 assert(next);
1144
1145 r = sd_bus_get_property_trivial(
1146 bus,
1147 "org.freedesktop.systemd1",
1148 path,
1149 "org.freedesktop.systemd1.Timer",
1150 "NextElapseUSecMonotonic",
1151 &error,
1152 't',
1153 &t.monotonic);
691395d8 1154 if (r < 0)
021723c6 1155 return log_error_errno(r, "Failed to get next elapse time: %s", bus_error_message(&error, r));
cbb76c29
LP
1156
1157 r = sd_bus_get_property_trivial(
1158 bus,
1159 "org.freedesktop.systemd1",
1160 path,
1161 "org.freedesktop.systemd1.Timer",
1162 "NextElapseUSecRealtime",
1163 &error,
1164 't',
1165 &t.realtime);
691395d8 1166 if (r < 0)
021723c6 1167 return log_error_errno(r, "Failed to get next elapse time: %s", bus_error_message(&error, r));
cbb76c29
LP
1168
1169 *next = t;
1170 return 0;
1171}
1172
d784e2db
LP
1173static int get_last_trigger(
1174 sd_bus *bus,
1175 const char *path,
1176 usec_t *last) {
1177
4afd3348 1178 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
d784e2db
LP
1179 int r;
1180
1181 assert(bus);
1182 assert(path);
1183 assert(last);
1184
1185 r = sd_bus_get_property_trivial(
1186 bus,
1187 "org.freedesktop.systemd1",
1188 path,
1189 "org.freedesktop.systemd1.Timer",
dedabea4 1190 "LastTriggerUSec",
d784e2db
LP
1191 &error,
1192 't',
1193 last);
691395d8
LP
1194 if (r < 0)
1195 return log_error_errno(r, "Failed to get last trigger time: %s", bus_error_message(&error, r));
d784e2db
LP
1196
1197 return 0;
1198}
1199
cbb76c29 1200struct timer_info {
806a37e7 1201 const char* machine;
cbb76c29
LP
1202 const char* id;
1203 usec_t next_elapse;
d784e2db 1204 usec_t last_trigger;
cbb76c29
LP
1205 char** triggered;
1206};
1207
1208static int timer_info_compare(const struct timer_info *a, const struct timer_info *b) {
93bab288 1209 int r;
806a37e7 1210
cbb76c29
LP
1211 assert(a);
1212 assert(b);
1213
806a37e7
TA
1214 if (!a->machine && b->machine)
1215 return -1;
1216 if (a->machine && !b->machine)
1217 return 1;
1218 if (a->machine && b->machine) {
93bab288
YW
1219 r = strcasecmp(a->machine, b->machine);
1220 if (r != 0)
1221 return r;
806a37e7
TA
1222 }
1223
93bab288
YW
1224 r = CMP(a->next_elapse, b->next_elapse);
1225 if (r != 0)
1226 return r;
cbb76c29
LP
1227
1228 return strcmp(a->id, b->id);
1229}
1230
1231static int output_timers_list(struct timer_info *timer_infos, unsigned n) {
de9a8fe1 1232 _cleanup_(table_unrefp) Table *table = NULL;
cbb76c29 1233 struct timer_info *t;
cbb76c29 1234 const char *on, *off;
de9a8fe1 1235 int r;
cbb76c29
LP
1236
1237 assert(timer_infos || n == 0);
1238
de9a8fe1
FS
1239 table = table_new("next", "left", "last", "passed", "unit", "activates");
1240 if (!table)
1241 return log_oom();
d784e2db 1242
de9a8fe1
FS
1243 table_set_header(table, !arg_no_legend);
1244 if (arg_full)
1245 table_set_width(table, 0);
cbb76c29
LP
1246
1247 if (n > 0) {
cbb76c29 1248 for (t = timer_infos; t < timer_infos + n; t++) {
de9a8fe1 1249 _cleanup_free_ char *j = NULL, *activates = NULL;
806a37e7 1250 const char *unit;
d784e2db 1251
806a37e7 1252 if (t->machine) {
605405c6 1253 j = strjoin(t->machine, ":", t->id);
806a37e7
TA
1254 if (!j)
1255 return log_oom();
1256 unit = j;
1257 } else
1258 unit = t->id;
1259
de9a8fe1
FS
1260 activates = strv_join(t->triggered, ", ");
1261 if (!activates)
1262 return log_oom();
cbb76c29 1263
de9a8fe1
FS
1264 r = table_add_many(table,
1265 TABLE_TIMESTAMP, t->next_elapse,
1266 TABLE_TIMESTAMP_RELATIVE, t->next_elapse,
1267 TABLE_TIMESTAMP, t->last_trigger,
1268 TABLE_TIMESTAMP_RELATIVE, t->last_trigger,
1269 TABLE_STRING, unit,
1270 TABLE_STRING, activates);
1271 if (r < 0)
1272 return table_log_add_error(r);
cbb76c29
LP
1273 }
1274
1275 on = ansi_highlight();
1fc464f6 1276 off = ansi_normal();
cbb76c29
LP
1277 } else {
1278 on = ansi_highlight_red();
1fc464f6 1279 off = ansi_normal();
cbb76c29
LP
1280 }
1281
de9a8fe1
FS
1282 r = table_print(table, NULL);
1283 if (r < 0)
1284 return log_error_errno(r, "Failed to print the table: %m");
1285
cbb76c29 1286 if (!arg_no_legend) {
de9a8fe1 1287 printf("\n%s%u timers listed.%s\n", on, n, off);
cbb76c29
LP
1288 if (!arg_all)
1289 printf("Pass --all to see loaded but inactive timers, too.\n");
1290 }
1291
1292 return 0;
1293}
1294
f5080e73
DH
1295static usec_t calc_next_elapse(dual_timestamp *nw, dual_timestamp *next) {
1296 usec_t next_elapse;
1297
1298 assert(nw);
1299 assert(next);
1300
1f65fd49 1301 if (timestamp_is_set(next->monotonic)) {
f5080e73
DH
1302 usec_t converted;
1303
1304 if (next->monotonic > nw->monotonic)
1305 converted = nw->realtime + (next->monotonic - nw->monotonic);
1306 else
1307 converted = nw->realtime - (nw->monotonic - next->monotonic);
1308
1f65fd49 1309 if (timestamp_is_set(next->realtime))
f5080e73
DH
1310 next_elapse = MIN(converted, next->realtime);
1311 else
1312 next_elapse = converted;
1313
1314 } else
1315 next_elapse = next->realtime;
1316
1317 return next_elapse;
1318}
1319
e449de87 1320static int list_timers(int argc, char *argv[], void *userdata) {
806a37e7
TA
1321 _cleanup_(message_set_freep) Set *replies = NULL;
1322 _cleanup_strv_free_ char **machines = NULL;
3a77f9fb 1323 _cleanup_strv_free_ char **timers_with_suffix = NULL;
cbb76c29
LP
1324 _cleanup_free_ struct timer_info *timer_infos = NULL;
1325 _cleanup_free_ UnitInfo *unit_infos = NULL;
1326 struct timer_info *t;
1327 const UnitInfo *u;
1328 size_t size = 0;
1823b86e 1329 int n, c = 0;
cbb76c29 1330 dual_timestamp nw;
4fbd7192 1331 sd_bus *bus;
1823b86e 1332 int r = 0;
cbb76c29 1333
4fbd7192
LP
1334 r = acquire_bus(BUS_MANAGER, &bus);
1335 if (r < 0)
1336 return r;
1337
0221d68a 1338 (void) pager_open(arg_pager_flags);
d2ad7e1b 1339
1d56bc09 1340 r = expand_names(bus, strv_skip(argv, 1), ".timer", &timers_with_suffix, NULL);
3a77f9fb
KK
1341 if (r < 0)
1342 return r;
cbb76c29 1343
3a77f9fb
KK
1344 if (argc == 1 || timers_with_suffix) {
1345 n = get_unit_list_recursive(bus, timers_with_suffix, &unit_infos, &replies, &machines);
1346 if (n < 0)
1347 return n;
cbb76c29 1348
3a77f9fb 1349 dual_timestamp_get(&nw);
cbb76c29 1350
3a77f9fb
KK
1351 for (u = unit_infos; u < unit_infos + n; u++) {
1352 _cleanup_strv_free_ char **triggered = NULL;
1353 dual_timestamp next = DUAL_TIMESTAMP_NULL;
1354 usec_t m, last = 0;
cbb76c29 1355
3a77f9fb
KK
1356 if (!endswith(u->id, ".timer"))
1357 continue;
cbb76c29 1358
3a77f9fb
KK
1359 r = get_triggered_units(bus, u->unit_path, &triggered);
1360 if (r < 0)
1361 goto cleanup;
cbb76c29 1362
3a77f9fb
KK
1363 r = get_next_elapse(bus, u->unit_path, &next);
1364 if (r < 0)
1365 goto cleanup;
d784e2db 1366
3a77f9fb 1367 get_last_trigger(bus, u->unit_path, &last);
cbb76c29 1368
3a77f9fb
KK
1369 if (!GREEDY_REALLOC(timer_infos, size, c+1)) {
1370 r = log_oom();
1371 goto cleanup;
1372 }
f5080e73 1373
3a77f9fb 1374 m = calc_next_elapse(&nw, &next);
cbb76c29 1375
3a77f9fb
KK
1376 timer_infos[c++] = (struct timer_info) {
1377 .machine = u->machine,
1378 .id = u->id,
1379 .next_elapse = m,
1380 .last_trigger = last,
1381 .triggered = TAKE_PTR(triggered),
1382 };
1383 }
1384
1385 typesafe_qsort(timer_infos, c, timer_info_compare);
1386 }
cbb76c29
LP
1387
1388 output_timers_list(timer_infos, c);
1389
1390 cleanup:
1391 for (t = timer_infos; t < timer_infos + c; t++)
1392 strv_free(t->triggered);
1393
1394 return r;
1395}
1396
93bab288 1397static int compare_unit_file_list(const UnitFileList *a, const UnitFileList *b) {
729e3769 1398 const char *d1, *d2;
729e3769 1399
93bab288
YW
1400 d1 = strrchr(a->path, '.');
1401 d2 = strrchr(b->path, '.');
729e3769
LP
1402
1403 if (d1 && d2) {
1404 int r;
1405
1406 r = strcasecmp(d1, d2);
1407 if (r != 0)
1408 return r;
1409 }
1410
93bab288 1411 return strcasecmp(basename(a->path), basename(b->path));
729e3769
LP
1412}
1413
313fe66f 1414static bool output_show_unit_file(const UnitFileList *u, char **states, char **patterns) {
f8591ee1
LP
1415 assert(u);
1416
2404701e 1417 if (!strv_fnmatch_or_empty(patterns, basename(u->path), FNM_NOESCAPE))
d8fba7c6 1418 return false;
d8fba7c6 1419
6c71341a
ZJS
1420 if (!strv_isempty(arg_types)) {
1421 const char *dot;
1422
1423 dot = strrchr(u->path, '.');
1424 if (!dot)
1425 return false;
1426
1427 if (!strv_find(arg_types, dot+1))
1428 return false;
1429 }
1430
313fe66f 1431 if (!strv_isempty(states) &&
1432 !strv_find(states, unit_file_state_to_string(u->state)))
bceccd5e 1433 return false;
fec1530e 1434
6c71341a 1435 return true;
729e3769
LP
1436}
1437
de9a8fe1
FS
1438static int output_unit_file_list(const UnitFileList *units, unsigned c) {
1439 _cleanup_(table_unrefp) Table *table = NULL;
729e3769 1440 const UnitFileList *u;
de9a8fe1 1441 int r;
729e3769 1442
de9a8fe1
FS
1443 table = table_new("unit file", "state", "vendor preset");
1444 if (!table)
1445 return log_oom();
1c0a113f 1446
de9a8fe1
FS
1447 table_set_header(table, !arg_no_legend);
1448 if (arg_full)
1449 table_set_width(table, 0);
729e3769
LP
1450
1451 for (u = units; u < units + c; u++) {
b01c1f30 1452 const char *on_underline = NULL, *on_unit_color = NULL, *id;
de9a8fe1 1453 const char *on_preset_color = NULL, *unit_preset_str;
aaa6732d
LP
1454 bool underline;
1455
1456 underline = u + 1 < units + c &&
1457 !streq(unit_type_suffix(u->path), unit_type_suffix((u + 1)->path));
6ae3e62a 1458
aaa6732d 1459 if (underline)
6ae3e62a 1460 on_underline = ansi_underline();
729e3769 1461
4c315c2c
IS
1462 if (IN_SET(u->state,
1463 UNIT_FILE_MASKED,
1464 UNIT_FILE_MASKED_RUNTIME,
1465 UNIT_FILE_DISABLED,
6ae3e62a 1466 UNIT_FILE_BAD))
b01c1f30 1467 on_unit_color = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
6ae3e62a 1468 else if (u->state == UNIT_FILE_ENABLED)
b01c1f30 1469 on_unit_color = underline ? ansi_highlight_green_underline() : ansi_highlight_green();
de9a8fe1
FS
1470 else
1471 on_unit_color = on_underline;
729e3769 1472
2b6bf07d 1473 id = basename(u->path);
729e3769 1474
b01c1f30
FS
1475 r = unit_file_query_preset(arg_scope, NULL, id);
1476 if (r < 0) {
1477 unit_preset_str = "n/a";
1478 on_preset_color = underline ? on_underline : ansi_normal();
1479 } else if (r == 0) {
1480 unit_preset_str = "disabled";
1481 on_preset_color = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
1482 } else {
1483 unit_preset_str = "enabled";
1484 on_preset_color = underline ? ansi_highlight_green_underline() : ansi_highlight_green();
1485 }
1486
de9a8fe1
FS
1487 r = table_add_many(table,
1488 TABLE_STRING, id,
1489 TABLE_SET_COLOR, strempty(on_underline),
1490 TABLE_STRING, unit_file_state_to_string(u->state),
1491 TABLE_SET_COLOR, strempty(on_unit_color),
1492 TABLE_STRING, unit_preset_str,
1493 TABLE_SET_COLOR, strempty(on_preset_color));
1494 if (r < 0)
1495 return table_log_add_error(r);
729e3769
LP
1496 }
1497
de9a8fe1
FS
1498 r = table_print(table, NULL);
1499 if (r < 0)
1500 return log_error_errno(r, "Failed to print the table: %m");
1501
1c0a113f 1502 if (!arg_no_legend)
0d292f5e 1503 printf("\n%u unit files listed.\n", c);
de9a8fe1
FS
1504
1505 return 0;
729e3769
LP
1506}
1507
e449de87 1508static int list_unit_files(int argc, char *argv[], void *userdata) {
4afd3348 1509 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f84190d8 1510 _cleanup_free_ UnitFileList *units = NULL;
8d5ba5a9
ZJS
1511 UnitFileList *unit;
1512 size_t size = 0;
f459b602
MAP
1513 unsigned c = 0;
1514 const char *state;
1515 char *path;
f84190d8 1516 int r;
313fe66f 1517 bool fallback = false;
729e3769 1518
4fbd7192 1519 if (install_client_side()) {
729e3769
LP
1520 Hashmap *h;
1521 UnitFileList *u;
1522 Iterator i;
f459b602 1523 unsigned n_units;
729e3769 1524
d5099efc 1525 h = hashmap_new(&string_hash_ops);
0d0f0c50
SL
1526 if (!h)
1527 return log_oom();
729e3769 1528
313fe66f 1529 r = unit_file_get_list(arg_scope, arg_root, h, arg_states, strv_skip(argv, 1));
729e3769 1530 if (r < 0) {
8ea913b2 1531 unit_file_list_free(h);
691395d8 1532 return log_error_errno(r, "Failed to get unit file list: %m");
729e3769
LP
1533 }
1534
1535 n_units = hashmap_size(h);
fdbdf6ec 1536
0da999fa
ZJS
1537 units = new(UnitFileList, n_units ?: 1); /* avoid malloc(0) */
1538 if (!units) {
729e3769 1539 unit_file_list_free(h);
0d0f0c50 1540 return log_oom();
729e3769
LP
1541 }
1542
1543 HASHMAP_FOREACH(u, h, i) {
313fe66f 1544 if (!output_show_unit_file(u, NULL, NULL))
8d5ba5a9
ZJS
1545 continue;
1546
1547 units[c++] = *u;
729e3769
LP
1548 free(u);
1549 }
1550
8d5ba5a9 1551 assert(c <= n_units);
729e3769 1552 hashmap_free(h);
5f056378
CH
1553
1554 r = 0;
729e3769 1555 } else {
313fe66f 1556 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
4afd3348 1557 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192
LP
1558 sd_bus *bus;
1559
1560 r = acquire_bus(BUS_MANAGER, &bus);
1561 if (r < 0)
1562 return r;
6e646d22 1563
313fe66f 1564 r = sd_bus_message_new_method_call(
f22f08cd 1565 bus,
313fe66f 1566 &m,
729e3769
LP
1567 "org.freedesktop.systemd1",
1568 "/org/freedesktop/systemd1",
1569 "org.freedesktop.systemd1.Manager",
313fe66f 1570 "ListUnitFilesByPatterns");
1571 if (r < 0)
1572 return bus_log_create_error(r);
1573
1574 r = sd_bus_message_append_strv(m, arg_states);
1575 if (r < 0)
1576 return bus_log_create_error(r);
1577
e9c387c8
KK
1578 if (arg_with_dependencies) {
1579 _cleanup_strv_free_ char **names_with_deps = NULL;
1580
1581 r = append_unit_dependencies(bus, strv_skip(argv, 1), &names_with_deps);
1582 if (r < 0)
1583 return log_error_errno(r, "Failed to append unit dependencies: %m");
1584
1585 r = sd_bus_message_append_strv(m, names_with_deps);
1586 if (r < 0)
1587 return bus_log_create_error(r);
1588 } else {
1589 r = sd_bus_message_append_strv(m, strv_skip(argv, 1));
1590 if (r < 0)
1591 return bus_log_create_error(r);
1592 }
313fe66f 1593
1594 r = sd_bus_call(bus, m, 0, &error, &reply);
1595 if (r < 0 && sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_METHOD)) {
1596 /* Fallback to legacy ListUnitFiles method */
1597 fallback = true;
1598 log_debug_errno(r, "Failed to list unit files: %s Falling back to ListUnitsFiles method.", bus_error_message(&error, r));
1599 m = sd_bus_message_unref(m);
1600 sd_bus_error_free(&error);
1601
1602 r = sd_bus_message_new_method_call(
1603 bus,
1604 &m,
1605 "org.freedesktop.systemd1",
1606 "/org/freedesktop/systemd1",
1607 "org.freedesktop.systemd1.Manager",
1608 "ListUnitFiles");
1609 if (r < 0)
1610 return bus_log_create_error(r);
1611
1612 r = sd_bus_call(bus, m, 0, &error, &reply);
1613 }
691395d8
LP
1614 if (r < 0)
1615 return log_error_errno(r, "Failed to list unit files: %s", bus_error_message(&error, r));
729e3769 1616
f459b602
MAP
1617 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ss)");
1618 if (r < 0)
1619 return bus_log_parse_error(r);
729e3769 1620
f459b602 1621 while ((r = sd_bus_message_read(reply, "(ss)", &path, &state)) > 0) {
729e3769 1622
f459b602
MAP
1623 if (!GREEDY_REALLOC(units, size, c + 1))
1624 return log_oom();
729e3769 1625
8d5ba5a9 1626 units[c] = (struct UnitFileList) {
f459b602
MAP
1627 path,
1628 unit_file_state_from_string(state)
1629 };
8d5ba5a9 1630
313fe66f 1631 if (output_show_unit_file(&units[c],
1632 fallback ? arg_states : NULL,
1633 fallback ? strv_skip(argv, 1) : NULL))
313cefa1 1634 c++;
8d5ba5a9 1635
729e3769 1636 }
f459b602
MAP
1637 if (r < 0)
1638 return bus_log_parse_error(r);
1639
1640 r = sd_bus_message_exit_container(reply);
1641 if (r < 0)
1642 return bus_log_parse_error(r);
729e3769
LP
1643 }
1644
0221d68a 1645 (void) pager_open(arg_pager_flags);
d2ad7e1b 1646
93bab288 1647 typesafe_qsort(units, c, compare_unit_file_list);
de9a8fe1
FS
1648 r = output_unit_file_list(units, c);
1649 if (r < 0)
1650 return r;
729e3769 1651
0da999fa 1652 if (install_client_side())
8d5ba5a9
ZJS
1653 for (unit = units; unit < units + c; unit++)
1654 free(unit->path);
1655
f84190d8 1656 return 0;
729e3769
LP
1657}
1658
14cb109d 1659static int list_dependencies_print(const char *name, int level, unsigned branches, bool last) {
55c0b89c 1660 _cleanup_free_ char *n = NULL;
9607d947 1661 size_t max_len = MAX(columns(),20u);
cbc9fbd1
LP
1662 size_t len = 0;
1663 int i;
55c0b89c 1664
5d0c05e5 1665 if (!arg_plain) {
cbc9fbd1 1666
5d0c05e5
LN
1667 for (i = level - 1; i >= 0; i--) {
1668 len += 2;
f168c273 1669 if (len > max_len - 3 && !arg_full) {
5d0c05e5
LN
1670 printf("%s...\n",max_len % 2 ? "" : " ");
1671 return 0;
1672 }
9a6f746f 1673 printf("%s", special_glyph(branches & (1 << i) ? SPECIAL_GLYPH_TREE_VERTICAL : SPECIAL_GLYPH_TREE_SPACE));
5d0c05e5 1674 }
55c0b89c 1675 len += 2;
cbc9fbd1 1676
f168c273 1677 if (len > max_len - 3 && !arg_full) {
55c0b89c
LN
1678 printf("%s...\n",max_len % 2 ? "" : " ");
1679 return 0;
1680 }
cbc9fbd1 1681
9a6f746f 1682 printf("%s", special_glyph(last ? SPECIAL_GLYPH_TREE_RIGHT : SPECIAL_GLYPH_TREE_BRANCH));
55c0b89c 1683 }
55c0b89c 1684
9ed794a3 1685 if (arg_full) {
55c0b89c
LN
1686 printf("%s\n", name);
1687 return 0;
1688 }
1689
1690 n = ellipsize(name, max_len-len, 100);
f168c273 1691 if (!n)
55c0b89c
LN
1692 return log_oom();
1693
1694 printf("%s\n", n);
1695 return 0;
1696}
1697
93bab288 1698static int list_dependencies_compare(char * const *a, char * const *b) {
55c0b89c
LN
1699 if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET)
1700 return 1;
1701 if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET)
1702 return -1;
cbc9fbd1 1703
55c0b89c
LN
1704 return strcasecmp(*a, *b);
1705}
1706
f459b602
MAP
1707static int list_dependencies_one(
1708 sd_bus *bus,
1709 const char *name,
1710 int level,
1711 char ***units,
14cb109d 1712 unsigned branches) {
f459b602 1713
e3e45d4f 1714 _cleanup_strv_free_ char **deps = NULL;
55c0b89c 1715 char **c;
55c0b89c
LN
1716 int r = 0;
1717
cbc9fbd1
LP
1718 assert(bus);
1719 assert(name);
1720 assert(units);
1721
e3e45d4f
SP
1722 r = strv_extend(units, name);
1723 if (r < 0)
55c0b89c
LN
1724 return log_oom();
1725
1726 r = list_dependencies_get_dependencies(bus, name, &deps);
1727 if (r < 0)
cec7eda5 1728 return r;
55c0b89c 1729
93bab288 1730 typesafe_qsort(deps, strv_length(deps), list_dependencies_compare);
55c0b89c
LN
1731
1732 STRV_FOREACH(c, deps) {
e3e45d4f 1733 if (strv_contains(*units, *c)) {
5d0c05e5 1734 if (!arg_plain) {
60705040 1735 printf(" ");
5d0c05e5
LN
1736 r = list_dependencies_print("...", level + 1, (branches << 1) | (c[1] == NULL ? 0 : 1), 1);
1737 if (r < 0)
1738 return r;
1739 }
55c0b89c
LN
1740 continue;
1741 }
1742
250ba664
ZJS
1743 if (arg_plain)
1744 printf(" ");
1745 else {
fa0d5878 1746 UnitActiveState active_state = _UNIT_ACTIVE_STATE_INVALID;
250ba664
ZJS
1747 const char *on;
1748
fa0d5878 1749 (void) get_state_one_unit(bus, *c, &active_state);
baa9ecc1 1750
fa0d5878 1751 switch (active_state) {
baa9ecc1
LP
1752 case UNIT_ACTIVE:
1753 case UNIT_RELOADING:
1754 case UNIT_ACTIVATING:
1755 on = ansi_highlight_green();
1756 break;
1757
1758 case UNIT_INACTIVE:
1759 case UNIT_DEACTIVATING:
1760 on = ansi_normal();
1761 break;
1762
1763 default:
1764 on = ansi_highlight_red();
1765 break;
fa0d5878
BR
1766 }
1767
9a6f746f 1768 printf("%s%s%s ", on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), ansi_normal());
250ba664 1769 }
dbc2c080 1770
55c0b89c 1771 r = list_dependencies_print(*c, level, branches, c[1] == NULL);
cec7eda5
ZJS
1772 if (r < 0)
1773 return r;
55c0b89c
LN
1774
1775 if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) {
e3e45d4f 1776 r = list_dependencies_one(bus, *c, level + 1, units, (branches << 1) | (c[1] == NULL ? 0 : 1));
f168c273 1777 if (r < 0)
cec7eda5 1778 return r;
55c0b89c
LN
1779 }
1780 }
f459b602 1781
e3e45d4f
SP
1782 if (!arg_plain)
1783 strv_remove(*units, name);
f459b602 1784
cec7eda5 1785 return 0;
55c0b89c
LN
1786}
1787
e449de87 1788static int list_dependencies(int argc, char *argv[], void *userdata) {
5d0c05e5 1789 _cleanup_strv_free_ char **units = NULL;
f459b602 1790 _cleanup_free_ char *unit = NULL;
e31165b2 1791 const char *u;
4fbd7192 1792 sd_bus *bus;
7410616c 1793 int r;
55c0b89c 1794
e449de87 1795 if (argv[1]) {
37cbc1d5 1796 r = unit_name_mangle(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, &unit);
7410616c
LP
1797 if (r < 0)
1798 return log_error_errno(r, "Failed to mangle unit name: %m");
1799
e31165b2
LP
1800 u = unit;
1801 } else
1802 u = SPECIAL_DEFAULT_TARGET;
55c0b89c 1803
4fbd7192
LP
1804 r = acquire_bus(BUS_MANAGER, &bus);
1805 if (r < 0)
1806 return r;
1807
0221d68a 1808 (void) pager_open(arg_pager_flags);
d2ad7e1b 1809
e31165b2
LP
1810 puts(u);
1811
5d0c05e5 1812 return list_dependencies_one(bus, u, 0, &units, 0);
55c0b89c
LN
1813}
1814
0d292f5e
LP
1815struct machine_info {
1816 bool is_host;
1817 char *name;
0d292f5e 1818 char *state;
8fcf784d
LP
1819 char *control_group;
1820 uint32_t n_failed_units;
1821 uint32_t n_jobs;
1822 usec_t timestamp;
1823};
1824
1825static const struct bus_properties_map machine_info_property_map[] = {
1826 { "SystemState", "s", NULL, offsetof(struct machine_info, state) },
1827 { "NJobs", "u", NULL, offsetof(struct machine_info, n_jobs) },
1828 { "NFailedUnits", "u", NULL, offsetof(struct machine_info, n_failed_units) },
1829 { "ControlGroup", "s", NULL, offsetof(struct machine_info, control_group) },
1830 { "UserspaceTimestamp", "t", NULL, offsetof(struct machine_info, timestamp) },
1831 {}
0d292f5e
LP
1832};
1833
e7e55dbd 1834static void machine_info_clear(struct machine_info *info) {
f8654baa
ZJS
1835 assert(info);
1836
1837 free(info->name);
1838 free(info->state);
1839 free(info->control_group);
1840 zero(*info);
e7e55dbd
DH
1841}
1842
0d292f5e
LP
1843static void free_machines_list(struct machine_info *machine_infos, int n) {
1844 int i;
1845
1846 if (!machine_infos)
1847 return;
1848
e7e55dbd
DH
1849 for (i = 0; i < n; i++)
1850 machine_info_clear(&machine_infos[i]);
0d292f5e
LP
1851
1852 free(machine_infos);
1853}
1854
93bab288
YW
1855static int compare_machine_info(const struct machine_info *a, const struct machine_info *b) {
1856 int r;
0d292f5e 1857
93bab288
YW
1858 r = CMP(b->is_host, a->is_host);
1859 if (r != 0)
1860 return r;
0d292f5e 1861
93bab288 1862 return strcasecmp(a->name, b->name);
0d292f5e
LP
1863}
1864
1865static int get_machine_properties(sd_bus *bus, struct machine_info *mi) {
4afd3348 1866 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *container = NULL;
0d292f5e
LP
1867 int r;
1868
1869 assert(mi);
1870
1871 if (!bus) {
de33fc62 1872 r = sd_bus_open_system_machine(&container, mi->name);
0d292f5e
LP
1873 if (r < 0)
1874 return r;
1875
1876 bus = container;
1877 }
1878
a7e4861c
YW
1879 r = bus_map_all_properties(
1880 bus,
1881 "org.freedesktop.systemd1",
1882 "/org/freedesktop/systemd1",
1883 machine_info_property_map,
1884 BUS_MAP_STRDUP,
1885 NULL,
1886 NULL,
1887 mi);
0d292f5e
LP
1888 if (r < 0)
1889 return r;
1890
1891 return 0;
1892}
1893
1894static bool output_show_machine(const char *name, char **patterns) {
2404701e 1895 return strv_fnmatch_or_empty(patterns, name, FNM_NOESCAPE);
0d292f5e
LP
1896}
1897
1898static int get_machine_list(
1899 sd_bus *bus,
1900 struct machine_info **_machine_infos,
1901 char **patterns) {
1902
1903 struct machine_info *machine_infos = NULL;
1904 _cleanup_strv_free_ char **m = NULL;
1905 _cleanup_free_ char *hn = NULL;
1906 size_t sz = 0;
1907 char **i;
4c3e8e39 1908 int c = 0, r;
0d292f5e
LP
1909
1910 hn = gethostname_malloc();
1911 if (!hn)
1912 return log_oom();
1913
1914 if (output_show_machine(hn, patterns)) {
1915 if (!GREEDY_REALLOC0(machine_infos, sz, c+1))
1916 return log_oom();
1917
1918 machine_infos[c].is_host = true;
ae2a15bc 1919 machine_infos[c].name = TAKE_PTR(hn);
0d292f5e 1920
f9e0eefc 1921 (void) get_machine_properties(bus, &machine_infos[c]);
0d292f5e
LP
1922 c++;
1923 }
1924
4c3e8e39
LP
1925 r = sd_get_machine_names(&m);
1926 if (r < 0)
1927 return log_error_errno(r, "Failed to get machine list: %m");
1928
0d292f5e
LP
1929 STRV_FOREACH(i, m) {
1930 _cleanup_free_ char *class = NULL;
1931
1932 if (!output_show_machine(*i, patterns))
1933 continue;
1934
1935 sd_machine_get_class(*i, &class);
1936 if (!streq_ptr(class, "container"))
1937 continue;
1938
1939 if (!GREEDY_REALLOC0(machine_infos, sz, c+1)) {
1940 free_machines_list(machine_infos, c);
1941 return log_oom();
1942 }
1943
1944 machine_infos[c].is_host = false;
1945 machine_infos[c].name = strdup(*i);
1946 if (!machine_infos[c].name) {
1947 free_machines_list(machine_infos, c);
1948 return log_oom();
1949 }
1950
f9e0eefc 1951 (void) get_machine_properties(NULL, &machine_infos[c]);
0d292f5e
LP
1952 c++;
1953 }
1954
1955 *_machine_infos = machine_infos;
1956 return c;
1957}
1958
de9a8fe1
FS
1959static int output_machines_list(struct machine_info *machine_infos, unsigned n) {
1960 _cleanup_(table_unrefp) Table *table = NULL;
0d292f5e 1961 struct machine_info *m;
aa91d592 1962 bool state_missing = false;
de9a8fe1 1963 int r;
0d292f5e
LP
1964
1965 assert(machine_infos || n == 0);
1966
de9a8fe1
FS
1967 table = table_new("", "name", "state", "failed", "jobs");
1968 if (!table)
1969 return log_oom();
0d292f5e 1970
de9a8fe1
FS
1971 table_set_header(table, !arg_no_legend);
1972 if (arg_full)
1973 table_set_width(table, 0);
0d292f5e
LP
1974
1975 for (m = machine_infos; m < machine_infos + n; m++) {
de9a8fe1
FS
1976 _cleanup_free_ char *mname = NULL;
1977 const char *on_state = "", *on_failed = "";
90c3f79d 1978 bool circle = false;
0d292f5e
LP
1979
1980 if (streq_ptr(m->state, "degraded")) {
1981 on_state = ansi_highlight_red();
90c3f79d 1982 circle = true;
0d292f5e
LP
1983 } else if (!streq_ptr(m->state, "running")) {
1984 on_state = ansi_highlight_yellow();
90c3f79d
LP
1985 circle = true;
1986 }
0d292f5e 1987
de9a8fe1 1988 if (m->n_failed_units > 0)
0d292f5e 1989 on_failed = ansi_highlight_red();
de9a8fe1
FS
1990 else
1991 on_failed = "";
90c3f79d 1992
4bea2469
ZJS
1993 if (!m->state)
1994 state_missing = true;
1995
0d292f5e 1996 if (m->is_host)
de9a8fe1
FS
1997 mname = strjoin(strna(m->name), " (host)");
1998
1999 r = table_add_many(table,
2000 TABLE_STRING, circle ? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE) : " ",
2001 TABLE_SET_COLOR, on_state,
2002 TABLE_STRING, m->is_host ? mname : strna(m->name),
2003 TABLE_STRING, strna(m->state),
2004 TABLE_SET_COLOR, on_state,
2005 TABLE_UINT32, m->n_failed_units,
2006 TABLE_SET_COLOR, on_failed,
2007 TABLE_UINT32, m->n_jobs);
2008 if (r < 0)
2009 return table_log_add_error(r);
0d292f5e
LP
2010 }
2011
de9a8fe1
FS
2012 r = table_print(table, NULL);
2013 if (r < 0)
2014 return log_error_errno(r, "Failed to print the table: %m");
2015
4bea2469
ZJS
2016 if (!arg_no_legend) {
2017 printf("\n");
2018 if (state_missing && geteuid() != 0)
2019 printf("Notice: some information only available to privileged users was not shown.\n");
2020 printf("%u machines listed.\n", n);
2021 }
de9a8fe1
FS
2022
2023 return 0;
0d292f5e
LP
2024}
2025
e449de87 2026static int list_machines(int argc, char *argv[], void *userdata) {
0d292f5e 2027 struct machine_info *machine_infos = NULL;
4fbd7192 2028 sd_bus *bus;
de9a8fe1 2029 int r, rc;
0d292f5e 2030
4fbd7192
LP
2031 r = acquire_bus(BUS_MANAGER, &bus);
2032 if (r < 0)
2033 return r;
2034
e449de87 2035 r = get_machine_list(bus, &machine_infos, strv_skip(argv, 1));
0d292f5e
LP
2036 if (r < 0)
2037 return r;
2038
0221d68a 2039 (void) pager_open(arg_pager_flags);
d2ad7e1b 2040
93bab288 2041 typesafe_qsort(machine_infos, r, compare_machine_info);
de9a8fe1 2042 rc = output_machines_list(machine_infos, r);
0d292f5e
LP
2043 free_machines_list(machine_infos, r);
2044
de9a8fe1 2045 return rc;
0d292f5e
LP
2046}
2047
e449de87 2048static int get_default(int argc, char *argv[], void *userdata) {
4afd3348 2049 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602
MAP
2050 _cleanup_free_ char *_path = NULL;
2051 const char *path;
99504dd4 2052 int r;
99504dd4 2053
4fbd7192 2054 if (install_client_side()) {
f459b602 2055 r = unit_file_get_default(arg_scope, arg_root, &_path);
f647962d
MS
2056 if (r < 0)
2057 return log_error_errno(r, "Failed to get default target: %m");
f459b602 2058 path = _path;
99504dd4 2059
5f056378 2060 r = 0;
99504dd4 2061 } else {
4afd3348 2062 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192
LP
2063 sd_bus *bus;
2064
2065 r = acquire_bus(BUS_MANAGER, &bus);
2066 if (r < 0)
2067 return r;
6e646d22 2068
f459b602
MAP
2069 r = sd_bus_call_method(
2070 bus,
2071 "org.freedesktop.systemd1",
2072 "/org/freedesktop/systemd1",
2073 "org.freedesktop.systemd1.Manager",
2074 "GetDefaultTarget",
2075 &error,
2076 &reply,
2077 NULL);
691395d8
LP
2078 if (r < 0)
2079 return log_error_errno(r, "Failed to get default target: %s", bus_error_message(&error, r));
99504dd4 2080
f459b602
MAP
2081 r = sd_bus_message_read(reply, "s", &path);
2082 if (r < 0)
2083 return bus_log_parse_error(r);
99504dd4
VP
2084 }
2085
2086 if (path)
2087 printf("%s\n", path);
2088
f459b602 2089 return 0;
99504dd4
VP
2090}
2091
e449de87 2092static int set_default(int argc, char *argv[], void *userdata) {
718db961 2093 _cleanup_free_ char *unit = NULL;
acc0269c 2094 UnitFileChange *changes = NULL;
da6053d0 2095 size_t n_changes = 0;
718db961
LP
2096 int r;
2097
e449de87
LP
2098 assert(argc >= 2);
2099 assert(argv);
2100
df7c4eb6
ZJS
2101 r = unit_name_mangle_with_suffix(argv[1], "set-default",
2102 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
2103 ".target", &unit);
7410616c
LP
2104 if (r < 0)
2105 return log_error_errno(r, "Failed to mangle unit name: %m");
718db961 2106
4fbd7192 2107 if (install_client_side()) {
b3796dd8 2108 r = unit_file_set_default(arg_scope, UNIT_FILE_FORCE, arg_root, unit, &changes, &n_changes);
af3d8113 2109 unit_file_dump_changes(r, "set default", changes, n_changes, arg_quiet);
5f056378
CH
2110
2111 if (r > 0)
2112 r = 0;
718db961 2113 } else {
4afd3348
LP
2114 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2115 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
4fbd7192 2116 sd_bus *bus;
718db961 2117
8a4b13c5 2118 polkit_agent_open_maybe();
6e646d22 2119
4fbd7192
LP
2120 r = acquire_bus(BUS_MANAGER, &bus);
2121 if (r < 0)
2122 return r;
2123
6e646d22 2124 r = sd_bus_call_method(
718db961
LP
2125 bus,
2126 "org.freedesktop.systemd1",
2127 "/org/freedesktop/systemd1",
2128 "org.freedesktop.systemd1.Manager",
6e646d22
LP
2129 "SetDefaultTarget",
2130 &error,
2131 &reply,
2132 "sb", unit, 1);
691395d8
LP
2133 if (r < 0)
2134 return log_error_errno(r, "Failed to set default target: %s", bus_error_message(&error, r));
718db961 2135
acc0269c 2136 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
718db961 2137 if (r < 0)
acc0269c 2138 goto finish;
718db961 2139
93c941e3 2140 /* Try to reload if enabled */
718db961 2141 if (!arg_no_reload)
e449de87 2142 r = daemon_reload(argc, argv, userdata);
718db961
LP
2143 else
2144 r = 0;
2145 }
2146
acc0269c
CH
2147finish:
2148 unit_file_changes_free(changes, n_changes);
2149
718db961
LP
2150 return r;
2151}
2152
de9a8fe1 2153static int output_waiting_jobs(sd_bus *bus, Table *table, uint32_t id, const char *method, const char *prefix) {
82948f6c
LP
2154 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2155 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
31d99bd1 2156 const char *name, *type;
82948f6c
LP
2157 uint32_t other_id;
2158 int r;
2159
2160 assert(bus);
2161
2162 r = sd_bus_call_method(
2163 bus,
2164 "org.freedesktop.systemd1",
2165 "/org/freedesktop/systemd1",
2166 "org.freedesktop.systemd1.Manager",
2167 method,
2168 &error,
2169 &reply,
2170 "u", id);
76d8ca22
ZJS
2171 if (r < 0)
2172 return log_debug_errno(r, "Failed to get waiting jobs for job %" PRIu32, id);
82948f6c
LP
2173
2174 r = sd_bus_message_enter_container(reply, 'a', "(usssoo)");
76d8ca22
ZJS
2175 if (r < 0)
2176 return bus_log_parse_error(r);
82948f6c 2177
de9a8fe1
FS
2178 while ((r = sd_bus_message_read(reply, "(usssoo)", &other_id, &name, &type, NULL, NULL, NULL)) > 0) {
2179 _cleanup_free_ char *row = NULL;
2180 int rc;
2181
2182 if (asprintf(&row, "%s %u (%s/%s)", prefix, other_id, name, type) < 0)
2183 return log_oom();
2184
2185 rc = table_add_many(table,
2186 TABLE_STRING, special_glyph(SPECIAL_GLYPH_TREE_RIGHT),
2187 TABLE_STRING, row,
2188 TABLE_EMPTY,
2189 TABLE_EMPTY);
2190 if (rc < 0)
2191 return table_log_add_error(r);
2192 }
2193
76d8ca22
ZJS
2194 if (r < 0)
2195 return bus_log_parse_error(r);
82948f6c
LP
2196
2197 r = sd_bus_message_exit_container(reply);
76d8ca22
ZJS
2198 if (r < 0)
2199 return bus_log_parse_error(r);
2200
2201 return 0;
82948f6c
LP
2202}
2203
75add28a
ZJS
2204struct job_info {
2205 uint32_t id;
f459b602 2206 const char *name, *type, *state;
75add28a
ZJS
2207};
2208
de9a8fe1
FS
2209static int output_jobs_list(sd_bus *bus, const struct job_info* jobs, unsigned n, bool skipped) {
2210 _cleanup_(table_unrefp) Table *table = NULL;
f459b602 2211 const struct job_info *j;
75add28a 2212 const char *on, *off;
de9a8fe1 2213 int r;
75add28a
ZJS
2214
2215 assert(n == 0 || jobs);
2216
2217 if (n == 0) {
250ba664
ZJS
2218 if (!arg_no_legend) {
2219 on = ansi_highlight_green();
1fc464f6 2220 off = ansi_normal();
75add28a 2221
250ba664
ZJS
2222 printf("%sNo jobs %s.%s\n", on, skipped ? "listed" : "running", off);
2223 }
de9a8fe1 2224 return 0;
75add28a
ZJS
2225 }
2226
0221d68a 2227 (void) pager_open(arg_pager_flags);
75add28a 2228
de9a8fe1
FS
2229 table = table_new("job", "unit", "type", "state");
2230 if (!table)
2231 return log_oom();
75add28a 2232
de9a8fe1
FS
2233 table_set_header(table, !arg_no_legend);
2234 if (arg_full)
2235 table_set_width(table, 0);
75add28a 2236
f459b602 2237 for (j = jobs; j < jobs + n; j++) {
de9a8fe1 2238 if (streq(j->state, "running"))
f459b602 2239 on = ansi_highlight();
de9a8fe1
FS
2240 else
2241 on = "";
2242
f459b602 2243
de9a8fe1
FS
2244 r = table_add_many(table,
2245 TABLE_UINT, j->id,
2246 TABLE_STRING, j->name,
2247 TABLE_SET_COLOR, on,
2248 TABLE_STRING, j->type,
2249 TABLE_STRING, j->state,
2250 TABLE_SET_COLOR, on);
2251 if (r < 0)
2252 return table_log_add_error(r);
82948f6c
LP
2253
2254 if (arg_jobs_after)
de9a8fe1 2255 output_waiting_jobs(bus, table, j->id, "GetJobAfter", "\twaiting for job");
82948f6c 2256 if (arg_jobs_before)
de9a8fe1 2257 output_waiting_jobs(bus, table, j->id, "GetJobBefore", "\tblocking job");
75add28a
ZJS
2258 }
2259
de9a8fe1
FS
2260 r = table_print(table, NULL);
2261 if (r < 0)
2262 return log_error_errno(r, "Failed to print the table: %m");
2263
6ce774fd
MM
2264 if (!arg_no_legend) {
2265 on = ansi_highlight();
1fc464f6 2266 off = ansi_normal();
75add28a 2267
6ce774fd
MM
2268 printf("\n%s%u jobs listed%s.\n", on, n, off);
2269 }
de9a8fe1
FS
2270
2271 return 0;
75add28a
ZJS
2272}
2273
d8fba7c6 2274static bool output_show_job(struct job_info *job, char **patterns) {
2404701e 2275 return strv_fnmatch_or_empty(patterns, job->name, FNM_NOESCAPE);
d8fba7c6
ZJS
2276}
2277
e449de87 2278static int list_jobs(int argc, char *argv[], void *userdata) {
4afd3348
LP
2279 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2280 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602 2281 _cleanup_free_ struct job_info *jobs = NULL;
31d99bd1
YW
2282 const char *name, *type, *state;
2283 bool skipped = false;
f459b602
MAP
2284 size_t size = 0;
2285 unsigned c = 0;
4fbd7192 2286 sd_bus *bus;
f459b602 2287 uint32_t id;
f84190d8 2288 int r;
ec14911e 2289
4fbd7192
LP
2290 r = acquire_bus(BUS_MANAGER, &bus);
2291 if (r < 0)
2292 return r;
2293
f459b602 2294 r = sd_bus_call_method(
f22f08cd
SP
2295 bus,
2296 "org.freedesktop.systemd1",
2297 "/org/freedesktop/systemd1",
2298 "org.freedesktop.systemd1.Manager",
2299 "ListJobs",
f459b602 2300 &error,
f22f08cd 2301 &reply,
f459b602 2302 NULL);
691395d8
LP
2303 if (r < 0)
2304 return log_error_errno(r, "Failed to list jobs: %s", bus_error_message(&error, r));
7e4249b9 2305
f459b602
MAP
2306 r = sd_bus_message_enter_container(reply, 'a', "(usssoo)");
2307 if (r < 0)
2308 return bus_log_parse_error(r);
7e4249b9 2309
31d99bd1 2310 while ((r = sd_bus_message_read(reply, "(usssoo)", &id, &name, &type, &state, NULL, NULL)) > 0) {
d8fba7c6
ZJS
2311 struct job_info job = { id, name, type, state };
2312
e449de87 2313 if (!output_show_job(&job, strv_skip(argv, 1))) {
d8fba7c6
ZJS
2314 skipped = true;
2315 continue;
2316 }
8fe914ec 2317
f459b602
MAP
2318 if (!GREEDY_REALLOC(jobs, size, c + 1))
2319 return log_oom();
7e4249b9 2320
d8fba7c6 2321 jobs[c++] = job;
7e4249b9 2322 }
f459b602
MAP
2323 if (r < 0)
2324 return bus_log_parse_error(r);
7e4249b9 2325
f459b602
MAP
2326 r = sd_bus_message_exit_container(reply);
2327 if (r < 0)
2328 return bus_log_parse_error(r);
f73e33d9 2329
0221d68a 2330 (void) pager_open(arg_pager_flags);
d2ad7e1b 2331
de9a8fe1 2332 return output_jobs_list(bus, jobs, c, skipped);
7e4249b9
LP
2333}
2334
e449de87 2335static int cancel_job(int argc, char *argv[], void *userdata) {
4fbd7192 2336 sd_bus *bus;
729e3769 2337 char **name;
342641fb 2338 int r = 0;
7e4249b9 2339
e449de87 2340 if (argc <= 1)
2853b60a 2341 return trivial_method(argc, argv, userdata);
ee5762e3 2342
4fbd7192
LP
2343 r = acquire_bus(BUS_MANAGER, &bus);
2344 if (r < 0)
2345 return r;
2346
8a4b13c5 2347 polkit_agent_open_maybe();
d2ad7e1b 2348
e449de87 2349 STRV_FOREACH(name, strv_skip(argv, 1)) {
4afd3348 2350 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5dd9014f 2351 uint32_t id;
342641fb 2352 int q;
7e4249b9 2353
342641fb 2354 q = safe_atou32(*name, &id);
f647962d
MS
2355 if (q < 0)
2356 return log_error_errno(q, "Failed to parse job id \"%s\": %m", *name);
7e4249b9 2357
6e646d22 2358 q = sd_bus_call_method(
f22f08cd
SP
2359 bus,
2360 "org.freedesktop.systemd1",
2361 "/org/freedesktop/systemd1",
2362 "org.freedesktop.systemd1.Manager",
6e646d22
LP
2363 "CancelJob",
2364 &error,
2365 NULL,
2366 "u", id);
342641fb 2367 if (q < 0) {
691395d8 2368 log_error_errno(q, "Failed to cancel job %"PRIu32": %s", id, bus_error_message(&error, q));
342641fb
LP
2369 if (r == 0)
2370 r = q;
f459b602 2371 }
7e4249b9
LP
2372 }
2373
342641fb 2374 return r;
7e4249b9
LP
2375}
2376
f459b602 2377static int need_daemon_reload(sd_bus *bus, const char *unit) {
4afd3348 2378 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602
MAP
2379 const char *path;
2380 int b, r;
94c01aeb 2381
f459b602
MAP
2382 /* We ignore all errors here, since this is used to show a
2383 * warning only */
45fb0699 2384
f459b602
MAP
2385 /* We don't use unit_dbus_path_from_name() directly since we
2386 * don't want to load the unit if it isn't loaded. */
f84190d8 2387
f459b602 2388 r = sd_bus_call_method(
f22f08cd
SP
2389 bus,
2390 "org.freedesktop.systemd1",
2391 "/org/freedesktop/systemd1",
2392 "org.freedesktop.systemd1.Manager",
2393 "GetUnit",
f459b602 2394 NULL,
f22f08cd 2395 &reply,
e3e0314b 2396 "s", unit);
f84190d8
LP
2397 if (r < 0)
2398 return r;
45fb0699 2399
f459b602
MAP
2400 r = sd_bus_message_read(reply, "o", &path);
2401 if (r < 0)
2402 return r;
f84190d8 2403
f459b602 2404 r = sd_bus_get_property_trivial(
f22f08cd 2405 bus,
b0193f1c
LP
2406 "org.freedesktop.systemd1",
2407 path,
f459b602
MAP
2408 "org.freedesktop.systemd1.Unit",
2409 "NeedDaemonReload",
2410 NULL,
2411 'b', &b);
f84190d8
LP
2412 if (r < 0)
2413 return r;
45fb0699 2414
45fb0699
LP
2415 return b;
2416}
2417
3f36991e 2418static void warn_unit_file_changed(const char *name) {
87ec20ef
LP
2419 assert(name);
2420
e9f4aabd 2421 log_warning("%sWarning:%s The unit file, source configuration file or drop-ins of %s changed on disk. Run 'systemctl%s daemon-reload' to reload units.",
3f36991e 2422 ansi_highlight_red(),
1fc464f6 2423 ansi_normal(),
3f36991e
ZJS
2424 name,
2425 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user");
2426}
2427
c45e7e0c 2428static int unit_file_find_path(LookupPaths *lp, const char *unit_name, char **ret_unit_path) {
33f6c497
ZJS
2429 char **p;
2430
2431 assert(lp);
2432 assert(unit_name);
33f6c497 2433
a3c4eb07 2434 STRV_FOREACH(p, lp->search_path) {
c6dd36b6
FS
2435 _cleanup_free_ char *path = NULL, *lpath = NULL;
2436 int r;
33f6c497 2437
62a85ee0 2438 path = path_join(*p, unit_name);
33f6c497
ZJS
2439 if (!path)
2440 return log_oom();
2441
a5648b80 2442 r = chase_symlinks(path, arg_root, 0, &lpath, NULL);
c6dd36b6
FS
2443 if (r == -ENOENT)
2444 continue;
2445 if (r == -ENOMEM)
2446 return log_oom();
2447 if (r < 0)
86f004fb 2448 return log_error_errno(r, "Failed to access path \"%s\": %m", path);
c6dd36b6 2449
c45e7e0c
LP
2450 if (ret_unit_path)
2451 *ret_unit_path = TAKE_PTR(lpath);
ae2a15bc 2452
c6dd36b6 2453 return 1;
33f6c497
ZJS
2454 }
2455
f67cb270
LP
2456 if (ret_unit_path)
2457 *ret_unit_path = NULL;
2458
33f6c497
ZJS
2459 return 0;
2460}
2461
173471b7
ZJS
2462static int unit_find_template_path(
2463 const char *unit_name,
2464 LookupPaths *lp,
b03677e2
LP
2465 char **ret_fragment_path,
2466 char **ret_template) {
173471b7 2467
b03677e2 2468 _cleanup_free_ char *t = NULL, *f = NULL;
173471b7
ZJS
2469 int r;
2470
2471 /* Returns 1 if a fragment was found, 0 if not found, negative on error. */
2472
b03677e2
LP
2473 r = unit_file_find_path(lp, unit_name, &f);
2474 if (r < 0)
2475 return r;
2476 if (r > 0) {
2477 if (ret_fragment_path)
2478 *ret_fragment_path = TAKE_PTR(f);
2479 if (ret_template)
2480 *ret_template = NULL;
2481 return r; /* found a real unit */
2482 }
2483
2484 r = unit_name_template(unit_name, &t);
2485 if (r == -EINVAL) {
2486 if (ret_fragment_path)
2487 *ret_fragment_path = NULL;
2488 if (ret_template)
2489 *ret_template = NULL;
173471b7 2490
173471b7 2491 return 0; /* not a template, does not exist */
b03677e2 2492 }
173471b7
ZJS
2493 if (r < 0)
2494 return log_error_errno(r, "Failed to determine template name: %m");
2495
b03677e2 2496 r = unit_file_find_path(lp, t, ret_fragment_path);
173471b7
ZJS
2497 if (r < 0)
2498 return r;
2499
b03677e2
LP
2500 if (ret_template)
2501 *ret_template = r > 0 ? TAKE_PTR(t) : NULL;
ae2a15bc 2502
173471b7
ZJS
2503 return r;
2504}
2505
6e646d22
LP
2506static int unit_find_paths(
2507 sd_bus *bus,
2508 const char *unit_name,
6e646d22 2509 LookupPaths *lp,
02a126a3
LP
2510 bool force_client_side,
2511 char **ret_fragment_path,
2512 char ***ret_dropin_paths) {
dab2bce8 2513
dab2bce8 2514 _cleanup_strv_free_ char **dropins = NULL;
02a126a3 2515 _cleanup_free_ char *path = NULL;
33f6c497
ZJS
2516 int r;
2517
ad2a0358 2518 /**
e04df06f
ZJS
2519 * Finds where the unit is defined on disk. Returns 0 if the unit is not found. Returns 1 if it is
2520 * found, and sets:
02a126a3 2521 * - the path to the unit in *ret_frament_path, if it exists on disk,
e04df06f
ZJS
2522 * - and a strv of existing drop-ins in *ret_dropin_paths, if the arg is not NULL and any dropins
2523 * were found.
02a126a3 2524 *
e04df06f
ZJS
2525 * Returns -ERFKILL if the unit is masked, and -EKEYREJECTED if the unit file could not be loaded for
2526 * some reason (the latter only applies if we are going through the service manager).
ad2a0358
ZJS
2527 */
2528
33f6c497 2529 assert(unit_name);
02a126a3 2530 assert(ret_fragment_path);
33f6c497
ZJS
2531 assert(lp);
2532
02a126a3
LP
2533 /* Go via the bus to acquire the path, unless we are explicitly told not to, or when the unit name is a template */
2534 if (!force_client_side &&
2535 !install_client_side() &&
2536 !unit_name_is_valid(unit_name, UNIT_NAME_TEMPLATE)) {
4afd3348 2537 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6176e89c 2538 _cleanup_free_ char *load_state = NULL, *dbus_path = NULL;
33f6c497 2539
6176e89c
ZJS
2540 dbus_path = unit_dbus_path_from_name(unit_name);
2541 if (!dbus_path)
33f6c497
ZJS
2542 return log_oom();
2543
02a126a3
LP
2544 r = sd_bus_get_property_string(
2545 bus,
2546 "org.freedesktop.systemd1",
6176e89c 2547 dbus_path,
02a126a3
LP
2548 "org.freedesktop.systemd1.Unit",
2549 "LoadState",
2550 &error,
2551 &load_state);
2552 if (r < 0)
2553 return log_error_errno(r, "Failed to get LoadState: %s", bus_error_message(&error, r));
2554
2555 if (streq(load_state, "masked"))
2556 return -ERFKILL;
2557 if (streq(load_state, "not-found")) {
2558 r = 0;
2559 goto not_found;
2560 }
e04df06f 2561 if (!STR_IN_SET(load_state, "loaded", "bad-setting"))
02a126a3
LP
2562 return -EKEYREJECTED;
2563
33f6c497
ZJS
2564 r = sd_bus_get_property_string(
2565 bus,
2566 "org.freedesktop.systemd1",
6176e89c 2567 dbus_path,
33f6c497
ZJS
2568 "org.freedesktop.systemd1.Unit",
2569 "FragmentPath",
2570 &error,
ad2a0358
ZJS
2571 &path);
2572 if (r < 0)
2573 return log_error_errno(r, "Failed to get FragmentPath: %s", bus_error_message(&error, r));
2574
02a126a3 2575 if (ret_dropin_paths) {
dab2bce8
IS
2576 r = sd_bus_get_property_strv(
2577 bus,
2578 "org.freedesktop.systemd1",
6176e89c 2579 dbus_path,
dab2bce8
IS
2580 "org.freedesktop.systemd1.Unit",
2581 "DropInPaths",
2582 &error,
2583 &dropins);
2584 if (r < 0)
2585 return log_error_errno(r, "Failed to get DropInPaths: %s", bus_error_message(&error, r));
33f6c497 2586 }
ad2a0358 2587 } else {
e8630e69
ZJS
2588 const char *_path;
2589 _cleanup_set_free_free_ Set *names = NULL;
33f6c497 2590
e8630e69 2591 if (!cached_name_map) {
91e0ee5f 2592 r = unit_file_build_name_map(lp, NULL, &cached_id_map, &cached_name_map, NULL);
e8630e69
ZJS
2593 if (r < 0)
2594 return r;
2595 }
33f6c497 2596
e8630e69 2597 r = unit_file_find_fragment(cached_id_map, cached_name_map, unit_name, &_path, &names);
ad2a0358
ZJS
2598 if (r < 0)
2599 return r;
6483ad89 2600
e8630e69
ZJS
2601 if (_path) {
2602 path = strdup(_path);
2603 if (!path)
2604 return log_oom();
2605 }
c6dd36b6 2606
02a126a3 2607 if (ret_dropin_paths) {
043fdc40
ZJS
2608 r = unit_file_find_dropin_paths(arg_root, lp->search_path, NULL,
2609 ".d", ".conf",
2610 names, &dropins);
dab2bce8
IS
2611 if (r < 0)
2612 return r;
2613 }
2614 }
2615
6176e89c
ZJS
2616 if (isempty(path)) {
2617 *ret_fragment_path = NULL;
02a126a3 2618 r = 0;
6176e89c 2619 } else {
02a126a3 2620 *ret_fragment_path = TAKE_PTR(path);
dab2bce8 2621 r = 1;
6176e89c 2622 }
dab2bce8 2623
02a126a3
LP
2624 if (ret_dropin_paths) {
2625 if (!strv_isempty(dropins)) {
2626 *ret_dropin_paths = TAKE_PTR(dropins);
2627 r = 1;
2628 } else
2629 *ret_dropin_paths = NULL;
33f6c497 2630 }
02a126a3 2631
6483ad89 2632 not_found:
39c38ce1 2633 if (r == 0 && !arg_force)
b5e6a600
IS
2634 log_error("No files found for %s.", unit_name);
2635
ad2a0358 2636 return r;
33f6c497
ZJS
2637}
2638
fa0d5878 2639static int get_state_one_unit(sd_bus *bus, const char *name, UnitActiveState *active_state) {
b430f85f 2640 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6176e89c 2641 _cleanup_free_ char *buf = NULL, *dbus_path = NULL;
fa0d5878 2642 UnitActiveState state;
f22f08cd 2643 int r;
701cdcb9 2644
31be1221 2645 assert(name);
fa0d5878 2646 assert(active_state);
701cdcb9 2647
6176e89c
ZJS
2648 dbus_path = unit_dbus_path_from_name(name);
2649 if (!dbus_path)
3d083b22
LP
2650 return log_oom();
2651
2652 r = sd_bus_get_property_string(
f22f08cd
SP
2653 bus,
2654 "org.freedesktop.systemd1",
6176e89c 2655 dbus_path,
3d083b22
LP
2656 "org.freedesktop.systemd1.Unit",
2657 "ActiveState",
b430f85f 2658 &error,
3d083b22
LP
2659 &buf);
2660 if (r < 0)
2661 return log_error_errno(r, "Failed to retrieve unit state: %s", bus_error_message(&error, r));
b430f85f 2662
3d083b22 2663 state = unit_active_state_from_string(buf);
2f50e59f
LP
2664 if (state < 0)
2665 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid unit state '%s' for: %s", buf, name);
701cdcb9 2666
fa0d5878
BR
2667 *active_state = state;
2668 return 0;
701cdcb9
MS
2669}
2670
86f004fb 2671static int unit_is_masked(sd_bus *bus, LookupPaths *lp, const char *name) {
bd062910 2672 _cleanup_free_ char *load_state = NULL;
f22f08cd 2673 int r;
701cdcb9 2674
86f004fb
ZJS
2675 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
2676 _cleanup_free_ char *path = NULL;
2677
2678 /* A template cannot be loaded, but it can be still masked, so
2679 * we need to use a different method. */
2680
2681 r = unit_file_find_path(lp, name, &path);
2682 if (r < 0)
2683 return r;
2684 if (r == 0)
2685 return false;
2686 return null_or_empty_path(path);
2687 }
2688
bd062910 2689 r = unit_load_state(bus, name, &load_state);
691395d8 2690 if (r < 0)
bd062910 2691 return r;
d0a5cdb2 2692
9d9dd746
ZJS
2693 return streq(load_state, "masked");
2694}
2695
2696static int check_triggering_units(sd_bus *bus, const char *name) {
2697 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6176e89c 2698 _cleanup_free_ char *n = NULL, *dbus_path = NULL, *load_state = NULL;
9d9dd746
ZJS
2699 _cleanup_strv_free_ char **triggered_by = NULL;
2700 bool print_warning_label = true;
2701 UnitActiveState active_state;
2702 char **i;
2703 int r;
2704
2705 r = unit_name_mangle(name, 0, &n);
2706 if (r < 0)
2707 return log_error_errno(r, "Failed to mangle unit name: %m");
2708
86f004fb
ZJS
2709 r = unit_load_state(bus, name, &load_state);
2710 if (r < 0)
2711 return r;
2712
2713 if (streq(load_state, "masked"))
2714 return 0;
9d9dd746 2715
6176e89c
ZJS
2716 dbus_path = unit_dbus_path_from_name(n);
2717 if (!dbus_path)
9d9dd746 2718 return log_oom();
701cdcb9 2719
f459b602
MAP
2720 r = sd_bus_get_property_strv(
2721 bus,
2722 "org.freedesktop.systemd1",
6176e89c 2723 dbus_path,
f459b602
MAP
2724 "org.freedesktop.systemd1.Unit",
2725 "TriggeredBy",
2726 &error,
2727 &triggered_by);
691395d8
LP
2728 if (r < 0)
2729 return log_error_errno(r, "Failed to get triggered by array of %s: %s", n, bus_error_message(&error, r));
701cdcb9 2730
f459b602 2731 STRV_FOREACH(i, triggered_by) {
fa0d5878 2732 r = get_state_one_unit(bus, *i, &active_state);
f647962d 2733 if (r < 0)
fa0d5878 2734 return r;
701cdcb9 2735
fa0d5878 2736 if (!IN_SET(active_state, UNIT_ACTIVE, UNIT_RELOADING))
f459b602 2737 continue;
60f9ba0b 2738
f459b602
MAP
2739 if (print_warning_label) {
2740 log_warning("Warning: Stopping %s, but it can still be activated by:", n);
2741 print_warning_label = false;
701cdcb9 2742 }
1c291cf3 2743
f459b602 2744 log_warning(" %s", *i);
701cdcb9 2745 }
f459b602
MAP
2746
2747 return 0;
701cdcb9
MS
2748}
2749
2fc9a280 2750static const struct {
85d9b598
LP
2751 const char *verb; /* systemctl verb */
2752 const char *method; /* Name of the specific D-Bus method */
2753 const char *job_type; /* Job type when passing to the generic EnqueueUnitJob() method */
2fc9a280 2754} unit_actions[] = {
85d9b598
LP
2755 { "start", "StartUnit", "start" },
2756 { "stop", "StopUnit", "stop" },
2757 { "condstop", "StopUnit", "stop" }, /* legacy alias */
2758 { "reload", "ReloadUnit", "reload" },
2759 { "restart", "RestartUnit", "restart" },
2760 { "try-restart", "TryRestartUnit", "try-restart" },
2761 { "condrestart", "TryRestartUnit", "try-restart" }, /* legacy alias */
2762 { "reload-or-restart", "ReloadOrRestartUnit", "reload-or-restart" },
2763 { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
2764 { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2765 { "condreload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2766 { "force-reload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
2fc9a280
LP
2767};
2768
39602c39 2769static const char *verb_to_method(const char *verb) {
85d9b598 2770 size_t i;
39602c39
TA
2771
2772 for (i = 0; i < ELEMENTSOF(unit_actions); i++)
2773 if (streq_ptr(unit_actions[i].verb, verb))
2774 return unit_actions[i].method;
2775
2776 return "StartUnit";
2777}
2778
85d9b598
LP
2779static const char *verb_to_job_type(const char *verb) {
2780 size_t i;
39602c39
TA
2781
2782 for (i = 0; i < ELEMENTSOF(unit_actions); i++)
85d9b598
LP
2783 if (streq_ptr(unit_actions[i].verb, verb))
2784 return unit_actions[i].job_type;
39602c39 2785
85d9b598 2786 return "start";
39602c39
TA
2787}
2788
e4b61340 2789static int start_unit_one(
f459b602 2790 sd_bus *bus,
85d9b598
LP
2791 const char *method, /* When using classic per-job bus methods */
2792 const char *job_type, /* When using new-style EnqueueUnitJob() */
e4b61340
LP
2793 const char *name,
2794 const char *mode,
f459b602 2795 sd_bus_error *error,
93a08841 2796 BusWaitForJobs *w,
a7056cde 2797 BusWaitForUnits *wu) {
7e4249b9 2798
4afd3348 2799 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
45fb0699 2800 const char *path;
85d9b598 2801 bool done = false;
7e4249b9 2802 int r;
7e4249b9 2803
e4b61340
LP
2804 assert(method);
2805 assert(name);
2806 assert(mode);
22f4096c 2807 assert(error);
7e4249b9 2808
dbc9830c
ZJS
2809 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2810 arg_dry_run ? "Would execute" : "Executing",
1ae17672 2811 method, name, mode);
85d9b598 2812
1ae17672
ZJS
2813 if (arg_dry_run)
2814 return 0;
342641fb 2815
85d9b598
LP
2816 if (arg_show_transaction) {
2817 _cleanup_(sd_bus_error_free) sd_bus_error enqueue_error = SD_BUS_ERROR_NULL;
39602c39 2818
85d9b598
LP
2819 /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
2820 r = sd_bus_call_method(
2821 bus,
2822 "org.freedesktop.systemd1",
2823 "/org/freedesktop/systemd1",
2824 "org.freedesktop.systemd1.Manager",
2825 "EnqueueUnitJob",
2826 &enqueue_error,
2827 &reply,
2828 "sss",
2829 name, job_type, mode);
2830 if (r < 0) {
2831 if (!sd_bus_error_has_name(&enqueue_error, SD_BUS_ERROR_UNKNOWN_METHOD)) {
2832 (void) sd_bus_error_move(error, &enqueue_error);
2833 goto fail;
2834 }
67f3c402 2835
85d9b598
LP
2836 /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
2837 log_notice("--show-transaction not supported by this service manager, proceeding without.");
2838 } else {
2839 const char *u, *jt;
2840 uint32_t id;
39602c39 2841
85d9b598
LP
2842 r = sd_bus_message_read(reply, "uosos", &id, &path, &u, NULL, &jt);
2843 if (r < 0)
2844 return bus_log_parse_error(r);
ee87525c 2845
85d9b598 2846 log_info("Enqueued anchor job %" PRIu32 " %s/%s.", id, u, jt);
ee87525c 2847
85d9b598
LP
2848 r = sd_bus_message_enter_container(reply, 'a', "(uosos)");
2849 if (r < 0)
2850 return bus_log_parse_error(r);
2851 for (;;) {
2852 r = sd_bus_message_read(reply, "(uosos)", &id, NULL, &u, NULL, &jt);
2853 if (r < 0)
2854 return bus_log_parse_error(r);
2855 if (r == 0)
2856 break;
2857
2858 log_info("Enqueued auxiliary job %" PRIu32 " %s/%s.", id, u, jt);
2859 }
2860
2861 r = sd_bus_message_exit_container(reply);
2862 if (r < 0)
2863 return bus_log_parse_error(r);
2864
2865 done = true;
2866 }
7e4249b9
LP
2867 }
2868
85d9b598
LP
2869 if (!done) {
2870 r = sd_bus_call_method(
2871 bus,
2872 "org.freedesktop.systemd1",
2873 "/org/freedesktop/systemd1",
2874 "org.freedesktop.systemd1.Manager",
2875 method,
2876 error,
2877 &reply,
2878 "ss", name, mode);
2879 if (r < 0)
2880 goto fail;
2881
2882 r = sd_bus_message_read(reply, "o", &path);
2883 if (r < 0)
2884 return bus_log_parse_error(r);
2885 }
45fb0699 2886
e3e0314b 2887 if (need_daemon_reload(bus, name) > 0)
3f36991e 2888 warn_unit_file_changed(name);
45fb0699 2889
ebd011d9
LP
2890 if (w) {
2891 log_debug("Adding %s to the set", path);
2892 r = bus_wait_for_jobs_add(w, path);
cbc9fbd1 2893 if (r < 0)
d2e1b2fd 2894 return log_error_errno(r, "Failed to watch job for %s: %m", name);
e4b61340 2895 }
7e4249b9 2896
a7056cde
LP
2897 if (wu) {
2898 r = bus_wait_for_units_add_unit(wu, name, BUS_WAIT_FOR_INACTIVE|BUS_WAIT_NO_JOB, NULL, NULL);
2899 if (r < 0)
2900 return log_error_errno(r, "Failed to watch unit %s: %m", name);
2901 }
2902
46eddbb5 2903 return 0;
85d9b598
LP
2904
2905fail:
2906 /* There's always a fallback possible for legacy actions. */
2907 if (arg_action != ACTION_SYSTEMCTL)
2908 return r;
2909
2910 log_error_errno(r, "Failed to %s %s: %s", job_type, name, bus_error_message(error, r));
2911
2912 if (!sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT) &&
2913 !sd_bus_error_has_name(error, BUS_ERROR_UNIT_MASKED) &&
2914 !sd_bus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE))
2915 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
2916 arg_scope == UNIT_FILE_SYSTEM ? "system" : "user",
2917 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user",
2918 name[0] == '-' ? " --" : "",
2919 name);
2920
2921 return r;
7e4249b9
LP
2922}
2923
47a0eaa6
MS
2924static const struct {
2925 const char *target;
2926 const char *verb;
2927 const char *mode;
2928} action_table[_ACTION_MAX] = {
5fd77930
LP
2929 [ACTION_HALT] = { SPECIAL_HALT_TARGET, "halt", "replace-irreversibly" },
2930 [ACTION_POWEROFF] = { SPECIAL_POWEROFF_TARGET, "poweroff", "replace-irreversibly" },
2931 [ACTION_REBOOT] = { SPECIAL_REBOOT_TARGET, "reboot", "replace-irreversibly" },
2932 [ACTION_KEXEC] = { SPECIAL_KEXEC_TARGET, "kexec", "replace-irreversibly" },
2933 [ACTION_RUNLEVEL2] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
2934 [ACTION_RUNLEVEL3] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
2935 [ACTION_RUNLEVEL4] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
2936 [ACTION_RUNLEVEL5] = { SPECIAL_GRAPHICAL_TARGET, NULL, "isolate" },
2937 [ACTION_RESCUE] = { SPECIAL_RESCUE_TARGET, "rescue", "isolate" },
2938 [ACTION_EMERGENCY] = { SPECIAL_EMERGENCY_TARGET, "emergency", "isolate" },
2939 [ACTION_DEFAULT] = { SPECIAL_DEFAULT_TARGET, "default", "isolate" },
2940 [ACTION_EXIT] = { SPECIAL_EXIT_TARGET, "exit", "replace-irreversibly" },
2941 [ACTION_SUSPEND] = { SPECIAL_SUSPEND_TARGET, "suspend", "replace-irreversibly" },
2942 [ACTION_HIBERNATE] = { SPECIAL_HIBERNATE_TARGET, "hibernate", "replace-irreversibly" },
2943 [ACTION_HYBRID_SLEEP] = { SPECIAL_HYBRID_SLEEP_TARGET, "hybrid-sleep", "replace-irreversibly" },
e68c79db 2944 [ACTION_SUSPEND_THEN_HIBERNATE] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET, "suspend-then-hibernate", "replace-irreversibly" },
47a0eaa6
MS
2945};
2946
514f4ef5 2947static enum action verb_to_action(const char *verb) {
47a0eaa6
MS
2948 enum action i;
2949
913c1916 2950 for (i = 0; i < _ACTION_MAX; i++)
f459b602 2951 if (streq_ptr(action_table[i].verb, verb))
47a0eaa6 2952 return i;
514f4ef5 2953
f459b602
MAP
2954 return _ACTION_INVALID;
2955}
e4b61340 2956
94369fc0
LP
2957static const char** make_extra_args(const char *extra_args[static 4]) {
2958 size_t n = 0;
2959
2caa38e9
LP
2960 assert(extra_args);
2961
94369fc0
LP
2962 if (arg_scope != UNIT_FILE_SYSTEM)
2963 extra_args[n++] = "--user";
2964
2965 if (arg_transport == BUS_TRANSPORT_REMOTE) {
2966 extra_args[n++] = "-H";
2967 extra_args[n++] = arg_host;
2968 } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
2969 extra_args[n++] = "-M";
2970 extra_args[n++] = arg_host;
2971 } else
2972 assert(arg_transport == BUS_TRANSPORT_LOCAL);
2973
2974 extra_args[n] = NULL;
2975 return extra_args;
2976}
2977
e449de87 2978static int start_unit(int argc, char *argv[], void *userdata) {
a7056cde 2979 _cleanup_(bus_wait_for_units_freep) BusWaitForUnits *wu = NULL;
ebd011d9 2980 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
85d9b598 2981 const char *method, *job_type, *mode, *one_name, *suffix = NULL;
416b8801 2982 _cleanup_free_ char **stopped_units = NULL; /* Do not use _cleanup_strv_free_ */
ebd011d9 2983 _cleanup_strv_free_ char **names = NULL;
0e8d9c0c 2984 int r, ret = EXIT_SUCCESS;
4fbd7192 2985 sd_bus *bus;
729e3769 2986 char **name;
e4b61340 2987
2f50e59f
LP
2988 if (arg_wait && !STR_IN_SET(argv[0], "start", "restart"))
2989 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2990 "--wait may only be used with the 'start' or 'restart' commands.");
93a08841
MP
2991
2992 /* we cannot do sender tracking on the private bus, so we need the full
2993 * one for RefUnit to implement --wait */
2994 r = acquire_bus(arg_wait ? BUS_FULL : BUS_MANAGER, &bus);
4fbd7192
LP
2995 if (r < 0)
2996 return r;
2997
c59e2ec6 2998 ask_password_agent_open_maybe();
8a4b13c5 2999 polkit_agent_open_maybe();
d2ad7e1b 3000
e4b61340 3001 if (arg_action == ACTION_SYSTEMCTL) {
47a0eaa6 3002 enum action action;
e4b61340 3003
e449de87
LP
3004 action = verb_to_action(argv[0]);
3005
913c1916 3006 if (action != _ACTION_INVALID) {
85d9b598 3007 /* A command in style "systemctl reboot", "systemctl poweroff", … */
913c1916 3008 method = "StartUnit";
85d9b598 3009 job_type = "start";
913c1916
AJ
3010 mode = action_table[action].mode;
3011 one_name = action_table[action].target;
3012 } else {
3013 if (streq(argv[0], "isolate")) {
85d9b598 3014 /* A "systemctl isolate <unit1> <unit2> …" command */
913c1916 3015 method = "StartUnit";
85d9b598 3016 job_type = "start";
913c1916 3017 mode = "isolate";
913c1916
AJ
3018 suffix = ".target";
3019 } else {
85d9b598 3020 /* A command in style of "systemctl start <unit1> <unit2> …", "sysemctl stop <unit1> <unit2> …" and so on */
913c1916 3021 method = verb_to_method(argv[0]);
85d9b598 3022 job_type = verb_to_job_type(argv[0]);
913c1916
AJ
3023 mode = arg_job_mode;
3024 }
3025 one_name = NULL;
3026 }
e4b61340 3027 } else {
85d9b598 3028 /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
78ca9099 3029 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
47a0eaa6 3030 assert(action_table[arg_action].target);
913c1916 3031 assert(action_table[arg_action].mode);
e4b61340
LP
3032
3033 method = "StartUnit";
85d9b598 3034 job_type = "start";
47a0eaa6 3035 mode = action_table[arg_action].mode;
e3e0314b 3036 one_name = action_table[arg_action].target;
514f4ef5
LP
3037 }
3038
8b7ec7bb 3039 if (one_name) {
bea1a013 3040 names = strv_new(one_name);
8b7ec7bb
LP
3041 if (!names)
3042 return log_oom();
3043 } else {
1d56bc09
ZJS
3044 bool expanded;
3045
3046 r = expand_names(bus, strv_skip(argv, 1), suffix, &names, &expanded);
e3e0314b 3047 if (r < 0)
691395d8 3048 return log_error_errno(r, "Failed to expand names: %m");
1d56bc09
ZJS
3049
3050 if (!arg_all && expanded && streq(job_type, "start") && !arg_quiet) {
3051 log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
3052 ansi_highlight_red(),
3053 ansi_normal());
3054 log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
3055 " Passing --all will also load units which are pulled in by other units.\n"
3056 " See systemctl(1) for more details.");
3057 }
e3e0314b 3058 }
b6520546 3059
6e905d93 3060 if (!arg_no_block) {
ebd011d9 3061 r = bus_wait_for_jobs_new(bus, &w);
f647962d
MS
3062 if (r < 0)
3063 return log_error_errno(r, "Could not watch jobs: %m");
e4b61340
LP
3064 }
3065
93a08841 3066 if (arg_wait) {
31b2cd5d 3067 r = sd_bus_call_method_async(
93a08841 3068 bus,
31b2cd5d 3069 NULL,
93a08841
MP
3070 "org.freedesktop.systemd1",
3071 "/org/freedesktop/systemd1",
3072 "org.freedesktop.systemd1.Manager",
3073 "Subscribe",
31b2cd5d
LP
3074 NULL, NULL,
3075 NULL);
93a08841 3076 if (r < 0)
31b2cd5d 3077 return log_error_errno(r, "Failed to enable subscription: %m");
85d9b598 3078
a7056cde 3079 r = bus_wait_for_units_new(bus, &wu);
93a08841 3080 if (r < 0)
a7056cde 3081 return log_error_errno(r, "Failed to allocate unit watch context: %m");
93a08841
MP
3082 }
3083
b6520546 3084 STRV_FOREACH(name, names) {
4afd3348 3085 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
f459b602 3086
a7056cde 3087 r = start_unit_one(bus, method, job_type, *name, mode, &error, w, wu);
0e8d9c0c
LP
3088 if (ret == EXIT_SUCCESS && r < 0)
3089 ret = translate_bus_error_to_exit_status(r, &error);
416b8801
YW
3090
3091 if (r >= 0 && streq(method, "StopUnit")) {
3092 r = strv_push(&stopped_units, *name);
3093 if (r < 0)
3094 return log_oom();
3095 }
e4b61340
LP
3096 }
3097
67f3c402 3098 if (!arg_no_block) {
94369fc0 3099 const char* extra_args[4];
f459b602 3100
94369fc0 3101 r = bus_wait_for_jobs(w, arg_quiet, make_extra_args(extra_args));
0e8d9c0c
LP
3102 if (r < 0)
3103 return r;
49111a70
ZJS
3104
3105 /* When stopping units, warn if they can still be triggered by
3106 * another active unit (socket, path, timer) */
416b8801
YW
3107 if (!arg_quiet)
3108 STRV_FOREACH(name, stopped_units)
86f004fb 3109 (void) check_triggering_units(bus, *name);
67f3c402 3110 }
514f4ef5 3111
a7056cde
LP
3112 if (arg_wait) {
3113 r = bus_wait_for_units_run(wu);
0e8d9c0c 3114 if (r < 0)
a7056cde
LP
3115 return log_error_errno(r, "Failed to wait for units: %m");
3116 if (r == BUS_WAIT_FAILURE && ret == EXIT_SUCCESS)
0e8d9c0c 3117 ret = EXIT_FAILURE;
93a08841
MP
3118 }
3119
0e8d9c0c 3120 return ret;
e4b61340
LP
3121}
3122
349cc4a5 3123#if ENABLE_LOGIND
4fbd7192 3124static int logind_set_wall_message(void) {
4afd3348 3125 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 3126 sd_bus *bus;
f2d11d35
LP
3127 _cleanup_free_ char *m = NULL;
3128 int r;
3129
4fbd7192
LP
3130 r = acquire_bus(BUS_FULL, &bus);
3131 if (r < 0)
3132 return r;
f2d11d35
LP
3133
3134 m = strv_join(arg_wall, " ");
3135 if (!m)
3136 return log_oom();
3137
dbc9830c
ZJS
3138 log_debug("%s wall message \"%s\".", arg_dry_run ? "Would set" : "Setting", m);
3139 if (arg_dry_run)
3140 return 0;
3141
f2d11d35
LP
3142 r = sd_bus_call_method(
3143 bus,
3144 "org.freedesktop.login1",
3145 "/org/freedesktop/login1",
3146 "org.freedesktop.login1.Manager",
3147 "SetWallMessage",
3148 &error,
3149 NULL,
3150 "sb",
3151 m,
3152 !arg_no_wall);
3153
3154 if (r < 0)
3155 return log_warning_errno(r, "Failed to set wall message, ignoring: %s", bus_error_message(&error, r));
f2d11d35
LP
3156 return 0;
3157}
79f1c8f6 3158#endif
f2d11d35 3159
c45e5fb8 3160/* Ask systemd-logind, which might grant access to unprivileged users through polkit */
4fbd7192 3161static int logind_reboot(enum action a) {
349cc4a5 3162#if ENABLE_LOGIND
c45e5fb8
LP
3163 static const struct {
3164 const char *method;
3165 const char *description;
3166 } actions[_ACTION_MAX] = {
3167 [ACTION_POWEROFF] = { "PowerOff", "power off system" },
3168 [ACTION_REBOOT] = { "Reboot", "reboot system" },
3169 [ACTION_HALT] = { "Halt", "halt system" },
3170 [ACTION_SUSPEND] = { "Suspend", "suspend system" },
3171 [ACTION_HIBERNATE] = { "Hibernate", "hibernate system" },
3172 [ACTION_HYBRID_SLEEP] = { "HybridSleep", "put system into hybrid sleep" },
3173 [ACTION_SUSPEND_THEN_HIBERNATE] = { "SuspendThenHibernate", "suspend system, hibernate later" },
3174 };
3175
4afd3348 3176 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 3177 sd_bus *bus;
f459b602 3178 int r;
4c80c73c 3179
c45e5fb8
LP
3180 if (a < 0 || a >= _ACTION_MAX || !actions[a].method)
3181 return -EINVAL;
3182
4fbd7192
LP
3183 r = acquire_bus(BUS_FULL, &bus);
3184 if (r < 0)
3185 return r;
f2d11d35 3186
8a4b13c5 3187 polkit_agent_open_maybe();
d2ad7e1b
ZJS
3188 (void) logind_set_wall_message();
3189
c45e5fb8
LP
3190 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run ? "Would execute" : "Executing", actions[a].method);
3191
dbc9830c
ZJS
3192 if (arg_dry_run)
3193 return 0;
3194
f459b602 3195 r = sd_bus_call_method(
f22f08cd
SP
3196 bus,
3197 "org.freedesktop.login1",
3198 "/org/freedesktop/login1",
3199 "org.freedesktop.login1.Manager",
c45e5fb8 3200 actions[a].method,
f459b602 3201 &error,
f22f08cd 3202 NULL,
342641fb 3203 "b", arg_ask_password);
f459b602 3204 if (r < 0)
c45e5fb8 3205 return log_error_errno(r, "Failed to %s via logind: %s", actions[a].description, bus_error_message(&error, r));
f459b602 3206
691395d8 3207 return 0;
4c80c73c
KS
3208#else
3209 return -ENOSYS;
3210#endif
3211}
3212
4fbd7192 3213static int logind_check_inhibitors(enum action a) {
349cc4a5 3214#if ENABLE_LOGIND
4afd3348 3215 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
59164be4 3216 _cleanup_strv_free_ char **sessions = NULL;
f459b602
MAP
3217 const char *what, *who, *why, *mode;
3218 uint32_t uid, pid;
4fbd7192 3219 sd_bus *bus;
f459b602 3220 unsigned c = 0;
59164be4 3221 char **s;
f459b602 3222 int r;
b37844d3 3223
748ebafa
LP
3224 if (arg_ignore_inhibitors || arg_force > 0)
3225 return 0;
3226
3227 if (arg_when > 0)
3228 return 0;
3229
3230 if (geteuid() == 0)
b37844d3
LP
3231 return 0;
3232
3233 if (!on_tty())
3234 return 0;
e08ab379
LP
3235
3236 if (arg_transport != BUS_TRANSPORT_LOCAL)
3237 return 0;
b37844d3 3238
4fbd7192
LP
3239 r = acquire_bus(BUS_FULL, &bus);
3240 if (r < 0)
3241 return r;
3242
f459b602 3243 r = sd_bus_call_method(
b37844d3
LP
3244 bus,
3245 "org.freedesktop.login1",
3246 "/org/freedesktop/login1",
3247 "org.freedesktop.login1.Manager",
3248 "ListInhibitors",
b37844d3 3249 NULL,
f459b602
MAP
3250 &reply,
3251 NULL);
b37844d3
LP
3252 if (r < 0)
3253 /* If logind is not around, then there are no inhibitors... */
3254 return 0;
3255
4aa2beac 3256 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
f459b602
MAP
3257 if (r < 0)
3258 return bus_log_parse_error(r);
b37844d3 3259
4aa2beac 3260 while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
59164be4 3261 _cleanup_free_ char *comm = NULL, *user = NULL;
f459b602 3262 _cleanup_strv_free_ char **sv = NULL;
b37844d3
LP
3263
3264 if (!streq(mode, "block"))
f459b602 3265 continue;
b37844d3
LP
3266
3267 sv = strv_split(what, ":");
3268 if (!sv)
3269 return log_oom();
3270
2f50e59f
LP
3271 if (!pid_is_valid((pid_t) pid))
3272 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Invalid PID "PID_FMT".", (pid_t) pid);
d028e018 3273
b37844d3 3274 if (!strv_contains(sv,
4c315c2c
IS
3275 IN_SET(a,
3276 ACTION_HALT,
3277 ACTION_POWEROFF,
3278 ACTION_REBOOT,
3279 ACTION_KEXEC) ? "shutdown" : "sleep"))
f459b602 3280 continue;
b37844d3
LP
3281
3282 get_process_comm(pid, &comm);
59164be4 3283 user = uid_to_name(uid);
f459b602 3284
de0671ee 3285 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT" \"%s\", user %s), reason is \"%s\".",
d028e018 3286 who, (pid_t) pid, strna(comm), strna(user), why);
b37844d3 3287
f459b602 3288 c++;
b37844d3 3289 }
f459b602
MAP
3290 if (r < 0)
3291 return bus_log_parse_error(r);
b37844d3 3292
f459b602
MAP
3293 r = sd_bus_message_exit_container(reply);
3294 if (r < 0)
3295 return bus_log_parse_error(r);
b37844d3 3296
59164be4
LP
3297 /* Check for current sessions */
3298 sd_get_sessions(&sessions);
3299 STRV_FOREACH(s, sessions) {
59164be4
LP
3300 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
3301
3302 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
3303 continue;
3304
3305 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
3306 continue;
3307
28abce5d 3308 if (sd_session_get_type(*s, &type) < 0 || !STR_IN_SET(type, "x11", "wayland", "tty", "mir"))
59164be4
LP
3309 continue;
3310
3311 sd_session_get_tty(*s, &tty);
3312 sd_session_get_seat(*s, &seat);
3313 sd_session_get_service(*s, &service);
3314 user = uid_to_name(uid);
3315
3316 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
3317 c++;
3318 }
3319
b37844d3
LP
3320 if (c <= 0)
3321 return 0;
3322
59164be4 3323 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
47a0eaa6 3324 action_table[a].verb);
b37844d3
LP
3325
3326 return -EPERM;
3327#else
3328 return 0;
3329#endif
3330}
3331
97af80c5
LP
3332static int prepare_firmware_setup(void) {
3333
3334 if (!arg_firmware_setup)
3335 return 0;
3336
349cc4a5 3337#if ENABLE_LOGIND
4afd3348 3338 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 3339 sd_bus *bus;
a4921cf4
JJ
3340 int r;
3341
4fbd7192
LP
3342 r = acquire_bus(BUS_FULL, &bus);
3343 if (r < 0)
3344 return r;
a4921cf4 3345
a4921cf4
JJ
3346 r = sd_bus_call_method(
3347 bus,
3348 "org.freedesktop.login1",
3349 "/org/freedesktop/login1",
3350 "org.freedesktop.login1.Manager",
3351 "SetRebootToFirmwareSetup",
3352 &error,
3353 NULL,
3354 "b", true);
4fbd7192
LP
3355 if (r < 0)
3356 return log_error_errno(r, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error, r));
a4921cf4
JJ
3357
3358 return 0;
3359#else
2f50e59f
LP
3360 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
3361 "Booting into firmware setup not supported.");
a4921cf4
JJ
3362#endif
3363}
3364
97af80c5
LP
3365static int prepare_boot_loader_menu(void) {
3366
3367 if (arg_boot_loader_menu == USEC_INFINITY)
3368 return 0;
3369
3370#if ENABLE_LOGIND
3371 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3372 sd_bus *bus;
4fbd7192
LP
3373 int r;
3374
97af80c5
LP
3375 r = acquire_bus(BUS_FULL, &bus);
3376 if (r < 0)
3377 return r;
3378
3379 r = sd_bus_call_method(
3380 bus,
3381 "org.freedesktop.login1",
3382 "/org/freedesktop/login1",
3383 "org.freedesktop.login1.Manager",
3384 "SetRebootToBootLoaderMenu",
3385 &error,
3386 NULL,
3387 "t", arg_boot_loader_menu);
3388 if (r < 0)
3389 return log_error_errno(r, "Cannot indicate to boot loader to enter boot loader entry menu: %s", bus_error_message(&error, r));
3390
3391 return 0;
3392#else
2f50e59f
LP
3393 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
3394 "Booting into boot loader menu not supported.");
97af80c5
LP
3395#endif
3396}
3397
3398static int prepare_boot_loader_entry(void) {
3399
3400 if (!arg_boot_loader_entry)
4fbd7192
LP
3401 return 0;
3402
97af80c5
LP
3403#if ENABLE_LOGIND
3404 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3405 sd_bus *bus;
3406 int r;
4fbd7192 3407
97af80c5
LP
3408 r = acquire_bus(BUS_FULL, &bus);
3409 if (r < 0)
3410 return r;
3411
3412 r = sd_bus_call_method(
3413 bus,
3414 "org.freedesktop.login1",
3415 "/org/freedesktop/login1",
3416 "org.freedesktop.login1.Manager",
3417 "SetRebootToBootLoaderEntry",
3418 &error,
3419 NULL,
3420 "s", arg_boot_loader_entry);
3421 if (r < 0)
3422 return log_error_errno(r, "Cannot set boot into loader entry '%s': %s", arg_boot_loader_entry, bus_error_message(&error, r));
4fbd7192 3423
97af80c5
LP
3424 return 0;
3425#else
ee429649
LP
3426 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
3427 "Booting into boot loader entry not supported.");
97af80c5 3428#endif
4fbd7192
LP
3429}
3430
4bb2e9d4
ZJS
3431static int load_kexec_kernel(void) {
3432 _cleanup_(boot_config_free) BootConfig config = {};
43b736a8 3433 _cleanup_free_ char *kernel = NULL, *initrd = NULL, *options = NULL;
4bb2e9d4
ZJS
3434 const BootEntry *e;
3435 pid_t pid;
3436 int r;
3437
3438 if (kexec_loaded()) {
3439 log_debug("Kexec kernel already loaded.");
3440 return 0;
3441 }
3442
c0d73214
ZJS
3443 if (access(KEXEC, X_OK) < 0)
3444 return log_error_errno(errno, KEXEC" is not available: %m");
3445
38bd74d6 3446 r = boot_entries_load_config_auto(NULL, NULL, &config);
2fec5854
ZJS
3447 if (r == -ENOKEY)
3448 /* The call doesn't log about ENOKEY, let's do so here. */
3449 return log_error_errno(r,
3450 "No kexec kernel loaded and autodetection failed.\n%s",
3451 is_efi_boot()
3452 ? "Cannot automatically load kernel: ESP partition mount point not found."
3453 : "Automatic loading works only on systems booted with EFI.");
4bb2e9d4 3454 if (r < 0)
1b20d889 3455 return r;
4bb2e9d4 3456
38bd74d6
LP
3457 e = boot_config_default_entry(&config);
3458 if (!e)
3459 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
3460 "No boot loader entry suitable as default, refusing to guess.");
3461
3462 log_debug("Found default boot loader entry in file \"%s\"", e->path);
3463
78c38fe7
LP
3464 if (!e->kernel)
3465 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3466 "Boot entry does not refer to Linux kernel, which is not supported currently.");
8a1ef3bf 3467 if (strv_length(e->initrd) > 1)
0f88d829 3468 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
8a1ef3bf 3469 "Boot entry specifies multiple initrds, which is not supported currently.");
4bb2e9d4 3470
43b736a8 3471 kernel = path_join(e->root, e->kernel);
9fc32cd9
LP
3472 if (!kernel)
3473 return log_oom();
3474
3475 if (!strv_isempty(e->initrd)) {
0f88d829 3476 initrd = path_join(e->root, e->initrd[0]);
9fc32cd9
LP
3477 if (!initrd)
3478 return log_oom();
3479 }
3480
4bb2e9d4
ZJS
3481 options = strv_join(e->options, " ");
3482 if (!options)
3483 return log_oom();
3484
cd086a01
ZJS
3485 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
3486 "%s "KEXEC" --load \"%s\" --append \"%s\"%s%s%s",
3487 arg_dry_run ? "Would run" : "Running",
3488 kernel,
3489 options,
3490 initrd ? " --initrd \"" : NULL, strempty(initrd), initrd ? "\"" : "");
4bb2e9d4
ZJS
3491 if (arg_dry_run)
3492 return 0;
3493
c943e95f 3494 r = safe_fork("(kexec)", FORK_WAIT|FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid);
4c253ed1 3495 if (r < 0)
b6e1fff1 3496 return r;
4c253ed1 3497 if (r == 0) {
4bb2e9d4
ZJS
3498 const char* const args[] = {
3499 KEXEC,
3500 "--load", kernel,
3501 "--append", options,
3502 initrd ? "--initrd" : NULL, initrd,
c943e95f
LP
3503 NULL
3504 };
4bb2e9d4
ZJS
3505
3506 /* Child */
4bb2e9d4
ZJS
3507 execv(args[0], (char * const *) args);
3508 _exit(EXIT_FAILURE);
4c253ed1
LP
3509 }
3510
df685d57 3511 return 0;
4bb2e9d4
ZJS
3512}
3513
57ab9006 3514static int set_exit_code(uint8_t code) {
4afd3348 3515 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
57ab9006
LP
3516 sd_bus *bus;
3517 int r;
3518
3519 r = acquire_bus(BUS_MANAGER, &bus);
3520 if (r < 0)
3521 return r;
3522
3523 r = sd_bus_call_method(
3524 bus,
3525 "org.freedesktop.systemd1",
3526 "/org/freedesktop/systemd1",
3527 "org.freedesktop.systemd1.Manager",
3528 "SetExitCode",
3529 &error,
3530 NULL,
3531 "y", code);
3532 if (r < 0)
af3d8113 3533 return log_error_errno(r, "Failed to set exit code: %s", bus_error_message(&error, r));
57ab9006
LP
3534
3535 return 0;
3536}
3537
e449de87 3538static int start_special(int argc, char *argv[], void *userdata) {
4c80c73c 3539 enum action a;
983d9c90 3540 int r;
2b0f4e6f
ZJS
3541 bool termination_action; /* an action that terminates the manager,
3542 * can be performed also by signal. */
983d9c90 3543
e449de87 3544 assert(argv);
514f4ef5 3545
e449de87 3546 a = verb_to_action(argv[0]);
4c80c73c 3547
4fbd7192 3548 r = logind_check_inhibitors(a);
748ebafa
LP
3549 if (r < 0)
3550 return r;
3551
fba868fa
LP
3552 if (arg_force >= 2) {
3553 r = must_be_root();
3554 if (r < 0)
3555 return r;
c32b90de
LP
3556 }
3557
4fbd7192 3558 r = prepare_firmware_setup();
a4921cf4
JJ
3559 if (r < 0)
3560 return r;
5bdf2243 3561
97af80c5
LP
3562 r = prepare_boot_loader_menu();
3563 if (r < 0)
3564 return r;
3565
3566 r = prepare_boot_loader_entry();
3567 if (r < 0)
3568 return r;
3569
e449de87 3570 if (a == ACTION_REBOOT && argc > 1) {
77defcf5 3571 r = update_reboot_parameter_and_warn(argv[1], false);
b986229e
SW
3572 if (r < 0)
3573 return r;
57ab9006 3574
4bb2e9d4
ZJS
3575 } else if (a == ACTION_KEXEC) {
3576 r = load_kexec_kernel();
d23b5ce2
ZJS
3577 if (r < 0 && arg_force >= 1)
3578 log_notice("Failed to load kexec kernel, continuing without.");
3579 else if (r < 0)
4bb2e9d4
ZJS
3580 return r;
3581
e449de87 3582 } else if (a == ACTION_EXIT && argc > 1) {
7bbb5359 3583 uint8_t code;
287419c1 3584
57ab9006
LP
3585 /* If the exit code is not given on the command line,
3586 * don't reset it to zero: just keep it as it might
3587 * have been set previously. */
287419c1 3588
e449de87 3589 r = safe_atou8(argv[1], &code);
4fbd7192 3590 if (r < 0)
57ab9006 3591 return log_error_errno(r, "Invalid exit code.");
4fbd7192 3592
57ab9006 3593 r = set_exit_code(code);
691395d8 3594 if (r < 0)
57ab9006 3595 return r;
b986229e
SW
3596 }
3597
2b0f4e6f
ZJS
3598 termination_action = IN_SET(a,
3599 ACTION_HALT,
3600 ACTION_POWEROFF,
3601 ACTION_REBOOT);
3602 if (termination_action && arg_force >= 2)
477def80 3603 return halt_now(a);
e606bb61 3604
7e59bfcb 3605 if (arg_force >= 1 &&
5955df2c 3606 (termination_action || IN_SET(a, ACTION_KEXEC, ACTION_EXIT)))
2b0f4e6f
ZJS
3607 r = trivial_method(argc, argv, userdata);
3608 else {
3609 /* First try logind, to allow authentication with polkit */
3610 if (IN_SET(a,
3611 ACTION_POWEROFF,
3612 ACTION_REBOOT,
36b69c31 3613 ACTION_HALT,
2b0f4e6f
ZJS
3614 ACTION_SUSPEND,
3615 ACTION_HIBERNATE,
c58493c0 3616 ACTION_HYBRID_SLEEP,
e68c79db 3617 ACTION_SUSPEND_THEN_HIBERNATE)) {
2b0f4e6f
ZJS
3618
3619 r = logind_reboot(a);
3620 if (r >= 0)
3621 return r;
3622 if (IN_SET(r, -EOPNOTSUPP, -EINPROGRESS))
3623 /* requested operation is not supported or already in progress */
3624 return r;
20b09ca7 3625
130246d2
LP
3626 /* On all other errors, try low-level operation. In order to minimize the difference between
3627 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3628 * logind's shutdown operations are always non-blocking. */
3629
3630 arg_no_block = true;
3631
3632 } else if (IN_SET(a, ACTION_EXIT, ACTION_KEXEC))
3633 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3634 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3635 arg_no_block = true;
7089051f 3636
2b0f4e6f 3637 r = start_unit(argc, argv, userdata);
4c80c73c 3638 }
983d9c90 3639
2b0f4e6f
ZJS
3640 if (termination_action && arg_force < 2 &&
3641 IN_SET(r, -ENOENT, -ETIMEDOUT))
cc7de2ba 3642 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
2b0f4e6f
ZJS
3643
3644 return r;
514f4ef5
LP
3645}
3646
988b3b17
ZJS
3647static int start_system_special(int argc, char *argv[], void *userdata) {
3648 /* Like start_special above, but raises an error when running in user mode */
3649
baaa35ad
ZJS
3650 if (arg_scope != UNIT_FILE_SYSTEM)
3651 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3652 "Bad action for %s mode.",
3653 arg_scope == UNIT_FILE_GLOBAL ? "--global" : "--user");
988b3b17
ZJS
3654
3655 return start_special(argc, argv, userdata);
3656}
3657
fa0d5878 3658static int check_unit_generic(int code, const UnitActiveState good_states[], int nb_states, char **args) {
e3e0314b 3659 _cleanup_strv_free_ char **names = NULL;
fa0d5878 3660 UnitActiveState active_state;
4fbd7192 3661 sd_bus *bus;
729e3769 3662 char **name;
fa0d5878 3663 int r, i;
d60f6ad0 3664 bool found = false;
0183528f 3665
4fbd7192
LP
3666 r = acquire_bus(BUS_MANAGER, &bus);
3667 if (r < 0)
3668 return r;
3669
1d56bc09 3670 r = expand_names(bus, args, NULL, &names, NULL);
f647962d
MS
3671 if (r < 0)
3672 return log_error_errno(r, "Failed to expand names: %m");
e3e0314b
ZJS
3673
3674 STRV_FOREACH(name, names) {
fa0d5878
BR
3675 r = get_state_one_unit(bus, *name, &active_state);
3676 if (r < 0)
3677 return r;
3678
3679 if (!arg_quiet)
3680 puts(unit_active_state_to_string(active_state));
60f9ba0b 3681
fa0d5878
BR
3682 for (i = 0; i < nb_states; ++i)
3683 if (good_states[i] == active_state)
3684 found = true;
1a0fce45
TA
3685 }
3686
d60f6ad0
LN
3687 /* use the given return code for the case that we won't find
3688 * any unit which matches the list */
3689 return found ? 0 : code;
1a0fce45
TA
3690}
3691
e449de87 3692static int check_unit_active(int argc, char *argv[], void *userdata) {
9897b09b
LP
3693 static const UnitActiveState states[] = {
3694 UNIT_ACTIVE,
3695 UNIT_RELOADING,
3696 };
3697
e3e0314b 3698 /* According to LSB: 3, "program is not running" */
b613907e 3699 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING, states, ELEMENTSOF(states), strv_skip(argv, 1));
e3e0314b 3700}
0183528f 3701
e449de87 3702static int check_unit_failed(int argc, char *argv[], void *userdata) {
9897b09b
LP
3703 static const UnitActiveState states[] = {
3704 UNIT_FAILED,
3705 };
3706
b613907e 3707 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS, states, ELEMENTSOF(states), strv_skip(argv, 1));
48220598
LP
3708}
3709
e449de87 3710static int kill_unit(int argc, char *argv[], void *userdata) {
e3e0314b 3711 _cleanup_strv_free_ char **names = NULL;
ac5e3a50 3712 char *kill_who = NULL, **name;
4fbd7192 3713 sd_bus *bus;
e3e0314b 3714 int r, q;
8a0867d6 3715
4fbd7192
LP
3716 r = acquire_bus(BUS_MANAGER, &bus);
3717 if (r < 0)
3718 return r;
3719
8a4b13c5 3720 polkit_agent_open_maybe();
d2ad7e1b 3721
8a0867d6
LP
3722 if (!arg_kill_who)
3723 arg_kill_who = "all";
3724
ac5e3a50
JS
3725 /* --fail was specified */
3726 if (streq(arg_job_mode, "fail"))
81d62103 3727 kill_who = strjoina(arg_kill_who, "-fail");
ac5e3a50 3728
1d56bc09 3729 r = expand_names(bus, strv_skip(argv, 1), NULL, &names, NULL);
e3e0314b 3730 if (r < 0)
691395d8 3731 return log_error_errno(r, "Failed to expand names: %m");
60f9ba0b 3732
e3e0314b 3733 STRV_FOREACH(name, names) {
4afd3348 3734 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
342641fb 3735
6e646d22 3736 q = sd_bus_call_method(
f22f08cd 3737 bus,
b0193f1c
LP
3738 "org.freedesktop.systemd1",
3739 "/org/freedesktop/systemd1",
3740 "org.freedesktop.systemd1.Manager",
6e646d22
LP
3741 "KillUnit",
3742 &error,
3743 NULL,
169d7fb6 3744 "ssi", *name, kill_who ? kill_who : arg_kill_who, arg_signal);
e3e0314b 3745 if (q < 0) {
169d7fb6 3746 log_error_errno(q, "Failed to kill unit %s: %s", *name, bus_error_message(&error, q));
e3e0314b
ZJS
3747 if (r == 0)
3748 r = q;
f459b602 3749 }
8a0867d6 3750 }
f459b602 3751
e3e0314b 3752 return r;
8a0867d6
LP
3753}
3754
d81bc51f
LP
3755static int clean_unit(int argc, char *argv[], void *userdata) {
3756 _cleanup_(bus_wait_for_units_freep) BusWaitForUnits *w = NULL;
3757 _cleanup_strv_free_ char **names = NULL;
3758 int r, ret = EXIT_SUCCESS;
3759 char **name;
3760 sd_bus *bus;
3761
3762 r = acquire_bus(BUS_FULL, &bus);
3763 if (r < 0)
3764 return r;
3765
3766 polkit_agent_open_maybe();
3767
3768 if (!arg_clean_what) {
3769 arg_clean_what = strv_new("cache", "runtime");
3770 if (!arg_clean_what)
3771 return log_oom();
3772 }
3773
1d56bc09 3774 r = expand_names(bus, strv_skip(argv, 1), NULL, &names, NULL);
d81bc51f
LP
3775 if (r < 0)
3776 return log_error_errno(r, "Failed to expand names: %m");
3777
3778 if (!arg_no_block) {
3779 r = bus_wait_for_units_new(bus, &w);
3780 if (r < 0)
3781 return log_error_errno(r, "Failed to allocate unit waiter: %m");
3782 }
3783
3784 STRV_FOREACH(name, names) {
3785 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3786 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
3787
3788 if (w) {
3789 /* If we shall wait for the cleaning to complete, let's add a ref on the unit first */
3790 r = sd_bus_call_method(
3791 bus,
3792 "org.freedesktop.systemd1",
3793 "/org/freedesktop/systemd1",
3794 "org.freedesktop.systemd1.Manager",
3795 "RefUnit",
3796 &error,
3797 NULL,
3798 "s", *name);
3799 if (r < 0) {
3800 log_error_errno(r, "Failed to add reference to unit %s: %s", *name, bus_error_message(&error, r));
3801 if (ret == EXIT_SUCCESS)
3802 ret = r;
3803 continue;
3804 }
3805 }
3806
3807 r = sd_bus_message_new_method_call(
3808 bus,
3809 &m,
3810 "org.freedesktop.systemd1",
3811 "/org/freedesktop/systemd1",
3812 "org.freedesktop.systemd1.Manager",
3813 "CleanUnit");
3814 if (r < 0)
3815 return bus_log_create_error(r);
3816
3817 r = sd_bus_message_append(m, "s", *name);
3818 if (r < 0)
3819 return bus_log_create_error(r);
3820
3821 r = sd_bus_message_append_strv(m, arg_clean_what);
3822 if (r < 0)
3823 return bus_log_create_error(r);
3824
3825 r = sd_bus_call(bus, m, 0, &error, NULL);
3826 if (r < 0) {
3827 log_error_errno(r, "Failed to clean unit %s: %s", *name, bus_error_message(&error, r));
3828 if (ret == EXIT_SUCCESS) {
3829 ret = r;
3830 continue;
3831 }
3832 }
3833
3834 if (w) {
3835 r = bus_wait_for_units_add_unit(w, *name, BUS_WAIT_REFFED|BUS_WAIT_FOR_MAINTENANCE_END, NULL, NULL);
3836 if (r < 0)
3837 return log_error_errno(r, "Failed to watch unit %s: %m", *name);
3838 }
3839 }
3840
3841 r = bus_wait_for_units_run(w);
3842 if (r < 0)
3843 return log_error_errno(r, "Failed to wait for units: %m");
3844 if (r == BUS_WAIT_FAILURE)
3845 ret = EXIT_FAILURE;
3846
3847 return ret;
3848}
3849
582a507f 3850typedef struct ExecStatusInfo {
0129173a
LP
3851 char *name;
3852
582a507f
LP
3853 char *path;
3854 char **argv;
3855
b708e7ce
LP
3856 bool ignore;
3857
582a507f
LP
3858 usec_t start_timestamp;
3859 usec_t exit_timestamp;
3860 pid_t pid;
3861 int code;
3862 int status;
3863
b3d59367
AZ
3864 ExecCommandFlags flags;
3865
582a507f
LP
3866 LIST_FIELDS(struct ExecStatusInfo, exec);
3867} ExecStatusInfo;
3868
3869static void exec_status_info_free(ExecStatusInfo *i) {
3870 assert(i);
3871
0129173a 3872 free(i->name);
582a507f
LP
3873 free(i->path);
3874 strv_free(i->argv);
3875 free(i);
3876}
3877
b3d59367
AZ
3878static int exec_status_info_deserialize(sd_bus_message *m, ExecStatusInfo *i, bool is_ex_prop) {
3879 _cleanup_strv_free_ char **ex_opts = NULL;
b21a0ef8 3880 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
f459b602 3881 const char *path;
582a507f
LP
3882 uint32_t pid;
3883 int32_t code, status;
f459b602 3884 int ignore, r;
582a507f 3885
f459b602 3886 assert(m);
582a507f 3887 assert(i);
582a507f 3888
b3d59367 3889 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_STRUCT, is_ex_prop ? "sasasttttuii" : "sasbttttuii");
f459b602
MAP
3890 if (r < 0)
3891 return bus_log_parse_error(r);
3892 else if (r == 0)
3893 return 0;
582a507f 3894
f459b602
MAP
3895 r = sd_bus_message_read(m, "s", &path);
3896 if (r < 0)
3897 return bus_log_parse_error(r);
582a507f 3898
f84190d8
LP
3899 i->path = strdup(path);
3900 if (!i->path)
f459b602 3901 return log_oom();
582a507f 3902
f459b602
MAP
3903 r = sd_bus_message_read_strv(m, &i->argv);
3904 if (r < 0)
3905 return bus_log_parse_error(r);
3906
b3d59367
AZ
3907 r = is_ex_prop ? sd_bus_message_read_strv(m, &ex_opts) : sd_bus_message_read(m, "b", &ignore);
3908 if (r < 0)
3909 return bus_log_parse_error(r);
3910
f459b602 3911 r = sd_bus_message_read(m,
b3d59367 3912 "ttttuii",
f459b602
MAP
3913 &start_timestamp, &start_timestamp_monotonic,
3914 &exit_timestamp, &exit_timestamp_monotonic,
3915 &pid,
3916 &code, &status);
3917 if (r < 0)
3918 return bus_log_parse_error(r);
582a507f 3919
b3d59367
AZ
3920 if (is_ex_prop) {
3921 r = exec_command_flags_from_strv(ex_opts, &i->flags);
3922 if (r < 0)
3923 return log_error_errno(r, "Failed to convert strv to ExecCommandFlags: %m");
3924
3925 i->ignore = FLAGS_SET(i->flags, EXEC_COMMAND_IGNORE_FAILURE);
3926 } else
3927 i->ignore = ignore;
3928
582a507f
LP
3929 i->start_timestamp = (usec_t) start_timestamp;
3930 i->exit_timestamp = (usec_t) exit_timestamp;
3931 i->pid = (pid_t) pid;
3932 i->code = code;
3933 i->status = status;
3934
f459b602
MAP
3935 r = sd_bus_message_exit_container(m);
3936 if (r < 0)
3937 return bus_log_parse_error(r);
3938
3939 return 1;
582a507f
LP
3940}
3941
d5db7fe6
WC
3942typedef struct UnitCondition {
3943 char *name;
b1ed76ae 3944 char *param;
d5db7fe6
WC
3945 bool trigger;
3946 bool negate;
d5db7fe6
WC
3947 int tristate;
3948
b1ed76ae 3949 LIST_FIELDS(struct UnitCondition, conditions);
d5db7fe6
WC
3950} UnitCondition;
3951
3952static void unit_condition_free(UnitCondition *c) {
9bb71940
ZJS
3953 if (!c)
3954 return;
d5db7fe6
WC
3955
3956 free(c->name);
3957 free(c->param);
3958 free(c);
3959}
3960
9bb71940
ZJS
3961DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition*, unit_condition_free);
3962
61cbdc4b
LP
3963typedef struct UnitStatusInfo {
3964 const char *id;
3965 const char *load_state;
3966 const char *active_state;
3967 const char *sub_state;
a4375746 3968 const char *unit_file_state;
d2dc52db 3969 const char *unit_file_preset;
61cbdc4b
LP
3970
3971 const char *description;
4a9e2fff 3972 const char *following;
61cbdc4b 3973
49dbfa7b
LP
3974 char **documentation;
3975
1b64d026
LP
3976 const char *fragment_path;
3977 const char *source_path;
4ad49000 3978 const char *control_group;
61cbdc4b 3979
76d14b87
OS
3980 char **dropin_paths;
3981
965c5d1d
KK
3982 char **triggered_by;
3983 char **triggers;
3984
9f39404c 3985 const char *load_error;
f42806df 3986 const char *result;
9f39404c 3987
584be568 3988 usec_t inactive_exit_timestamp;
df50185b 3989 usec_t inactive_exit_timestamp_monotonic;
584be568
LP
3990 usec_t active_enter_timestamp;
3991 usec_t active_exit_timestamp;
3992 usec_t inactive_enter_timestamp;
3993
45fb0699 3994 bool need_daemon_reload;
055ef36b 3995 bool transient;
45fb0699 3996
61cbdc4b
LP
3997 /* Service */
3998 pid_t main_pid;
3999 pid_t control_pid;
4000 const char *status_text;
175728c4 4001 const char *pid_file;
d06dacd0 4002 bool running:1;
b4af5a80 4003 int status_errno;
61cbdc4b
LP
4004
4005 usec_t start_timestamp;
4006 usec_t exit_timestamp;
4007
4008 int exit_code, exit_status;
4009
d93dda3a
LP
4010 const char *log_namespace;
4011
90bbc946
LP
4012 usec_t condition_timestamp;
4013 bool condition_result;
b1ed76ae 4014 LIST_HEAD(UnitCondition, conditions);
59fccdc5
LP
4015
4016 usec_t assert_timestamp;
4017 bool assert_result;
4018 bool failed_assert_trigger;
4019 bool failed_assert_negate;
4020 const char *failed_assert;
4021 const char *failed_assert_parameter;
601b0842
GS
4022 usec_t next_elapse_real;
4023 usec_t next_elapse_monotonic;
90bbc946 4024
61cbdc4b
LP
4025 /* Socket */
4026 unsigned n_accepted;
4027 unsigned n_connections;
a98f7575 4028 unsigned n_refused;
b8131a87 4029 bool accept;
61cbdc4b 4030
13160134 4031 /* Pairs of type, path */
67419600
OS
4032 char **listen;
4033
61cbdc4b
LP
4034 /* Device */
4035 const char *sysfs_path;
4036
4037 /* Mount, Automount */
4038 const char *where;
4039
4040 /* Swap */
4041 const char *what;
582a507f 4042
934277fe
LP
4043 /* CGroup */
4044 uint64_t memory_current;
48422635 4045 uint64_t memory_min;
da4d897e
TH
4046 uint64_t memory_low;
4047 uint64_t memory_high;
4048 uint64_t memory_max;
96e131ea 4049 uint64_t memory_swap_max;
934277fe 4050 uint64_t memory_limit;
5ad096b3 4051 uint64_t cpu_usage_nsec;
03a7b521
LP
4052 uint64_t tasks_current;
4053 uint64_t tasks_max;
0e97c93f
DM
4054 uint64_t ip_ingress_bytes;
4055 uint64_t ip_egress_bytes;
7a5de3f9
LP
4056 uint64_t io_read_bytes;
4057 uint64_t io_write_bytes;
0e97c93f 4058
7ad5439e 4059 uint64_t default_memory_min;
c52db42b
CD
4060 uint64_t default_memory_low;
4061
582a507f 4062 LIST_HEAD(ExecStatusInfo, exec);
61cbdc4b
LP
4063} UnitStatusInfo;
4064
a7335518
ZJS
4065static void unit_status_info_free(UnitStatusInfo *info) {
4066 ExecStatusInfo *p;
4067 UnitCondition *c;
4068
4069 strv_free(info->documentation);
4070 strv_free(info->dropin_paths);
965c5d1d
KK
4071 strv_free(info->triggered_by);
4072 strv_free(info->triggers);
a7335518
ZJS
4073 strv_free(info->listen);
4074
4075 while ((c = info->conditions)) {
4076 LIST_REMOVE(conditions, info->conditions, c);
4077 unit_condition_free(c);
4078 }
4079
4080 while ((p = info->exec)) {
4081 LIST_REMOVE(exec, info->exec, p);
4082 exec_status_info_free(p);
4083 }
4084}
4085
965c5d1d
KK
4086static void format_active_state(const char *active_state, const char **active_on, const char **active_off) {
4087 if (streq_ptr(active_state, "failed")) {
4088 *active_on = ansi_highlight_red();
4089 *active_off = ansi_normal();
4090 } else if (STRPTR_IN_SET(active_state, "active", "reloading")) {
4091 *active_on = ansi_highlight_green();
4092 *active_off = ansi_normal();
4093 } else
4094 *active_on = *active_off = "";
4095}
4096
f459b602 4097static void print_status_info(
291d565a 4098 sd_bus *bus,
f459b602
MAP
4099 UnitStatusInfo *i,
4100 bool *ellipsized) {
4101
4d9685be
ZJS
4102 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX];
4103 const char *s1, *s2, *active_on, *active_off, *on, *off, *ss;
c7080257
LP
4104 _cleanup_free_ char *formatted_path = NULL;
4105 ExecStatusInfo *p;
584be568 4106 usec_t timestamp;
1b64d026 4107 const char *path;
13160134 4108 char **t, **t2;
291d565a 4109 int r;
582a507f 4110
61cbdc4b
LP
4111 assert(i);
4112
4113 /* This shows pretty information about a unit. See
4114 * print_property() for a low-level property printer */
4115
965c5d1d 4116 format_active_state(i->active_state, &active_on, &active_off);
b0d14c69 4117
9a6f746f 4118 printf("%s%s%s %s", active_on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), active_off, strna(i->id));
61cbdc4b
LP
4119
4120 if (i->description && !streq_ptr(i->id, i->description))
4121 printf(" - %s", i->description);
4122
4123 printf("\n");
4124
4a9e2fff 4125 if (i->following)
856323c9 4126 printf(" Follow: unit currently follows state of %s\n", i->following);
4a9e2fff 4127
c4555ad8 4128 if (STRPTR_IN_SET(i->load_state, "error", "not-found", "bad-setting")) {
0b5a519c 4129 on = ansi_highlight_red();
1fc464f6 4130 off = ansi_normal();
c31b4423
LP
4131 } else
4132 on = off = "";
4133
c7080257
LP
4134 path = i->source_path ?: i->fragment_path;
4135 if (path && terminal_urlify_path(path, NULL, &formatted_path) >= 0)
4136 path = formatted_path;
1b64d026 4137
9a0abfa8 4138 if (!isempty(i->load_error))
0d588dea 4139 printf(" Loaded: %s%s%s (Reason: %s)\n",
856323c9 4140 on, strna(i->load_state), off, i->load_error);
15ce1647
LP
4141 else if (path && !isempty(i->unit_file_state) && !isempty(i->unit_file_preset) &&
4142 !STR_IN_SET(i->unit_file_state, "generated", "transient"))
0d588dea 4143 printf(" Loaded: %s%s%s (%s; %s; vendor preset: %s)\n",
d2dc52db
LP
4144 on, strna(i->load_state), off, path, i->unit_file_state, i->unit_file_preset);
4145 else if (path && !isempty(i->unit_file_state))
0d588dea 4146 printf(" Loaded: %s%s%s (%s; %s)\n",
856323c9 4147 on, strna(i->load_state), off, path, i->unit_file_state);
1b64d026 4148 else if (path)
0d588dea 4149 printf(" Loaded: %s%s%s (%s)\n",
856323c9 4150 on, strna(i->load_state), off, path);
61cbdc4b 4151 else
0d588dea 4152 printf(" Loaded: %s%s%s\n",
856323c9 4153 on, strna(i->load_state), off);
61cbdc4b 4154
055ef36b 4155 if (i->transient)
0d588dea 4156 printf(" Transient: yes\n");
055ef36b 4157
76d14b87 4158 if (!strv_isempty(i->dropin_paths)) {
f459b602 4159 _cleanup_free_ char *dir = NULL;
76d14b87 4160 bool last = false;
f459b602 4161 char ** dropin;
76d14b87
OS
4162
4163 STRV_FOREACH(dropin, i->dropin_paths) {
c7080257
LP
4164 _cleanup_free_ char *dropin_formatted = NULL;
4165 const char *df;
4166
eb2c3192 4167 if (!dir || last) {
0d588dea
KK
4168 printf(dir ? " " :
4169 " Drop-In: ");
76d14b87 4170
97b11eed 4171 dir = mfree(dir);
76d14b87 4172
5f311f8c
LP
4173 dir = dirname_malloc(*dropin);
4174 if (!dir) {
76d14b87
OS
4175 log_oom();
4176 return;
4177 }
4178
eb2c3192 4179 printf("%s\n"
0d588dea 4180 " %s", dir,
9a6f746f 4181 special_glyph(SPECIAL_GLYPH_TREE_RIGHT));
76d14b87
OS
4182 }
4183
4184 last = ! (*(dropin + 1) && startswith(*(dropin + 1), dir));
4185
c7080257
LP
4186 if (terminal_urlify_path(*dropin, basename(*dropin), &dropin_formatted) >= 0)
4187 df = dropin_formatted;
4188 else
4189 df = *dropin;
4190
4191 printf("%s%s", df, last ? "\n" : ", ");
76d14b87 4192 }
76d14b87
OS
4193 }
4194
2ee68f72 4195 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2ee68f72 4196 if (ss)
0d588dea 4197 printf(" Active: %s%s (%s)%s",
b0d14c69 4198 active_on, strna(i->active_state), ss, active_off);
2ee68f72 4199 else
0d588dea 4200 printf(" Active: %s%s%s",
b0d14c69 4201 active_on, strna(i->active_state), active_off);
61cbdc4b 4202
f42806df
LP
4203 if (!isempty(i->result) && !streq(i->result, "success"))
4204 printf(" (Result: %s)", i->result);
4205
1cf03a4f
ZJS
4206 timestamp = STRPTR_IN_SET(i->active_state, "active", "reloading") ? i->active_enter_timestamp :
4207 STRPTR_IN_SET(i->active_state, "inactive", "failed") ? i->inactive_enter_timestamp :
4208 STRPTR_IN_SET(i->active_state, "activating") ? i->inactive_exit_timestamp :
4209 i->active_exit_timestamp;
584be568 4210
bbb8486e 4211 s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
584be568
LP
4212 s2 = format_timestamp(since2, sizeof(since2), timestamp);
4213
4214 if (s1)
538da63d 4215 printf(" since %s; %s\n", s2, s1);
584be568 4216 else if (s2)
538da63d 4217 printf(" since %s\n", s2);
584be568
LP
4218 else
4219 printf("\n");
4220
bc9aa96b
ZJS
4221 STRV_FOREACH(t, i->triggered_by) {
4222 UnitActiveState state = _UNIT_ACTIVE_STATE_INVALID;
965c5d1d 4223
bc9aa96b
ZJS
4224 (void) get_state_one_unit(bus, *t, &state);
4225 format_active_state(unit_active_state_to_string(state), &on, &off);
965c5d1d 4226
bc9aa96b
ZJS
4227 printf("%s %s%s%s %s\n",
4228 t == i->triggered_by ? "TriggeredBy:" : " ",
4229 on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), off,
4230 *t);
965c5d1d
KK
4231 }
4232
601b0842
GS
4233 if (endswith(i->id, ".timer")) {
4234 char tstamp1[FORMAT_TIMESTAMP_RELATIVE_MAX],
4235 tstamp2[FORMAT_TIMESTAMP_MAX];
4d9685be 4236 const char *next_rel_time, *next_time;
601b0842
GS
4237 dual_timestamp nw, next = {i->next_elapse_real,
4238 i->next_elapse_monotonic};
4239 usec_t next_elapse;
4240
0d588dea 4241 printf(" Trigger: ");
601b0842
GS
4242
4243 dual_timestamp_get(&nw);
4244 next_elapse = calc_next_elapse(&nw, &next);
4d9685be
ZJS
4245 next_rel_time = format_timestamp_relative(tstamp1, sizeof tstamp1, next_elapse);
4246 next_time = format_timestamp(tstamp2, sizeof tstamp2, next_elapse);
601b0842
GS
4247
4248 if (next_time && next_rel_time)
4249 printf("%s; %s\n", next_time, next_rel_time);
4250 else
4251 printf("n/a\n");
4252 }
4253
bc9aa96b
ZJS
4254 STRV_FOREACH(t, i->triggers) {
4255 UnitActiveState state = _UNIT_ACTIVE_STATE_INVALID;
965c5d1d 4256
bc9aa96b
ZJS
4257 (void) get_state_one_unit(bus, *t, &state);
4258 format_active_state(unit_active_state_to_string(state), &on, &off);
965c5d1d 4259
bc9aa96b
ZJS
4260 printf("%s %s%s%s %s\n",
4261 t == i->triggers ? " Triggers:" : " ",
4262 on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), off,
4263 *t);
965c5d1d
KK
4264 }
4265
90bbc946 4266 if (!i->condition_result && i->condition_timestamp > 0) {
d5db7fe6
WC
4267 UnitCondition *c;
4268 int n = 0;
4269
bbb8486e 4270 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
90bbc946
LP
4271 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
4272
0d588dea 4273 printf(" Condition: start %scondition failed%s at %s%s%s\n",
1fc464f6 4274 ansi_highlight_yellow(), ansi_normal(),
5cfee414 4275 s2, s1 ? "; " : "", strempty(s1));
d5db7fe6 4276
b1ed76ae 4277 LIST_FOREACH(conditions, c, i->conditions)
d5db7fe6
WC
4278 if (c->tristate < 0)
4279 n++;
d5db7fe6 4280
b1ed76ae
ZJS
4281 LIST_FOREACH(conditions, c, i->conditions)
4282 if (c->tristate < 0)
0d588dea 4283 printf(" %s %s=%s%s%s was not met\n",
9a6f746f 4284 --n ? special_glyph(SPECIAL_GLYPH_TREE_BRANCH) : special_glyph(SPECIAL_GLYPH_TREE_RIGHT),
b1ed76ae
ZJS
4285 c->name,
4286 c->trigger ? "|" : "",
4287 c->negate ? "!" : "",
4288 c->param);
59fccdc5
LP
4289 }
4290
4291 if (!i->assert_result && i->assert_timestamp > 0) {
4292 s1 = format_timestamp_relative(since1, sizeof(since1), i->assert_timestamp);
4293 s2 = format_timestamp(since2, sizeof(since2), i->assert_timestamp);
4294
0d588dea 4295 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
1fc464f6 4296 ansi_highlight_red(), ansi_normal(),
5cfee414 4297 s2, s1 ? "; " : "", strempty(s1));
59fccdc5 4298 if (i->failed_assert_trigger)
0d588dea 4299 printf(" none of the trigger assertions were met\n");
59fccdc5 4300 else if (i->failed_assert)
0d588dea 4301 printf(" %s=%s%s was not met\n",
59fccdc5
LP
4302 i->failed_assert,
4303 i->failed_assert_negate ? "!" : "",
4304 i->failed_assert_parameter);
90bbc946
LP
4305 }
4306
61cbdc4b 4307 if (i->sysfs_path)
0d588dea 4308 printf(" Device: %s\n", i->sysfs_path);
9feeba4b 4309 if (i->where)
0d588dea 4310 printf(" Where: %s\n", i->where);
9feeba4b 4311 if (i->what)
0d588dea 4312 printf(" What: %s\n", i->what);
49dbfa7b 4313
78c7d20e
LP
4314 STRV_FOREACH(t, i->documentation) {
4315 _cleanup_free_ char *formatted = NULL;
4316 const char *q;
4317
4318 if (terminal_urlify(*t, NULL, &formatted) >= 0)
4319 q = formatted;
4320 else
4321 q = *t;
4322
0d588dea 4323 printf(" %*s %s\n", 9, t == i->documentation ? "Docs:" : "", q);
78c7d20e 4324 }
49dbfa7b 4325
13160134 4326 STRV_FOREACH_PAIR(t, t2, i->listen)
0d588dea 4327 printf(" %*s %s (%s)\n", 9, t == i->listen ? "Listen:" : "", *t2, *t);
67419600 4328
a98f7575 4329 if (i->accept) {
0d588dea 4330 printf(" Accepted: %u; Connected: %u;", i->n_accepted, i->n_connections);
a98f7575 4331 if (i->n_refused)
0d588dea 4332 printf(" Refused: %u", i->n_refused);
a98f7575
MM
4333 printf("\n");
4334 }
4335
582a507f 4336 LIST_FOREACH(exec, p, i->exec) {
13160134 4337 _cleanup_free_ char *argv = NULL;
9a57c629 4338 bool good;
582a507f
LP
4339
4340 /* Only show exited processes here */
4341 if (p->code == 0)
4342 continue;
4343
e5c85244
AZ
4344 /* Don't print ExecXYZEx= properties here since it will appear as a
4345 * duplicate of the non-Ex= variant. */
4346 if (endswith(p->name, "Ex"))
4347 continue;
4348
13160134 4349 argv = strv_join(p->argv, " ");
0d588dea 4350 printf(" Process: "PID_FMT" %s=%s ", p->pid, p->name, strna(argv));
582a507f 4351
1f0958f6 4352 good = is_clean_exit(p->code, p->status, EXIT_CLEAN_DAEMON, NULL);
9a57c629 4353 if (!good) {
0b5a519c 4354 on = ansi_highlight_red();
1fc464f6 4355 off = ansi_normal();
9a57c629
LP
4356 } else
4357 on = off = "";
4358
4359 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
4360
d06dacd0
LP
4361 if (p->code == CLD_EXITED) {
4362 const char *c;
4363
582a507f 4364 printf("status=%i", p->status);
d06dacd0 4365
e04ed6db 4366 c = exit_status_to_string(p->status, EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD);
1b64d026 4367 if (c)
d06dacd0
LP
4368 printf("/%s", c);
4369
4370 } else
582a507f 4371 printf("signal=%s", signal_to_string(p->status));
9a57c629
LP
4372
4373 printf(")%s\n", off);
4374
582a507f
LP
4375 if (i->main_pid == p->pid &&
4376 i->start_timestamp == p->start_timestamp &&
4377 i->exit_timestamp == p->start_timestamp)
4378 /* Let's not show this twice */
4379 i->main_pid = 0;
4380
4381 if (p->pid == i->control_pid)
4382 i->control_pid = 0;
4383 }
4384
61cbdc4b 4385 if (i->main_pid > 0 || i->control_pid > 0) {
61cbdc4b 4386 if (i->main_pid > 0) {
0d588dea 4387 printf(" Main PID: "PID_FMT, i->main_pid);
61cbdc4b
LP
4388
4389 if (i->running) {
a081b9ce
LP
4390
4391 if (arg_transport == BUS_TRANSPORT_LOCAL) {
4392 _cleanup_free_ char *comm = NULL;
4393
4394 (void) get_process_comm(i->main_pid, &comm);
4395 if (comm)
4396 printf(" (%s)", comm);
4397 }
4398
6d4fc029 4399 } else if (i->exit_code > 0) {
61cbdc4b
LP
4400 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
4401
d06dacd0
LP
4402 if (i->exit_code == CLD_EXITED) {
4403 const char *c;
4404
61cbdc4b 4405 printf("status=%i", i->exit_status);
d06dacd0 4406
e1714f02 4407 c = exit_status_to_string(i->exit_status,
e04ed6db 4408 EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD);
1b64d026 4409 if (c)
d06dacd0
LP
4410 printf("/%s", c);
4411
4412 } else
582a507f 4413 printf("signal=%s", signal_to_string(i->exit_status));
6d4fc029
LP
4414 printf(")");
4415 }
13160134 4416 }
61cbdc4b
LP
4417
4418 if (i->control_pid > 0) {
13160134 4419 _cleanup_free_ char *c = NULL;
61cbdc4b 4420
1089dcd4
LP
4421 if (i->main_pid > 0)
4422 fputs("; Control PID: ", stdout);
4423 else
4424 fputs("Cntrl PID: ", stdout); /* if first in column, abbreviated so it fits alignment */
4425
4426 printf(PID_FMT, i->control_pid);
61cbdc4b 4427
a081b9ce
LP
4428 if (arg_transport == BUS_TRANSPORT_LOCAL) {
4429 (void) get_process_comm(i->control_pid, &c);
4430 if (c)
4431 printf(" (%s)", c);
4432 }
61cbdc4b
LP
4433 }
4434
4435 printf("\n");
4436 }
4437
17bb7382 4438 if (i->status_text)
0d588dea 4439 printf(" Status: \"%s\"\n", i->status_text);
b4af5a80 4440 if (i->status_errno > 0)
0d588dea 4441 printf(" Error: %i (%s)\n", i->status_errno, strerror_safe(i->status_errno));
17bb7382 4442
0e97c93f
DM
4443 if (i->ip_ingress_bytes != (uint64_t) -1 && i->ip_egress_bytes != (uint64_t) -1) {
4444 char buf_in[FORMAT_BYTES_MAX], buf_out[FORMAT_BYTES_MAX];
4445
0d588dea 4446 printf(" IP: %s in, %s out\n",
0e97c93f
DM
4447 format_bytes(buf_in, sizeof(buf_in), i->ip_ingress_bytes),
4448 format_bytes(buf_out, sizeof(buf_out), i->ip_egress_bytes));
4449 }
4450
7a5de3f9
LP
4451 if (i->io_read_bytes != UINT64_MAX && i->io_write_bytes != UINT64_MAX) {
4452 char buf_in[FORMAT_BYTES_MAX], buf_out[FORMAT_BYTES_MAX];
4453
0d588dea 4454 printf(" IO: %s read, %s written\n",
7a5de3f9
LP
4455 format_bytes(buf_in, sizeof(buf_in), i->io_read_bytes),
4456 format_bytes(buf_out, sizeof(buf_out), i->io_write_bytes));
4457 }
4458
03a7b521 4459 if (i->tasks_current != (uint64_t) -1) {
0d588dea 4460 printf(" Tasks: %" PRIu64, i->tasks_current);
03a7b521
LP
4461
4462 if (i->tasks_max != (uint64_t) -1)
2a6736dd 4463 printf(" (limit: %" PRIu64 ")\n", i->tasks_max);
03a7b521
LP
4464 else
4465 printf("\n");
4466 }
4467
934277fe
LP
4468 if (i->memory_current != (uint64_t) -1) {
4469 char buf[FORMAT_BYTES_MAX];
4470
0d588dea 4471 printf(" Memory: %s", format_bytes(buf, sizeof(buf), i->memory_current));
934277fe 4472
48422635
TH
4473 if (i->memory_min > 0 || i->memory_low > 0 ||
4474 i->memory_high != CGROUP_LIMIT_MAX || i->memory_max != CGROUP_LIMIT_MAX ||
4475 i->memory_swap_max != CGROUP_LIMIT_MAX ||
da4d897e
TH
4476 i->memory_limit != CGROUP_LIMIT_MAX) {
4477 const char *prefix = "";
4478
4479 printf(" (");
48422635
TH
4480 if (i->memory_min > 0) {
4481 printf("%smin: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_min));
4482 prefix = " ";
4483 }
da4d897e
TH
4484 if (i->memory_low > 0) {
4485 printf("%slow: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_low));
4486 prefix = " ";
4487 }
4488 if (i->memory_high != CGROUP_LIMIT_MAX) {
4489 printf("%shigh: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_high));
4490 prefix = " ";
4491 }
4492 if (i->memory_max != CGROUP_LIMIT_MAX) {
4493 printf("%smax: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_max));
4494 prefix = " ";
4495 }
96e131ea
WC
4496 if (i->memory_swap_max != CGROUP_LIMIT_MAX) {
4497 printf("%sswap max: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_swap_max));
4498 prefix = " ";
4499 }
da4d897e
TH
4500 if (i->memory_limit != CGROUP_LIMIT_MAX) {
4501 printf("%slimit: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_limit));
4502 prefix = " ";
4503 }
4504 printf(")");
4505 }
4506 printf("\n");
934277fe
LP
4507 }
4508
5ad096b3
LP
4509 if (i->cpu_usage_nsec != (uint64_t) -1) {
4510 char buf[FORMAT_TIMESPAN_MAX];
0d588dea 4511 printf(" CPU: %s\n", format_timespan(buf, sizeof(buf), i->cpu_usage_nsec / NSEC_PER_USEC, USEC_PER_MSEC));
5ad096b3
LP
4512 }
4513
51e22f88 4514 if (i->control_group) {
291d565a 4515 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
a434236a 4516 static const char prefix[] = " ";
ab35fb1b
LP
4517 unsigned c;
4518
0d588dea 4519 printf(" CGroup: %s\n", i->control_group);
51e22f88 4520
291d565a
LP
4521 c = columns();
4522 if (c > sizeof(prefix) - 1)
4523 c -= sizeof(prefix) - 1;
4524 else
4525 c = 0;
ab35fb1b 4526
291d565a
LP
4527 r = unit_show_processes(bus, i->id, i->control_group, prefix, c, get_output_flags(), &error);
4528 if (r == -EBADR) {
b69d29ce
LP
4529 unsigned k = 0;
4530 pid_t extra[2];
4531
291d565a 4532 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
ab35fb1b 4533
b69d29ce
LP
4534 if (i->main_pid > 0)
4535 extra[k++] = i->main_pid;
4536
4537 if (i->control_pid > 0)
4538 extra[k++] = i->control_pid;
4539
0ff308c8 4540 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER, i->control_group, prefix, c, extra, k, get_output_flags());
291d565a 4541 } else if (r < 0)
107c2051
ZJS
4542 log_warning_errno(r, "Failed to dump process list for '%s', ignoring: %s",
4543 i->id, bus_error_message(&error, r));
c59760ee 4544 }
45fb0699 4545
ece174c5 4546 if (i->id && arg_transport == BUS_TRANSPORT_LOCAL)
3c756001
LP
4547 show_journal_by_unit(
4548 stdout,
4549 i->id,
d93dda3a 4550 i->log_namespace,
3c756001
LP
4551 arg_output,
4552 0,
4553 i->inactive_exit_timestamp_monotonic,
4554 arg_lines,
4555 getuid(),
4556 get_output_flags() | OUTPUT_BEGIN_NEWLINE,
4557 SD_JOURNAL_LOCAL_ONLY,
4558 arg_scope == UNIT_FILE_SYSTEM,
4559 ellipsized);
86aa7ba4 4560
45fb0699 4561 if (i->need_daemon_reload)
3f36991e 4562 warn_unit_file_changed(i->id);
61cbdc4b
LP
4563}
4564
b43f208f 4565static void show_unit_help(UnitStatusInfo *i) {
256425cc
LP
4566 char **p;
4567
4568 assert(i);
4569
4570 if (!i->documentation) {
4571 log_info("Documentation for %s not known.", i->id);
4572 return;
4573 }
4574
78002a67
ZJS
4575 STRV_FOREACH(p, i->documentation)
4576 if (startswith(*p, "man:"))
4577 show_man_page(*p + 4, false);
4578 else
0315fe37 4579 log_info("Can't show: %s", *p);
256425cc
LP
4580}
4581
4679a8c3
YW
4582static int map_main_pid(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4583 UnitStatusInfo *i = userdata;
4584 uint32_t u;
f459b602 4585 int r;
61cbdc4b 4586
4679a8c3
YW
4587 r = sd_bus_message_read(m, "u", &u);
4588 if (r < 0)
4589 return r;
61cbdc4b 4590
4679a8c3
YW
4591 i->main_pid = (pid_t) u;
4592 i->running = u > 0;
b8131a87 4593
4679a8c3
YW
4594 return 0;
4595}
b8131a87 4596
4679a8c3 4597static int map_load_error(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
31d99bd1 4598 const char *message, **p = userdata;
4679a8c3 4599 int r;
b8131a87 4600
31d99bd1 4601 r = sd_bus_message_read(m, "(ss)", NULL, &message);
4679a8c3
YW
4602 if (r < 0)
4603 return r;
b8131a87 4604
4679a8c3
YW
4605 if (!isempty(message))
4606 *p = message;
61cbdc4b 4607
4679a8c3
YW
4608 return 0;
4609}
61cbdc4b 4610
4679a8c3
YW
4611static int map_listen(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4612 const char *type, *path;
4613 char ***p = userdata;
4614 int r;
61cbdc4b 4615
4679a8c3
YW
4616 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4617 if (r < 0)
4618 return r;
61cbdc4b 4619
4679a8c3 4620 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0) {
61cbdc4b 4621
4679a8c3 4622 r = strv_extend(p, type);
f459b602 4623 if (r < 0)
4679a8c3 4624 return r;
61cbdc4b 4625
4679a8c3 4626 r = strv_extend(p, path);
f459b602 4627 if (r < 0)
4679a8c3 4628 return r;
61cbdc4b 4629 }
4679a8c3
YW
4630 if (r < 0)
4631 return r;
582a507f 4632
4679a8c3
YW
4633 r = sd_bus_message_exit_container(m);
4634 if (r < 0)
4635 return r;
49dbfa7b 4636
4679a8c3
YW
4637 return 0;
4638}
52990c2e 4639
4679a8c3
YW
4640static int map_conditions(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4641 UnitStatusInfo *i = userdata;
4642 const char *cond, *param;
4643 int trigger, negate;
4644 int32_t state;
4645 int r;
52990c2e 4646
4679a8c3
YW
4647 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sbbsi)");
4648 if (r < 0)
4649 return r;
f459b602 4650
4679a8c3
YW
4651 while ((r = sd_bus_message_read(m, "(sbbsi)", &cond, &trigger, &negate, &param, &state)) > 0) {
4652 _cleanup_(unit_condition_freep) UnitCondition *c = NULL;
d5db7fe6 4653
3bfa8668 4654 c = new(UnitCondition, 1);
4679a8c3
YW
4655 if (!c)
4656 return -ENOMEM;
d5db7fe6 4657
3bfa8668
LP
4658 *c = (UnitCondition) {
4659 .name = strdup(cond),
4660 .param = strdup(param),
4661 .trigger = trigger,
4662 .negate = negate,
4663 .tristate = state,
4664 };
4665
4679a8c3
YW
4666 if (!c->name || !c->param)
4667 return -ENOMEM;
d5db7fe6 4668
3bfa8668 4669 LIST_PREPEND(conditions, i->conditions, TAKE_PTR(c));
4679a8c3
YW
4670 }
4671 if (r < 0)
4672 return r;
d5db7fe6 4673
4679a8c3
YW
4674 r = sd_bus_message_exit_container(m);
4675 if (r < 0)
4676 return r;
59fccdc5 4677
4679a8c3
YW
4678 return 0;
4679}
59fccdc5 4680
4679a8c3
YW
4681static int map_asserts(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4682 UnitStatusInfo *i = userdata;
4683 const char *cond, *param;
4684 int trigger, negate;
4685 int32_t state;
4686 int r;
59fccdc5 4687
4679a8c3
YW
4688 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sbbsi)");
4689 if (r < 0)
4690 return r;
59fccdc5 4691
4679a8c3
YW
4692 while ((r = sd_bus_message_read(m, "(sbbsi)", &cond, &trigger, &negate, &param, &state)) > 0) {
4693 if (state < 0 && (!trigger || !i->failed_assert)) {
4694 i->failed_assert = cond;
4695 i->failed_assert_trigger = trigger;
4696 i->failed_assert_negate = negate;
4697 i->failed_assert_parameter = param;
4698 }
4699 }
4700 if (r < 0)
4701 return r;
f459b602 4702
4679a8c3
YW
4703 r = sd_bus_message_exit_container(m);
4704 if (r < 0)
4705 return r;
f459b602 4706
4679a8c3
YW
4707 return 0;
4708}
582a507f 4709
4679a8c3
YW
4710static int map_exec(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4711 _cleanup_free_ ExecStatusInfo *info = NULL;
3e14d36a 4712 ExecStatusInfo *last;
4679a8c3 4713 UnitStatusInfo *i = userdata;
b3d59367 4714 bool is_ex_prop = endswith(member, "Ex");
4679a8c3 4715 int r;
9f39404c 4716
b3d59367 4717 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, is_ex_prop ? "(sasasttttuii)" : "(sasbttttuii)");
4679a8c3
YW
4718 if (r < 0)
4719 return r;
9f39404c 4720
4679a8c3
YW
4721 info = new0(ExecStatusInfo, 1);
4722 if (!info)
4723 return -ENOMEM;
9f39404c 4724
3e14d36a
LP
4725 LIST_FIND_TAIL(exec, i->exec, last);
4726
b3d59367 4727 while ((r = exec_status_info_deserialize(m, info, is_ex_prop)) > 0) {
9f39404c 4728
4679a8c3
YW
4729 info->name = strdup(member);
4730 if (!info->name)
4731 return -ENOMEM;
9f39404c 4732
3e14d36a
LP
4733 LIST_INSERT_AFTER(exec, i->exec, last, info);
4734 last = info;
f459b602 4735
4679a8c3
YW
4736 info = new0(ExecStatusInfo, 1);
4737 if (!info)
4738 return -ENOMEM;
9f39404c 4739 }
4679a8c3
YW
4740 if (r < 0)
4741 return r;
f459b602 4742
4679a8c3 4743 r = sd_bus_message_exit_container(m);
f459b602 4744 if (r < 0)
4679a8c3 4745 return r;
61cbdc4b
LP
4746
4747 return 0;
4748}
4749
eda19357 4750static int print_property(const char *name, const char *expected_value, sd_bus_message *m, bool value, bool all) {
07636114
YW
4751 char bus_type;
4752 const char *contents;
f459b602
MAP
4753 int r;
4754
48220598 4755 assert(name);
f459b602 4756 assert(m);
48220598 4757
61cbdc4b
LP
4758 /* This is a low-level property printer, see
4759 * print_status_info() for the nicer output */
4760
07636114
YW
4761 r = sd_bus_message_peek_type(m, &bus_type, &contents);
4762 if (r < 0)
852c1b4d 4763 return r;
48220598 4764
07636114 4765 switch (bus_type) {
48220598 4766
a3ddd457
YW
4767 case SD_BUS_TYPE_INT32:
4768 if (endswith(name, "ActionExitStatus")) {
4769 int32_t i;
4770
4771 r = sd_bus_message_read_basic(m, bus_type, &i);
4772 if (r < 0)
4773 return r;
4774
4775 if (i >= 0 && i <= 255)
4776 bus_print_property_valuef(name, expected_value, value, "%"PRIi32, i);
4777 else if (all)
4778 bus_print_property_value(name, expected_value, value, "[not set]");
4779
b070c7c0
MS
4780 return 1;
4781 } else if (streq(name, "NUMAPolicy")) {
4782 int32_t i;
4783
4784 r = sd_bus_message_read_basic(m, bus_type, &i);
4785 if (r < 0)
4786 return r;
4787
4788 bus_print_property_valuef(name, expected_value, value, "%s", strna(mpol_to_string(i)));
4789
a3ddd457
YW
4790 return 1;
4791 }
4792 break;
4793
07636114 4794 case SD_BUS_TYPE_STRUCT:
48220598 4795
07636114 4796 if (contents[0] == SD_BUS_TYPE_UINT32 && streq(name, "Job")) {
48220598
LP
4797 uint32_t u;
4798
f459b602
MAP
4799 r = sd_bus_message_read(m, "(uo)", &u, NULL);
4800 if (r < 0)
4801 return bus_log_parse_error(r);
48220598 4802
f459b602 4803 if (u > 0)
102b0214 4804 bus_print_property_valuef(name, expected_value, value, "%"PRIu32, u);
07636114 4805 else if (all)
102b0214 4806 bus_print_property_value(name, expected_value, value, "");
48220598 4807
07636114 4808 return 1;
f459b602 4809
07636114 4810 } else if (contents[0] == SD_BUS_TYPE_STRING && streq(name, "Unit")) {
48220598
LP
4811 const char *s;
4812
f459b602
MAP
4813 r = sd_bus_message_read(m, "(so)", &s, NULL);
4814 if (r < 0)
4815 return bus_log_parse_error(r);
48220598 4816
07636114 4817 if (all || !isempty(s))
102b0214 4818 bus_print_property_value(name, expected_value, value, s);
48220598 4819
07636114 4820 return 1;
f459b602 4821
07636114 4822 } else if (contents[0] == SD_BUS_TYPE_STRING && streq(name, "LoadError")) {
9f39404c
LP
4823 const char *a = NULL, *b = NULL;
4824
f459b602
MAP
4825 r = sd_bus_message_read(m, "(ss)", &a, &b);
4826 if (r < 0)
4827 return bus_log_parse_error(r);
9f39404c 4828
48d3358d 4829 if (!isempty(a) || !isempty(b))
102b0214 4830 bus_print_property_valuef(name, expected_value, value, "%s \"%s\"", strempty(a), strempty(b));
48d3358d
YW
4831 else if (all)
4832 bus_print_property_value(name, expected_value, value, "");
f786e80d 4833
07636114 4834 return 1;
04749e40
YW
4835
4836 } else if (STR_IN_SET(name, "SystemCallFilter", "RestrictAddressFamilies")) {
57183d11
LP
4837 _cleanup_strv_free_ char **l = NULL;
4838 int whitelist;
4839
4840 r = sd_bus_message_enter_container(m, 'r', "bas");
4841 if (r < 0)
4842 return bus_log_parse_error(r);
4843
4844 r = sd_bus_message_read(m, "b", &whitelist);
4845 if (r < 0)
4846 return bus_log_parse_error(r);
4847
4848 r = sd_bus_message_read_strv(m, &l);
4849 if (r < 0)
4850 return bus_log_parse_error(r);
4851
4852 r = sd_bus_message_exit_container(m);
4853 if (r < 0)
4854 return bus_log_parse_error(r);
4855
07636114 4856 if (all || whitelist || !strv_isempty(l)) {
57183d11
LP
4857 bool first = true;
4858 char **i;
4859
07636114 4860 if (!value) {
4f9a9105
ZJS
4861 fputs(name, stdout);
4862 fputc('=', stdout);
4863 }
57183d11
LP
4864
4865 if (!whitelist)
4866 fputc('~', stdout);
4867
4868 STRV_FOREACH(i, l) {
4869 if (first)
4870 first = false;
4871 else
4872 fputc(' ', stdout);
4873
4874 fputs(*i, stdout);
4875 }
4876 fputc('\n', stdout);
4877 }
4878
c7bb2fec 4879 return 1;
102b0214 4880
c7bb2fec
IP
4881 } else if (STR_IN_SET(name, "SELinuxContext", "AppArmorProfile", "SmackProcessLabel")) {
4882 int ignore;
4883 const char *s;
4884
4885 r = sd_bus_message_read(m, "(bs)", &ignore, &s);
4886 if (r < 0)
4887 return bus_log_parse_error(r);
4888
4889 if (!isempty(s))
102b0214 4890 bus_print_property_valuef(name, expected_value, value, "%s%s", ignore ? "-" : "", s);
c7bb2fec 4891 else if (all)
102b0214 4892 bus_print_property_value(name, expected_value, value, "");
c7bb2fec 4893
07636114 4894 return 1;
4a220712
YW
4895
4896 } else if (endswith(name, "ExitStatus") && streq(contents, "aiai")) {
4897 const int32_t *status, *signal;
62b21e2e 4898 size_t n_status, n_signal, i;
4a220712
YW
4899
4900 r = sd_bus_message_enter_container(m, 'r', "aiai");
4901 if (r < 0)
4902 return bus_log_parse_error(r);
4903
62b21e2e 4904 r = sd_bus_message_read_array(m, 'i', (const void **) &status, &n_status);
4a220712
YW
4905 if (r < 0)
4906 return bus_log_parse_error(r);
4907
62b21e2e 4908 r = sd_bus_message_read_array(m, 'i', (const void **) &signal, &n_signal);
4a220712
YW
4909 if (r < 0)
4910 return bus_log_parse_error(r);
4911
4912 r = sd_bus_message_exit_container(m);
4913 if (r < 0)
4914 return bus_log_parse_error(r);
4915
62b21e2e
ZJS
4916 n_status /= sizeof(int32_t);
4917 n_signal /= sizeof(int32_t);
4a220712 4918
62b21e2e 4919 if (all || n_status > 0 || n_signal > 0) {
4a220712
YW
4920 bool first = true;
4921
4922 if (!value) {
4923 fputs(name, stdout);
4924 fputc('=', stdout);
4925 }
4926
62b21e2e 4927 for (i = 0; i < n_status; i++) {
4a220712
YW
4928 if (first)
4929 first = false;
4930 else
4931 fputc(' ', stdout);
4932
4933 printf("%"PRIi32, status[i]);
4934 }
4935
62b21e2e 4936 for (i = 0; i < n_signal; i++) {
4a220712
YW
4937 const char *str;
4938
4939 str = signal_to_string((int) signal[i]);
4a220712
YW
4940
4941 if (first)
4942 first = false;
4943 else
4944 fputc(' ', stdout);
4945
148ffa2e
ZJS
4946 if (str)
4947 fputs(str, stdout);
4948 else
4949 printf("%"PRIi32, status[i]);
4a220712
YW
4950 }
4951
4952 fputc('\n', stdout);
4953 }
4954 return 1;
48220598
LP
4955 }
4956
4957 break;
48220598 4958
f459b602 4959 case SD_BUS_TYPE_ARRAY:
48220598 4960
07636114 4961 if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "EnvironmentFiles")) {
f459b602
MAP
4962 const char *path;
4963 int ignore;
8c7be95e 4964
f459b602
MAP
4965 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sb)");
4966 if (r < 0)
4967 return bus_log_parse_error(r);
8c7be95e 4968
f459b602 4969 while ((r = sd_bus_message_read(m, "(sb)", &path, &ignore)) > 0)
102b0214 4970 bus_print_property_valuef(name, expected_value, value, "%s (ignore_errors=%s)", path, yes_no(ignore));
8c7be95e 4971
f459b602
MAP
4972 if (r < 0)
4973 return bus_log_parse_error(r);
8c7be95e 4974
f459b602
MAP
4975 r = sd_bus_message_exit_container(m);
4976 if (r < 0)
4977 return bus_log_parse_error(r);
8c7be95e 4978
07636114 4979 return 1;
8c7be95e 4980
07636114 4981 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Paths")) {
f459b602 4982 const char *type, *path;
67419600 4983
f459b602
MAP
4984 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4985 if (r < 0)
4986 return bus_log_parse_error(r);
ebf57b80 4987
f459b602 4988 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
102b0214 4989 bus_print_property_valuef(name, expected_value, value, "%s (%s)", path, type);
f459b602
MAP
4990 if (r < 0)
4991 return bus_log_parse_error(r);
ebf57b80 4992
f459b602
MAP
4993 r = sd_bus_message_exit_container(m);
4994 if (r < 0)
4995 return bus_log_parse_error(r);
ebf57b80 4996
07636114 4997 return 1;
582a507f 4998
07636114 4999 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Listen")) {
f459b602 5000 const char *type, *path;
67419600 5001
f459b602
MAP
5002 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
5003 if (r < 0)
5004 return bus_log_parse_error(r);
67419600 5005
f459b602 5006 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
102b0214 5007 bus_print_property_valuef(name, expected_value, value, "%s (%s)", path, type);
f459b602
MAP
5008 if (r < 0)
5009 return bus_log_parse_error(r);
67419600 5010
f459b602
MAP
5011 r = sd_bus_message_exit_container(m);
5012 if (r < 0)
5013 return bus_log_parse_error(r);
67419600 5014
07636114 5015 return 1;
67419600 5016
07636114 5017 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "TimersMonotonic")) {
f459b602 5018 const char *base;
07636114 5019 uint64_t v, next_elapse;
707e5e52 5020
f459b602
MAP
5021 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(stt)");
5022 if (r < 0)
5023 return bus_log_parse_error(r);
552e4331 5024
07636114 5025 while ((r = sd_bus_message_read(m, "(stt)", &base, &v, &next_elapse)) > 0) {
860f2be0 5026 char timespan1[FORMAT_TIMESPAN_MAX] = "n/a", timespan2[FORMAT_TIMESPAN_MAX] = "n/a";
fe68089d 5027
860f2be0
ZJS
5028 (void) format_timespan(timespan1, sizeof timespan1, v, 0);
5029 (void) format_timespan(timespan2, sizeof timespan2, next_elapse, 0);
5030
5031 bus_print_property_valuef(name, expected_value, value,
5032 "{ %s=%s ; next_elapse=%s }", base, timespan1, timespan2);
fe68089d 5033 }
f459b602
MAP
5034 if (r < 0)
5035 return bus_log_parse_error(r);
5036
5037 r = sd_bus_message_exit_container(m);
5038 if (r < 0)
5039 return bus_log_parse_error(r);
fe68089d 5040
07636114 5041 return 1;
fe68089d 5042
07636114 5043 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "TimersCalendar")) {
fa6dee52
YW
5044 const char *base, *spec;
5045 uint64_t next_elapse;
5046
5047 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sst)");
5048 if (r < 0)
5049 return bus_log_parse_error(r);
5050
5051 while ((r = sd_bus_message_read(m, "(sst)", &base, &spec, &next_elapse)) > 0) {
860f2be0 5052 char timestamp[FORMAT_TIMESTAMP_MAX] = "n/a";
fa6dee52 5053
860f2be0
ZJS
5054 (void) format_timestamp(timestamp, sizeof(timestamp), next_elapse);
5055 bus_print_property_valuef(name, expected_value, value,
5056 "{ %s=%s ; next_elapse=%s }", base, spec, timestamp);
fa6dee52
YW
5057 }
5058 if (r < 0)
5059 return bus_log_parse_error(r);
5060
5061 r = sd_bus_message_exit_container(m);
5062 if (r < 0)
5063 return bus_log_parse_error(r);
5064
07636114 5065 return 1;
fa6dee52 5066
07636114 5067 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && startswith(name, "Exec")) {
f459b602 5068 ExecStatusInfo info = {};
b3d59367 5069 bool is_ex_prop = endswith(name, "Ex");
f459b602 5070
b3d59367 5071 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, is_ex_prop ? "(sasasttttuii)" : "(sasbttttuii)");
f459b602
MAP
5072 if (r < 0)
5073 return bus_log_parse_error(r);
5074
b3d59367 5075 while ((r = exec_status_info_deserialize(m, &info, is_ex_prop)) > 0) {
f459b602 5076 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
b3d59367
AZ
5077 _cleanup_strv_free_ char **optv = NULL;
5078 _cleanup_free_ char *tt, *o = NULL;
f459b602
MAP
5079
5080 tt = strv_join(info.argv, " ");
5081
b3d59367
AZ
5082 if (is_ex_prop) {
5083 r = exec_command_flags_to_strv(info.flags, &optv);
5084 if (r < 0)
5085 return log_error_errno(r, "Failed to convert ExecCommandFlags to strv: %m");
5086
5087 o = strv_join(optv, " ");
5088
5089 bus_print_property_valuef(name, expected_value, value,
5090 "{ path=%s ; argv[]=%s ; flags=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT" ; code=%s ; status=%i%s%s }",
5091 strna(info.path),
5092 strna(tt),
5093 strna(o),
5094 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
5095 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
5096 info.pid,
5097 sigchld_code_to_string(info.code),
5098 info.status,
5099 info.code == CLD_EXITED ? "" : "/",
5100 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
5101 } else
5102 bus_print_property_valuef(name, expected_value, value,
5103 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT" ; code=%s ; status=%i%s%s }",
5104 strna(info.path),
5105 strna(tt),
5106 yes_no(info.ignore),
5107 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
5108 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
5109 info.pid,
5110 sigchld_code_to_string(info.code),
5111 info.status,
5112 info.code == CLD_EXITED ? "" : "/",
5113 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
fe68089d 5114
582a507f
LP
5115 free(info.path);
5116 strv_free(info.argv);
f459b602 5117 zero(info);
707e5e52
LP
5118 }
5119
f459b602
MAP
5120 r = sd_bus_message_exit_container(m);
5121 if (r < 0)
5122 return bus_log_parse_error(r);
5123
07636114 5124 return 1;
4ad49000 5125
07636114 5126 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "DeviceAllow")) {
f459b602 5127 const char *path, *rwm;
4ad49000 5128
f459b602
MAP
5129 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
5130 if (r < 0)
5131 return bus_log_parse_error(r);
4ad49000 5132
f459b602 5133 while ((r = sd_bus_message_read(m, "(ss)", &path, &rwm)) > 0)
102b0214 5134 bus_print_property_valuef(name, expected_value, value, "%s %s", strna(path), strna(rwm));
f459b602
MAP
5135 if (r < 0)
5136 return bus_log_parse_error(r);
4ad49000 5137
f459b602
MAP
5138 r = sd_bus_message_exit_container(m);
5139 if (r < 0)
5140 return bus_log_parse_error(r);
4ad49000 5141
07636114 5142 return 1;
4ad49000 5143
07636114 5144 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
72240b52 5145 STR_IN_SET(name, "IODeviceWeight", "BlockIODeviceWeight")) {
f459b602
MAP
5146 const char *path;
5147 uint64_t weight;
b8ab2dc6 5148
f459b602
MAP
5149 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
5150 if (r < 0)
5151 return bus_log_parse_error(r);
b8ab2dc6 5152
f459b602 5153 while ((r = sd_bus_message_read(m, "(st)", &path, &weight)) > 0)
102b0214 5154 bus_print_property_valuef(name, expected_value, value, "%s %"PRIu64, strna(path), weight);
f459b602
MAP
5155 if (r < 0)
5156 return bus_log_parse_error(r);
b8ab2dc6 5157
f459b602
MAP
5158 r = sd_bus_message_exit_container(m);
5159 if (r < 0)
5160 return bus_log_parse_error(r);
b8ab2dc6 5161
07636114 5162 return 1;
b8ab2dc6 5163
07636114 5164 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
72240b52
ZJS
5165 (cgroup_io_limit_type_from_string(name) >= 0 ||
5166 STR_IN_SET(name, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
f459b602
MAP
5167 const char *path;
5168 uint64_t bandwidth;
4ad49000 5169
f459b602
MAP
5170 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
5171 if (r < 0)
5172 return bus_log_parse_error(r);
4ad49000 5173
f459b602 5174 while ((r = sd_bus_message_read(m, "(st)", &path, &bandwidth)) > 0)
102b0214 5175 bus_print_property_valuef(name, expected_value, value, "%s %"PRIu64, strna(path), bandwidth);
f459b602
MAP
5176 if (r < 0)
5177 return bus_log_parse_error(r);
4ad49000 5178
f459b602
MAP
5179 r = sd_bus_message_exit_container(m);
5180 if (r < 0)
5181 return bus_log_parse_error(r);
4ad49000 5182
07636114 5183 return 1;
6ae4283c
TH
5184
5185 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
5186 streq(name, "IODeviceLatencyTargetUSec")) {
5187 char ts[FORMAT_TIMESPAN_MAX];
5188 const char *path;
5189 uint64_t target;
5190
5191 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
5192 if (r < 0)
5193 return bus_log_parse_error(r);
5194
5195 while ((r = sd_bus_message_read(m, "(st)", &path, &target)) > 0)
102b0214
YW
5196 bus_print_property_valuef(name, expected_value, value, "%s %s", strna(path),
5197 format_timespan(ts, sizeof(ts), target, 1));
6ae4283c
TH
5198 if (r < 0)
5199 return bus_log_parse_error(r);
5200
5201 r = sd_bus_message_exit_container(m);
5202 if (r < 0)
5203 return bus_log_parse_error(r);
5204
5205 return 1;
08f3be7a 5206
07636114 5207 } else if (contents[0] == SD_BUS_TYPE_BYTE && streq(name, "StandardInputData")) {
08f3be7a
LP
5208 _cleanup_free_ char *h = NULL;
5209 const void *p;
5210 size_t sz;
5211 ssize_t n;
5212
5213 r = sd_bus_message_read_array(m, 'y', &p, &sz);
5214 if (r < 0)
5215 return bus_log_parse_error(r);
5216
5217 n = base64mem(p, sz, &h);
5218 if (n < 0)
5219 return log_oom();
5220
102b0214 5221 bus_print_property_value(name, expected_value, value, h);
08f3be7a 5222
07636114 5223 return 1;
9c1f9465
YW
5224
5225 } else if (STR_IN_SET(name, "IPAddressAllow", "IPAddressDeny")) {
5226 _cleanup_free_ char *addresses = NULL;
5227
5228 r = sd_bus_message_enter_container(m, 'a', "(iayu)");
5229 if (r < 0)
5230 return bus_log_parse_error(r);
5231
5232 for (;;) {
5233 _cleanup_free_ char *str = NULL;
5234 uint32_t prefixlen;
5235 int32_t family;
5236 const void *ap;
5237 size_t an;
5238
5239 r = sd_bus_message_enter_container(m, 'r', "iayu");
5240 if (r < 0)
5241 return bus_log_parse_error(r);
5242 if (r == 0)
5243 break;
5244
5245 r = sd_bus_message_read(m, "i", &family);
5246 if (r < 0)
5247 return bus_log_parse_error(r);
5248
5249 r = sd_bus_message_read_array(m, 'y', &ap, &an);
5250 if (r < 0)
5251 return bus_log_parse_error(r);
5252
5253 r = sd_bus_message_read(m, "u", &prefixlen);
5254 if (r < 0)
5255 return bus_log_parse_error(r);
5256
5257 r = sd_bus_message_exit_container(m);
5258 if (r < 0)
5259 return bus_log_parse_error(r);
5260
5261 if (!IN_SET(family, AF_INET, AF_INET6))
5262 continue;
5263
5264 if (an != FAMILY_ADDRESS_SIZE(family))
5265 continue;
5266
5267 if (prefixlen > FAMILY_ADDRESS_SIZE(family) * 8)
5268 continue;
5269
5270 if (in_addr_prefix_to_string(family, (union in_addr_union *) ap, prefixlen, &str) < 0)
5271 continue;
5272
5273 if (!strextend_with_separator(&addresses, " ", str, NULL))
5274 return log_oom();
5275 }
5276
5277 r = sd_bus_message_exit_container(m);
5278 if (r < 0)
5279 return bus_log_parse_error(r);
5280
5281 if (all || !isempty(addresses))
5282 bus_print_property_value(name, expected_value, value, strempty(addresses));
5283
5284 return 1;
4c787df7
YW
5285
5286 } else if (STR_IN_SET(name, "BindPaths", "BindReadOnlyPaths")) {
5287 _cleanup_free_ char *paths = NULL;
5288 const char *source, *dest;
5289 int ignore_enoent;
5290 uint64_t rbind;
5291
5292 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ssbt)");
5293 if (r < 0)
5294 return bus_log_parse_error(r);
5295
5296 while ((r = sd_bus_message_read(m, "(ssbt)", &source, &dest, &ignore_enoent, &rbind)) > 0) {
5297 _cleanup_free_ char *str = NULL;
5298
5299 if (isempty(source))
5300 continue;
5301
5302 if (asprintf(&str, "%s%s%s%s%s",
5303 ignore_enoent ? "-" : "",
5304 source,
5305 isempty(dest) ? "" : ":",
5306 strempty(dest),
5307 rbind == MS_REC ? ":rbind" : "") < 0)
5308 return log_oom();
5309
5310 if (!strextend_with_separator(&paths, " ", str, NULL))
5311 return log_oom();
5312 }
5313 if (r < 0)
5314 return bus_log_parse_error(r);
5315
5316 r = sd_bus_message_exit_container(m);
5317 if (r < 0)
5318 return bus_log_parse_error(r);
5319
5320 if (all || !isempty(paths))
5321 bus_print_property_value(name, expected_value, value, strempty(paths));
5322
5323 return 1;
5324
5325 } else if (streq(name, "TemporaryFileSystem")) {
5326 _cleanup_free_ char *paths = NULL;
5327 const char *target, *option;
5328
5329 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
5330 if (r < 0)
5331 return bus_log_parse_error(r);
5332
5333 while ((r = sd_bus_message_read(m, "(ss)", &target, &option)) > 0) {
5334 _cleanup_free_ char *str = NULL;
5335
5336 if (isempty(target))
5337 continue;
5338
5339 if (asprintf(&str, "%s%s%s", target, isempty(option) ? "" : ":", strempty(option)) < 0)
5340 return log_oom();
5341
5342 if (!strextend_with_separator(&paths, " ", str, NULL))
5343 return log_oom();
5344 }
5345 if (r < 0)
5346 return bus_log_parse_error(r);
5347
5348 r = sd_bus_message_exit_container(m);
5349 if (r < 0)
5350 return bus_log_parse_error(r);
5351
5352 if (all || !isempty(paths))
5353 bus_print_property_value(name, expected_value, value, strempty(paths));
5354
5355 return 1;
305a2850
YW
5356
5357 } else if (streq(name, "LogExtraFields")) {
5358 _cleanup_free_ char *fields = NULL;
5359 const void *p;
5360 size_t sz;
5361
5362 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "ay");
5363 if (r < 0)
5364 return bus_log_parse_error(r);
5365
5366 while ((r = sd_bus_message_read_array(m, 'y', &p, &sz)) > 0) {
5367 _cleanup_free_ char *str = NULL;
5368 const char *eq;
5369
5370 if (memchr(p, 0, sz))
5371 continue;
5372
5373 eq = memchr(p, '=', sz);
5374 if (!eq)
5375 continue;
5376
5377 if (!journal_field_valid(p, eq - (const char*) p, false))
5378 continue;
5379
5380 str = malloc(sz + 1);
5381 if (!str)
5382 return log_oom();
5383
5384 memcpy(str, p, sz);
5385 str[sz] = '\0';
5386
5387 if (!utf8_is_valid(str))
5388 continue;
5389
5390 if (!strextend_with_separator(&fields, " ", str, NULL))
5391 return log_oom();
5392 }
5393 if (r < 0)
5394 return bus_log_parse_error(r);
5395
5396 r = sd_bus_message_exit_container(m);
5397 if (r < 0)
5398 return bus_log_parse_error(r);
5399
5400 if (all || !isempty(fields))
5401 bus_print_property_value(name, expected_value, value, strempty(fields));
5402
a047f4f1 5403 return 1;
047f5d63 5404 } else if (contents[0] == SD_BUS_TYPE_BYTE && STR_IN_SET(name, "CPUAffinity", "NUMAMask", "AllowedCPUs", "AllowedMemoryNodes", "EffectiveCPUs", "EffectiveMemoryNodes")) {
a047f4f1
MS
5405 _cleanup_free_ char *affinity = NULL;
5406 _cleanup_(cpu_set_reset) CPUSet set = {};
5407 const void *a;
5408 size_t n;
5409
5410 r = sd_bus_message_read_array(m, 'y', &a, &n);
5411 if (r < 0)
5412 return bus_log_parse_error(r);
5413
5414 r = cpu_set_from_dbus(a, n, &set);
5415 if (r < 0)
b070c7c0 5416 return log_error_errno(r, "Failed to deserialize %s: %m", name);
a047f4f1
MS
5417
5418 affinity = cpu_set_to_range_string(&set);
5419 if (!affinity)
5420 return log_oom();
5421
5422 bus_print_property_value(name, expected_value, value, affinity);
5423
305a2850 5424 return 1;
48220598
LP
5425 }
5426
5427 break;
5428 }
5429
48220598
LP
5430 return 0;
5431}
5432
8559e61d
YW
5433typedef enum SystemctlShowMode{
5434 SYSTEMCTL_SHOW_PROPERTIES,
5435 SYSTEMCTL_SHOW_STATUS,
5436 SYSTEMCTL_SHOW_HELP,
5437 _SYSTEMCTL_SHOW_MODE_MAX,
5438 _SYSTEMCTL_SHOW_MODE_INVALID = -1,
5439} SystemctlShowMode;
5440
aa8d423e 5441static const char* const systemctl_show_mode_table[_SYSTEMCTL_SHOW_MODE_MAX] = {
8559e61d
YW
5442 [SYSTEMCTL_SHOW_PROPERTIES] = "show",
5443 [SYSTEMCTL_SHOW_STATUS] = "status",
5444 [SYSTEMCTL_SHOW_HELP] = "help",
5445};
5446
5447DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode, SystemctlShowMode);
5448
f459b602 5449static int show_one(
f459b602
MAP
5450 sd_bus *bus,
5451 const char *path,
3dced37b 5452 const char *unit,
8559e61d 5453 SystemctlShowMode show_mode,
f459b602
MAP
5454 bool *new_line,
5455 bool *ellipsized) {
5456
3dced37b 5457 static const struct bus_properties_map property_map[] = {
b3d59367
AZ
5458 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
5459 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
5460 { "Documentation", "as", NULL, offsetof(UnitStatusInfo, documentation) },
4679a8c3
YW
5461 {}
5462 }, status_map[] = {
b3d59367
AZ
5463 { "Id", "s", NULL, offsetof(UnitStatusInfo, id) },
5464 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
5465 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
5466 { "SubState", "s", NULL, offsetof(UnitStatusInfo, sub_state) },
5467 { "UnitFileState", "s", NULL, offsetof(UnitStatusInfo, unit_file_state) },
5468 { "UnitFilePreset", "s", NULL, offsetof(UnitStatusInfo, unit_file_preset) },
5469 { "Description", "s", NULL, offsetof(UnitStatusInfo, description) },
5470 { "Following", "s", NULL, offsetof(UnitStatusInfo, following) },
5471 { "Documentation", "as", NULL, offsetof(UnitStatusInfo, documentation) },
5472 { "FragmentPath", "s", NULL, offsetof(UnitStatusInfo, fragment_path) },
5473 { "SourcePath", "s", NULL, offsetof(UnitStatusInfo, source_path) },
5474 { "ControlGroup", "s", NULL, offsetof(UnitStatusInfo, control_group) },
5475 { "DropInPaths", "as", NULL, offsetof(UnitStatusInfo, dropin_paths) },
5476 { "LoadError", "(ss)", map_load_error, offsetof(UnitStatusInfo, load_error) },
5477 { "Result", "s", NULL, offsetof(UnitStatusInfo, result) },
965c5d1d
KK
5478 { "TriggeredBy", "as", NULL, offsetof(UnitStatusInfo, triggered_by) },
5479 { "Triggers", "as", NULL, offsetof(UnitStatusInfo, triggers) },
b3d59367
AZ
5480 { "InactiveExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, inactive_exit_timestamp) },
5481 { "InactiveExitTimestampMonotonic", "t", NULL, offsetof(UnitStatusInfo, inactive_exit_timestamp_monotonic) },
5482 { "ActiveEnterTimestamp", "t", NULL, offsetof(UnitStatusInfo, active_enter_timestamp) },
5483 { "ActiveExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, active_exit_timestamp) },
5484 { "InactiveEnterTimestamp", "t", NULL, offsetof(UnitStatusInfo, inactive_enter_timestamp) },
5485 { "NeedDaemonReload", "b", NULL, offsetof(UnitStatusInfo, need_daemon_reload) },
5486 { "Transient", "b", NULL, offsetof(UnitStatusInfo, transient) },
5487 { "ExecMainPID", "u", NULL, offsetof(UnitStatusInfo, main_pid) },
5488 { "MainPID", "u", map_main_pid, 0 },
5489 { "ControlPID", "u", NULL, offsetof(UnitStatusInfo, control_pid) },
5490 { "StatusText", "s", NULL, offsetof(UnitStatusInfo, status_text) },
5491 { "PIDFile", "s", NULL, offsetof(UnitStatusInfo, pid_file) },
5492 { "StatusErrno", "i", NULL, offsetof(UnitStatusInfo, status_errno) },
5493 { "ExecMainStartTimestamp", "t", NULL, offsetof(UnitStatusInfo, start_timestamp) },
5494 { "ExecMainExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, exit_timestamp) },
5495 { "ExecMainCode", "i", NULL, offsetof(UnitStatusInfo, exit_code) },
5496 { "ExecMainStatus", "i", NULL, offsetof(UnitStatusInfo, exit_status) },
d93dda3a 5497 { "LogNamespace", "s", NULL, offsetof(UnitStatusInfo, log_namespace) },
b3d59367
AZ
5498 { "ConditionTimestamp", "t", NULL, offsetof(UnitStatusInfo, condition_timestamp) },
5499 { "ConditionResult", "b", NULL, offsetof(UnitStatusInfo, condition_result) },
5500 { "Conditions", "a(sbbsi)", map_conditions, 0 },
5501 { "AssertTimestamp", "t", NULL, offsetof(UnitStatusInfo, assert_timestamp) },
5502 { "AssertResult", "b", NULL, offsetof(UnitStatusInfo, assert_result) },
5503 { "Asserts", "a(sbbsi)", map_asserts, 0 },
5504 { "NextElapseUSecRealtime", "t", NULL, offsetof(UnitStatusInfo, next_elapse_real) },
5505 { "NextElapseUSecMonotonic", "t", NULL, offsetof(UnitStatusInfo, next_elapse_monotonic) },
5506 { "NAccepted", "u", NULL, offsetof(UnitStatusInfo, n_accepted) },
5507 { "NConnections", "u", NULL, offsetof(UnitStatusInfo, n_connections) },
5508 { "NRefused", "u", NULL, offsetof(UnitStatusInfo, n_refused) },
5509 { "Accept", "b", NULL, offsetof(UnitStatusInfo, accept) },
5510 { "Listen", "a(ss)", map_listen, offsetof(UnitStatusInfo, listen) },
5511 { "SysFSPath", "s", NULL, offsetof(UnitStatusInfo, sysfs_path) },
5512 { "Where", "s", NULL, offsetof(UnitStatusInfo, where) },
5513 { "What", "s", NULL, offsetof(UnitStatusInfo, what) },
5514 { "MemoryCurrent", "t", NULL, offsetof(UnitStatusInfo, memory_current) },
5515 { "DefaultMemoryMin", "t", NULL, offsetof(UnitStatusInfo, default_memory_min) },
5516 { "DefaultMemoryLow", "t", NULL, offsetof(UnitStatusInfo, default_memory_low) },
5517 { "MemoryMin", "t", NULL, offsetof(UnitStatusInfo, memory_min) },
5518 { "MemoryLow", "t", NULL, offsetof(UnitStatusInfo, memory_low) },
5519 { "MemoryHigh", "t", NULL, offsetof(UnitStatusInfo, memory_high) },
5520 { "MemoryMax", "t", NULL, offsetof(UnitStatusInfo, memory_max) },
5521 { "MemorySwapMax", "t", NULL, offsetof(UnitStatusInfo, memory_swap_max) },
5522 { "MemoryLimit", "t", NULL, offsetof(UnitStatusInfo, memory_limit) },
5523 { "CPUUsageNSec", "t", NULL, offsetof(UnitStatusInfo, cpu_usage_nsec) },
5524 { "TasksCurrent", "t", NULL, offsetof(UnitStatusInfo, tasks_current) },
5525 { "TasksMax", "t", NULL, offsetof(UnitStatusInfo, tasks_max) },
5526 { "IPIngressBytes", "t", NULL, offsetof(UnitStatusInfo, ip_ingress_bytes) },
5527 { "IPEgressBytes", "t", NULL, offsetof(UnitStatusInfo, ip_egress_bytes) },
5528 { "IOReadBytes", "t", NULL, offsetof(UnitStatusInfo, io_read_bytes) },
5529 { "IOWriteBytes", "t", NULL, offsetof(UnitStatusInfo, io_write_bytes) },
898fc00e
AZ
5530 { "ExecCondition", "a(sasbttttuii)", map_exec, 0 },
5531 { "ExecConditionEx", "a(sasasttttuii)", map_exec, 0 },
b3d59367
AZ
5532 { "ExecStartPre", "a(sasbttttuii)", map_exec, 0 },
5533 { "ExecStartPreEx", "a(sasasttttuii)", map_exec, 0 },
5534 { "ExecStart", "a(sasbttttuii)", map_exec, 0 },
5535 { "ExecStartEx", "a(sasasttttuii)", map_exec, 0 },
5536 { "ExecStartPost", "a(sasbttttuii)", map_exec, 0 },
5537 { "ExecStartPostEx", "a(sasasttttuii)", map_exec, 0 },
5538 { "ExecReload", "a(sasbttttuii)", map_exec, 0 },
898fc00e 5539 { "ExecReloadEx", "a(sasasttttuii)", map_exec, 0 },
b3d59367
AZ
5540 { "ExecStopPre", "a(sasbttttuii)", map_exec, 0 },
5541 { "ExecStop", "a(sasbttttuii)", map_exec, 0 },
898fc00e 5542 { "ExecStopEx", "a(sasasttttuii)", map_exec, 0 },
b3d59367 5543 { "ExecStopPost", "a(sasbttttuii)", map_exec, 0 },
898fc00e 5544 { "ExecStopPostEx", "a(sasasttttuii)", map_exec, 0 },
3dced37b
LP
5545 {}
5546 };
5547
4afd3348
LP
5548 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
5549 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3dced37b 5550 _cleanup_set_free_ Set *found_properties = NULL;
a7335518 5551 _cleanup_(unit_status_info_free) UnitStatusInfo info = {
934277fe 5552 .memory_current = (uint64_t) -1,
da4d897e
TH
5553 .memory_high = CGROUP_LIMIT_MAX,
5554 .memory_max = CGROUP_LIMIT_MAX,
96e131ea 5555 .memory_swap_max = CGROUP_LIMIT_MAX,
934277fe 5556 .memory_limit = (uint64_t) -1,
5ad096b3 5557 .cpu_usage_nsec = (uint64_t) -1,
03a7b521
LP
5558 .tasks_current = (uint64_t) -1,
5559 .tasks_max = (uint64_t) -1,
0e97c93f
DM
5560 .ip_ingress_bytes = (uint64_t) -1,
5561 .ip_egress_bytes = (uint64_t) -1,
7a5de3f9
LP
5562 .io_read_bytes = UINT64_MAX,
5563 .io_write_bytes = UINT64_MAX,
934277fe 5564 };
4679a8c3 5565 char **pp;
f459b602 5566 int r;
48220598 5567
48220598 5568 assert(path);
61cbdc4b 5569 assert(new_line);
48220598 5570
e3e0314b
ZJS
5571 log_debug("Showing one %s", path);
5572
4679a8c3 5573 r = bus_map_all_properties(
f22f08cd
SP
5574 bus,
5575 "org.freedesktop.systemd1",
5576 path,
4679a8c3 5577 show_mode == SYSTEMCTL_SHOW_STATUS ? status_map : property_map,
a7e4861c 5578 BUS_MAP_BOOLEAN_AS_BOOL,
f459b602 5579 &error,
f22f08cd 5580 &reply,
4679a8c3 5581 &info);
4c3e8e39
LP
5582 if (r < 0)
5583 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
48220598 5584
4679a8c3
YW
5585 if (unit && streq_ptr(info.load_state, "not-found") && streq_ptr(info.active_state, "inactive")) {
5586 log_full(show_mode == SYSTEMCTL_SHOW_STATUS ? LOG_ERR : LOG_DEBUG,
5587 "Unit %s could not be found.", unit);
e33a06a1 5588
4679a8c3
YW
5589 if (show_mode == SYSTEMCTL_SHOW_STATUS)
5590 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN;
5591 else if (show_mode == SYSTEMCTL_SHOW_HELP)
5592 return -ENOENT;
5593 }
e33a06a1 5594
4679a8c3
YW
5595 if (*new_line)
5596 printf("\n");
3dced37b 5597
4679a8c3
YW
5598 *new_line = true;
5599
5600 if (show_mode == SYSTEMCTL_SHOW_STATUS) {
5601 print_status_info(bus, &info, ellipsized);
5602
5603 if (info.active_state && !STR_IN_SET(info.active_state, "active", "reloading"))
5604 return EXIT_PROGRAM_NOT_RUNNING;
5605
5606 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK;
5607
5608 } else if (show_mode == SYSTEMCTL_SHOW_HELP) {
5609 show_unit_help(&info);
5610 return 0;
3dced37b 5611 }
e33a06a1 5612
4679a8c3
YW
5613 r = sd_bus_message_rewind(reply, true);
5614 if (r < 0)
5615 return log_error_errno(r, "Failed to rewind: %s", bus_error_message(&error, r));
5616
07636114 5617 r = bus_message_print_all_properties(reply, print_property, arg_properties, arg_value, arg_all, &found_properties);
f459b602
MAP
5618 if (r < 0)
5619 return bus_log_parse_error(r);
48220598 5620
4679a8c3
YW
5621 STRV_FOREACH(pp, arg_properties)
5622 if (!set_contains(found_properties, *pp))
5623 log_debug("Property %s does not exist.", *pp);
3dced37b 5624
4679a8c3 5625 return 0;
48220598
LP
5626}
5627
f74294c1 5628static int get_unit_dbus_path_by_pid(
f459b602
MAP
5629 sd_bus *bus,
5630 uint32_t pid,
f74294c1 5631 char **unit) {
f459b602 5632
4afd3348
LP
5633 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5634 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
373d32c9 5635 char *u;
a223b325
MS
5636 int r;
5637
f459b602 5638 r = sd_bus_call_method(
f22f08cd
SP
5639 bus,
5640 "org.freedesktop.systemd1",
5641 "/org/freedesktop/systemd1",
5642 "org.freedesktop.systemd1.Manager",
5643 "GetUnitByPID",
f459b602 5644 &error,
f22f08cd 5645 &reply,
f459b602 5646 "u", pid);
691395d8
LP
5647 if (r < 0)
5648 return log_error_errno(r, "Failed to get unit for PID %"PRIu32": %s", pid, bus_error_message(&error, r));
a223b325 5649
373d32c9 5650 r = sd_bus_message_read(reply, "o", &u);
f459b602
MAP
5651 if (r < 0)
5652 return bus_log_parse_error(r);
5653
373d32c9
LP
5654 u = strdup(u);
5655 if (!u)
5656 return log_oom();
5657
5658 *unit = u;
f74294c1 5659 return 0;
a223b325
MS
5660}
5661
f459b602 5662static int show_all(
f459b602 5663 sd_bus *bus,
f459b602
MAP
5664 bool *new_line,
5665 bool *ellipsized) {
5666
4afd3348 5667 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602
MAP
5668 _cleanup_free_ UnitInfo *unit_infos = NULL;
5669 const UnitInfo *u;
5670 unsigned c;
5bb75bc7 5671 int r, ret = 0;
265a7a2a 5672
1238ee09 5673 r = get_unit_list(bus, NULL, NULL, &unit_infos, 0, &reply);
265a7a2a
ZJS
5674 if (r < 0)
5675 return r;
5676
0221d68a 5677 (void) pager_open(arg_pager_flags);
dbed408b 5678
f459b602
MAP
5679 c = (unsigned) r;
5680
93bab288 5681 typesafe_qsort(unit_infos, c, compare_unit_info);
991f2a39 5682
265a7a2a 5683 for (u = unit_infos; u < unit_infos + c; u++) {
7fd1b19b 5684 _cleanup_free_ char *p = NULL;
265a7a2a 5685
265a7a2a
ZJS
5686 p = unit_dbus_path_from_name(u->id);
5687 if (!p)
5688 return log_oom();
5689
8559e61d 5690 r = show_one(bus, p, u->id, SYSTEMCTL_SHOW_STATUS, new_line, ellipsized);
3df538da 5691 if (r < 0)
265a7a2a 5692 return r;
5bb75bc7
ZJS
5693 else if (r > 0 && ret == 0)
5694 ret = r;
265a7a2a
ZJS
5695 }
5696
5bb75bc7 5697 return ret;
265a7a2a
ZJS
5698}
5699
8fcf784d
LP
5700static int show_system_status(sd_bus *bus) {
5701 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX];
f9e0eefc 5702 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
e7e55dbd 5703 _cleanup_(machine_info_clear) struct machine_info mi = {};
f9e0eefc 5704 _cleanup_free_ char *hn = NULL;
8fcf784d
LP
5705 const char *on, *off;
5706 int r;
5707
5708 hn = gethostname_malloc();
5709 if (!hn)
5710 return log_oom();
5711
a7e4861c
YW
5712 r = bus_map_all_properties(
5713 bus,
5714 "org.freedesktop.systemd1",
5715 "/org/freedesktop/systemd1",
5716 machine_info_property_map,
5717 BUS_MAP_STRDUP,
5718 &error,
5719 NULL,
5720 &mi);
f647962d 5721 if (r < 0)
f9e0eefc 5722 return log_error_errno(r, "Failed to read server status: %s", bus_error_message(&error, r));
8fcf784d 5723
8fcf784d
LP
5724 if (streq_ptr(mi.state, "degraded")) {
5725 on = ansi_highlight_red();
1fc464f6 5726 off = ansi_normal();
92f34a9c
JR
5727 } else if (streq_ptr(mi.state, "running")) {
5728 on = ansi_highlight_green();
5729 off = ansi_normal();
5730 } else {
8fcf784d 5731 on = ansi_highlight_yellow();
1fc464f6 5732 off = ansi_normal();
92f34a9c 5733 }
8fcf784d 5734
9a6f746f 5735 printf("%s%s%s %s\n", on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), off, arg_host ? arg_host : hn);
b0d14c69 5736
8fcf784d
LP
5737 printf(" State: %s%s%s\n",
5738 on, strna(mi.state), off);
5739
c6ba5b80
MP
5740 printf(" Jobs: %" PRIu32 " queued\n", mi.n_jobs);
5741 printf(" Failed: %" PRIu32 " units\n", mi.n_failed_units);
8fcf784d
LP
5742
5743 printf(" Since: %s; %s\n",
5744 format_timestamp(since2, sizeof(since2), mi.timestamp),
5745 format_timestamp_relative(since1, sizeof(since1), mi.timestamp));
5746
5747 printf(" CGroup: %s\n", mi.control_group ?: "/");
4c315c2c
IS
5748 if (IN_SET(arg_transport,
5749 BUS_TRANSPORT_LOCAL,
5750 BUS_TRANSPORT_MACHINE)) {
8fcf784d
LP
5751 static const char prefix[] = " ";
5752 unsigned c;
5753
5754 c = columns();
5755 if (c > sizeof(prefix) - 1)
5756 c -= sizeof(prefix) - 1;
5757 else
5758 c = 0;
5759
0ff308c8 5760 show_cgroup(SYSTEMD_CGROUP_CONTROLLER, strempty(mi.control_group), prefix, c, get_output_flags());
8fcf784d
LP
5761 }
5762
8fcf784d
LP
5763 return 0;
5764}
5765
e449de87 5766static int show(int argc, char *argv[], void *userdata) {
8559e61d
YW
5767 bool new_line = false, ellipsized = false;
5768 SystemctlShowMode show_mode;
e3e0314b 5769 int r, ret = 0;
4fbd7192 5770 sd_bus *bus;
48220598 5771
e449de87 5772 assert(argv);
48220598 5773
8559e61d 5774 show_mode = systemctl_show_mode_from_string(argv[0]);
baaa35ad
ZJS
5775 if (show_mode < 0)
5776 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5777 "Invalid argument.");
e449de87 5778
baaa35ad
ZJS
5779 if (show_mode == SYSTEMCTL_SHOW_HELP && argc <= 1)
5780 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5781 "This command expects one or more unit names. Did you mean --help?");
61cbdc4b 5782
d2ad7e1b
ZJS
5783 r = acquire_bus(BUS_MANAGER, &bus);
5784 if (r < 0)
5785 return r;
5786
0221d68a 5787 (void) pager_open(arg_pager_flags);
ec14911e 5788
4fbd7192 5789 /* If no argument is specified inspect the manager itself */
8559e61d
YW
5790 if (show_mode == SYSTEMCTL_SHOW_PROPERTIES && argc <= 1)
5791 return show_one(bus, "/org/freedesktop/systemd1", NULL, show_mode, &new_line, &ellipsized);
48220598 5792
8559e61d 5793 if (show_mode == SYSTEMCTL_SHOW_STATUS && argc <= 1) {
8fcf784d 5794
8fcf784d
LP
5795 show_system_status(bus);
5796 new_line = true;
5797
5798 if (arg_all)
8559e61d 5799 ret = show_all(bus, &new_line, &ellipsized);
8fcf784d 5800 } else {
e3e0314b
ZJS
5801 _cleanup_free_ char **patterns = NULL;
5802 char **name;
5803
e449de87 5804 STRV_FOREACH(name, strv_skip(argv, 1)) {
3dced37b 5805 _cleanup_free_ char *path = NULL, *unit = NULL;
94e0bd7d 5806 uint32_t id;
48220598 5807
94e0bd7d 5808 if (safe_atou32(*name, &id) < 0) {
e3e0314b 5809 if (strv_push(&patterns, *name) < 0)
94e0bd7d 5810 return log_oom();
48220598 5811
e3e0314b 5812 continue;
8559e61d 5813 } else if (show_mode == SYSTEMCTL_SHOW_PROPERTIES) {
94e0bd7d 5814 /* Interpret as job id */
3dced37b 5815 if (asprintf(&path, "/org/freedesktop/systemd1/job/%u", id) < 0)
94e0bd7d 5816 return log_oom();
48220598 5817
94e0bd7d
ZJS
5818 } else {
5819 /* Interpret as PID */
3dced37b 5820 r = get_unit_dbus_path_by_pid(bus, id, &path);
373d32c9 5821 if (r < 0) {
94e0bd7d 5822 ret = r;
373d32c9
LP
5823 continue;
5824 }
3dced37b
LP
5825
5826 r = unit_name_from_dbus_path(path, &unit);
5827 if (r < 0)
5828 return log_oom();
94e0bd7d 5829 }
f74294c1 5830
8559e61d 5831 r = show_one(bus, path, unit, show_mode, &new_line, &ellipsized);
5bb75bc7
ZJS
5832 if (r < 0)
5833 return r;
5834 else if (r > 0 && ret == 0)
5835 ret = r;
48220598 5836 }
94e0bd7d 5837
e3e0314b
ZJS
5838 if (!strv_isempty(patterns)) {
5839 _cleanup_strv_free_ char **names = NULL;
5840
1d56bc09 5841 r = expand_names(bus, patterns, NULL, &names, NULL);
e3e0314b 5842 if (r < 0)
691395d8 5843 return log_error_errno(r, "Failed to expand names: %m");
e3e0314b 5844
e9c387c8
KK
5845 r = maybe_extend_with_unit_dependencies(bus, &names);
5846 if (r < 0)
5847 return r;
5848
e3e0314b 5849 STRV_FOREACH(name, names) {
3dced37b 5850 _cleanup_free_ char *path;
e3e0314b 5851
3dced37b
LP
5852 path = unit_dbus_path_from_name(*name);
5853 if (!path)
e3e0314b
ZJS
5854 return log_oom();
5855
8559e61d 5856 r = show_one(bus, path, *name, show_mode, &new_line, &ellipsized);
5bb75bc7
ZJS
5857 if (r < 0)
5858 return r;
3dced37b 5859 if (r > 0 && ret == 0)
5bb75bc7 5860 ret = r;
e3e0314b
ZJS
5861 }
5862 }
5863 }
5864
94e0bd7d
ZJS
5865 if (ellipsized && !arg_quiet)
5866 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
48220598 5867
22f4096c 5868 return ret;
0183528f
LP
5869}
5870
e449de87 5871static int cat(int argc, char *argv[], void *userdata) {
8e766630 5872 _cleanup_(lookup_paths_free) LookupPaths lp = {};
15ef1144
LP
5873 _cleanup_strv_free_ char **names = NULL;
5874 char **name;
4fbd7192
LP
5875 sd_bus *bus;
5876 bool first = true;
a25457f5 5877 int r, rc = 0;
15ef1144 5878
4c70211c 5879 /* Include all units by default — i.e. continue as if the --all
4eb53120
FS
5880 * option was used */
5881 if (strv_isempty(arg_states))
5882 arg_all = true;
5883
2f50e59f
LP
5884 if (arg_transport != BUS_TRANSPORT_LOCAL)
5885 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot remotely cat units.");
3e495a66 5886
4943d143 5887 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
ad2a0358 5888 if (r < 0)
c51932be 5889 return log_error_errno(r, "Failed to determine unit paths: %m");
ad2a0358 5890
4fbd7192 5891 r = acquire_bus(BUS_MANAGER, &bus);
15ef1144 5892 if (r < 0)
4fbd7192 5893 return r;
15ef1144 5894
1d56bc09 5895 r = expand_names(bus, strv_skip(argv, 1), NULL, &names, NULL);
4fbd7192
LP
5896 if (r < 0)
5897 return log_error_errno(r, "Failed to expand names: %m");
ad2a0358 5898
e9c387c8
KK
5899 r = maybe_extend_with_unit_dependencies(bus, &names);
5900 if (r < 0)
5901 return r;
5902
0221d68a 5903 (void) pager_open(arg_pager_flags);
15ef1144
LP
5904
5905 STRV_FOREACH(name, names) {
ad2a0358 5906 _cleanup_free_ char *fragment_path = NULL;
15ef1144 5907 _cleanup_strv_free_ char **dropin_paths = NULL;
15ef1144 5908
02a126a3 5909 r = unit_find_paths(bus, *name, &lp, false, &fragment_path, &dropin_paths);
86f004fb 5910 if (r == -ERFKILL) {
02a126a3
LP
5911 printf("%s# Unit %s is masked%s.\n",
5912 ansi_highlight_magenta(),
5913 *name,
5914 ansi_normal());
5915 continue;
5916 }
5917 if (r == -EKEYREJECTED) {
5918 printf("%s# Unit %s could not be loaded.%s\n",
86f004fb
ZJS
5919 ansi_highlight_magenta(),
5920 *name,
5921 ansi_normal());
5922 continue;
5923 }
ad2a0358
ZJS
5924 if (r < 0)
5925 return r;
a25457f5
FS
5926 if (r == 0) {
5927 /* Skip units which have no on-disk counterpart, but
5928 * propagate the error to the user */
5929 rc = -ENOENT;
5930 continue;
5931 }
15ef1144
LP
5932
5933 if (first)
5934 first = false;
5935 else
5936 puts("");
5937
5b9635d1 5938 if (need_daemon_reload(bus, *name) > 0) /* ignore errors (<0), this is informational output */
e100155d
LW
5939 fprintf(stderr,
5940 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
5941 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
5942 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
5943 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
5944 ansi_highlight_red(),
5945 *name,
5946 ansi_highlight_red(),
5947 ansi_highlight_red(),
5948 ansi_highlight_red(),
5949 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user",
5950 ansi_normal());
5951
854a42fb 5952 r = cat_files(fragment_path, dropin_paths, 0);
81f5e513
ZJS
5953 if (r < 0)
5954 return r;
15ef1144
LP
5955 }
5956
a25457f5 5957 return rc;
15ef1144
LP
5958}
5959
e449de87 5960static int set_property(int argc, char *argv[], void *userdata) {
4afd3348
LP
5961 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5962 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
68372da6 5963 _cleanup_free_ char *n = NULL;
89ada3ba 5964 UnitType t;
4fbd7192 5965 sd_bus *bus;
8e2af478
LP
5966 int r;
5967
4fbd7192
LP
5968 r = acquire_bus(BUS_MANAGER, &bus);
5969 if (r < 0)
5970 return r;
5971
8a4b13c5 5972 polkit_agent_open_maybe();
d2ad7e1b 5973
f459b602
MAP
5974 r = sd_bus_message_new_method_call(
5975 bus,
151b9b96 5976 &m,
8e2af478
LP
5977 "org.freedesktop.systemd1",
5978 "/org/freedesktop/systemd1",
5979 "org.freedesktop.systemd1.Manager",
151b9b96 5980 "SetUnitProperties");
f459b602
MAP
5981 if (r < 0)
5982 return bus_log_create_error(r);
8e2af478 5983
37cbc1d5 5984 r = unit_name_mangle(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, &n);
7410616c
LP
5985 if (r < 0)
5986 return log_error_errno(r, "Failed to mangle unit name: %m");
68372da6 5987
89ada3ba 5988 t = unit_name_to_type(n);
2f50e59f
LP
5989 if (t < 0)
5990 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid unit type: %s", n);
89ada3ba 5991
f459b602
MAP
5992 r = sd_bus_message_append(m, "sb", n, arg_runtime);
5993 if (r < 0)
5994 return bus_log_create_error(r);
8e2af478 5995
f459b602
MAP
5996 r = sd_bus_message_open_container(m, SD_BUS_TYPE_ARRAY, "(sv)");
5997 if (r < 0)
5998 return bus_log_create_error(r);
8e2af478 5999
89ada3ba 6000 r = bus_append_unit_property_assignment_many(m, t, strv_skip(argv, 2));
8673cf13
LP
6001 if (r < 0)
6002 return r;
8e2af478 6003
f459b602
MAP
6004 r = sd_bus_message_close_container(m);
6005 if (r < 0)
6006 return bus_log_create_error(r);
8e2af478 6007
c49b30a2 6008 r = sd_bus_call(bus, m, 0, &error, NULL);
691395d8
LP
6009 if (r < 0)
6010 return log_error_errno(r, "Failed to set unit properties on %s: %s", n, bus_error_message(&error, r));
8e2af478
LP
6011
6012 return 0;
6013}
6014
e449de87 6015static int daemon_reload(int argc, char *argv[], void *userdata) {
4afd3348 6016 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2853b60a 6017 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
7e4249b9 6018 const char *method;
4fbd7192 6019 sd_bus *bus;
f459b602 6020 int r;
7e4249b9 6021
4fbd7192
LP
6022 r = acquire_bus(BUS_MANAGER, &bus);
6023 if (r < 0)
6024 return r;
6025
8a4b13c5 6026 polkit_agent_open_maybe();
d2ad7e1b 6027
2853b60a
LP
6028 switch (arg_action) {
6029
6030 case ACTION_RELOAD:
e4b61340 6031 method = "Reload";
2853b60a
LP
6032 break;
6033
6034 case ACTION_REEXEC:
e4b61340 6035 method = "Reexecute";
2853b60a
LP
6036 break;
6037
6038 case ACTION_SYSTEMCTL:
6039 method = streq(argv[0], "daemon-reexec") ? "Reexecute" :
6040 /* "daemon-reload" */ "Reload";
6041 break;
e4b61340 6042
2853b60a
LP
6043 default:
6044 assert_not_reached("Unexpected action");
e4b61340 6045 }
7e4249b9 6046
2853b60a
LP
6047 r = sd_bus_message_new_method_call(
6048 bus,
6049 &m,
6050 "org.freedesktop.systemd1",
6051 "/org/freedesktop/systemd1",
6052 "org.freedesktop.systemd1.Manager",
6053 method);
6054 if (r < 0)
6055 return bus_log_create_error(r);
6056
6057 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
6058 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
6059 * their timeout, and for everything else there's the same time budget in place. */
6060
6061 r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC * 2, &error, NULL);
6062
6063 /* On reexecution, we expect a disconnect, not a reply */
6064 if (IN_SET(r, -ETIMEDOUT, -ECONNRESET) && streq(method, "Reexecute"))
6065 r = 0;
6066
6067 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
6068 return log_error_errno(r, "Failed to reload daemon: %s", bus_error_message(&error, r));
6069
6070 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6071 * old ways of doing things, hence don't log any error in that case here. */
6072
6073 return r < 0 ? r : 0;
6074}
6075
6076static int trivial_method(int argc, char *argv[], void *userdata) {
6077 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6078 const char *method;
6079 sd_bus *bus;
6080 int r;
6081
1ae17672
ZJS
6082 if (arg_dry_run)
6083 return 0;
6084
2853b60a
LP
6085 r = acquire_bus(BUS_MANAGER, &bus);
6086 if (r < 0)
6087 return r;
6088
8a4b13c5 6089 polkit_agent_open_maybe();
d2ad7e1b 6090
2853b60a
LP
6091 method =
6092 streq(argv[0], "clear-jobs") ||
6093 streq(argv[0], "cancel") ? "ClearJobs" :
6094 streq(argv[0], "reset-failed") ? "ResetFailed" :
6095 streq(argv[0], "halt") ? "Halt" :
6096 streq(argv[0], "reboot") ? "Reboot" :
6097 streq(argv[0], "kexec") ? "KExec" :
6098 streq(argv[0], "exit") ? "Exit" :
6099 /* poweroff */ "PowerOff";
6100
6e646d22 6101 r = sd_bus_call_method(
f22f08cd
SP
6102 bus,
6103 "org.freedesktop.systemd1",
6104 "/org/freedesktop/systemd1",
6105 "org.freedesktop.systemd1.Manager",
6e646d22
LP
6106 method,
6107 &error,
6108 NULL,
6109 NULL);
2853b60a
LP
6110 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
6111 return log_error_errno(r, "Failed to execute operation: %s", bus_error_message(&error, r));
6112
6113 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6114 * old ways of doing things, hence don't log any error in that case here. */
7e4249b9 6115
0a9776c2 6116 return r < 0 ? r : 0;
7e4249b9
LP
6117}
6118
e449de87 6119static int reset_failed(int argc, char *argv[], void *userdata) {
e3e0314b 6120 _cleanup_strv_free_ char **names = NULL;
4fbd7192 6121 sd_bus *bus;
f84190d8 6122 char **name;
e3e0314b 6123 int r, q;
5632e374 6124
e449de87 6125 if (argc <= 1)
2853b60a 6126 return trivial_method(argc, argv, userdata);
5632e374 6127
4fbd7192
LP
6128 r = acquire_bus(BUS_MANAGER, &bus);
6129 if (r < 0)
6130 return r;
6131
8a4b13c5 6132 polkit_agent_open_maybe();
d2ad7e1b 6133
1d56bc09 6134 r = expand_names(bus, strv_skip(argv, 1), NULL, &names, NULL);
e3e0314b 6135 if (r < 0)
691395d8 6136 return log_error_errno(r, "Failed to expand names: %m");
f84190d8 6137
e3e0314b 6138 STRV_FOREACH(name, names) {
4afd3348 6139 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
342641fb 6140
6e646d22 6141 q = sd_bus_call_method(
f22f08cd 6142 bus,
b0193f1c
LP
6143 "org.freedesktop.systemd1",
6144 "/org/freedesktop/systemd1",
6145 "org.freedesktop.systemd1.Manager",
6e646d22
LP
6146 "ResetFailedUnit",
6147 &error,
6148 NULL,
6149 "s", *name);
e3e0314b 6150 if (q < 0) {
691395d8 6151 log_error_errno(q, "Failed to reset failed state of unit %s: %s", *name, bus_error_message(&error, q));
e3e0314b
ZJS
6152 if (r == 0)
6153 r = q;
f459b602 6154 }
5632e374
LP
6155 }
6156
e3e0314b 6157 return r;
5632e374
LP
6158}
6159
804ee07c
ZJS
6160static int print_variable(const char *s) {
6161 const char *sep;
6162 _cleanup_free_ char *esc = NULL;
6163
6164 sep = strchr(s, '=');
baaa35ad
ZJS
6165 if (!sep)
6166 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN),
6167 "Invalid environment block");
804ee07c
ZJS
6168
6169 esc = shell_maybe_quote(sep + 1, ESCAPE_POSIX);
6170 if (!esc)
6171 return log_oom();
6172
6173 printf("%.*s=%s\n", (int)(sep-s), s, esc);
6174 return 0;
6175}
6176
e449de87 6177static int show_environment(int argc, char *argv[], void *userdata) {
4afd3348
LP
6178 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6179 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602 6180 const char *text;
4fbd7192 6181 sd_bus *bus;
7e4249b9 6182 int r;
7e4249b9 6183
4fbd7192
LP
6184 r = acquire_bus(BUS_MANAGER, &bus);
6185 if (r < 0)
6186 return r;
6187
0221d68a 6188 (void) pager_open(arg_pager_flags);
d2ad7e1b 6189
f459b602 6190 r = sd_bus_get_property(
f22f08cd
SP
6191 bus,
6192 "org.freedesktop.systemd1",
6193 "/org/freedesktop/systemd1",
f459b602
MAP
6194 "org.freedesktop.systemd1.Manager",
6195 "Environment",
6196 &error,
f22f08cd 6197 &reply,
f459b602 6198 "as");
691395d8
LP
6199 if (r < 0)
6200 return log_error_errno(r, "Failed to get environment: %s", bus_error_message(&error, r));
7e4249b9 6201
f459b602
MAP
6202 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
6203 if (r < 0)
6204 return bus_log_parse_error(r);
7e4249b9 6205
804ee07c
ZJS
6206 while ((r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &text)) > 0) {
6207 r = print_variable(text);
6208 if (r < 0)
6209 return r;
6210 }
f459b602
MAP
6211 if (r < 0)
6212 return bus_log_parse_error(r);
7e4249b9 6213
f459b602
MAP
6214 r = sd_bus_message_exit_container(reply);
6215 if (r < 0)
6216 return bus_log_parse_error(r);
7e4249b9 6217
f84190d8 6218 return 0;
7e4249b9
LP
6219}
6220
e449de87 6221static int switch_root(int argc, char *argv[], void *userdata) {
4afd3348 6222 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
f39d4a08
HH
6223 _cleanup_free_ char *cmdline_init = NULL;
6224 const char *root, *init;
4fbd7192 6225 sd_bus *bus;
f459b602 6226 int r;
957eb8ca 6227
2f50e59f
LP
6228 if (arg_transport != BUS_TRANSPORT_LOCAL)
6229 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot switch root remotely.");
4fbd7192 6230
2f50e59f
LP
6231 if (argc < 2 || argc > 3)
6232 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Wrong number of arguments.");
957eb8ca 6233
e449de87 6234 root = argv[1];
13068da8 6235
e449de87
LP
6236 if (argc >= 3)
6237 init = argv[2];
13068da8 6238 else {
01771226 6239 r = proc_cmdline_get_key("init", 0, &cmdline_init);
f39d4a08 6240 if (r < 0)
da927ba9 6241 log_debug_errno(r, "Failed to parse /proc/cmdline: %m");
13068da8 6242
f39d4a08 6243 init = cmdline_init;
13068da8 6244 }
f459b602 6245
3c6f7c34 6246 init = empty_to_null(init);
f39d4a08
HH
6247 if (init) {
6248 const char *root_systemd_path = NULL, *root_init_path = NULL;
6249
270384b2
YW
6250 root_systemd_path = prefix_roota(root, "/" SYSTEMD_BINARY_PATH);
6251 root_init_path = prefix_roota(root, init);
f39d4a08
HH
6252
6253 /* If the passed init is actually the same as the
6254 * systemd binary, then let's suppress it. */
e3f791a2 6255 if (files_same(root_init_path, root_systemd_path, 0) > 0)
f39d4a08
HH
6256 init = NULL;
6257 }
13068da8 6258
d86e4c97
LP
6259 /* Instruct PID1 to exclude us from its killing spree applied during the transition. Otherwise we
6260 * would exit with a failure status even though the switch to the new root has succeed. */
6261 assert(saved_argv);
6262 assert(saved_argv[0]);
6263 saved_argv[0][0] = '@';
acc28e2e 6264
4fbd7192
LP
6265 r = acquire_bus(BUS_MANAGER, &bus);
6266 if (r < 0)
6267 return r;
6268
8a7a9cea
ZJS
6269 /* If we are slow to exit after the root switch, the new systemd instance
6270 * will send us a signal to terminate. Just ignore it and exit normally.
6271 * This way the unit does not end up as failed.
6272 */
6273 r = ignore_signals(SIGTERM, -1);
6274 if (r < 0)
6275 log_warning_errno(r, "Failed to change disposition of SIGTERM to ignore: %m");
6276
f39d4a08 6277 log_debug("Switching root - root: %s; init: %s", root, strna(init));
957eb8ca 6278
f459b602 6279 r = sd_bus_call_method(
f22f08cd 6280 bus,
957eb8ca
LP
6281 "org.freedesktop.systemd1",
6282 "/org/freedesktop/systemd1",
6283 "org.freedesktop.systemd1.Manager",
f22f08cd 6284 "SwitchRoot",
f459b602 6285 &error,
f22f08cd 6286 NULL,
f459b602 6287 "ss", root, init);
8a7a9cea
ZJS
6288 if (r < 0) {
6289 (void) default_signals(SIGTERM, -1);
6290
691395d8 6291 return log_error_errno(r, "Failed to switch root: %s", bus_error_message(&error, r));
8a7a9cea 6292 }
f459b602
MAP
6293
6294 return 0;
957eb8ca
LP
6295}
6296
38fcb7f7
ZJS
6297static int log_level(int argc, char *argv[], void *userdata) {
6298 sd_bus *bus;
6299 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6300 int r;
6301
6302 r = acquire_bus(BUS_MANAGER, &bus);
6303 if (r < 0)
6304 return r;
6305
6306 if (argc == 1) {
6307 _cleanup_free_ char *level = NULL;
6308
6309 r = sd_bus_get_property_string(
6310 bus,
6311 "org.freedesktop.systemd1",
6312 "/org/freedesktop/systemd1",
6313 "org.freedesktop.systemd1.Manager",
6314 "LogLevel",
6315 &error,
6316 &level);
6317 if (r < 0)
6318 return log_error_errno(r, "Failed to get log level: %s", bus_error_message(&error, r));
6319
6320 puts(level);
6321
6322 } else {
6323 assert(argc == 2);
6324
6325 r = sd_bus_set_property(
6326 bus,
6327 "org.freedesktop.systemd1",
6328 "/org/freedesktop/systemd1",
6329 "org.freedesktop.systemd1.Manager",
6330 "LogLevel",
6331 &error,
6332 "s",
6333 argv[1]);
6334 if (r < 0)
6335 return log_error_errno(r, "Failed to set log level: %s", bus_error_message(&error, r));
6336 }
6337
6338 return 0;
6339}
6340
6341static int log_target(int argc, char *argv[], void *userdata) {
6342 sd_bus *bus;
6343 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6344 int r;
6345
6346 r = acquire_bus(BUS_MANAGER, &bus);
6347 if (r < 0)
6348 return r;
6349
6350 if (argc == 1) {
6351 _cleanup_free_ char *target = NULL;
6352
6353 r = sd_bus_get_property_string(
6354 bus,
6355 "org.freedesktop.systemd1",
6356 "/org/freedesktop/systemd1",
6357 "org.freedesktop.systemd1.Manager",
6358 "LogTarget",
6359 &error,
6360 &target);
6361 if (r < 0)
6362 return log_error_errno(r, "Failed to get log target: %s", bus_error_message(&error, r));
6363
6364 puts(target);
6365
6366 } else {
6367 assert(argc == 2);
6368
6369 r = sd_bus_set_property(
6370 bus,
6371 "org.freedesktop.systemd1",
6372 "/org/freedesktop/systemd1",
6373 "org.freedesktop.systemd1.Manager",
6374 "LogTarget",
6375 &error,
6376 "s",
6377 argv[1]);
6378 if (r < 0)
6379 return log_error_errno(r, "Failed to set log target: %s", bus_error_message(&error, r));
6380 }
6381
6382 return 0;
6383}
6384
6ab86319
ZJS
6385static int service_watchdogs(int argc, char *argv[], void *userdata) {
6386 sd_bus *bus;
6387 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6388 int b, r;
6389
6390 assert(argv);
6391
6392 r = acquire_bus(BUS_MANAGER, &bus);
6393 if (r < 0)
6394 return r;
6395
6396 if (argc == 1) {
6397 /* get ServiceWatchdogs */
6398 r = sd_bus_get_property_trivial(
6399 bus,
6400 "org.freedesktop.systemd1",
6401 "/org/freedesktop/systemd1",
6402 "org.freedesktop.systemd1.Manager",
6403 "ServiceWatchdogs",
6404 &error,
6405 'b',
6406 &b);
6407 if (r < 0)
6408 return log_error_errno(r, "Failed to get service-watchdog state: %s", bus_error_message(&error, r));
6409
6410 printf("%s\n", yes_no(!!b));
6411
6412 } else {
6413 /* set ServiceWatchdogs */
6414 assert(argc == 2);
6415
6416 b = parse_boolean(argv[1]);
6417 if (b < 0)
6418 return log_error_errno(b, "Failed to parse service-watchdogs argument: %m");
6419
6420 r = sd_bus_set_property(
6421 bus,
6422 "org.freedesktop.systemd1",
6423 "/org/freedesktop/systemd1",
6424 "org.freedesktop.systemd1.Manager",
6425 "ServiceWatchdogs",
6426 &error,
6427 "b",
6428 b);
6429 if (r < 0)
6430 return log_error_errno(r, "Failed to set service-watchdog state: %s", bus_error_message(&error, r));
6431 }
6432
6433 return 0;
6434}
6435
e449de87 6436static int set_environment(int argc, char *argv[], void *userdata) {
4afd3348
LP
6437 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6438 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
7e4249b9 6439 const char *method;
4fbd7192 6440 sd_bus *bus;
31e767f7
LP
6441 int r;
6442
e449de87
LP
6443 assert(argc > 1);
6444 assert(argv);
7e4249b9 6445
4fbd7192
LP
6446 r = acquire_bus(BUS_MANAGER, &bus);
6447 if (r < 0)
6448 return r;
6449
8a4b13c5 6450 polkit_agent_open_maybe();
d2ad7e1b 6451
e449de87 6452 method = streq(argv[0], "set-environment")
7e4249b9
LP
6453 ? "SetEnvironment"
6454 : "UnsetEnvironment";
6455
f459b602
MAP
6456 r = sd_bus_message_new_method_call(
6457 bus,
151b9b96 6458 &m,
31e767f7
LP
6459 "org.freedesktop.systemd1",
6460 "/org/freedesktop/systemd1",
6461 "org.freedesktop.systemd1.Manager",
151b9b96 6462 method);
f459b602
MAP
6463 if (r < 0)
6464 return bus_log_create_error(r);
7e4249b9 6465
e449de87 6466 r = sd_bus_message_append_strv(m, strv_skip(argv, 1));
31e767f7 6467 if (r < 0)
f459b602 6468 return bus_log_create_error(r);
7e4249b9 6469
c49b30a2 6470 r = sd_bus_call(bus, m, 0, &error, NULL);
691395d8
LP
6471 if (r < 0)
6472 return log_error_errno(r, "Failed to set environment: %s", bus_error_message(&error, r));
7e4249b9 6473
f84190d8 6474 return 0;
7e4249b9
LP
6475}
6476
e449de87 6477static int import_environment(int argc, char *argv[], void *userdata) {
4afd3348
LP
6478 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6479 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
4fbd7192 6480 sd_bus *bus;
ac3efa8a
LP
6481 int r;
6482
4fbd7192
LP
6483 r = acquire_bus(BUS_MANAGER, &bus);
6484 if (r < 0)
6485 return r;
6486
8a4b13c5 6487 polkit_agent_open_maybe();
d2ad7e1b 6488
ac3efa8a
LP
6489 r = sd_bus_message_new_method_call(
6490 bus,
151b9b96 6491 &m,
ac3efa8a
LP
6492 "org.freedesktop.systemd1",
6493 "/org/freedesktop/systemd1",
6494 "org.freedesktop.systemd1.Manager",
151b9b96 6495 "SetEnvironment");
ac3efa8a
LP
6496 if (r < 0)
6497 return bus_log_create_error(r);
6498
e449de87 6499 if (argc < 2)
ac3efa8a
LP
6500 r = sd_bus_message_append_strv(m, environ);
6501 else {
6502 char **a, **b;
6503
6504 r = sd_bus_message_open_container(m, 'a', "s");
6505 if (r < 0)
6506 return bus_log_create_error(r);
6507
e449de87 6508 STRV_FOREACH(a, strv_skip(argv, 1)) {
ac3efa8a 6509
2f50e59f
LP
6510 if (!env_name_is_valid(*a))
6511 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Not a valid environment variable name: %s", *a);
ac3efa8a
LP
6512
6513 STRV_FOREACH(b, environ) {
6514 const char *eq;
6515
6516 eq = startswith(*b, *a);
6517 if (eq && *eq == '=') {
6518
6519 r = sd_bus_message_append(m, "s", *b);
6520 if (r < 0)
6521 return bus_log_create_error(r);
6522
6523 break;
6524 }
6525 }
6526 }
6527
6528 r = sd_bus_message_close_container(m);
6529 }
6530 if (r < 0)
6531 return bus_log_create_error(r);
6532
6533 r = sd_bus_call(bus, m, 0, &error, NULL);
691395d8
LP
6534 if (r < 0)
6535 return log_error_errno(r, "Failed to import environment: %s", bus_error_message(&error, r));
ac3efa8a
LP
6536
6537 return 0;
6538}
6539
cbb13b2a 6540static int enable_sysv_units(const char *verb, char **args) {
729e3769 6541 int r = 0;
ee5762e3 6542
349cc4a5 6543#if HAVE_SYSV_COMPAT
8e766630 6544 _cleanup_(lookup_paths_free) LookupPaths paths = {};
e735decc
LP
6545 unsigned f = 0;
6546
6547 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
ee5762e3 6548
729e3769
LP
6549 if (arg_scope != UNIT_FILE_SYSTEM)
6550 return 0;
ee5762e3 6551
b41b9d2a
LP
6552 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
6553 return 0;
6554
4c315c2c
IS
6555 if (!STR_IN_SET(verb,
6556 "enable",
6557 "disable",
6558 "is-enabled"))
729e3769 6559 return 0;
ee5762e3 6560
4943d143 6561 r = lookup_paths_init(&paths, arg_scope, LOOKUP_PATHS_EXCLUDE_GENERATED, arg_root);
729e3769
LP
6562 if (r < 0)
6563 return r;
ee5762e3 6564
729e3769 6565 r = 0;
a644abed 6566 while (args[f]) {
e735decc
LP
6567
6568 const char *argv[] = {
6569 ROOTLIBEXECDIR "/systemd-sysv-install",
3483460c
LP
6570 NULL, /* --root= */
6571 NULL, /* verb */
6572 NULL, /* service */
e735decc
LP
6573 NULL,
6574 };
6575
8d1ee648 6576 _cleanup_free_ char *p = NULL, *q = NULL, *l = NULL, *v = NULL;
729e3769 6577 bool found_native = false, found_sysv;
e735decc 6578 const char *name;
729e3769 6579 unsigned c = 1;
729e3769 6580 pid_t pid;
e735decc 6581 int j;
ee5762e3 6582
a644abed 6583 name = args[f++];
ee5762e3 6584
729e3769
LP
6585 if (!endswith(name, ".service"))
6586 continue;
ee5762e3 6587
729e3769
LP
6588 if (path_is_absolute(name))
6589 continue;
ee5762e3 6590
e735decc 6591 j = unit_file_exists(arg_scope, &paths, name);
76ec966f 6592 if (j < 0 && !IN_SET(j, -ELOOP, -ERFKILL, -EADDRNOTAVAIL))
e735decc 6593 return log_error_errno(j, "Failed to lookup unit file state: %m");
3c6d8e57 6594 found_native = j != 0;
ee5762e3 6595
e735decc
LP
6596 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
6597 * prefer the native unit */
355ff449 6598 if (found_native && streq(verb, "is-enabled"))
729e3769 6599 continue;
ee5762e3 6600
652ef298 6601 p = path_join(arg_root, SYSTEM_SYSVINIT_PATH, name);
0c6ea3a4 6602 if (!p)
60731f32 6603 return log_oom();
ee5762e3 6604
fbd0b64f 6605 p[strlen(p) - STRLEN(".service")] = 0;
729e3769 6606 found_sysv = access(p, F_OK) >= 0;
4b6756a8 6607 if (!found_sysv)
729e3769 6608 continue;
71fad675 6609
689e4e6a
CR
6610 if (!arg_quiet) {
6611 if (found_native)
6612 log_info("Synchronizing state of %s with SysV service script with %s.", name, argv[0]);
6613 else
6614 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name);
6615 }
ee5762e3 6616
b1dffbb9 6617 if (!isempty(arg_root)) {
b910cc72 6618 q = strjoin("--root=", arg_root);
b1dffbb9
LP
6619 if (!q)
6620 return log_oom();
6621
6622 argv[c++] = q;
6623 }
ee5762e3 6624
8d1ee648
LP
6625 /* Let's copy the verb, since it's still pointing directly into the original argv[] array we
6626 * got passed, but safe_fork() is likely going to rewrite that for the new child */
6627 v = strdup(verb);
6628 if (!v)
6629 return log_oom();
6630
6631 argv[c++] = v;
2b6bf07d 6632 argv[c++] = basename(p);
729e3769 6633 argv[c] = NULL;
ee5762e3 6634
729e3769 6635 l = strv_join((char**)argv, " ");
60731f32
ZJS
6636 if (!l)
6637 return log_oom();
ee5762e3 6638
8ecc68f4
LP
6639 if (!arg_quiet)
6640 log_info("Executing: %s", l);
ee5762e3 6641
0672e2c6 6642 j = safe_fork("(sysv-install)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid);
4c253ed1 6643 if (j < 0)
b6e1fff1 6644 return j;
4c253ed1 6645 if (j == 0) {
729e3769 6646 /* Child */
729e3769 6647 execv(argv[0], (char**) argv);
cc7cb0ca 6648 log_error_errno(errno, "Failed to execute %s: %m", argv[0]);
729e3769
LP
6649 _exit(EXIT_FAILURE);
6650 }
ee5762e3 6651
2e87a1fd 6652 j = wait_for_terminate_and_check("sysv-install", pid, WAIT_LOG_ABNORMAL);
d710aaf7 6653 if (j < 0)
2e87a1fd
LP
6654 return j;
6655 if (streq(verb, "is-enabled")) {
b4a34311 6656 if (j == EXIT_SUCCESS) {
2e87a1fd
LP
6657 if (!arg_quiet)
6658 puts("enabled");
6659 r = 1;
6660 } else {
6661 if (!arg_quiet)
6662 puts("disabled");
6663 }
ee5762e3 6664
b4a34311 6665 } else if (j != EXIT_SUCCESS)
2e87a1fd 6666 return -EBADE; /* We don't warn here, under the assumption the script already showed an explanation */
ee5762e3 6667
355ff449
MP
6668 if (found_native)
6669 continue;
6670
a644abed 6671 /* Remove this entry, so that we don't try enabling it as native unit */
aba84331
LP
6672 assert(f > 0);
6673 f--;
6674 assert(args[f] == name);
290cb8e8 6675 strv_remove(args + f, name);
729e3769 6676 }
ee5762e3 6677
729e3769
LP
6678#endif
6679 return r;
6680}
ee5762e3 6681
df7c4eb6 6682static int mangle_names(const char *operation, char **original_names, char ***mangled_names) {
a33fdebb 6683 char **i, **l, **name;
7410616c 6684 int r;
37370d0c 6685
7410616c 6686 l = i = new(char*, strv_length(original_names) + 1);
a33fdebb 6687 if (!l)
37370d0c
VP
6688 return log_oom();
6689
37370d0c 6690 STRV_FOREACH(name, original_names) {
44386fc1
LN
6691
6692 /* When enabling units qualified path names are OK,
6693 * too, hence allow them explicitly. */
6694
7410616c 6695 if (is_path(*name)) {
44386fc1 6696 *i = strdup(*name);
7410616c
LP
6697 if (!*i) {
6698 strv_free(l);
6699 return log_oom();
6700 }
6701 } else {
df7c4eb6
ZJS
6702 r = unit_name_mangle_with_suffix(*name, operation,
6703 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
6704 ".service", i);
7410616c 6705 if (r < 0) {
523f8cde 6706 *i = NULL;
7410616c
LP
6707 strv_free(l);
6708 return log_error_errno(r, "Failed to mangle unit name: %m");
6709 }
a33fdebb
LP
6710 }
6711
6712 i++;
37370d0c 6713 }
a33fdebb
LP
6714
6715 *i = NULL;
6716 *mangled_names = l;
37370d0c
VP
6717
6718 return 0;
6719}
6720
decd7982
JR
6721static int normalize_filenames(char **names) {
6722 char **u;
6723 int r;
6724
6725 STRV_FOREACH(u, names)
6726 if (!path_is_absolute(*u)) {
6727 char* normalized_path;
6728
baaa35ad
ZJS
6729 if (!isempty(arg_root))
6730 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
6731 "Non-absolute paths are not allowed when --root is used: %s",
6732 *u);
decd7982 6733
baaa35ad
ZJS
6734 if (!strchr(*u,'/'))
6735 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
6736 "Link argument does contain at least one directory separator: %s",
6737 *u);
decd7982
JR
6738
6739 r = path_make_absolute_cwd(*u, &normalized_path);
6740 if (r < 0)
6741 return r;
6742
6743 free_and_replace(*u, normalized_path);
6744 }
6745
6746 return 0;
6747}
6748
1d3c86c0
MS
6749static int normalize_names(char **names, bool warn_if_path) {
6750 char **u;
6751 bool was_path = false;
6752
6753 STRV_FOREACH(u, names) {
6754 int r;
6755
6756 if (!is_path(*u))
6757 continue;
6758
6759 r = free_and_strdup(u, basename(*u));
6760 if (r < 0)
6761 return log_error_errno(r, "Failed to normalize unit file path: %m");
6762
6763 was_path = true;
6764 }
6765
6766 if (warn_if_path && was_path)
6767 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6768
6769 return 0;
6770}
6771
173471b7 6772static int unit_exists(LookupPaths *lp, const char *unit) {
d6568222 6773 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
f37f8a61 6774 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
d6568222
SS
6775 _cleanup_free_ char *path = NULL;
6776 static const struct bus_properties_map property_map[] = {
f37f8a61
YW
6777 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
6778 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state)},
d6568222
SS
6779 {},
6780 };
6781 UnitStatusInfo info = {};
6782 sd_bus *bus;
6783 int r;
6784
173471b7
ZJS
6785 if (unit_name_is_valid(unit, UNIT_NAME_TEMPLATE))
6786 return unit_find_template_path(unit, lp, NULL, NULL);
6787
d6568222
SS
6788 path = unit_dbus_path_from_name(unit);
6789 if (!path)
6790 return log_oom();
6791
6792 r = acquire_bus(BUS_MANAGER, &bus);
6793 if (r < 0)
6794 return r;
6795
a7e4861c 6796 r = bus_map_all_properties(bus, "org.freedesktop.systemd1", path, property_map, 0, &error, &m, &info);
d6568222
SS
6797 if (r < 0)
6798 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
6799
d6568222
SS
6800 return !streq_ptr(info.load_state, "not-found") || !streq_ptr(info.active_state, "inactive");
6801}
6802
e449de87 6803static int enable_unit(int argc, char *argv[], void *userdata) {
e3e0314b 6804 _cleanup_strv_free_ char **names = NULL;
e449de87 6805 const char *verb = argv[0];
729e3769 6806 UnitFileChange *changes = NULL;
da6053d0 6807 size_t n_changes = 0;
729e3769 6808 int carries_install_info = -1;
35b132e8 6809 bool ignore_carries_install_info = arg_quiet;
729e3769 6810 int r;
ee5762e3 6811
e449de87 6812 if (!argv[1])
ab5919fa
MS
6813 return 0;
6814
df7c4eb6 6815 r = mangle_names("to enable", strv_skip(argv, 1), &names);
3a05c0f9 6816 if (r < 0)
cbb13b2a
VP
6817 return r;
6818
e3e0314b 6819 r = enable_sysv_units(verb, names);
cbb13b2a
VP
6820 if (r < 0)
6821 return r;
3a05c0f9 6822
c61b443d 6823 /* If the operation was fully executed by the SysV compat, let's finish early */
823e5fab
FB
6824 if (strv_isempty(names)) {
6825 if (arg_no_reload || install_client_side())
6826 return 0;
6827 return daemon_reload(argc, argv, userdata);
6828 }
67d66210 6829
1d3c86c0
MS
6830 if (streq(verb, "disable")) {
6831 r = normalize_names(names, true);
6832 if (r < 0)
6833 return r;
6834 }
6835
decd7982
JR
6836 if (streq(verb, "link")) {
6837 r = normalize_filenames(names);
6838 if (r < 0)
6839 return r;
6840 }
6841
4fbd7192 6842 if (install_client_side()) {
b3796dd8
JS
6843 UnitFileFlags flags;
6844
6845 flags = args_to_flags();
729e3769 6846 if (streq(verb, "enable")) {
b3796dd8 6847 r = unit_file_enable(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769
LP
6848 carries_install_info = r;
6849 } else if (streq(verb, "disable"))
b3796dd8 6850 r = unit_file_disable(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769 6851 else if (streq(verb, "reenable")) {
b3796dd8 6852 r = unit_file_reenable(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769
LP
6853 carries_install_info = r;
6854 } else if (streq(verb, "link"))
b3796dd8 6855 r = unit_file_link(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769 6856 else if (streq(verb, "preset")) {
b3796dd8 6857 r = unit_file_preset(arg_scope, flags, arg_root, names, arg_preset_mode, &changes, &n_changes);
729e3769 6858 } else if (streq(verb, "mask"))
b3796dd8 6859 r = unit_file_mask(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769 6860 else if (streq(verb, "unmask"))
b3796dd8 6861 r = unit_file_unmask(arg_scope, flags, arg_root, names, &changes, &n_changes);
344ca755
LP
6862 else if (streq(verb, "revert"))
6863 r = unit_file_revert(arg_scope, arg_root, names, &changes, &n_changes);
729e3769
LP
6864 else
6865 assert_not_reached("Unknown verb");
ee5762e3 6866
af3d8113 6867 unit_file_dump_changes(r, verb, changes, n_changes, arg_quiet);
d073dea0 6868 if (r < 0)
85b78539 6869 goto finish;
df77cdf0 6870 r = 0;
729e3769 6871 } else {
4afd3348
LP
6872 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
6873 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
39207373 6874 bool expect_carries_install_info = false;
344ca755 6875 bool send_runtime = true, send_force = true, send_preset_mode = false;
718db961 6876 const char *method;
4fbd7192 6877 sd_bus *bus;
729e3769 6878
d6568222 6879 if (STR_IN_SET(verb, "mask", "unmask")) {
f8d6cb48 6880 char **name;
8e766630 6881 _cleanup_(lookup_paths_free) LookupPaths lp = {};
173471b7
ZJS
6882
6883 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
d6568222
SS
6884 if (r < 0)
6885 return r;
f8d6cb48
ZJS
6886
6887 STRV_FOREACH(name, names) {
173471b7 6888 r = unit_exists(&lp, *name);
f8d6cb48
ZJS
6889 if (r < 0)
6890 return r;
6891 if (r == 0)
25c59b5d 6892 log_notice("Unit %s does not exist, proceeding anyway.", *name);
f8d6cb48 6893 }
d6568222
SS
6894 }
6895
4fbd7192
LP
6896 r = acquire_bus(BUS_MANAGER, &bus);
6897 if (r < 0)
6898 return r;
6899
8a4b13c5 6900 polkit_agent_open_maybe();
d2ad7e1b 6901
729e3769
LP
6902 if (streq(verb, "enable")) {
6903 method = "EnableUnitFiles";
6904 expect_carries_install_info = true;
6905 } else if (streq(verb, "disable")) {
6906 method = "DisableUnitFiles";
6907 send_force = false;
6908 } else if (streq(verb, "reenable")) {
6909 method = "ReenableUnitFiles";
6910 expect_carries_install_info = true;
6911 } else if (streq(verb, "link"))
6912 method = "LinkUnitFiles";
6913 else if (streq(verb, "preset")) {
d309c1c3
LP
6914
6915 if (arg_preset_mode != UNIT_FILE_PRESET_FULL) {
6916 method = "PresetUnitFilesWithMode";
6917 send_preset_mode = true;
6918 } else
6919 method = "PresetUnitFiles";
6920
729e3769 6921 expect_carries_install_info = true;
39207373 6922 ignore_carries_install_info = true;
729e3769
LP
6923 } else if (streq(verb, "mask"))
6924 method = "MaskUnitFiles";
6925 else if (streq(verb, "unmask")) {
6926 method = "UnmaskUnitFiles";
6927 send_force = false;
344ca755
LP
6928 } else if (streq(verb, "revert")) {
6929 method = "RevertUnitFiles";
6930 send_runtime = send_force = false;
729e3769
LP
6931 } else
6932 assert_not_reached("Unknown verb");
6933
f459b602
MAP
6934 r = sd_bus_message_new_method_call(
6935 bus,
151b9b96 6936 &m,
729e3769
LP
6937 "org.freedesktop.systemd1",
6938 "/org/freedesktop/systemd1",
6939 "org.freedesktop.systemd1.Manager",
151b9b96 6940 method);
f459b602
MAP
6941 if (r < 0)
6942 return bus_log_create_error(r);
ee5762e3 6943
e3e0314b 6944 r = sd_bus_message_append_strv(m, names);
f459b602
MAP
6945 if (r < 0)
6946 return bus_log_create_error(r);
ee5762e3 6947
d309c1c3
LP
6948 if (send_preset_mode) {
6949 r = sd_bus_message_append(m, "s", unit_file_preset_mode_to_string(arg_preset_mode));
6950 if (r < 0)
6951 return bus_log_create_error(r);
6952 }
6953
344ca755
LP
6954 if (send_runtime) {
6955 r = sd_bus_message_append(m, "b", arg_runtime);
6956 if (r < 0)
6957 return bus_log_create_error(r);
6958 }
ee5762e3 6959
729e3769 6960 if (send_force) {
f459b602
MAP
6961 r = sd_bus_message_append(m, "b", arg_force);
6962 if (r < 0)
6963 return bus_log_create_error(r);
ee5762e3
LP
6964 }
6965
c49b30a2 6966 r = sd_bus_call(bus, m, 0, &error, &reply);
691395d8 6967 if (r < 0)
af3d8113 6968 return log_error_errno(r, "Failed to %s unit: %s", verb, bus_error_message(&error, r));
be394c48 6969
729e3769 6970 if (expect_carries_install_info) {
f459b602
MAP
6971 r = sd_bus_message_read(reply, "b", &carries_install_info);
6972 if (r < 0)
6973 return bus_log_parse_error(r);
ee5762e3
LP
6974 }
6975
57ab2eab 6976 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
f459b602 6977 if (r < 0)
85b78539 6978 goto finish;
b77398f7 6979
93c941e3 6980 /* Try to reload if enabled */
d6cb60c7 6981 if (!arg_no_reload)
e449de87 6982 r = daemon_reload(argc, argv, userdata);
f459b602
MAP
6983 else
6984 r = 0;
b647f10d 6985 }
3d3961f2 6986
39207373 6987 if (carries_install_info == 0 && !ignore_carries_install_info)
46efc978
LP
6988 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
6989 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
2811184a
ZJS
6990 "units). This means they are not meant to be enabled using systemctl.\n"
6991 " \n" /* trick: the space is needed so that the line does not get stripped from output */
46efc978 6992 "Possible reasons for having this kind of units are:\n"
18c93ee3
LP
6993 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
6994 " .wants/ or .requires/ directory.\n"
6995 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
6996 " a requirement dependency on it.\n"
6997 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
6998 " D-Bus, udev, scripted systemctl call, ...).\n"
6999 "%1$s In case of template units, the unit is meant to be enabled with some\n"
7000 " instance name specified.",
9a6f746f 7001 special_glyph(SPECIAL_GLYPH_BULLET));
ee5762e3 7002
6bc30691 7003 if (arg_now && STR_IN_SET(argv[0], "enable", "disable", "mask")) {
4fbd7192 7004 sd_bus *bus;
da6053d0 7005 size_t len, i;
57ab2eab 7006
4fbd7192
LP
7007 r = acquire_bus(BUS_MANAGER, &bus);
7008 if (r < 0)
d073dea0 7009 goto finish;
4fbd7192 7010
6bc30691
JS
7011 len = strv_length(names);
7012 {
7013 char *new_args[len + 2];
57ab2eab 7014
6bc30691
JS
7015 new_args[0] = (char*) (streq(argv[0], "enable") ? "start" : "stop");
7016 for (i = 0; i < len; i++)
7017 new_args[i + 1] = basename(names[i]);
7018 new_args[i + 1] = NULL;
7019
7020 r = start_unit(len + 1, new_args, userdata);
7021 }
57ab2eab
JS
7022 }
7023
729e3769 7024finish:
729e3769 7025 unit_file_changes_free(changes, n_changes);
ee5762e3 7026
729e3769 7027 return r;
ee5762e3
LP
7028}
7029
e449de87 7030static int add_dependency(int argc, char *argv[], void *userdata) {
e94937df
LN
7031 _cleanup_strv_free_ char **names = NULL;
7032 _cleanup_free_ char *target = NULL;
e449de87 7033 const char *verb = argv[0];
acc0269c 7034 UnitFileChange *changes = NULL;
da6053d0 7035 size_t n_changes = 0;
e94937df
LN
7036 UnitDependency dep;
7037 int r = 0;
7038
e449de87 7039 if (!argv[1])
e94937df
LN
7040 return 0;
7041
df7c4eb6
ZJS
7042 r = unit_name_mangle_with_suffix(argv[1], "as target",
7043 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
7044 ".target", &target);
7410616c
LP
7045 if (r < 0)
7046 return log_error_errno(r, "Failed to mangle unit name: %m");
e94937df 7047
df7c4eb6 7048 r = mangle_names("as dependency", strv_skip(argv, 2), &names);
e94937df
LN
7049 if (r < 0)
7050 return r;
7051
7052 if (streq(verb, "add-wants"))
7053 dep = UNIT_WANTS;
7054 else if (streq(verb, "add-requires"))
7055 dep = UNIT_REQUIRES;
7056 else
7057 assert_not_reached("Unknown verb");
7058
4fbd7192 7059 if (install_client_side()) {
b3796dd8 7060 r = unit_file_add_dependency(arg_scope, args_to_flags(), arg_root, names, target, dep, &changes, &n_changes);
af3d8113 7061 unit_file_dump_changes(r, "add dependency on", changes, n_changes, arg_quiet);
5f056378
CH
7062
7063 if (r > 0)
7064 r = 0;
e94937df 7065 } else {
4afd3348
LP
7066 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
7067 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 7068 sd_bus *bus;
e94937df 7069
4fbd7192
LP
7070 r = acquire_bus(BUS_MANAGER, &bus);
7071 if (r < 0)
7072 return r;
7073
8a4b13c5 7074 polkit_agent_open_maybe();
d2ad7e1b 7075
e94937df
LN
7076 r = sd_bus_message_new_method_call(
7077 bus,
7078 &m,
7079 "org.freedesktop.systemd1",
7080 "/org/freedesktop/systemd1",
7081 "org.freedesktop.systemd1.Manager",
7082 "AddDependencyUnitFiles");
7083 if (r < 0)
7084 return bus_log_create_error(r);
7085
342641fb 7086 r = sd_bus_message_append_strv(m, names);
e94937df
LN
7087 if (r < 0)
7088 return bus_log_create_error(r);
7089
342641fb 7090 r = sd_bus_message_append(m, "ssbb", target, unit_dependency_to_string(dep), arg_runtime, arg_force);
e94937df
LN
7091 if (r < 0)
7092 return bus_log_create_error(r);
7093
7094 r = sd_bus_call(bus, m, 0, &error, &reply);
691395d8 7095 if (r < 0)
af3d8113 7096 return log_error_errno(r, "Failed to add dependency: %s", bus_error_message(&error, r));
e94937df 7097
acc0269c 7098 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
e94937df 7099 if (r < 0)
acc0269c 7100 goto finish;
e94937df 7101
acc0269c
CH
7102 if (arg_no_reload) {
7103 r = 0;
7104 goto finish;
7105 }
7106
7107 r = daemon_reload(argc, argv, userdata);
e94937df 7108 }
acc0269c
CH
7109
7110finish:
7111 unit_file_changes_free(changes, n_changes);
7112
7113 return r;
e94937df
LN
7114}
7115
e449de87 7116static int preset_all(int argc, char *argv[], void *userdata) {
acc0269c 7117 UnitFileChange *changes = NULL;
da6053d0 7118 size_t n_changes = 0;
d309c1c3
LP
7119 int r;
7120
4fbd7192 7121 if (install_client_side()) {
b3796dd8 7122 r = unit_file_preset_all(arg_scope, args_to_flags(), arg_root, arg_preset_mode, &changes, &n_changes);
af3d8113 7123 unit_file_dump_changes(r, "preset", changes, n_changes, arg_quiet);
5f056378
CH
7124
7125 if (r > 0)
7126 r = 0;
d309c1c3 7127 } else {
4afd3348
LP
7128 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
7129 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
4fbd7192 7130 sd_bus *bus;
d309c1c3 7131
4fbd7192
LP
7132 r = acquire_bus(BUS_MANAGER, &bus);
7133 if (r < 0)
7134 return r;
7135
8a4b13c5 7136 polkit_agent_open_maybe();
d2ad7e1b 7137
6e646d22 7138 r = sd_bus_call_method(
d309c1c3
LP
7139 bus,
7140 "org.freedesktop.systemd1",
7141 "/org/freedesktop/systemd1",
7142 "org.freedesktop.systemd1.Manager",
6e646d22
LP
7143 "PresetAllUnitFiles",
7144 &error,
7145 &reply,
d309c1c3
LP
7146 "sbb",
7147 unit_file_preset_mode_to_string(arg_preset_mode),
7148 arg_runtime,
7149 arg_force);
691395d8 7150 if (r < 0)
af3d8113 7151 return log_error_errno(r, "Failed to preset all units: %s", bus_error_message(&error, r));
d309c1c3 7152
acc0269c 7153 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
d309c1c3 7154 if (r < 0)
acc0269c 7155 goto finish;
d309c1c3 7156
acc0269c
CH
7157 if (arg_no_reload) {
7158 r = 0;
7159 goto finish;
7160 }
7161
7162 r = daemon_reload(argc, argv, userdata);
d309c1c3 7163 }
acc0269c
CH
7164
7165finish:
7166 unit_file_changes_free(changes, n_changes);
7167
7168 return r;
d309c1c3
LP
7169}
7170
3b3557c4
JS
7171static int show_installation_targets_client_side(const char *name) {
7172 UnitFileChange *changes = NULL;
da6053d0 7173 size_t n_changes = 0, i;
3b3557c4
JS
7174 UnitFileFlags flags;
7175 char **p;
7176 int r;
7177
7178 p = STRV_MAKE(name);
7179 flags = UNIT_FILE_DRY_RUN |
7180 (arg_runtime ? UNIT_FILE_RUNTIME : 0);
7181
7182 r = unit_file_disable(UNIT_FILE_SYSTEM, flags, NULL, p, &changes, &n_changes);
7183 if (r < 0)
7184 return log_error_errno(r, "Failed to get file links for %s: %m", name);
7185
7186 for (i = 0; i < n_changes; i++)
7187 if (changes[i].type == UNIT_FILE_UNLINK)
7188 printf(" %s\n", changes[i].path);
7189
7190 return 0;
7191}
7192
7193static int show_installation_targets(sd_bus *bus, const char *name) {
7194 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
7195 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
7196 const char *link;
7197 int r;
7198
7199 r = sd_bus_call_method(
7200 bus,
7201 "org.freedesktop.systemd1",
7202 "/org/freedesktop/systemd1",
7203 "org.freedesktop.systemd1.Manager",
7204 "GetUnitFileLinks",
7205 &error,
7206 &reply,
7207 "sb", name, arg_runtime);
7208 if (r < 0)
7209 return log_error_errno(r, "Failed to get unit file links for %s: %s", name, bus_error_message(&error, r));
7210
7211 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
7212 if (r < 0)
7213 return bus_log_parse_error(r);
7214
7215 while ((r = sd_bus_message_read(reply, "s", &link)) > 0)
7216 printf(" %s\n", link);
7217
7218 if (r < 0)
7219 return bus_log_parse_error(r);
7220
7221 r = sd_bus_message_exit_container(reply);
7222 if (r < 0)
7223 return bus_log_parse_error(r);
7224
7225 return 0;
7226}
7227
e449de87 7228static int unit_is_enabled(int argc, char *argv[], void *userdata) {
e3e0314b 7229 _cleanup_strv_free_ char **names = NULL;
729e3769
LP
7230 bool enabled;
7231 char **name;
f459b602 7232 int r;
ee5762e3 7233
df7c4eb6 7234 r = mangle_names("to check", strv_skip(argv, 1), &names);
cbb13b2a
VP
7235 if (r < 0)
7236 return r;
7237
e449de87 7238 r = enable_sysv_units(argv[0], names);
729e3769
LP
7239 if (r < 0)
7240 return r;
ee5762e3 7241
729e3769 7242 enabled = r > 0;
ee5762e3 7243
4fbd7192 7244 if (install_client_side()) {
e3e0314b 7245 STRV_FOREACH(name, names) {
729e3769 7246 UnitFileState state;
ee5762e3 7247
0ec0deaa
LP
7248 r = unit_file_get_state(arg_scope, arg_root, *name, &state);
7249 if (r < 0)
c5024cd0 7250 return log_error_errno(r, "Failed to get unit file state for %s: %m", *name);
ee5762e3 7251
4c315c2c
IS
7252 if (IN_SET(state,
7253 UNIT_FILE_ENABLED,
7254 UNIT_FILE_ENABLED_RUNTIME,
7255 UNIT_FILE_STATIC,
f4139308
LP
7256 UNIT_FILE_INDIRECT,
7257 UNIT_FILE_GENERATED))
729e3769
LP
7258 enabled = true;
7259
3b3557c4 7260 if (!arg_quiet) {
729e3769 7261 puts(unit_file_state_to_string(state));
3b3557c4
JS
7262 if (arg_full) {
7263 r = show_installation_targets_client_side(*name);
7264 if (r < 0)
7265 return r;
7266 }
7267 }
71fad675 7268 }
ee5762e3 7269
5f056378 7270 r = 0;
729e3769 7271 } else {
4afd3348 7272 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192
LP
7273 sd_bus *bus;
7274
7275 r = acquire_bus(BUS_MANAGER, &bus);
7276 if (r < 0)
7277 return r;
7278
e3e0314b 7279 STRV_FOREACH(name, names) {
4afd3348 7280 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
729e3769 7281 const char *s;
63a723f3 7282
f459b602 7283 r = sd_bus_call_method(
f22f08cd 7284 bus,
729e3769
LP
7285 "org.freedesktop.systemd1",
7286 "/org/freedesktop/systemd1",
7287 "org.freedesktop.systemd1.Manager",
f22f08cd 7288 "GetUnitFileState",
f459b602 7289 &error,
f22f08cd 7290 &reply,
04504f93 7291 "s", *name);
691395d8
LP
7292 if (r < 0)
7293 return log_error_errno(r, "Failed to get unit file state for %s: %s", *name, bus_error_message(&error, r));
ee5762e3 7294
f459b602
MAP
7295 r = sd_bus_message_read(reply, "s", &s);
7296 if (r < 0)
7297 return bus_log_parse_error(r);
ee5762e3 7298
f4139308 7299 if (STR_IN_SET(s, "enabled", "enabled-runtime", "static", "indirect", "generated"))
729e3769
LP
7300 enabled = true;
7301
3b3557c4 7302 if (!arg_quiet) {
729e3769 7303 puts(s);
3b3557c4
JS
7304 if (arg_full) {
7305 r = show_installation_targets(bus, *name);
7306 if (r < 0)
7307 return r;
7308 }
7309 }
560d8f23 7310 }
ee5762e3
LP
7311 }
7312
f4139308 7313 return enabled ? EXIT_SUCCESS : EXIT_FAILURE;
ee5762e3
LP
7314}
7315
adb6cd9b
FB
7316static int match_startup_finished(sd_bus_message *m, void *userdata, sd_bus_error *error) {
7317 char **state = userdata;
7318 int r;
7319
7320 assert(state);
7321
7322 r = sd_bus_get_property_string(
7323 sd_bus_message_get_bus(m),
7324 "org.freedesktop.systemd1",
7325 "/org/freedesktop/systemd1",
7326 "org.freedesktop.systemd1.Manager",
7327 "SystemState",
7328 NULL,
7329 state);
7330
7331 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), r);
7332 return 0;
7333}
7334
e449de87 7335static int is_system_running(int argc, char *argv[], void *userdata) {
e686a616 7336 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
adb6cd9b
FB
7337 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot_startup_finished = NULL;
7338 _cleanup_(sd_event_unrefp) sd_event* event = NULL;
99813a19 7339 _cleanup_free_ char *state = NULL;
4fbd7192 7340 sd_bus *bus;
99813a19
LP
7341 int r;
7342
040524b4 7343 if (running_in_chroot() > 0 || (arg_transport == BUS_TRANSPORT_LOCAL && !sd_booted())) {
94f099d8
LP
7344 if (!arg_quiet)
7345 puts("offline");
7346 return EXIT_FAILURE;
7347 }
7348
4fbd7192
LP
7349 r = acquire_bus(BUS_MANAGER, &bus);
7350 if (r < 0)
7351 return r;
7352
adb6cd9b
FB
7353 if (arg_wait) {
7354 r = sd_event_default(&event);
7355 if (r >= 0)
7356 r = sd_bus_attach_event(bus, event, 0);
7357 if (r >= 0)
7358 r = sd_bus_match_signal_async(
7359 bus,
7360 &slot_startup_finished,
7361 "org.freedesktop.systemd1",
7362 "/org/freedesktop/systemd1",
7363 "org.freedesktop.systemd1.Manager",
7364 "StartupFinished",
7365 match_startup_finished, NULL, &state);
7366 if (r < 0) {
7367 log_warning_errno(r, "Failed to request match for StartupFinished: %m");
7368 arg_wait = false;
7369 }
7370 }
7371
99813a19
LP
7372 r = sd_bus_get_property_string(
7373 bus,
7374 "org.freedesktop.systemd1",
7375 "/org/freedesktop/systemd1",
7376 "org.freedesktop.systemd1.Manager",
7377 "SystemState",
e686a616 7378 &error,
99813a19
LP
7379 &state);
7380 if (r < 0) {
adb6cd9b 7381 log_warning_errno(r, "Failed to query system state: %s", bus_error_message(&error, r));
e686a616 7382
99813a19
LP
7383 if (!arg_quiet)
7384 puts("unknown");
bfeec178 7385 return EXIT_FAILURE;
99813a19
LP
7386 }
7387
adb6cd9b
FB
7388 if (arg_wait && STR_IN_SET(state, "initializing", "starting")) {
7389 r = sd_event_loop(event);
7390 if (r < 0) {
7391 log_warning_errno(r, "Failed to get property from event loop: %m");
7392 if (!arg_quiet)
7393 puts("unknown");
7394 return EXIT_FAILURE;
7395 }
7396 }
7397
99813a19
LP
7398 if (!arg_quiet)
7399 puts(state);
7400
7401 return streq(state, "running") ? EXIT_SUCCESS : EXIT_FAILURE;
7402}
7403
7d4fb3b1 7404static int create_edit_temp_file(const char *new_path, const char *original_path, char **ret_tmp_fn) {
45519fd6 7405 _cleanup_free_ char *t = NULL;
ae6c3cc0 7406 int r;
7d4fb3b1
RC
7407
7408 assert(new_path);
7409 assert(original_path);
7410 assert(ret_tmp_fn);
7411
14bcf25c 7412 r = tempfn_random(new_path, NULL, &t);
ae6c3cc0 7413 if (r < 0)
029009d4 7414 return log_error_errno(r, "Failed to determine temporary filename for \"%s\": %m", new_path);
7d4fb3b1
RC
7415
7416 r = mkdir_parents(new_path, 0755);
45519fd6 7417 if (r < 0)
691395d8 7418 return log_error_errno(r, "Failed to create directories for \"%s\": %m", new_path);
7d4fb3b1 7419
8a016c74 7420 r = copy_file(original_path, t, 0, 0644, 0, 0, COPY_REFLINK);
7d4fb3b1 7421 if (r == -ENOENT) {
45519fd6 7422
7d4fb3b1 7423 r = touch(t);
45519fd6
LP
7424 if (r < 0)
7425 return log_error_errno(r, "Failed to create temporary file \"%s\": %m", t);
7426
7427 } else if (r < 0)
39c38ce1 7428 return log_error_errno(r, "Failed to create temporary file for \"%s\": %m", new_path);
7d4fb3b1 7429
ae2a15bc 7430 *ret_tmp_fn = TAKE_PTR(t);
7d4fb3b1
RC
7431
7432 return 0;
7433}
7434
c51932be
LP
7435static int get_file_to_edit(
7436 const LookupPaths *paths,
7437 const char *name,
7438 char **ret_path) {
7439
7440 _cleanup_free_ char *path = NULL, *run = NULL;
7d4fb3b1 7441
45519fd6
LP
7442 assert(name);
7443 assert(ret_path);
7444
657ee2d8 7445 path = path_join(paths->persistent_config, name);
c51932be 7446 if (!path)
7d4fb3b1
RC
7447 return log_oom();
7448
c51932be 7449 if (arg_runtime) {
657ee2d8 7450 run = path_join(paths->runtime_config, name);
c51932be
LP
7451 if (!run)
7452 return log_oom();
7453 }
7454
bc854dc7 7455 if (arg_runtime) {
baaa35ad
ZJS
7456 if (access(path, F_OK) >= 0)
7457 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
7458 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
7459 run, path);
691395d8 7460
ae2a15bc
LP
7461 *ret_path = TAKE_PTR(run);
7462 } else
7463 *ret_path = TAKE_PTR(path);
7d4fb3b1
RC
7464
7465 return 0;
7466}
7467
39c38ce1 7468static int unit_file_create_new(
c51932be
LP
7469 const LookupPaths *paths,
7470 const char *unit_name,
39c38ce1 7471 const char *suffix,
c51932be
LP
7472 char **ret_new_path,
7473 char **ret_tmp_path) {
7474
919d2720
LP
7475 _cleanup_free_ char *new_path = NULL, *tmp_path = NULL;
7476 const char *ending;
7d4fb3b1
RC
7477 int r;
7478
7479 assert(unit_name);
7480 assert(ret_new_path);
7481 assert(ret_tmp_path);
7482
39c38ce1 7483 ending = strjoina(unit_name, suffix);
919d2720 7484 r = get_file_to_edit(paths, ending, &new_path);
7d4fb3b1
RC
7485 if (r < 0)
7486 return r;
7487
919d2720
LP
7488 r = create_edit_temp_file(new_path, new_path, &tmp_path);
7489 if (r < 0)
7d4fb3b1 7490 return r;
7d4fb3b1 7491
919d2720
LP
7492 *ret_new_path = TAKE_PTR(new_path);
7493 *ret_tmp_path = TAKE_PTR(tmp_path);
7d4fb3b1
RC
7494
7495 return 0;
7496}
7497
1cfa9a4c 7498static int unit_file_create_copy(
c51932be 7499 const LookupPaths *paths,
1cfa9a4c
LP
7500 const char *unit_name,
7501 const char *fragment_path,
1cfa9a4c
LP
7502 char **ret_new_path,
7503 char **ret_tmp_path) {
7504
92d6b0bf 7505 _cleanup_free_ char *new_path = NULL, *tmp_path = NULL;
7d4fb3b1
RC
7506 int r;
7507
7508 assert(fragment_path);
7509 assert(unit_name);
7510 assert(ret_new_path);
7511 assert(ret_tmp_path);
7512
92d6b0bf 7513 r = get_file_to_edit(paths, unit_name, &new_path);
7d4fb3b1
RC
7514 if (r < 0)
7515 return r;
7516
92d6b0bf 7517 if (!path_equal(fragment_path, new_path) && access(new_path, F_OK) >= 0) {
7d4fb3b1
RC
7518 char response;
7519
92d6b0bf
LP
7520 r = ask_char(&response, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path, fragment_path);
7521 if (r < 0)
7d4fb3b1 7522 return r;
5daacba2
LP
7523 if (response != 'y')
7524 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED), "%s skipped.", unit_name);
7d4fb3b1
RC
7525 }
7526
92d6b0bf
LP
7527 r = create_edit_temp_file(new_path, fragment_path, &tmp_path);
7528 if (r < 0)
7d4fb3b1 7529 return r;
7d4fb3b1 7530
92d6b0bf
LP
7531 *ret_new_path = TAKE_PTR(new_path);
7532 *ret_tmp_path = TAKE_PTR(tmp_path);
7d4fb3b1
RC
7533
7534 return 0;
7535}
7536
7537static int run_editor(char **paths) {
7d4fb3b1
RC
7538 int r;
7539
7540 assert(paths);
7541
0672e2c6 7542 r = safe_fork("(editor)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG|FORK_WAIT, NULL);
4c253ed1 7543 if (r < 0)
b6e1fff1 7544 return r;
4c253ed1 7545 if (r == 0) {
b2238e38 7546 char **editor_args = NULL, **tmp_path, **original_path;
70d6e5bd 7547 size_t n_editor_args = 0, i = 1, argc;
b2238e38 7548 const char **args, *editor, *p;
7d4fb3b1
RC
7549
7550 argc = strv_length(paths)/2 + 1;
7d4fb3b1
RC
7551
7552 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
7553 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
7554 * we try to execute well known editors
7555 */
7556 editor = getenv("SYSTEMD_EDITOR");
7557 if (!editor)
7558 editor = getenv("EDITOR");
7559 if (!editor)
7560 editor = getenv("VISUAL");
7561
7562 if (!isempty(editor)) {
9ef5d8f2
JS
7563 editor_args = strv_split(editor, WHITESPACE);
7564 if (!editor_args) {
7565 (void) log_oom();
7566 _exit(EXIT_FAILURE);
7567 }
7568 n_editor_args = strv_length(editor_args);
7569 argc += n_editor_args - 1;
7570 }
02a126a3 7571
9ef5d8f2
JS
7572 args = newa(const char*, argc + 1);
7573
7574 if (n_editor_args > 0) {
7575 args[0] = editor_args[0];
7576 for (; i < n_editor_args; i++)
7577 args[i] = editor_args[i];
7578 }
7579
df79fdab
LP
7580 STRV_FOREACH_PAIR(original_path, tmp_path, paths)
7581 args[i++] = *tmp_path;
9ef5d8f2
JS
7582 args[i] = NULL;
7583
7584 if (n_editor_args > 0)
7585 execvp(args[0], (char* const*) args);
7d4fb3b1 7586
9391a1c3 7587 FOREACH_STRING(p, "editor", "nano", "vim", "vi") {
1cfa9a4c
LP
7588 args[0] = p;
7589 execvp(p, (char* const*) args);
7d4fb3b1
RC
7590 /* We do not fail if the editor doesn't exist
7591 * because we want to try each one of them before
7592 * failing.
7593 */
7594 if (errno != ENOENT) {
691395d8 7595 log_error_errno(errno, "Failed to execute %s: %m", editor);
7d4fb3b1
RC
7596 _exit(EXIT_FAILURE);
7597 }
7598 }
7599
1cfa9a4c 7600 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7d4fb3b1
RC
7601 _exit(EXIT_FAILURE);
7602 }
7603
45519fd6 7604 return 0;
7d4fb3b1
RC
7605}
7606
7607static int find_paths_to_edit(sd_bus *bus, char **names, char ***paths) {
8e766630 7608 _cleanup_(lookup_paths_free) LookupPaths lp = {};
7d4fb3b1
RC
7609 char **name;
7610 int r;
7611
7612 assert(names);
7613 assert(paths);
7614
4943d143 7615 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
5b013a2f 7616 if (r < 0)
8df18507 7617 return r;
7d4fb3b1 7618
e9e310f8 7619 STRV_FOREACH(name, names) {
b74df547
ZJS
7620 _cleanup_free_ char *path = NULL, *new_path = NULL, *tmp_path = NULL, *tmp_name = NULL;
7621 const char *unit_name;
7d4fb3b1 7622
02a126a3
LP
7623 r = unit_find_paths(bus, *name, &lp, false, &path, NULL);
7624 if (r == -EKEYREJECTED) {
7625 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7626 * file path. In that case, find the file client side. */
7627 log_debug_errno(r, "Unit '%s' was not loaded correctly, retrying client-side.", *name);
7628 r = unit_find_paths(bus, *name, &lp, true, &path, NULL);
7629 }
7630 if (r == -ERFKILL)
7631 return log_error_errno(r, "Unit '%s' masked, cannot edit.", *name);
e9e310f8
RC
7632 if (r < 0)
7633 return r;
b3734d98
ZJS
7634
7635 if (r == 0) {
7636 assert(!path);
7637
7638 if (!arg_force) {
85163756
LP
7639 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7640 arg_scope == UNIT_FILE_GLOBAL ? " --global" :
7641 arg_scope == UNIT_FILE_USER ? " --user" : "",
7642 *name);
39c38ce1
DC
7643 return -ENOENT;
7644 }
39c38ce1 7645
b3734d98
ZJS
7646 /* Create a new unit from scratch */
7647 unit_name = *name;
7648 r = unit_file_create_new(&lp, unit_name,
7649 arg_full ? NULL : ".d/override.conf",
7650 &new_path, &tmp_path);
7651 } else {
7652 assert(path);
b74df547 7653
b3734d98
ZJS
7654 unit_name = basename(path);
7655 /* We follow unit aliases, but we need to propagate the instance */
7656 if (unit_name_is_valid(*name, UNIT_NAME_INSTANCE) &&
7657 unit_name_is_valid(unit_name, UNIT_NAME_TEMPLATE)) {
7658 _cleanup_free_ char *instance = NULL;
b74df547 7659
b3734d98
ZJS
7660 r = unit_name_to_instance(*name, &instance);
7661 if (r < 0)
7662 return r;
b74df547 7663
b3734d98
ZJS
7664 r = unit_name_replace_instance(unit_name, instance, &tmp_name);
7665 if (r < 0)
7666 return r;
7667
7668 unit_name = tmp_name;
7669 }
b74df547 7670
39c38ce1 7671 if (arg_full)
b74df547 7672 r = unit_file_create_copy(&lp, unit_name, path, &new_path, &tmp_path);
39c38ce1 7673 else
b74df547 7674 r = unit_file_create_new(&lp, unit_name, ".d/override.conf", &new_path, &tmp_path);
b3734d98 7675 }
e9e310f8 7676 if (r < 0)
ad2a0358 7677 return r;
7d4fb3b1 7678
e9e310f8
RC
7679 r = strv_push_pair(paths, new_path, tmp_path);
7680 if (r < 0)
7681 return log_oom();
02a126a3 7682
78df0edc 7683 new_path = tmp_path = NULL;
7d4fb3b1
RC
7684 }
7685
7686 return 0;
7687}
7688
e449de87 7689static int edit(int argc, char *argv[], void *userdata) {
86f004fb 7690 _cleanup_(lookup_paths_free) LookupPaths lp = {};
7d4fb3b1
RC
7691 _cleanup_strv_free_ char **names = NULL;
7692 _cleanup_strv_free_ char **paths = NULL;
7693 char **original, **tmp;
4fbd7192 7694 sd_bus *bus;
7d4fb3b1
RC
7695 int r;
7696
2f50e59f
LP
7697 if (!on_tty())
7698 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot edit units if not on a tty.");
7d4fb3b1 7699
2f50e59f
LP
7700 if (arg_transport != BUS_TRANSPORT_LOCAL)
7701 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot edit units remotely.");
7d4fb3b1 7702
86f004fb
ZJS
7703 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
7704 if (r < 0)
7705 return log_error_errno(r, "Failed to determine unit paths: %m");
7706
4fbd7192
LP
7707 r = acquire_bus(BUS_MANAGER, &bus);
7708 if (r < 0)
7709 return r;
7710
1d56bc09 7711 r = expand_names(bus, strv_skip(argv, 1), NULL, &names, NULL);
7d4fb3b1
RC
7712 if (r < 0)
7713 return log_error_errno(r, "Failed to expand names: %m");
7714
9d9dd746 7715 STRV_FOREACH(tmp, names) {
86f004fb 7716 r = unit_is_masked(bus, &lp, *tmp);
9d9dd746
ZJS
7717 if (r < 0)
7718 return r;
2f50e59f
LP
7719 if (r > 0)
7720 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot edit %s: unit is masked.", *tmp);
9d9dd746
ZJS
7721 }
7722
7d4fb3b1
RC
7723 r = find_paths_to_edit(bus, names, &paths);
7724 if (r < 0)
7725 return r;
7726
b5e6a600 7727 if (strv_isempty(paths))
7d4fb3b1 7728 return -ENOENT;
7d4fb3b1
RC
7729
7730 r = run_editor(paths);
7731 if (r < 0)
7732 goto end;
7733
7734 STRV_FOREACH_PAIR(original, tmp, paths) {
9d9dd746
ZJS
7735 /* If the temporary file is empty we ignore it.
7736 * This allows the user to cancel the modification.
7d4fb3b1
RC
7737 */
7738 if (null_or_empty_path(*tmp)) {
45519fd6 7739 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original);
7d4fb3b1
RC
7740 continue;
7741 }
45519fd6 7742
7d4fb3b1
RC
7743 r = rename(*tmp, *original);
7744 if (r < 0) {
029009d4 7745 r = log_error_errno(errno, "Failed to rename \"%s\" to \"%s\": %m", *tmp, *original);
7d4fb3b1
RC
7746 goto end;
7747 }
7748 }
7749
45519fd6
LP
7750 r = 0;
7751
7752 if (!arg_no_reload && !install_client_side())
e449de87 7753 r = daemon_reload(argc, argv, userdata);
7d4fb3b1
RC
7754
7755end:
5f18271e 7756 STRV_FOREACH_PAIR(original, tmp, paths) {
45519fd6 7757 (void) unlink(*tmp);
7d4fb3b1 7758
5f18271e
RC
7759 /* Removing empty dropin dirs */
7760 if (!arg_full) {
043717f9
RC
7761 _cleanup_free_ char *dir;
7762
7763 dir = dirname_malloc(*original);
7764 if (!dir)
7765 return log_oom();
7766
5f18271e
RC
7767 /* no need to check if the dir is empty, rmdir
7768 * does nothing if it is not the case.
7769 */
7770 (void) rmdir(dir);
7771 }
7772 }
7773
7d4fb3b1
RC
7774 return r;
7775}
7776
37ec0fdd
LP
7777static int systemctl_help(void) {
7778 _cleanup_free_ char *link = NULL;
7779 int r;
7780
0221d68a 7781 (void) pager_open(arg_pager_flags);
729e3769 7782
37ec0fdd
LP
7783 r = terminal_urlify_man("systemctl", "1", &link);
7784 if (r < 0)
7785 return log_oom();
7786
353b2baa
LP
7787 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
7788 "%5$sQuery or send control commands to the system manager.%6$s\n"
7789 "\n%3$sUnit Commands:%4$s\n"
fbf3283b
ZJS
7790 " list-units [PATTERN...] List units currently in memory\n"
7791 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7792 " ordered by address\n"
7793 " list-timers [PATTERN...] List timer units currently in memory,\n"
7794 " ordered by next elapse\n"
7795 " start UNIT... Start (activate) one or more units\n"
7796 " stop UNIT... Stop (deactivate) one or more units\n"
7797 " reload UNIT... Reload one or more units\n"
7798 " restart UNIT... Start or restart one or more units\n"
7799 " try-restart UNIT... Restart one or more units if active\n"
7800 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7801 " otherwise start or restart\n"
7802 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7803 " if supported, otherwise restart\n"
7804 " isolate UNIT Start one unit and stop all others\n"
7805 " kill UNIT... Send signal to processes of a unit\n"
d81bc51f 7806 " clean UNIT... Clean runtime, cache, state, logs or\n"
ab4fae0c 7807 " configuration of unit\n"
fbf3283b
ZJS
7808 " is-active PATTERN... Check whether units are active\n"
7809 " is-failed PATTERN... Check whether units are failed\n"
7810 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7811 " show [PATTERN...|JOB...] Show properties of one or more\n"
7812 " units/jobs or the manager\n"
7813 " cat PATTERN... Show files and drop-ins of specified units\n"
7814 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7815 " help PATTERN...|PID... Show manual for one or more units\n"
7816 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7817 " units\n"
7818 " list-dependencies [UNIT] Recursively show units which are required\n"
7819 " or wanted by this unit or by which this\n"
4d985a31 7820 " unit is required or wanted"
353b2baa 7821 "\n%3$sUnit File Commands:%4$s\n"
fbf3283b
ZJS
7822 " list-unit-files [PATTERN...] List installed unit files\n"
7823 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7824 " disable UNIT... Disable one or more unit files\n"
7825 " reenable UNIT... Reenable one or more unit files\n"
7826 " preset UNIT... Enable/disable one or more unit files\n"
7827 " based on preset configuration\n"
7828 " preset-all Enable/disable all unit files based on\n"
7829 " preset configuration\n"
7830 " is-enabled UNIT... Check whether unit files are enabled\n"
7831 " mask UNIT... Mask one or more units\n"
7832 " unmask UNIT... Unmask one or more units\n"
7833 " link PATH... Link one or more units files into\n"
7834 " the search path\n"
7835 " revert UNIT... Revert one or more unit files to vendor\n"
7836 " version\n"
7837 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7838 " on specified one or more units\n"
7839 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7840 " on specified one or more units\n"
7841 " edit UNIT... Edit one or more unit files\n"
7842 " get-default Get the name of the default target\n"
353b2baa
LP
7843 " set-default TARGET Set the default target\n"
7844 "\n%3$sMachine Commands:%4$s\n"
4d985a31 7845 " list-machines [PATTERN...] List local containers and host\n"
353b2baa 7846 "\n%3$sJob Commands:%4$s\n"
fbf3283b 7847 " list-jobs [PATTERN...] List jobs\n"
353b2baa
LP
7848 " cancel [JOB...] Cancel all, one, or more jobs\n"
7849 "\n%3$sEnvironment Commands:%4$s\n"
fbf3283b 7850 " show-environment Dump environment\n"
135775c1
ZJS
7851 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7852 " unset-environment VARIABLE... Unset one or more environment variables\n"
4d985a31 7853 " import-environment [VARIABLE...] Import all or some environment variables\n"
38fcb7f7 7854 "\n%3$sManager State Commands:%4$s\n"
fbf3283b 7855 " daemon-reload Reload systemd manager configuration\n"
353b2baa 7856 " daemon-reexec Reexecute systemd manager\n"
38fcb7f7
ZJS
7857 " log-level [LEVEL] Get/set logging threshold for manager\n"
7858 " log-target [TARGET] Get/set logging target for manager\n"
6ab86319 7859 " service-watchdogs [BOOL] Get/set service watchdog state\n"
353b2baa 7860 "\n%3$sSystem Commands:%4$s\n"
fbf3283b
ZJS
7861 " is-system-running Check whether system is fully running\n"
7862 " default Enter system default mode\n"
7863 " rescue Enter system rescue mode\n"
7864 " emergency Enter system emergency mode\n"
7865 " halt Shut down and halt the system\n"
7866 " poweroff Shut down and power-off the system\n"
7867 " reboot [ARG] Shut down and reboot the system\n"
7868 " kexec Shut down and reboot the system with kexec\n"
7869 " exit [EXIT_CODE] Request user instance or container exit\n"
7870 " switch-root ROOT [INIT] Change to a different root file system\n"
7871 " suspend Suspend the system\n"
7872 " hibernate Hibernate the system\n"
c58493c0 7873 " hybrid-sleep Hibernate and suspend the system\n"
e68c79db 7874 " suspend-then-hibernate Suspend the system, wake after a period of\n"
4d985a31 7875 " time, and hibernate"
353b2baa 7876 "\n%3$sOptions:%4$s\n"
4d985a31
ZJS
7877 " -h --help Show this help\n"
7878 " --version Show package version\n"
7879 " --system Connect to system manager\n"
7880 " --user Connect to user service manager\n"
7881 " -H --host=[USER@]HOST Operate on remote host\n"
7882 " -M --machine=CONTAINER Operate on a local container\n"
7883 " -t --type=TYPE List units of a particular type\n"
7884 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
7885 " --failed Shorcut for --state=failed\n"
7886 " -p --property=NAME Show only properties by this name\n"
7887 " -a --all Show all properties/all units currently in memory,\n"
7888 " including dead/empty ones. To list all units installed\n"
7889 " on the system, use 'list-unit-files' instead.\n"
7890 " -l --full Don't ellipsize unit names on output\n"
7891 " -r --recursive Show unit list of host and local containers\n"
7892 " --reverse Show reverse dependencies with 'list-dependencies'\n"
e9c387c8
KK
7893 " --with-dependencies Show unit dependencies with 'status', 'cat',\n"
7894 " 'list-units', and 'list-unit-files'.\n"
4d985a31
ZJS
7895 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7896 " queueing a new job\n"
7897 " -T --show-transaction When enqueuing a unit job, show full transaction\n"
7898 " --show-types When showing sockets, explicitly show their type\n"
7899 " --value When showing properties, only print the value\n"
7900 " -i --ignore-inhibitors When shutting down or sleeping, ignore inhibitors\n"
7901 " --kill-who=WHO Whom to send signal to\n"
7902 " -s --signal=SIGNAL Which signal to send\n"
7903 " --what=RESOURCES Which types of resources to remove\n"
7904 " --now Start or stop unit after enabling or disabling it\n"
7905 " --dry-run Only print what would be done\n"
4afb4a9c
BW
7906 " Currently supported by verbs: halt, poweroff, reboot,\n"
7907 " kexec, suspend, hibernate, suspend-then-hibernate,\n"
7908 " hybrid-sleep, default, rescue, emergency, and exit.\n"
4d985a31
ZJS
7909 " -q --quiet Suppress output\n"
7910 " --wait For (re)start, wait until service stopped again\n"
7911 " For is-system-running, wait until startup is completed\n"
7912 " --no-block Do not wait until operation finished\n"
7913 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7914 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
7915 " --no-legend Do not print a legend (column headers and hints)\n"
7916 " --no-pager Do not pipe output into a pager\n"
7917 " --no-ask-password Do not ask for system passwords\n"
7918 " --global Enable/disable/mask unit files globally\n"
7919 " --runtime Enable/disable/mask unit files temporarily until next\n"
7920 " reboot\n"
7921 " -f --force When enabling unit files, override existing symlinks\n"
7922 " When shutting down, execute action immediately\n"
7923 " --preset-mode= Apply only enable, only disable, or all presets\n"
7924 " --root=PATH Enable/disable/mask unit files in the specified root\n"
7925 " directory\n"
7926 " -n --lines=INTEGER Number of journal entries to show\n"
7927 " -o --output=STRING Change journal output mode (short, short-precise,\n"
e1fac8a6
ZJS
7928 " short-iso, short-iso-precise, short-full,\n"
7929 " short-monotonic, short-unix,\n"
7930 " verbose, export, json, json-pretty, json-sse, cat)\n"
4d985a31 7931 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
e1fac8a6 7932 " --boot-loader-menu=TIME\n"
4d985a31 7933 " Boot into boot loader menu on next boot\n"
e1fac8a6 7934 " --boot-loader-entry=NAME\n"
4d985a31
ZJS
7935 " Boot into a specific boot loader entry on next boot\n"
7936 " --plain Print unit dependencies as a list instead of a tree\n"
8e543004 7937 "\nSee the %2$s for details.\n"
37ec0fdd
LP
7938 , program_invocation_short_name
7939 , link
8e543004 7940 , ansi_underline(), ansi_normal()
ce2529b4 7941 , ansi_highlight(), ansi_normal()
37ec0fdd
LP
7942 );
7943
7944 return 0;
7e4249b9
LP
7945}
7946
37ec0fdd
LP
7947static int halt_help(void) {
7948 _cleanup_free_ char *link = NULL;
7949 int r;
7950
7951 r = terminal_urlify_man("halt", "8", &link);
7952 if (r < 0)
7953 return log_oom();
7954
353b2baa
LP
7955 printf("%s [OPTIONS...]%s\n"
7956 "\n%s%s the system.%s\n"
7957 "\nOptions:\n"
e4b61340
LP
7958 " --help Show this help\n"
7959 " --halt Halt the machine\n"
7960 " -p --poweroff Switch off the machine\n"
7961 " --reboot Reboot the machine\n"
2e33c433
LP
7962 " -f --force Force immediate halt/power-off/reboot\n"
7963 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
e4b61340 7964 " -d --no-wtmp Don't write wtmp record\n"
37ec0fdd
LP
7965 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7966 "\nSee the %s for details.\n"
7967 , program_invocation_short_name
353b2baa
LP
7968 , arg_action == ACTION_REBOOT ? " [ARG]" : ""
7969 , ansi_highlight()
7970 , arg_action == ACTION_REBOOT ? "Reboot" :
37ec0fdd
LP
7971 arg_action == ACTION_POWEROFF ? "Power off" :
7972 "Halt"
353b2baa 7973 , ansi_normal()
37ec0fdd
LP
7974 , link
7975 );
7976
7977 return 0;
e4b61340
LP
7978}
7979
37ec0fdd
LP
7980static int shutdown_help(void) {
7981 _cleanup_free_ char *link = NULL;
7982 int r;
7983
7984 r = terminal_urlify_man("shutdown", "8", &link);
7985 if (r < 0)
7986 return log_oom();
7987
353b2baa
LP
7988 printf("%s [OPTIONS...] [TIME] [WALL...]\n"
7989 "\n%sShut down the system.%s\n"
7990 "\nOptions:\n"
e4b61340
LP
7991 " --help Show this help\n"
7992 " -H --halt Halt the machine\n"
7993 " -P --poweroff Power-off the machine\n"
7994 " -r --reboot Reboot the machine\n"
386da858 7995 " -h Equivalent to --poweroff, overridden by --halt\n"
2e33c433 7996 " -k Don't halt/power-off/reboot, just send warnings\n"
f6144808 7997 " --no-wall Don't send wall message before halt/power-off/reboot\n"
37ec0fdd
LP
7998 " -c Cancel a pending shutdown\n"
7999 "\nSee the %s for details.\n"
8000 , program_invocation_short_name
353b2baa 8001 , ansi_highlight(), ansi_normal()
37ec0fdd
LP
8002 , link
8003 );
8004
8005 return 0;
e4b61340
LP
8006}
8007
37ec0fdd
LP
8008static int telinit_help(void) {
8009 _cleanup_free_ char *link = NULL;
8010 int r;
8011
8012 r = terminal_urlify_man("telinit", "8", &link);
8013 if (r < 0)
8014 return log_oom();
8015
353b2baa
LP
8016 printf("%s [OPTIONS...] COMMAND\n\n"
8017 "%sSend control commands to the init daemon.%s\n"
8018 "\nCommands:\n"
e4b61340
LP
8019 " 0 Power-off the machine\n"
8020 " 6 Reboot the machine\n"
514f4ef5
LP
8021 " 2, 3, 4, 5 Start runlevelX.target unit\n"
8022 " 1, s, S Enter rescue mode\n"
8023 " q, Q Reload init daemon configuration\n"
37ec0fdd 8024 " u, U Reexecute init daemon\n"
353b2baa
LP
8025 "\nOptions:\n"
8026 " --help Show this help\n"
8027 " --no-wall Don't send wall message before halt/power-off/reboot\n"
37ec0fdd
LP
8028 "\nSee the %s for details.\n"
8029 , program_invocation_short_name
353b2baa 8030 , ansi_highlight(), ansi_normal()
37ec0fdd
LP
8031 , link
8032 );
8033
8034 return 0;
e4b61340
LP
8035}
8036
37ec0fdd
LP
8037static int runlevel_help(void) {
8038 _cleanup_free_ char *link = NULL;
8039 int r;
8040
8041 r = terminal_urlify_man("runlevel", "8", &link);
8042 if (r < 0)
8043 return log_oom();
8044
353b2baa
LP
8045 printf("%s [OPTIONS...]\n"
8046 "\n%sPrints the previous and current runlevel of the init system.%s\n"
8047 "\nOptions:\n"
37ec0fdd
LP
8048 " --help Show this help\n"
8049 "\nSee the %s for details.\n"
8050 , program_invocation_short_name
353b2baa 8051 , ansi_highlight(), ansi_normal()
37ec0fdd
LP
8052 , link
8053 );
8054
8055 return 0;
e4b61340
LP
8056}
8057
b93312f5 8058static void help_types(void) {
b93312f5
ZJS
8059 if (!arg_no_legend)
8060 puts("Available unit types:");
5c828e66
LP
8061
8062 DUMP_STRING_TABLE(unit_type, UnitType, _UNIT_TYPE_MAX);
e16972e6
ZJS
8063}
8064
8065static void help_states(void) {
e16972e6
ZJS
8066 if (!arg_no_legend)
8067 puts("Available unit load states:");
5c828e66 8068 DUMP_STRING_TABLE(unit_load_state, UnitLoadState, _UNIT_LOAD_STATE_MAX);
e16972e6
ZJS
8069
8070 if (!arg_no_legend)
8071 puts("\nAvailable unit active states:");
5c828e66 8072 DUMP_STRING_TABLE(unit_active_state, UnitActiveState, _UNIT_ACTIVE_STATE_MAX);
7e55de3b 8073
46ff70ca
RP
8074 if (!arg_no_legend)
8075 puts("\nAvailable unit file states:");
8076 DUMP_STRING_TABLE(unit_file_state, UnitFileState, _UNIT_FILE_STATE_MAX);
8077
7e55de3b
ZJS
8078 if (!arg_no_legend)
8079 puts("\nAvailable automount unit substates:");
5c828e66 8080 DUMP_STRING_TABLE(automount_state, AutomountState, _AUTOMOUNT_STATE_MAX);
7e55de3b 8081
7e55de3b
ZJS
8082 if (!arg_no_legend)
8083 puts("\nAvailable device unit substates:");
5c828e66 8084 DUMP_STRING_TABLE(device_state, DeviceState, _DEVICE_STATE_MAX);
7e55de3b
ZJS
8085
8086 if (!arg_no_legend)
8087 puts("\nAvailable mount unit substates:");
5c828e66 8088 DUMP_STRING_TABLE(mount_state, MountState, _MOUNT_STATE_MAX);
7e55de3b
ZJS
8089
8090 if (!arg_no_legend)
8091 puts("\nAvailable path unit substates:");
5c828e66 8092 DUMP_STRING_TABLE(path_state, PathState, _PATH_STATE_MAX);
7e55de3b
ZJS
8093
8094 if (!arg_no_legend)
8095 puts("\nAvailable scope unit substates:");
5c828e66 8096 DUMP_STRING_TABLE(scope_state, ScopeState, _SCOPE_STATE_MAX);
7e55de3b
ZJS
8097
8098 if (!arg_no_legend)
8099 puts("\nAvailable service unit substates:");
5c828e66 8100 DUMP_STRING_TABLE(service_state, ServiceState, _SERVICE_STATE_MAX);
7e55de3b
ZJS
8101
8102 if (!arg_no_legend)
8103 puts("\nAvailable slice unit substates:");
5c828e66 8104 DUMP_STRING_TABLE(slice_state, SliceState, _SLICE_STATE_MAX);
7e55de3b 8105
7e55de3b
ZJS
8106 if (!arg_no_legend)
8107 puts("\nAvailable socket unit substates:");
5c828e66 8108 DUMP_STRING_TABLE(socket_state, SocketState, _SOCKET_STATE_MAX);
7e55de3b
ZJS
8109
8110 if (!arg_no_legend)
8111 puts("\nAvailable swap unit substates:");
5c828e66 8112 DUMP_STRING_TABLE(swap_state, SwapState, _SWAP_STATE_MAX);
7e55de3b
ZJS
8113
8114 if (!arg_no_legend)
8115 puts("\nAvailable target unit substates:");
5c828e66 8116 DUMP_STRING_TABLE(target_state, TargetState, _TARGET_STATE_MAX);
7e55de3b
ZJS
8117
8118 if (!arg_no_legend)
8119 puts("\nAvailable timer unit substates:");
5c828e66 8120 DUMP_STRING_TABLE(timer_state, TimerState, _TIMER_STATE_MAX);
45c0c61d
ZJS
8121}
8122
97af80c5
LP
8123static int help_boot_loader_entry(void) {
8124 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
13f697b7 8125 _cleanup_strv_free_ char **l = NULL;
97af80c5
LP
8126 sd_bus *bus;
8127 char **i;
8128 int r;
8129
8130 r = acquire_bus(BUS_FULL, &bus);
8131 if (r < 0)
8132 return r;
8133
8134 r = sd_bus_get_property_strv(
8135 bus,
8136 "org.freedesktop.login1",
8137 "/org/freedesktop/login1",
8138 "org.freedesktop.login1.Manager",
8139 "BootLoaderEntries",
8140 &error,
8141 &l);
8142 if (r < 0)
8143 return log_error_errno(r, "Failed to enumerate boot loader entries: %s", bus_error_message(&error, r));
8144
2f50e59f
LP
8145 if (strv_isempty(l))
8146 return log_error_errno(SYNTHETIC_ERRNO(ENODATA), "No boot loader entries discovered.");
97af80c5
LP
8147
8148 STRV_FOREACH(i, l)
8149 puts(*i);
8150
8151 return 0;
8152}
8153
e4b61340 8154static int systemctl_parse_argv(int argc, char *argv[]) {
7e4249b9 8155 enum {
90d473a1 8156 ARG_FAIL = 0x100,
afba4199
ZJS
8157 ARG_REVERSE,
8158 ARG_AFTER,
8159 ARG_BEFORE,
1ae17672 8160 ARG_DRY_RUN,
991f2a39 8161 ARG_SHOW_TYPES,
23ade460 8162 ARG_IRREVERSIBLE,
e67c3609 8163 ARG_IGNORE_DEPENDENCIES,
4f9a9105 8164 ARG_VALUE,
35df8f27 8165 ARG_VERSION,
af2d49f7 8166 ARG_USER,
7e4249b9 8167 ARG_SYSTEM,
ee5762e3 8168 ARG_GLOBAL,
6e905d93 8169 ARG_NO_BLOCK,
ebed32bf 8170 ARG_NO_LEGEND,
611efaac 8171 ARG_NO_PAGER,
4445a875 8172 ARG_NO_WALL,
be394c48 8173 ARG_ROOT,
ee5762e3 8174 ARG_NO_RELOAD,
501fc174 8175 ARG_KILL_WHO,
30732560 8176 ARG_NO_ASK_PASSWORD,
729e3769 8177 ARG_FAILED,
df50185b 8178 ARG_RUNTIME,
9b9b3d36 8179 ARG_PLAIN,
4dc5b821 8180 ARG_STATE,
d309c1c3
LP
8181 ARG_JOB_MODE,
8182 ARG_PRESET_MODE,
5bdf2243 8183 ARG_FIRMWARE_SETUP,
97af80c5
LP
8184 ARG_BOOT_LOADER_MENU,
8185 ARG_BOOT_LOADER_ENTRY,
57ab2eab 8186 ARG_NOW,
9ef15026 8187 ARG_MESSAGE,
e9c387c8 8188 ARG_WITH_DEPENDENCIES,
93a08841 8189 ARG_WAIT,
d81bc51f 8190 ARG_WHAT,
7e4249b9
LP
8191 };
8192
8193 static const struct option options[] = {
9ea9d4cf
LP
8194 { "help", no_argument, NULL, 'h' },
8195 { "version", no_argument, NULL, ARG_VERSION },
8196 { "type", required_argument, NULL, 't' },
8197 { "property", required_argument, NULL, 'p' },
8198 { "all", no_argument, NULL, 'a' },
8199 { "reverse", no_argument, NULL, ARG_REVERSE },
8200 { "after", no_argument, NULL, ARG_AFTER },
8201 { "before", no_argument, NULL, ARG_BEFORE },
8202 { "show-types", no_argument, NULL, ARG_SHOW_TYPES },
8203 { "failed", no_argument, NULL, ARG_FAILED }, /* compatibility only */
8204 { "full", no_argument, NULL, 'l' },
4dc5b821
LP
8205 { "job-mode", required_argument, NULL, ARG_JOB_MODE },
8206 { "fail", no_argument, NULL, ARG_FAIL }, /* compatibility only */
8207 { "irreversible", no_argument, NULL, ARG_IRREVERSIBLE }, /* compatibility only */
8208 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES }, /* compatibility only */
9ea9d4cf 8209 { "ignore-inhibitors", no_argument, NULL, 'i' },
4f9a9105 8210 { "value", no_argument, NULL, ARG_VALUE },
9ea9d4cf
LP
8211 { "user", no_argument, NULL, ARG_USER },
8212 { "system", no_argument, NULL, ARG_SYSTEM },
8213 { "global", no_argument, NULL, ARG_GLOBAL },
93a08841 8214 { "wait", no_argument, NULL, ARG_WAIT },
9ea9d4cf
LP
8215 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
8216 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
8217 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
8218 { "no-wall", no_argument, NULL, ARG_NO_WALL },
1ae17672 8219 { "dry-run", no_argument, NULL, ARG_DRY_RUN },
9ea9d4cf
LP
8220 { "quiet", no_argument, NULL, 'q' },
8221 { "root", required_argument, NULL, ARG_ROOT },
68da321f 8222 { "force", no_argument, NULL, 'f' },
9ea9d4cf
LP
8223 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
8224 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
8225 { "signal", required_argument, NULL, 's' },
8226 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
8227 { "host", required_argument, NULL, 'H' },
f459b602 8228 { "machine", required_argument, NULL, 'M' },
9ea9d4cf
LP
8229 { "runtime", no_argument, NULL, ARG_RUNTIME },
8230 { "lines", required_argument, NULL, 'n' },
8231 { "output", required_argument, NULL, 'o' },
8232 { "plain", no_argument, NULL, ARG_PLAIN },
8233 { "state", required_argument, NULL, ARG_STATE },
1238ee09 8234 { "recursive", no_argument, NULL, 'r' },
e9c387c8 8235 { "with-dependencies", no_argument, NULL, ARG_WITH_DEPENDENCIES },
d309c1c3 8236 { "preset-mode", required_argument, NULL, ARG_PRESET_MODE },
5bdf2243 8237 { "firmware-setup", no_argument, NULL, ARG_FIRMWARE_SETUP },
97af80c5
LP
8238 { "boot-loader-menu", required_argument, NULL, ARG_BOOT_LOADER_MENU },
8239 { "boot-loader-entry", required_argument, NULL, ARG_BOOT_LOADER_ENTRY },
57ab2eab 8240 { "now", no_argument, NULL, ARG_NOW },
9ef15026 8241 { "message", required_argument, NULL, ARG_MESSAGE },
85d9b598 8242 { "show-transaction", no_argument, NULL, 'T' },
d81bc51f 8243 { "what", required_argument, NULL, ARG_WHAT },
eb9da376 8244 {}
7e4249b9
LP
8245 };
8246
0f03c2a4 8247 int c, r;
7e4249b9 8248
e4b61340 8249 assert(argc >= 0);
7e4249b9
LP
8250 assert(argv);
8251
16f017fa
IS
8252 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
8253 arg_ask_password = true;
8254
85d9b598 8255 while ((c = getopt_long(argc, argv, "ht:p:alqfs:H:M:n:o:iTr.::", options, NULL)) >= 0)
7e4249b9
LP
8256
8257 switch (c) {
8258
8259 case 'h':
37ec0fdd 8260 return systemctl_help();
35df8f27
LP
8261
8262 case ARG_VERSION:
3f6fd1ba 8263 return version();
7e4249b9 8264
20b3f379 8265 case 't': {
fb1ac50e
LP
8266 const char *p;
8267
baaa35ad
ZJS
8268 if (isempty(optarg))
8269 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8270 "--type= requires arguments.");
45c0c61d 8271
c58bd76a 8272 for (p = optarg;;) {
5ab22f33 8273 _cleanup_free_ char *type = NULL;
20b3f379 8274
5ab22f33
SS
8275 r = extract_first_word(&p, &type, ",", 0);
8276 if (r < 0)
8277 return log_error_errno(r, "Failed to parse type: %s", optarg);
5ab22f33
SS
8278 if (r == 0)
8279 break;
20b3f379
ZJS
8280
8281 if (streq(type, "help")) {
8282 help_types();
8283 return 0;
8284 }
8285
8286 if (unit_type_from_string(type) >= 0) {
96e895ef 8287 if (strv_consume(&arg_types, TAKE_PTR(type)) < 0)
20b3f379 8288 return log_oom();
20b3f379
ZJS
8289 continue;
8290 }
8291
9b9b3d36
MW
8292 /* It's much nicer to use --state= for
8293 * load states, but let's support this
8294 * in --types= too for compatibility
8295 * with old versions */
7e9d36e0 8296 if (unit_load_state_from_string(type) >= 0) {
96e895ef 8297 if (strv_consume(&arg_states, TAKE_PTR(type)) < 0)
20b3f379 8298 return log_oom();
20b3f379
ZJS
8299 continue;
8300 }
8301
ab06eef8 8302 log_error("Unknown unit type or load state '%s'.", type);
baaa35ad
ZJS
8303 return log_info_errno(SYNTHETIC_ERRNO(EINVAL),
8304 "Use -t help to see a list of allowed values.");
c147dc42 8305 }
20b3f379
ZJS
8306
8307 break;
8308 }
8309
aee7082f
LP
8310 case 'p':
8311 /* Make sure that if the empty property list was specified, we won't show any
8312 properties. */
20b3f379 8313 if (isempty(optarg) && !arg_properties) {
cbc9fbd1 8314 arg_properties = new0(char*, 1);
20b3f379
ZJS
8315 if (!arg_properties)
8316 return log_oom();
fb1ac50e
LP
8317 } else {
8318 const char *p;
8319
c58bd76a 8320 for (p = optarg;;) {
5ab22f33 8321 _cleanup_free_ char *prop = NULL;
033a842c 8322
5ab22f33
SS
8323 r = extract_first_word(&p, &prop, ",", 0);
8324 if (r < 0)
8325 return log_error_errno(r, "Failed to parse property: %s", optarg);
5ab22f33
SS
8326 if (r == 0)
8327 break;
ea4a240d 8328
9dccc6d3 8329 if (strv_consume(&arg_properties, TAKE_PTR(prop)) < 0)
20b3f379 8330 return log_oom();
20b3f379 8331 }
fb1ac50e 8332 }
48220598
LP
8333
8334 /* If the user asked for a particular
8335 * property, show it to him, even if it is
8336 * empty. */
8337 arg_all = true;
033a842c 8338
48220598
LP
8339 break;
8340
7e4249b9
LP
8341 case 'a':
8342 arg_all = true;
8343 break;
8344
afba4199
ZJS
8345 case ARG_REVERSE:
8346 arg_dependency = DEPENDENCY_REVERSE;
8347 break;
8348
8349 case ARG_AFTER:
8350 arg_dependency = DEPENDENCY_AFTER;
82948f6c 8351 arg_jobs_after = true;
afba4199
ZJS
8352 break;
8353
8354 case ARG_BEFORE:
8355 arg_dependency = DEPENDENCY_BEFORE;
82948f6c 8356 arg_jobs_before = true;
afba4199
ZJS
8357 break;
8358
991f2a39
ZJS
8359 case ARG_SHOW_TYPES:
8360 arg_show_types = true;
8361 break;
8362
4f9a9105
ZJS
8363 case ARG_VALUE:
8364 arg_value = true;
8365 break;
8366
4dc5b821
LP
8367 case ARG_JOB_MODE:
8368 arg_job_mode = optarg;
8369 break;
8370
90d473a1 8371 case ARG_FAIL:
e67c3609
LP
8372 arg_job_mode = "fail";
8373 break;
8374
23ade460
MS
8375 case ARG_IRREVERSIBLE:
8376 arg_job_mode = "replace-irreversibly";
8377 break;
8378
e67c3609
LP
8379 case ARG_IGNORE_DEPENDENCIES:
8380 arg_job_mode = "ignore-dependencies";
7e4249b9
LP
8381 break;
8382
af2d49f7 8383 case ARG_USER:
729e3769 8384 arg_scope = UNIT_FILE_USER;
7e4249b9
LP
8385 break;
8386
8387 case ARG_SYSTEM:
729e3769
LP
8388 arg_scope = UNIT_FILE_SYSTEM;
8389 break;
8390
8391 case ARG_GLOBAL:
8392 arg_scope = UNIT_FILE_GLOBAL;
7e4249b9
LP
8393 break;
8394
93a08841
MP
8395 case ARG_WAIT:
8396 arg_wait = true;
8397 break;
8398
6e905d93
LP
8399 case ARG_NO_BLOCK:
8400 arg_no_block = true;
7e4249b9
LP
8401 break;
8402
ebed32bf
MS
8403 case ARG_NO_LEGEND:
8404 arg_no_legend = true;
8405 break;
8406
611efaac 8407 case ARG_NO_PAGER:
0221d68a 8408 arg_pager_flags |= PAGER_DISABLE;
611efaac 8409 break;
0736af98 8410
514f4ef5
LP
8411 case ARG_NO_WALL:
8412 arg_no_wall = true;
8413 break;
8414
be394c48 8415 case ARG_ROOT:
bac75eb3 8416 r = parse_path_argument_and_warn(optarg, false, &arg_root);
0f03c2a4
LP
8417 if (r < 0)
8418 return r;
be394c48
FC
8419 break;
8420
98a6e132 8421 case 'l':
8fe914ec
LP
8422 arg_full = true;
8423 break;
8424
30732560 8425 case ARG_FAILED:
9b9b3d36
MW
8426 if (strv_extend(&arg_states, "failed") < 0)
8427 return log_oom();
8428
30732560
LP
8429 break;
8430
1ae17672
ZJS
8431 case ARG_DRY_RUN:
8432 arg_dry_run = true;
8433 break;
8434
0183528f
LP
8435 case 'q':
8436 arg_quiet = true;
8437 break;
8438
b4f27ccc 8439 case 'f':
313cefa1 8440 arg_force++;
ee5762e3
LP
8441 break;
8442
8443 case ARG_NO_RELOAD:
8444 arg_no_reload = true;
8445 break;
8446
8a0867d6
LP
8447 case ARG_KILL_WHO:
8448 arg_kill_who = optarg;
8449 break;
8450
8a0867d6 8451 case 's':
5c828e66
LP
8452 if (streq(optarg, "help")) {
8453 DUMP_STRING_TABLE(signal, int, _NSIG);
8454 return 0;
8455 }
8456
29a3db75 8457 arg_signal = signal_from_string(optarg);
baaa35ad
ZJS
8458 if (arg_signal < 0)
8459 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8460 "Failed to parse signal string %s.",
8461 optarg);
8a0867d6
LP
8462 break;
8463
501fc174
LP
8464 case ARG_NO_ASK_PASSWORD:
8465 arg_ask_password = false;
8466 break;
8467
f459b602
MAP
8468 case 'H':
8469 arg_transport = BUS_TRANSPORT_REMOTE;
8470 arg_host = optarg;
a8f11321
LP
8471 break;
8472
f459b602 8473 case 'M':
de33fc62 8474 arg_transport = BUS_TRANSPORT_MACHINE;
f459b602 8475 arg_host = optarg;
a8f11321
LP
8476 break;
8477
729e3769
LP
8478 case ARG_RUNTIME:
8479 arg_runtime = true;
8480 break;
8481
df50185b 8482 case 'n':
baaa35ad
ZJS
8483 if (safe_atou(optarg, &arg_lines) < 0)
8484 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8485 "Failed to parse lines '%s'",
8486 optarg);
df50185b
LP
8487 break;
8488
df50185b 8489 case 'o':
5c828e66
LP
8490 if (streq(optarg, "help")) {
8491 DUMP_STRING_TABLE(output_mode, OutputMode, _OUTPUT_MODE_MAX);
8492 return 0;
8493 }
8494
df50185b 8495 arg_output = output_mode_from_string(optarg);
baaa35ad
ZJS
8496 if (arg_output < 0)
8497 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8498 "Unknown output '%s'.",
8499 optarg);
df50185b
LP
8500 break;
8501
b37844d3
LP
8502 case 'i':
8503 arg_ignore_inhibitors = true;
8504 break;
8505
5d0c05e5
LN
8506 case ARG_PLAIN:
8507 arg_plain = true;
8508 break;
8509
5bdf2243
JJ
8510 case ARG_FIRMWARE_SETUP:
8511 arg_firmware_setup = true;
8512 break;
8513
97af80c5
LP
8514 case ARG_BOOT_LOADER_MENU:
8515
8516 r = parse_sec(optarg, &arg_boot_loader_menu);
8517 if (r < 0)
8518 return log_error_errno(r, "Failed to parse --boot-loader-menu= argument '%s': %m", optarg);
8519
8520 break;
8521
8522 case ARG_BOOT_LOADER_ENTRY:
8523
8524 if (streq(optarg, "help")) { /* Yes, this means, "help" is not a valid boot loader entry name we can deal with */
8525 r = help_boot_loader_entry();
8526 if (r < 0)
8527 return r;
8528
8529 return 0;
8530 }
8531
8532 arg_boot_loader_entry = empty_to_null(optarg);
8533 break;
8534
9b9b3d36 8535 case ARG_STATE: {
fb1ac50e
LP
8536 const char *p;
8537
baaa35ad
ZJS
8538 if (isempty(optarg))
8539 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8540 "--state= requires arguments.");
9b9b3d36 8541
c58bd76a 8542 for (p = optarg;;) {
bc6c18fe 8543 _cleanup_free_ char *s = NULL;
9b9b3d36 8544
5ab22f33
SS
8545 r = extract_first_word(&p, &s, ",", 0);
8546 if (r < 0)
6862111e 8547 return log_error_errno(r, "Failed to parse state: %s", optarg);
5ab22f33
SS
8548 if (r == 0)
8549 break;
9b9b3d36 8550
e16972e6
ZJS
8551 if (streq(s, "help")) {
8552 help_states();
8553 return 0;
8554 }
8555
9dccc6d3 8556 if (strv_consume(&arg_states, TAKE_PTR(s)) < 0)
9b9b3d36 8557 return log_oom();
9b9b3d36
MW
8558 }
8559 break;
8560 }
8561
1238ee09 8562 case 'r':
baaa35ad
ZJS
8563 if (geteuid() != 0)
8564 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
8565 "--recursive requires root privileges.");
1238ee09
LP
8566
8567 arg_recursive = true;
8568 break;
8569
d309c1c3 8570 case ARG_PRESET_MODE:
5c828e66
LP
8571 if (streq(optarg, "help")) {
8572 DUMP_STRING_TABLE(unit_file_preset_mode, UnitFilePresetMode, _UNIT_FILE_PRESET_MAX);
8573 return 0;
8574 }
d309c1c3
LP
8575
8576 arg_preset_mode = unit_file_preset_mode_from_string(optarg);
baaa35ad
ZJS
8577 if (arg_preset_mode < 0)
8578 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8579 "Failed to parse preset mode: %s.", optarg);
d309c1c3
LP
8580
8581 break;
8582
57ab2eab
JS
8583 case ARG_NOW:
8584 arg_now = true;
8585 break;
8586
9ef15026
JS
8587 case ARG_MESSAGE:
8588 if (strv_extend(&arg_wall, optarg) < 0)
8589 return log_oom();
8590 break;
8591
85d9b598
LP
8592 case 'T':
8593 arg_show_transaction = true;
8594 break;
8595
e9c387c8
KK
8596 case ARG_WITH_DEPENDENCIES:
8597 arg_with_dependencies = true;
8598 break;
8599
d81bc51f
LP
8600 case ARG_WHAT: {
8601 const char *p;
8602
8603 if (isempty(optarg))
8604 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--what= requires arguments.");
8605
8606 for (p = optarg;;) {
8607 _cleanup_free_ char *k = NULL;
8608
8609 r = extract_first_word(&p, &k, ",", 0);
8610 if (r < 0)
8611 return log_error_errno(r, "Failed to parse directory type: %s", optarg);
8612 if (r == 0)
8613 break;
8614
8615 if (streq(k, "help")) {
8616 puts("runtime\n"
8617 "state\n"
8618 "cache\n"
8619 "logs\n"
8620 "configuration");
8621 return 0;
8622 }
8623
8624 r = strv_consume(&arg_clean_what, TAKE_PTR(k));
8625 if (r < 0)
8626 return log_oom();
8627 }
8628
8629 break;
8630 }
8631
2e7e19ca
ZJS
8632 case '.':
8633 /* Output an error mimicking getopt, and print a hint afterwards */
8634 log_error("%s: invalid option -- '.'", program_invocation_name);
8635 log_notice("Hint: to specify units starting with a dash, use \"--\":\n"
353b2baa 8636 " %s [OPTIONS...] COMMAND -- -.%s ...",
2e7e19ca
ZJS
8637 program_invocation_name, optarg ?: "mount");
8638 _fallthrough_;
8639
7e4249b9
LP
8640 case '?':
8641 return -EINVAL;
8642
8643 default:
eb9da376 8644 assert_not_reached("Unhandled option");
7e4249b9 8645 }
7e4249b9 8646
baaa35ad
ZJS
8647 if (arg_transport != BUS_TRANSPORT_LOCAL && arg_scope != UNIT_FILE_SYSTEM)
8648 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8649 "Cannot access user instance remotely.");
a8f11321 8650
baaa35ad
ZJS
8651 if (arg_wait && arg_no_block)
8652 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8653 "--wait may not be combined with --no-block.");
93a08841 8654
7e4249b9
LP
8655 return 1;
8656}
8657
e4b61340 8658static int halt_parse_argv(int argc, char *argv[]) {
e4b61340
LP
8659 enum {
8660 ARG_HELP = 0x100,
8661 ARG_HALT,
514f4ef5
LP
8662 ARG_REBOOT,
8663 ARG_NO_WALL
e4b61340
LP
8664 };
8665
8666 static const struct option options[] = {
8667 { "help", no_argument, NULL, ARG_HELP },
8668 { "halt", no_argument, NULL, ARG_HALT },
8669 { "poweroff", no_argument, NULL, 'p' },
8670 { "reboot", no_argument, NULL, ARG_REBOOT },
8671 { "force", no_argument, NULL, 'f' },
8672 { "wtmp-only", no_argument, NULL, 'w' },
8673 { "no-wtmp", no_argument, NULL, 'd' },
f3f054f0 8674 { "no-sync", no_argument, NULL, 'n' },
514f4ef5 8675 { "no-wall", no_argument, NULL, ARG_NO_WALL },
eb9da376 8676 {}
e4b61340
LP
8677 };
8678
37185ec8 8679 int c, r, runlevel;
e4b61340
LP
8680
8681 assert(argc >= 0);
8682 assert(argv);
8683
8684 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4c701096 8685 if (IN_SET(runlevel, '0', '6'))
65491fd8 8686 arg_force = 2;
e4b61340 8687
601185b4 8688 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0)
e4b61340
LP
8689 switch (c) {
8690
8691 case ARG_HELP:
37ec0fdd 8692 return halt_help();
e4b61340
LP
8693
8694 case ARG_HALT:
8695 arg_action = ACTION_HALT;
8696 break;
8697
8698 case 'p':
a042efad
MS
8699 if (arg_action != ACTION_REBOOT)
8700 arg_action = ACTION_POWEROFF;
e4b61340
LP
8701 break;
8702
8703 case ARG_REBOOT:
8704 arg_action = ACTION_REBOOT;
8705 break;
8706
8707 case 'f':
65491fd8 8708 arg_force = 2;
e4b61340
LP
8709 break;
8710
8711 case 'w':
1ae17672 8712 arg_dry_run = true;
e4b61340
LP
8713 break;
8714
8715 case 'd':
8716 arg_no_wtmp = true;
8717 break;
8718
f3f054f0
TB
8719 case 'n':
8720 arg_no_sync = true;
8721 break;
8722
514f4ef5
LP
8723 case ARG_NO_WALL:
8724 arg_no_wall = true;
8725 break;
8726
e4b61340
LP
8727 case 'i':
8728 case 'h':
8729 /* Compatibility nops */
8730 break;
8731
8732 case '?':
8733 return -EINVAL;
8734
8735 default:
eb9da376 8736 assert_not_reached("Unhandled option");
e4b61340 8737 }
e4b61340 8738
c5220a94 8739 if (arg_action == ACTION_REBOOT && (argc == optind || argc == optind + 1)) {
77defcf5 8740 r = update_reboot_parameter_and_warn(argc == optind + 1 ? argv[optind] : NULL, false);
c5220a94 8741 if (r < 0)
37185ec8 8742 return r;
baaa35ad
ZJS
8743 } else if (optind < argc)
8744 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8745 "Too many arguments.");
e4b61340
LP
8746
8747 return 1;
8748}
8749
8750static int shutdown_parse_argv(int argc, char *argv[]) {
e4b61340
LP
8751 enum {
8752 ARG_HELP = 0x100,
514f4ef5 8753 ARG_NO_WALL
e4b61340
LP
8754 };
8755
8756 static const struct option options[] = {
8757 { "help", no_argument, NULL, ARG_HELP },
8758 { "halt", no_argument, NULL, 'H' },
8759 { "poweroff", no_argument, NULL, 'P' },
8760 { "reboot", no_argument, NULL, 'r' },
04ebb595 8761 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
514f4ef5 8762 { "no-wall", no_argument, NULL, ARG_NO_WALL },
eb9da376 8763 {}
e4b61340
LP
8764 };
8765
172d7abf 8766 char **wall = NULL;
f6144808 8767 int c, r;
e4b61340
LP
8768
8769 assert(argc >= 0);
8770 assert(argv);
8771
b068c6f5 8772 while ((c = getopt_long(argc, argv, "HPrhkKat:fFc", options, NULL)) >= 0)
e4b61340
LP
8773 switch (c) {
8774
8775 case ARG_HELP:
37ec0fdd 8776 return shutdown_help();
e4b61340
LP
8777
8778 case 'H':
8779 arg_action = ACTION_HALT;
8780 break;
8781
8782 case 'P':
8783 arg_action = ACTION_POWEROFF;
8784 break;
8785
8786 case 'r':
5622dde3
KS
8787 if (kexec_loaded())
8788 arg_action = ACTION_KEXEC;
8789 else
8790 arg_action = ACTION_REBOOT;
e4b61340
LP
8791 break;
8792
04ebb595
LP
8793 case 'K':
8794 arg_action = ACTION_KEXEC;
8795 break;
8796
e4b61340
LP
8797 case 'h':
8798 if (arg_action != ACTION_HALT)
8799 arg_action = ACTION_POWEROFF;
8800 break;
8801
8802 case 'k':
1ae17672 8803 arg_dry_run = true;
e4b61340
LP
8804 break;
8805
514f4ef5
LP
8806 case ARG_NO_WALL:
8807 arg_no_wall = true;
8808 break;
8809
e4b61340 8810 case 'a':
b068c6f5 8811 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
75836b9d
JS
8812 case 'f':
8813 case 'F':
e4b61340
LP
8814 /* Compatibility nops */
8815 break;
8816
f6144808
LP
8817 case 'c':
8818 arg_action = ACTION_CANCEL_SHUTDOWN;
8819 break;
8820
e4b61340
LP
8821 case '?':
8822 return -EINVAL;
8823
8824 default:
eb9da376 8825 assert_not_reached("Unhandled option");
e4b61340 8826 }
e4b61340 8827
dfcc5c33 8828 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
2cc7b0a2 8829 r = parse_shutdown_time_spec(argv[optind], &arg_when);
7e59bfcb 8830 if (r < 0) {
f6144808
LP
8831 log_error("Failed to parse time specification: %s", argv[optind]);
8832 return r;
8833 }
6b5ad000 8834 } else
08e4b1c5 8835 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
442b9094 8836
dfcc5c33
MS
8837 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
8838 /* No time argument for shutdown cancel */
172d7abf 8839 wall = argv + optind;
dfcc5c33
MS
8840 else if (argc > optind + 1)
8841 /* We skip the time argument */
172d7abf
LP
8842 wall = argv + optind + 1;
8843
8844 if (wall) {
8845 arg_wall = strv_copy(wall);
8846 if (!arg_wall)
8847 return log_oom();
8848 }
e4b61340
LP
8849
8850 optind = argc;
8851
8852 return 1;
e4b61340
LP
8853}
8854
8855static int telinit_parse_argv(int argc, char *argv[]) {
e4b61340
LP
8856 enum {
8857 ARG_HELP = 0x100,
514f4ef5 8858 ARG_NO_WALL
e4b61340
LP
8859 };
8860
8861 static const struct option options[] = {
8862 { "help", no_argument, NULL, ARG_HELP },
514f4ef5 8863 { "no-wall", no_argument, NULL, ARG_NO_WALL },
eb9da376 8864 {}
e4b61340
LP
8865 };
8866
8867 static const struct {
8868 char from;
8869 enum action to;
8870 } table[] = {
8871 { '0', ACTION_POWEROFF },
8872 { '6', ACTION_REBOOT },
ef2f1067 8873 { '1', ACTION_RESCUE },
e4b61340
LP
8874 { '2', ACTION_RUNLEVEL2 },
8875 { '3', ACTION_RUNLEVEL3 },
8876 { '4', ACTION_RUNLEVEL4 },
8877 { '5', ACTION_RUNLEVEL5 },
8878 { 's', ACTION_RESCUE },
8879 { 'S', ACTION_RESCUE },
8880 { 'q', ACTION_RELOAD },
8881 { 'Q', ACTION_RELOAD },
8882 { 'u', ACTION_REEXEC },
8883 { 'U', ACTION_REEXEC }
8884 };
8885
8886 unsigned i;
8887 int c;
8888
8889 assert(argc >= 0);
8890 assert(argv);
8891
601185b4 8892 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
e4b61340
LP
8893 switch (c) {
8894
8895 case ARG_HELP:
37ec0fdd 8896 return telinit_help();
e4b61340 8897
514f4ef5
LP
8898 case ARG_NO_WALL:
8899 arg_no_wall = true;
8900 break;
8901
e4b61340
LP
8902 case '?':
8903 return -EINVAL;
8904
8905 default:
eb9da376 8906 assert_not_reached("Unhandled option");
e4b61340 8907 }
e4b61340 8908
baaa35ad
ZJS
8909 if (optind >= argc)
8910 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8911 "%s: required argument missing.",
8912 program_invocation_short_name);
e4b61340 8913
baaa35ad
ZJS
8914 if (optind + 1 < argc)
8915 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8916 "Too many arguments.");
e4b61340 8917
baaa35ad
ZJS
8918 if (strlen(argv[optind]) != 1)
8919 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8920 "Expected single character argument.");
e4b61340
LP
8921
8922 for (i = 0; i < ELEMENTSOF(table); i++)
8923 if (table[i].from == argv[optind][0])
8924 break;
8925
baaa35ad
ZJS
8926 if (i >= ELEMENTSOF(table))
8927 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8928 "Unknown command '%s'.", argv[optind]);
e4b61340
LP
8929
8930 arg_action = table[i].to;
8931
313cefa1 8932 optind++;
e4b61340
LP
8933
8934 return 1;
8935}
8936
8937static int runlevel_parse_argv(int argc, char *argv[]) {
e4b61340
LP
8938 enum {
8939 ARG_HELP = 0x100,
8940 };
8941
8942 static const struct option options[] = {
8943 { "help", no_argument, NULL, ARG_HELP },
eb9da376 8944 {}
e4b61340
LP
8945 };
8946
8947 int c;
8948
8949 assert(argc >= 0);
8950 assert(argv);
8951
601185b4 8952 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
e4b61340
LP
8953 switch (c) {
8954
8955 case ARG_HELP:
37ec0fdd 8956 return runlevel_help();
e4b61340
LP
8957
8958 case '?':
8959 return -EINVAL;
8960
8961 default:
eb9da376 8962 assert_not_reached("Unhandled option");
e4b61340 8963 }
e4b61340 8964
baaa35ad
ZJS
8965 if (optind < argc)
8966 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8967 "Too many arguments.");
e4b61340
LP
8968
8969 return 1;
8970}
8971
8972static int parse_argv(int argc, char *argv[]) {
8973 assert(argc >= 0);
8974 assert(argv);
8975
8976 if (program_invocation_short_name) {
8977
8978 if (strstr(program_invocation_short_name, "halt")) {
8979 arg_action = ACTION_HALT;
8980 return halt_parse_argv(argc, argv);
c54819ca 8981
e4b61340
LP
8982 } else if (strstr(program_invocation_short_name, "poweroff")) {
8983 arg_action = ACTION_POWEROFF;
8984 return halt_parse_argv(argc, argv);
c54819ca 8985
e4b61340 8986 } else if (strstr(program_invocation_short_name, "reboot")) {
5622dde3
KS
8987 if (kexec_loaded())
8988 arg_action = ACTION_KEXEC;
8989 else
8990 arg_action = ACTION_REBOOT;
e4b61340 8991 return halt_parse_argv(argc, argv);
c54819ca 8992
e4b61340
LP
8993 } else if (strstr(program_invocation_short_name, "shutdown")) {
8994 arg_action = ACTION_POWEROFF;
8995 return shutdown_parse_argv(argc, argv);
c54819ca 8996
e4b61340 8997 } else if (strstr(program_invocation_short_name, "init")) {
d5ca5f11 8998
c54819ca
LP
8999 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
9000 * 1 on SysV.
9001 *
9002 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
9003 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
9004 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
9005 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
9006 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
9007 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
9008 * quick way to match both.
9009 *
9010 * Also see redirect_telinit() in src/core/main.c. */
9011
d5ca5f11 9012 if (sd_booted() > 0) {
f459b602 9013 arg_action = _ACTION_INVALID;
d5ca5f11
LP
9014 return telinit_parse_argv(argc, argv);
9015 } else {
c54819ca
LP
9016 /* Hmm, so some other init system is running, we need to forward this request to
9017 * it. For now we simply guess that it is Upstart. */
d5ca5f11 9018
595225af 9019 (void) rlimit_nofile_safe();
4ad61fd1 9020 execv(TELINIT, argv);
d5ca5f11 9021
baaa35ad
ZJS
9022 return log_error_errno(SYNTHETIC_ERRNO(EIO),
9023 "Couldn't find an alternative telinit implementation to spawn.");
d5ca5f11
LP
9024 }
9025
e4b61340
LP
9026 } else if (strstr(program_invocation_short_name, "runlevel")) {
9027 arg_action = ACTION_RUNLEVEL;
9028 return runlevel_parse_argv(argc, argv);
9029 }
9030 }
9031
9032 arg_action = ACTION_SYSTEMCTL;
9033 return systemctl_parse_argv(argc, argv);
9034}
9035
349cc4a5 9036#if HAVE_SYSV_COMPAT
44a6b1b6 9037_pure_ static int action_to_runlevel(void) {
eb22ac37
LP
9038 static const char table[_ACTION_MAX] = {
9039 [ACTION_HALT] = '0',
9040 [ACTION_POWEROFF] = '0',
9041 [ACTION_REBOOT] = '6',
9042 [ACTION_RUNLEVEL2] = '2',
9043 [ACTION_RUNLEVEL3] = '3',
9044 [ACTION_RUNLEVEL4] = '4',
9045 [ACTION_RUNLEVEL5] = '5',
9046 [ACTION_RESCUE] = '1'
9047 };
9048
78ca9099 9049 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
d55ae9e6
LP
9050 return table[arg_action];
9051}
d2e79673 9052#endif
d55ae9e6 9053
e449de87 9054static int systemctl_main(int argc, char *argv[]) {
e449de87 9055 static const Verb verbs[] = {
c56d1e2c 9056 { "list-units", VERB_ANY, VERB_ANY, VERB_DEFAULT|VERB_ONLINE_ONLY, list_units },
38fcb7f7
ZJS
9057 { "list-unit-files", VERB_ANY, VERB_ANY, 0, list_unit_files },
9058 { "list-sockets", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_sockets },
9059 { "list-timers", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_timers },
9060 { "list-jobs", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_jobs },
9061 { "list-machines", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_machines },
9062 { "clear-jobs", VERB_ANY, 1, VERB_ONLINE_ONLY, trivial_method },
9063 { "cancel", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, cancel_job },
9064 { "start", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
9065 { "stop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
9066 { "condstop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
9067 { "reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
9068 { "restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
9069 { "try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
9070 { "reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
9071 { "reload-or-try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with old systemctl <= 228 */
9072 { "try-reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
9073 { "force-reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with SysV */
9074 { "condreload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
9075 { "condrestart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with RH */
9076 { "isolate", 2, 2, VERB_ONLINE_ONLY, start_unit },
9077 { "kill", 2, VERB_ANY, VERB_ONLINE_ONLY, kill_unit },
9078 { "clean", 2, VERB_ANY, VERB_ONLINE_ONLY, clean_unit },
9079 { "is-active", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active },
9080 { "check", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active }, /* deprecated alias of is-active */
9081 { "is-failed", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_failed },
9082 { "show", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
9083 { "cat", 2, VERB_ANY, VERB_ONLINE_ONLY, cat },
9084 { "status", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
9085 { "help", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
9086 { "daemon-reload", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
9087 { "daemon-reexec", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
9088 { "log-level", VERB_ANY, 2, 0, log_level },
9089 { "log-target", VERB_ANY, 2, 0, log_target },
6ab86319 9090 { "service-watchdogs", VERB_ANY, 2, 0, service_watchdogs },
38fcb7f7
ZJS
9091 { "show-environment", VERB_ANY, 1, VERB_ONLINE_ONLY, show_environment },
9092 { "set-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
9093 { "unset-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
9094 { "import-environment", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, import_environment },
9095 { "halt", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
9096 { "poweroff", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
9097 { "reboot", VERB_ANY, 2, VERB_ONLINE_ONLY, start_system_special },
9098 { "kexec", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
9099 { "suspend", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
9100 { "hibernate", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
9101 { "hybrid-sleep", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
9102 { "suspend-then-hibernate",VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
9103 { "default", VERB_ANY, 1, VERB_ONLINE_ONLY, start_special },
9104 { "rescue", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
9105 { "emergency", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
9106 { "exit", VERB_ANY, 2, VERB_ONLINE_ONLY, start_special },
9107 { "reset-failed", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, reset_failed },
9108 { "enable", 2, VERB_ANY, 0, enable_unit },
9109 { "disable", 2, VERB_ANY, 0, enable_unit },
9110 { "is-enabled", 2, VERB_ANY, 0, unit_is_enabled },
9111 { "reenable", 2, VERB_ANY, 0, enable_unit },
9112 { "preset", 2, VERB_ANY, 0, enable_unit },
9113 { "preset-all", VERB_ANY, 1, 0, preset_all },
9114 { "mask", 2, VERB_ANY, 0, enable_unit },
9115 { "unmask", 2, VERB_ANY, 0, enable_unit },
9116 { "link", 2, VERB_ANY, 0, enable_unit },
9117 { "revert", 2, VERB_ANY, 0, enable_unit },
9118 { "switch-root", 2, VERB_ANY, VERB_ONLINE_ONLY, switch_root },
9119 { "list-dependencies", VERB_ANY, 2, VERB_ONLINE_ONLY, list_dependencies },
9120 { "set-default", 2, 2, 0, set_default },
9121 { "get-default", VERB_ANY, 1, 0, get_default },
9122 { "set-property", 3, VERB_ANY, VERB_ONLINE_ONLY, set_property },
9123 { "is-system-running", VERB_ANY, 1, 0, is_system_running },
9124 { "add-wants", 3, VERB_ANY, 0, add_dependency },
9125 { "add-requires", 3, VERB_ANY, 0, add_dependency },
9126 { "edit", 2, VERB_ANY, VERB_ONLINE_ONLY, edit },
d08e75ed 9127 {}
e449de87 9128 };
7e4249b9 9129
e449de87 9130 return dispatch_verb(argc, argv, verbs, NULL);
e4b61340
LP
9131}
9132
4fbd7192 9133static int reload_with_fallback(void) {
4fbd7192 9134 /* First, try systemd via D-Bus. */
e449de87 9135 if (daemon_reload(0, NULL, NULL) >= 0)
4fbd7192 9136 return 0;
e4b61340
LP
9137
9138 /* Nothing else worked, so let's try signals */
2853b60a 9139 assert(IN_SET(arg_action, ACTION_RELOAD, ACTION_REEXEC));
e4b61340 9140
4a62c710
MS
9141 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0)
9142 return log_error_errno(errno, "kill() failed: %m");
e4b61340
LP
9143
9144 return 0;
9145}
9146
4fbd7192 9147static int start_with_fallback(void) {
4fbd7192 9148 /* First, try systemd via D-Bus. */
2e13c0c3 9149 if (start_unit(0, NULL, NULL) == 0)
4fbd7192 9150 return 0;
e4b61340 9151
2771aaf5 9152#if HAVE_SYSV_COMPAT
2853b60a 9153 /* Nothing else worked, so let's try /dev/initctl */
63a3b3cb 9154 if (talk_initctl(action_to_runlevel()) > 0)
48ec22bc 9155 return 0;
2771aaf5 9156#endif
d55ae9e6 9157
baaa35ad
ZJS
9158 return log_error_errno(SYNTHETIC_ERRNO(EIO),
9159 "Failed to talk to init daemon.");
e4b61340
LP
9160}
9161
477def80 9162static int halt_now(enum action a) {
c01dcddf 9163 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
f03ec2b1 9164 * synced explicitly in advance. */
1ae17672 9165 if (!arg_no_sync && !arg_dry_run)
f3f054f0 9166 (void) sync();
4a3ad399 9167
1ae17672
ZJS
9168 /* Make sure C-A-D is handled by the kernel from this point on... */
9169 if (!arg_dry_run)
9170 (void) reboot(RB_ENABLE_CAD);
e606bb61 9171
4c80c73c 9172 switch (a) {
e606bb61
LP
9173
9174 case ACTION_HALT:
60675884
LP
9175 if (!arg_quiet)
9176 log_info("Halting.");
1ae17672
ZJS
9177 if (arg_dry_run)
9178 return 0;
19578bb2 9179 (void) reboot(RB_HALT_SYSTEM);
477def80 9180 return -errno;
e606bb61
LP
9181
9182 case ACTION_POWEROFF:
60675884
LP
9183 if (!arg_quiet)
9184 log_info("Powering off.");
1ae17672
ZJS
9185 if (arg_dry_run)
9186 return 0;
19578bb2 9187 (void) reboot(RB_POWER_OFF);
477def80 9188 return -errno;
e606bb61 9189
98d52feb 9190 case ACTION_KEXEC:
c01dcddf
LP
9191 case ACTION_REBOOT:
9192 return reboot_with_parameter(REBOOT_FALLBACK |
9193 (arg_quiet ? 0 : REBOOT_LOG) |
9194 (arg_dry_run ? REBOOT_DRY_RUN : 0));
e606bb61 9195
477def80
LP
9196 default:
9197 assert_not_reached("Unknown action.");
9198 }
e606bb61
LP
9199}
9200
56a730fa 9201static int logind_schedule_shutdown(void) {
7f56c3d4 9202
cf9cda44 9203#if ENABLE_LOGIND
4afd3348 9204 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
56a730fa
LP
9205 char date[FORMAT_TIMESTAMP_MAX];
9206 const char *action;
4fbd7192 9207 sd_bus *bus;
56a730fa
LP
9208 int r;
9209
4fbd7192 9210 r = acquire_bus(BUS_FULL, &bus);
56a730fa 9211 if (r < 0)
4fbd7192 9212 return r;
56a730fa
LP
9213
9214 switch (arg_action) {
9215 case ACTION_HALT:
9216 action = "halt";
9217 break;
9218 case ACTION_POWEROFF:
9219 action = "poweroff";
9220 break;
9221 case ACTION_KEXEC:
9222 action = "kexec";
9223 break;
a4420f7b
LP
9224 case ACTION_EXIT:
9225 action = "exit";
9226 break;
9227 case ACTION_REBOOT:
56a730fa
LP
9228 default:
9229 action = "reboot";
9230 break;
9231 }
9232
1ae17672 9233 if (arg_dry_run)
56a730fa
LP
9234 action = strjoina("dry-", action);
9235
d2ad7e1b
ZJS
9236 (void) logind_set_wall_message();
9237
56a730fa 9238 r = sd_bus_call_method(
4fbd7192 9239 bus,
56a730fa
LP
9240 "org.freedesktop.login1",
9241 "/org/freedesktop/login1",
9242 "org.freedesktop.login1.Manager",
9243 "ScheduleShutdown",
9244 &error,
9245 NULL,
9246 "st",
9247 action,
9248 arg_when);
9249 if (r < 0)
9250 return log_warning_errno(r, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error, r));
9251
60675884
LP
9252 if (!arg_quiet)
9253 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date, sizeof(date), arg_when));
56a730fa 9254 return 0;
cf9cda44 9255#else
2f50e59f
LP
9256 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
9257 "Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
807690fb 9258#endif
56a730fa
LP
9259}
9260
4fbd7192 9261static int halt_main(void) {
e4b61340
LP
9262 int r;
9263
4fbd7192 9264 r = logind_check_inhibitors(arg_action);
748ebafa
LP
9265 if (r < 0)
9266 return r;
b37844d3 9267
940bec70
DJL
9268 /* Delayed shutdown requested, and was successful */
9269 if (arg_when > 0 && logind_schedule_shutdown() == 0)
9270 return 0;
9271 /* no delay, or logind failed or is not at all available */
7f96539d 9272
bc8c2f5c 9273 if (geteuid() != 0) {
1ae17672 9274 if (arg_dry_run || arg_force > 0) {
fba868fa 9275 (void) must_be_root();
2ac3930f
IS
9276 return -EPERM;
9277 }
9278
7e59bfcb 9279 /* Try logind if we are a normal user and no special
d35f51ea 9280 * mode applies. Maybe polkit allows us to shutdown
7e59bfcb 9281 * the machine. */
36b69c31 9282 if (IN_SET(arg_action, ACTION_POWEROFF, ACTION_REBOOT, ACTION_HALT)) {
4fbd7192 9283 r = logind_reboot(arg_action);
4c80c73c
KS
9284 if (r >= 0)
9285 return r;
a9085ea3 9286 if (IN_SET(r, -EOPNOTSUPP, -EINPROGRESS))
7f96539d
LP
9287 /* requested operation is not
9288 * supported on the local system or
9289 * already in progress */
a9085ea3
IS
9290 return r;
9291 /* on all other errors, try low-level operation */
4c80c73c 9292 }
bc8c2f5c
LP
9293 }
9294
2955e0d4
GJ
9295 /* In order to minimize the difference between operation with and
9296 * without logind, we explicitly enable non-blocking mode for this,
9297 * as logind's shutdown operations are always non-blocking. */
9298 arg_no_block = true;
9299
1ae17672 9300 if (!arg_dry_run && !arg_force)
4fbd7192 9301 return start_with_fallback();
e4b61340 9302
2ac3930f
IS
9303 assert(geteuid() == 0);
9304
d90e1a30
LP
9305 if (!arg_no_wtmp) {
9306 if (sd_booted() > 0)
9307 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
7e59bfcb
LP
9308 else {
9309 r = utmp_put_shutdown();
9310 if (r < 0)
da927ba9 9311 log_warning_errno(r, "Failed to write utmp record: %m");
7e59bfcb 9312 }
d90e1a30 9313 }
e4b61340 9314
1ae17672 9315 if (arg_dry_run)
e4b61340
LP
9316 return 0;
9317
477def80 9318 r = halt_now(arg_action);
691395d8 9319 return log_error_errno(r, "Failed to reboot: %m");
e4b61340
LP
9320}
9321
9322static int runlevel_main(void) {
9323 int r, runlevel, previous;
9324
729e3769
LP
9325 r = utmp_get_runlevel(&runlevel, &previous);
9326 if (r < 0) {
9327 puts("unknown");
e4b61340
LP
9328 return r;
9329 }
9330
9331 printf("%c %c\n",
9332 previous <= 0 ? 'N' : previous,
9333 runlevel <= 0 ? 'N' : runlevel);
9334
9335 return 0;
9336}
9337
2cf05793 9338static int logind_cancel_shutdown(void) {
349cc4a5 9339#if ENABLE_LOGIND
4afd3348 9340 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 9341 sd_bus *bus;
949d9ce9
LP
9342 int r;
9343
4fbd7192 9344 r = acquire_bus(BUS_FULL, &bus);
949d9ce9 9345 if (r < 0)
4fbd7192 9346 return r;
949d9ce9 9347
4fbd7192 9348 (void) logind_set_wall_message();
949d9ce9
LP
9349
9350 r = sd_bus_call_method(
4fbd7192 9351 bus,
949d9ce9
LP
9352 "org.freedesktop.login1",
9353 "/org/freedesktop/login1",
9354 "org.freedesktop.login1.Manager",
9355 "CancelScheduledShutdown",
9356 &error,
9357 NULL, NULL);
9358 if (r < 0)
9359 return log_warning_errno(r, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error, r));
9360
9361 return 0;
2cf05793 9362#else
2f50e59f
LP
9363 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
9364 "Not compiled with logind support, cannot cancel scheduled shutdowns.");
2cf05793 9365#endif
949d9ce9
LP
9366}
9367
f2a3de01 9368static int run(int argc, char *argv[]) {
f459b602 9369 int r;
e4b61340 9370
a9cdc94f 9371 setlocale(LC_ALL, "");
e4b61340 9372 log_parse_environment();
2396fb04 9373 log_open();
1abaf488
LP
9374
9375 /* The journal merging logic potentially needs a lot of fds. */
9376 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
9377
592705f2 9378 sigbus_install();
e4b61340 9379
184ecaf7
DR
9380 /* Explicitly not on_tty() to avoid setting cached value.
9381 * This becomes relevant for piping output which might be
9382 * ellipsized. */
9383 original_stdout_is_tty = isatty(STDOUT_FILENO);
9384
04ebb595 9385 r = parse_argv(argc, argv);
f459b602 9386 if (r <= 0)
e4b61340 9387 goto finish;
7e4249b9 9388
040524b4 9389 if (arg_action != ACTION_SYSTEMCTL && running_in_chroot() > 0) {
60675884
LP
9390 if (!arg_quiet)
9391 log_info("Running in chroot, ignoring request.");
f459b602 9392 r = 0;
82e23ddd
LP
9393 goto finish;
9394 }
9395
41dd15e4
LP
9396 /* systemctl_main() will print an error message for the bus
9397 * connection, but only if it needs to */
e4b61340
LP
9398
9399 switch (arg_action) {
9400
22f4096c 9401 case ACTION_SYSTEMCTL:
e449de87 9402 r = systemctl_main(argc, argv);
e4b61340 9403 break;
e4b61340 9404
081dc638
AJ
9405 /* Legacy command aliases set arg_action. They provide some fallbacks,
9406 * e.g. to tell sysvinit to reboot after you have installed systemd
9407 * binaries. */
9408
e4b61340
LP
9409 case ACTION_HALT:
9410 case ACTION_POWEROFF:
9411 case ACTION_REBOOT:
5622dde3 9412 case ACTION_KEXEC:
4fbd7192 9413 r = halt_main();
e4b61340
LP
9414 break;
9415
e4b61340
LP
9416 case ACTION_RUNLEVEL2:
9417 case ACTION_RUNLEVEL3:
9418 case ACTION_RUNLEVEL4:
9419 case ACTION_RUNLEVEL5:
9420 case ACTION_RESCUE:
4fbd7192 9421 r = start_with_fallback();
e4b61340 9422 break;
7e4249b9 9423
e4b61340
LP
9424 case ACTION_RELOAD:
9425 case ACTION_REEXEC:
4fbd7192 9426 r = reload_with_fallback();
e4b61340
LP
9427 break;
9428
949d9ce9 9429 case ACTION_CANCEL_SHUTDOWN:
2cf05793 9430 r = logind_cancel_shutdown();
f6144808
LP
9431 break;
9432
eb22ac37 9433 case ACTION_RUNLEVEL:
4f16c1f4
LP
9434 r = runlevel_main();
9435 break;
9436
081dc638
AJ
9437 case ACTION_EXIT:
9438 case ACTION_SUSPEND:
9439 case ACTION_HIBERNATE:
9440 case ACTION_HYBRID_SLEEP:
e68c79db 9441 case ACTION_SUSPEND_THEN_HIBERNATE:
081dc638
AJ
9442 case ACTION_EMERGENCY:
9443 case ACTION_DEFAULT:
9444 /* systemctl verbs with no equivalent in the legacy commands.
9445 * These cannot appear in arg_action. Fall through. */
9446
f459b602 9447 case _ACTION_INVALID:
e4b61340
LP
9448 default:
9449 assert_not_reached("Unknown action");
9450 }
7e4249b9
LP
9451
9452finish:
cf647b69
LP
9453 release_busses();
9454
d1405af3
ZJS
9455 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
9456 return r;
7e4249b9 9457}
d1405af3
ZJS
9458
9459DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);