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