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