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