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