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