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