]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/systemctl/systemctl.c
systemctl: use strv_consume() where appropriate
[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
9a199645
LP
2896static int wait_context_watch(
2897 WaitContext *wait_context,
2898 sd_bus *bus,
2899 const char *name) {
2900
2901 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2902 _cleanup_free_ char *unit_path = NULL;
2903 int r;
2904
2905 assert(wait_context);
2906 assert(name);
2907
2908 log_debug("Watching for property changes of %s", name);
2909 r = sd_bus_call_method(
2910 bus,
2911 "org.freedesktop.systemd1",
2912 "/org/freedesktop/systemd1",
2913 "org.freedesktop.systemd1.Manager",
2914 "RefUnit",
2915 &error,
2916 NULL,
2917 "s", name);
2918 if (r < 0)
2919 return log_error_errno(r, "Failed to add reference to unit %s: %s", name, bus_error_message(&error, r));
2920
2921 unit_path = unit_dbus_path_from_name(name);
2922 if (!unit_path)
2923 return log_oom();
2924
2925 r = set_ensure_allocated(&wait_context->unit_paths, &string_hash_ops);
2926 if (r < 0)
2927 return log_oom();
2928
2929 r = set_put_strdup(wait_context->unit_paths, unit_path);
2930 if (r < 0)
2931 return log_error_errno(r, "Failed to add unit path %s to set: %m", unit_path);
2932
2933 r = sd_bus_match_signal_async(bus,
2934 &wait_context->match,
2935 NULL,
2936 unit_path,
2937 "org.freedesktop.DBus.Properties",
2938 "PropertiesChanged",
2939 on_properties_changed, NULL, wait_context);
2940 if (r < 0)
2941 return log_error_errno(r, "Failed to request match for PropertiesChanged signal: %m");
2942
2943 return 0;
2944}
2945
e4b61340 2946static int start_unit_one(
f459b602 2947 sd_bus *bus,
e4b61340
LP
2948 const char *method,
2949 const char *name,
2950 const char *mode,
f459b602 2951 sd_bus_error *error,
93a08841
MP
2952 BusWaitForJobs *w,
2953 WaitContext *wait_context) {
7e4249b9 2954
4afd3348 2955 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
45fb0699 2956 const char *path;
7e4249b9 2957 int r;
7e4249b9 2958
e4b61340
LP
2959 assert(method);
2960 assert(name);
2961 assert(mode);
22f4096c 2962 assert(error);
7e4249b9 2963
93a08841 2964 if (wait_context) {
9a199645 2965 r = wait_context_watch(wait_context, bus, name);
93a08841 2966 if (r < 0)
9a199645 2967 return r;
93a08841
MP
2968 }
2969
dbc9830c
ZJS
2970 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2971 arg_dry_run ? "Would execute" : "Executing",
1ae17672
ZJS
2972 method, name, mode);
2973 if (arg_dry_run)
2974 return 0;
342641fb 2975
6e646d22 2976 r = sd_bus_call_method(
f22f08cd 2977 bus,
b0193f1c
LP
2978 "org.freedesktop.systemd1",
2979 "/org/freedesktop/systemd1",
2980 "org.freedesktop.systemd1.Manager",
6e646d22
LP
2981 method,
2982 error,
2983 &reply,
2984 "ss", name, mode);
f459b602 2985 if (r < 0) {
39602c39
TA
2986 const char *verb;
2987
033f0ab8
LP
2988 /* There's always a fallback possible for legacy actions. */
2989 if (arg_action != ACTION_SYSTEMCTL)
2990 return r;
67f3c402 2991
39602c39
TA
2992 verb = method_to_verb(method);
2993
ee87525c
FB
2994 log_error("Failed to %s %s: %s", verb, name, bus_error_message(error, r));
2995
2996 if (!sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT) &&
5b464a18
ZJS
2997 !sd_bus_error_has_name(error, BUS_ERROR_UNIT_MASKED) &&
2998 !sd_bus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE))
a6405ca2 2999 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
0b8505b7
RC
3000 arg_scope == UNIT_FILE_SYSTEM ? "system" : "user",
3001 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user",
a6405ca2 3002 name[0] == '-' ? " --" : "",
0b8505b7 3003 name);
ee87525c
FB
3004
3005 return r;
7e4249b9
LP
3006 }
3007
f459b602
MAP
3008 r = sd_bus_message_read(reply, "o", &path);
3009 if (r < 0)
3010 return bus_log_parse_error(r);
45fb0699 3011
e3e0314b 3012 if (need_daemon_reload(bus, name) > 0)
3f36991e 3013 warn_unit_file_changed(name);
45fb0699 3014
ebd011d9
LP
3015 if (w) {
3016 log_debug("Adding %s to the set", path);
3017 r = bus_wait_for_jobs_add(w, path);
cbc9fbd1
LP
3018 if (r < 0)
3019 return log_oom();
e4b61340 3020 }
7e4249b9 3021
46eddbb5 3022 return 0;
7e4249b9
LP
3023}
3024
e3e0314b 3025static int expand_names(sd_bus *bus, char **names, const char* suffix, char ***ret) {
e3e0314b
ZJS
3026 _cleanup_strv_free_ char **mangled = NULL, **globs = NULL;
3027 char **name;
7410616c 3028 int r, i;
e3e0314b 3029
4fbd7192
LP
3030 assert(bus);
3031 assert(ret);
3032
e3e0314b
ZJS
3033 STRV_FOREACH(name, names) {
3034 char *t;
37cbc1d5 3035 UnitNameMangle options = UNIT_NAME_MANGLE_GLOB | (arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN);
e3e0314b 3036
e80733be 3037 if (suffix)
37cbc1d5 3038 r = unit_name_mangle_with_suffix(*name, options, suffix, &t);
e80733be 3039 else
37cbc1d5 3040 r = unit_name_mangle(*name, options, &t);
7410616c
LP
3041 if (r < 0)
3042 return log_error_errno(r, "Failed to mangle name: %m");
e3e0314b
ZJS
3043
3044 if (string_is_glob(t))
6e18964d 3045 r = strv_consume(&globs, t);
e3e0314b 3046 else
6e18964d
ZJS
3047 r = strv_consume(&mangled, t);
3048 if (r < 0)
e3e0314b 3049 return log_oom();
e3e0314b
ZJS
3050 }
3051
3052 /* Query the manager only if any of the names are a glob, since
3053 * this is fairly expensive */
3054 if (!strv_isempty(globs)) {
4afd3348 3055 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
e3e0314b 3056 _cleanup_free_ UnitInfo *unit_infos = NULL;
1b53f64b 3057 size_t allocated, n;
e3e0314b 3058
1238ee09 3059 r = get_unit_list(bus, NULL, globs, &unit_infos, 0, &reply);
e3e0314b
ZJS
3060 if (r < 0)
3061 return r;
3062
1b53f64b
LP
3063 n = strv_length(mangled);
3064 allocated = n + 1;
3065
3066 for (i = 0; i < r; i++) {
3067 if (!GREEDY_REALLOC(mangled, allocated, n+2))
3068 return log_oom();
3069
3070 mangled[n] = strdup(unit_infos[i].id);
3071 if (!mangled[n])
e3e0314b 3072 return log_oom();
1b53f64b
LP
3073
3074 mangled[++n] = NULL;
3075 }
e3e0314b
ZJS
3076 }
3077
1cc6c93a 3078 *ret = TAKE_PTR(mangled);
1238ee09 3079
e3e0314b
ZJS
3080 return 0;
3081}
3082
47a0eaa6
MS
3083static const struct {
3084 const char *target;
3085 const char *verb;
3086 const char *mode;
3087} action_table[_ACTION_MAX] = {
e68c79db
ML
3088 [ACTION_HALT] = { SPECIAL_HALT_TARGET, "halt", "replace-irreversibly" },
3089 [ACTION_POWEROFF] = { SPECIAL_POWEROFF_TARGET, "poweroff", "replace-irreversibly" },
3090 [ACTION_REBOOT] = { SPECIAL_REBOOT_TARGET, "reboot", "replace-irreversibly" },
3091 [ACTION_KEXEC] = { SPECIAL_KEXEC_TARGET, "kexec", "replace-irreversibly" },
3092 [ACTION_RUNLEVEL2] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
3093 [ACTION_RUNLEVEL3] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
3094 [ACTION_RUNLEVEL4] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
3095 [ACTION_RUNLEVEL5] = { SPECIAL_GRAPHICAL_TARGET, NULL, "isolate" },
3096 [ACTION_RESCUE] = { SPECIAL_RESCUE_TARGET, "rescue", "isolate" },
3097 [ACTION_EMERGENCY] = { SPECIAL_EMERGENCY_TARGET, "emergency", "isolate" },
3098 [ACTION_DEFAULT] = { SPECIAL_DEFAULT_TARGET, "default", "isolate" },
3099 [ACTION_EXIT] = { SPECIAL_EXIT_TARGET, "exit", "replace-irreversibly" },
3100 [ACTION_SUSPEND] = { SPECIAL_SUSPEND_TARGET, "suspend", "replace-irreversibly" },
3101 [ACTION_HIBERNATE] = { SPECIAL_HIBERNATE_TARGET, "hibernate", "replace-irreversibly" },
3102 [ACTION_HYBRID_SLEEP] = { SPECIAL_HYBRID_SLEEP_TARGET, "hybrid-sleep", "replace-irreversibly" },
3103 [ACTION_SUSPEND_THEN_HIBERNATE] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET, "suspend-then-hibernate", "replace-irreversibly" },
47a0eaa6
MS
3104};
3105
514f4ef5 3106static enum action verb_to_action(const char *verb) {
47a0eaa6
MS
3107 enum action i;
3108
913c1916 3109 for (i = 0; i < _ACTION_MAX; i++)
f459b602 3110 if (streq_ptr(action_table[i].verb, verb))
47a0eaa6 3111 return i;
514f4ef5 3112
f459b602
MAP
3113 return _ACTION_INVALID;
3114}
e4b61340 3115
e449de87 3116static int start_unit(int argc, char *argv[], void *userdata) {
ebd011d9 3117 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
0e8d9c0c 3118 _cleanup_(wait_context_free) WaitContext wait_context = {};
08073121 3119 const char *method, *mode, *one_name, *suffix = NULL;
416b8801 3120 _cleanup_free_ char **stopped_units = NULL; /* Do not use _cleanup_strv_free_ */
ebd011d9 3121 _cleanup_strv_free_ char **names = NULL;
0e8d9c0c 3122 int r, ret = EXIT_SUCCESS;
4fbd7192 3123 sd_bus *bus;
729e3769 3124 char **name;
e4b61340 3125
f886603b
AJ
3126 if (arg_wait && !STR_IN_SET(argv[0], "start", "restart")) {
3127 log_error("--wait may only be used with the 'start' or 'restart' commands.");
93a08841
MP
3128 return -EINVAL;
3129 }
3130
3131 /* we cannot do sender tracking on the private bus, so we need the full
3132 * one for RefUnit to implement --wait */
3133 r = acquire_bus(arg_wait ? BUS_FULL : BUS_MANAGER, &bus);
4fbd7192
LP
3134 if (r < 0)
3135 return r;
3136
d2ad7e1b 3137 ask_password_agent_open_if_enabled();
8a4b13c5 3138 polkit_agent_open_maybe();
d2ad7e1b 3139
e4b61340 3140 if (arg_action == ACTION_SYSTEMCTL) {
47a0eaa6 3141 enum action action;
e4b61340 3142
e449de87
LP
3143 action = verb_to_action(argv[0]);
3144
913c1916
AJ
3145 if (action != _ACTION_INVALID) {
3146 method = "StartUnit";
3147 mode = action_table[action].mode;
3148 one_name = action_table[action].target;
3149 } else {
3150 if (streq(argv[0], "isolate")) {
3151 method = "StartUnit";
3152 mode = "isolate";
3153
3154 suffix = ".target";
3155 } else {
3156 method = verb_to_method(argv[0]);
3157 mode = arg_job_mode;
3158 }
3159 one_name = NULL;
3160 }
e4b61340 3161 } else {
78ca9099 3162 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
47a0eaa6 3163 assert(action_table[arg_action].target);
913c1916 3164 assert(action_table[arg_action].mode);
e4b61340
LP
3165
3166 method = "StartUnit";
47a0eaa6 3167 mode = action_table[arg_action].mode;
e3e0314b 3168 one_name = action_table[arg_action].target;
514f4ef5
LP
3169 }
3170
8b7ec7bb 3171 if (one_name) {
bea1a013 3172 names = strv_new(one_name);
8b7ec7bb
LP
3173 if (!names)
3174 return log_oom();
3175 } else {
e449de87 3176 r = expand_names(bus, strv_skip(argv, 1), suffix, &names);
e3e0314b 3177 if (r < 0)
691395d8 3178 return log_error_errno(r, "Failed to expand names: %m");
e3e0314b 3179 }
b6520546 3180
6e905d93 3181 if (!arg_no_block) {
ebd011d9 3182 r = bus_wait_for_jobs_new(bus, &w);
f647962d
MS
3183 if (r < 0)
3184 return log_error_errno(r, "Could not watch jobs: %m");
e4b61340
LP
3185 }
3186
93a08841 3187 if (arg_wait) {
31b2cd5d 3188 r = sd_bus_call_method_async(
93a08841 3189 bus,
31b2cd5d 3190 NULL,
93a08841
MP
3191 "org.freedesktop.systemd1",
3192 "/org/freedesktop/systemd1",
3193 "org.freedesktop.systemd1.Manager",
3194 "Subscribe",
31b2cd5d
LP
3195 NULL, NULL,
3196 NULL);
93a08841 3197 if (r < 0)
31b2cd5d 3198 return log_error_errno(r, "Failed to enable subscription: %m");
93a08841
MP
3199 r = sd_event_default(&wait_context.event);
3200 if (r < 0)
3201 return log_error_errno(r, "Failed to allocate event loop: %m");
3202 r = sd_bus_attach_event(bus, wait_context.event, 0);
3203 if (r < 0)
3204 return log_error_errno(r, "Failed to attach bus to event loop: %m");
3205 }
3206
b6520546 3207 STRV_FOREACH(name, names) {
4afd3348 3208 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
f459b602 3209
0e8d9c0c
LP
3210 r = start_unit_one(bus, method, *name, mode, &error, w, arg_wait ? &wait_context : NULL);
3211 if (ret == EXIT_SUCCESS && r < 0)
3212 ret = translate_bus_error_to_exit_status(r, &error);
416b8801
YW
3213
3214 if (r >= 0 && streq(method, "StopUnit")) {
3215 r = strv_push(&stopped_units, *name);
3216 if (r < 0)
3217 return log_oom();
3218 }
e4b61340
LP
3219 }
3220
67f3c402 3221 if (!arg_no_block) {
c11bda1e 3222 const char* extra_args[4] = {};
0e8d9c0c 3223 int arg_count = 0;
4524439e 3224
4524439e
ZJS
3225 if (arg_scope != UNIT_FILE_SYSTEM)
3226 extra_args[arg_count++] = "--user";
3227
3228 assert(IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_REMOTE, BUS_TRANSPORT_MACHINE));
3229 if (arg_transport == BUS_TRANSPORT_REMOTE) {
3230 extra_args[arg_count++] = "-H";
3231 extra_args[arg_count++] = arg_host;
3232 } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
3233 extra_args[arg_count++] = "-M";
3234 extra_args[arg_count++] = arg_host;
3235 }
f459b602 3236
0e8d9c0c
LP
3237 r = bus_wait_for_jobs(w, arg_quiet, extra_args);
3238 if (r < 0)
3239 return r;
49111a70
ZJS
3240
3241 /* When stopping units, warn if they can still be triggered by
3242 * another active unit (socket, path, timer) */
416b8801
YW
3243 if (!arg_quiet)
3244 STRV_FOREACH(name, stopped_units)
86f004fb 3245 (void) check_triggering_units(bus, *name);
67f3c402 3246 }
514f4ef5 3247
0e8d9c0c
LP
3248 if (ret == EXIT_SUCCESS && arg_wait && !set_isempty(wait_context.unit_paths)) {
3249 r = sd_event_loop(wait_context.event);
3250 if (r < 0)
3251 return log_error_errno(r, "Failed to run event loop: %m");
93a08841 3252 if (wait_context.any_failed)
0e8d9c0c 3253 ret = EXIT_FAILURE;
93a08841
MP
3254 }
3255
0e8d9c0c 3256 return ret;
e4b61340
LP
3257}
3258
349cc4a5 3259#if ENABLE_LOGIND
4fbd7192 3260static int logind_set_wall_message(void) {
4afd3348 3261 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 3262 sd_bus *bus;
f2d11d35
LP
3263 _cleanup_free_ char *m = NULL;
3264 int r;
3265
4fbd7192
LP
3266 r = acquire_bus(BUS_FULL, &bus);
3267 if (r < 0)
3268 return r;
f2d11d35
LP
3269
3270 m = strv_join(arg_wall, " ");
3271 if (!m)
3272 return log_oom();
3273
dbc9830c
ZJS
3274 log_debug("%s wall message \"%s\".", arg_dry_run ? "Would set" : "Setting", m);
3275 if (arg_dry_run)
3276 return 0;
3277
f2d11d35
LP
3278 r = sd_bus_call_method(
3279 bus,
3280 "org.freedesktop.login1",
3281 "/org/freedesktop/login1",
3282 "org.freedesktop.login1.Manager",
3283 "SetWallMessage",
3284 &error,
3285 NULL,
3286 "sb",
3287 m,
3288 !arg_no_wall);
3289
3290 if (r < 0)
3291 return log_warning_errno(r, "Failed to set wall message, ignoring: %s", bus_error_message(&error, r));
f2d11d35
LP
3292 return 0;
3293}
79f1c8f6 3294#endif
f2d11d35 3295
7e59bfcb 3296/* Ask systemd-logind, which might grant access to unprivileged users
d35f51ea 3297 * through polkit */
4fbd7192 3298static int logind_reboot(enum action a) {
349cc4a5 3299#if ENABLE_LOGIND
4afd3348 3300 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
58158dc7 3301 const char *method, *description;
4fbd7192 3302 sd_bus *bus;
f459b602 3303 int r;
4c80c73c 3304
4fbd7192
LP
3305 r = acquire_bus(BUS_FULL, &bus);
3306 if (r < 0)
3307 return r;
f2d11d35 3308
4c80c73c
KS
3309 switch (a) {
3310
36b69c31
LP
3311 case ACTION_POWEROFF:
3312 method = "PowerOff";
3313 description = "power off system";
3314 break;
3315
4c80c73c
KS
3316 case ACTION_REBOOT:
3317 method = "Reboot";
58158dc7 3318 description = "reboot system";
4c80c73c
KS
3319 break;
3320
36b69c31
LP
3321 case ACTION_HALT:
3322 method = "Halt";
3323 description = "halt system";
4c80c73c
KS
3324 break;
3325
d889a206
LP
3326 case ACTION_SUSPEND:
3327 method = "Suspend";
58158dc7 3328 description = "suspend system";
d889a206
LP
3329 break;
3330
3331 case ACTION_HIBERNATE:
3332 method = "Hibernate";
58158dc7 3333 description = "hibernate system";
d889a206
LP
3334 break;
3335
6524990f
LP
3336 case ACTION_HYBRID_SLEEP:
3337 method = "HybridSleep";
58158dc7 3338 description = "put system into hybrid sleep";
6524990f
LP
3339 break;
3340
e68c79db
ML
3341 case ACTION_SUSPEND_THEN_HIBERNATE:
3342 method = "SuspendThenHibernate";
c58493c0
ML
3343 description = "put system into suspend followed by hibernate";
3344 break;
3345
4c80c73c
KS
3346 default:
3347 return -EINVAL;
3348 }
3349
8a4b13c5 3350 polkit_agent_open_maybe();
d2ad7e1b
ZJS
3351 (void) logind_set_wall_message();
3352
dbc9830c
ZJS
3353 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run ? "Would execute" : "Executing", method);
3354 if (arg_dry_run)
3355 return 0;
3356
f459b602 3357 r = sd_bus_call_method(
f22f08cd
SP
3358 bus,
3359 "org.freedesktop.login1",
3360 "/org/freedesktop/login1",
3361 "org.freedesktop.login1.Manager",
3362 method,
f459b602 3363 &error,
f22f08cd 3364 NULL,
342641fb 3365 "b", arg_ask_password);
f459b602 3366 if (r < 0)
691395d8 3367 return log_error_errno(r, "Failed to %s via logind: %s", description, bus_error_message(&error, r));
f459b602 3368
691395d8 3369 return 0;
4c80c73c
KS
3370#else
3371 return -ENOSYS;
3372#endif
3373}
3374
4fbd7192 3375static int logind_check_inhibitors(enum action a) {
349cc4a5 3376#if ENABLE_LOGIND
4afd3348 3377 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
59164be4 3378 _cleanup_strv_free_ char **sessions = NULL;
f459b602
MAP
3379 const char *what, *who, *why, *mode;
3380 uint32_t uid, pid;
4fbd7192 3381 sd_bus *bus;
f459b602 3382 unsigned c = 0;
59164be4 3383 char **s;
f459b602 3384 int r;
b37844d3 3385
748ebafa
LP
3386 if (arg_ignore_inhibitors || arg_force > 0)
3387 return 0;
3388
3389 if (arg_when > 0)
3390 return 0;
3391
3392 if (geteuid() == 0)
b37844d3
LP
3393 return 0;
3394
3395 if (!on_tty())
3396 return 0;
e08ab379
LP
3397
3398 if (arg_transport != BUS_TRANSPORT_LOCAL)
3399 return 0;
b37844d3 3400
4fbd7192
LP
3401 r = acquire_bus(BUS_FULL, &bus);
3402 if (r < 0)
3403 return r;
3404
f459b602 3405 r = sd_bus_call_method(
b37844d3
LP
3406 bus,
3407 "org.freedesktop.login1",
3408 "/org/freedesktop/login1",
3409 "org.freedesktop.login1.Manager",
3410 "ListInhibitors",
b37844d3 3411 NULL,
f459b602
MAP
3412 &reply,
3413 NULL);
b37844d3
LP
3414 if (r < 0)
3415 /* If logind is not around, then there are no inhibitors... */
3416 return 0;
3417
4aa2beac 3418 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
f459b602
MAP
3419 if (r < 0)
3420 return bus_log_parse_error(r);
b37844d3 3421
4aa2beac 3422 while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
59164be4 3423 _cleanup_free_ char *comm = NULL, *user = NULL;
f459b602 3424 _cleanup_strv_free_ char **sv = NULL;
b37844d3
LP
3425
3426 if (!streq(mode, "block"))
f459b602 3427 continue;
b37844d3
LP
3428
3429 sv = strv_split(what, ":");
3430 if (!sv)
3431 return log_oom();
3432
ee043777 3433 if (!pid_is_valid((pid_t) pid)) {
72b3f82e 3434 log_error("Invalid PID "PID_FMT".", (pid_t) pid);
ee043777
LP
3435 return -ERANGE;
3436 }
d028e018 3437
b37844d3 3438 if (!strv_contains(sv,
4c315c2c
IS
3439 IN_SET(a,
3440 ACTION_HALT,
3441 ACTION_POWEROFF,
3442 ACTION_REBOOT,
3443 ACTION_KEXEC) ? "shutdown" : "sleep"))
f459b602 3444 continue;
b37844d3
LP
3445
3446 get_process_comm(pid, &comm);
59164be4 3447 user = uid_to_name(uid);
f459b602 3448
de0671ee 3449 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT" \"%s\", user %s), reason is \"%s\".",
d028e018 3450 who, (pid_t) pid, strna(comm), strna(user), why);
b37844d3 3451
f459b602 3452 c++;
b37844d3 3453 }
f459b602
MAP
3454 if (r < 0)
3455 return bus_log_parse_error(r);
b37844d3 3456
f459b602
MAP
3457 r = sd_bus_message_exit_container(reply);
3458 if (r < 0)
3459 return bus_log_parse_error(r);
b37844d3 3460
59164be4
LP
3461 /* Check for current sessions */
3462 sd_get_sessions(&sessions);
3463 STRV_FOREACH(s, sessions) {
59164be4
LP
3464 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
3465
3466 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
3467 continue;
3468
3469 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
3470 continue;
3471
28abce5d 3472 if (sd_session_get_type(*s, &type) < 0 || !STR_IN_SET(type, "x11", "wayland", "tty", "mir"))
59164be4
LP
3473 continue;
3474
3475 sd_session_get_tty(*s, &tty);
3476 sd_session_get_seat(*s, &seat);
3477 sd_session_get_service(*s, &service);
3478 user = uid_to_name(uid);
3479
3480 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
3481 c++;
3482 }
3483
b37844d3
LP
3484 if (c <= 0)
3485 return 0;
3486
59164be4 3487 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
47a0eaa6 3488 action_table[a].verb);
b37844d3
LP
3489
3490 return -EPERM;
3491#else
3492 return 0;
3493#endif
3494}
3495
97af80c5
LP
3496static int prepare_firmware_setup(void) {
3497
3498 if (!arg_firmware_setup)
3499 return 0;
3500
349cc4a5 3501#if ENABLE_LOGIND
4afd3348 3502 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 3503 sd_bus *bus;
a4921cf4
JJ
3504 int r;
3505
4fbd7192
LP
3506 r = acquire_bus(BUS_FULL, &bus);
3507 if (r < 0)
3508 return r;
a4921cf4 3509
a4921cf4
JJ
3510 r = sd_bus_call_method(
3511 bus,
3512 "org.freedesktop.login1",
3513 "/org/freedesktop/login1",
3514 "org.freedesktop.login1.Manager",
3515 "SetRebootToFirmwareSetup",
3516 &error,
3517 NULL,
3518 "b", true);
4fbd7192
LP
3519 if (r < 0)
3520 return log_error_errno(r, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error, r));
a4921cf4
JJ
3521
3522 return 0;
3523#else
97af80c5 3524 log_error("Booting into firmware setup not supported.");
4fbd7192 3525 return -ENOSYS;
a4921cf4
JJ
3526#endif
3527}
3528
97af80c5
LP
3529static int prepare_boot_loader_menu(void) {
3530
3531 if (arg_boot_loader_menu == USEC_INFINITY)
3532 return 0;
3533
3534#if ENABLE_LOGIND
3535 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3536 sd_bus *bus;
4fbd7192
LP
3537 int r;
3538
97af80c5
LP
3539 r = acquire_bus(BUS_FULL, &bus);
3540 if (r < 0)
3541 return r;
3542
3543 r = sd_bus_call_method(
3544 bus,
3545 "org.freedesktop.login1",
3546 "/org/freedesktop/login1",
3547 "org.freedesktop.login1.Manager",
3548 "SetRebootToBootLoaderMenu",
3549 &error,
3550 NULL,
3551 "t", arg_boot_loader_menu);
3552 if (r < 0)
3553 return log_error_errno(r, "Cannot indicate to boot loader to enter boot loader entry menu: %s", bus_error_message(&error, r));
3554
3555 return 0;
3556#else
3557 log_error("Booting into boot loader menu not supported.");
3558 return -ENOSYS;
3559#endif
3560}
3561
3562static int prepare_boot_loader_entry(void) {
3563
3564 if (!arg_boot_loader_entry)
4fbd7192
LP
3565 return 0;
3566
97af80c5
LP
3567#if ENABLE_LOGIND
3568 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3569 sd_bus *bus;
3570 int r;
4fbd7192 3571
97af80c5
LP
3572 r = acquire_bus(BUS_FULL, &bus);
3573 if (r < 0)
3574 return r;
3575
3576 r = sd_bus_call_method(
3577 bus,
3578 "org.freedesktop.login1",
3579 "/org/freedesktop/login1",
3580 "org.freedesktop.login1.Manager",
3581 "SetRebootToBootLoaderEntry",
3582 &error,
3583 NULL,
3584 "s", arg_boot_loader_entry);
3585 if (r < 0)
3586 return log_error_errno(r, "Cannot set boot into loader entry '%s': %s", arg_boot_loader_entry, bus_error_message(&error, r));
4fbd7192 3587
97af80c5
LP
3588 return 0;
3589#else
3590 log_error("Booting into boot loader entry not supported.");
3591 return -ENOSYS;
3592#endif
4fbd7192
LP
3593}
3594
4bb2e9d4
ZJS
3595static int load_kexec_kernel(void) {
3596 _cleanup_(boot_config_free) BootConfig config = {};
43b736a8 3597 _cleanup_free_ char *kernel = NULL, *initrd = NULL, *options = NULL;
4bb2e9d4
ZJS
3598 const BootEntry *e;
3599 pid_t pid;
3600 int r;
3601
3602 if (kexec_loaded()) {
3603 log_debug("Kexec kernel already loaded.");
3604 return 0;
3605 }
3606
c0d73214
ZJS
3607 if (access(KEXEC, X_OK) < 0)
3608 return log_error_errno(errno, KEXEC" is not available: %m");
3609
38bd74d6 3610 r = boot_entries_load_config_auto(NULL, NULL, &config);
cc5957dc
LP
3611 if (r == -ENOKEY) /* The call doesn't log about ENOKEY, let's do so here. */
3612 return log_error_errno(r, "Cannot find the ESP partition mount point.");
4bb2e9d4 3613 if (r < 0)
1b20d889 3614 return r;
4bb2e9d4 3615
38bd74d6
LP
3616 e = boot_config_default_entry(&config);
3617 if (!e)
3618 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
3619 "No boot loader entry suitable as default, refusing to guess.");
3620
3621 log_debug("Found default boot loader entry in file \"%s\"", e->path);
3622
78c38fe7
LP
3623 if (!e->kernel)
3624 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3625 "Boot entry does not refer to Linux kernel, which is not supported currently.");
8a1ef3bf 3626 if (strv_length(e->initrd) > 1)
0f88d829 3627 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
8a1ef3bf 3628 "Boot entry specifies multiple initrds, which is not supported currently.");
4bb2e9d4 3629
43b736a8 3630 kernel = path_join(e->root, e->kernel);
9fc32cd9
LP
3631 if (!kernel)
3632 return log_oom();
3633
3634 if (!strv_isempty(e->initrd)) {
0f88d829 3635 initrd = path_join(e->root, e->initrd[0]);
9fc32cd9
LP
3636 if (!initrd)
3637 return log_oom();
3638 }
3639
4bb2e9d4
ZJS
3640 options = strv_join(e->options, " ");
3641 if (!options)
3642 return log_oom();
3643
cd086a01
ZJS
3644 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
3645 "%s "KEXEC" --load \"%s\" --append \"%s\"%s%s%s",
3646 arg_dry_run ? "Would run" : "Running",
3647 kernel,
3648 options,
3649 initrd ? " --initrd \"" : NULL, strempty(initrd), initrd ? "\"" : "");
4bb2e9d4
ZJS
3650 if (arg_dry_run)
3651 return 0;
3652
c943e95f 3653 r = safe_fork("(kexec)", FORK_WAIT|FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid);
4c253ed1 3654 if (r < 0)
b6e1fff1 3655 return r;
4c253ed1 3656 if (r == 0) {
4bb2e9d4
ZJS
3657 const char* const args[] = {
3658 KEXEC,
3659 "--load", kernel,
3660 "--append", options,
3661 initrd ? "--initrd" : NULL, initrd,
c943e95f
LP
3662 NULL
3663 };
4bb2e9d4
ZJS
3664
3665 /* Child */
4bb2e9d4
ZJS
3666 execv(args[0], (char * const *) args);
3667 _exit(EXIT_FAILURE);
4c253ed1
LP
3668 }
3669
df685d57 3670 return 0;
4bb2e9d4
ZJS
3671}
3672
57ab9006 3673static int set_exit_code(uint8_t code) {
4afd3348 3674 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
57ab9006
LP
3675 sd_bus *bus;
3676 int r;
3677
3678 r = acquire_bus(BUS_MANAGER, &bus);
3679 if (r < 0)
3680 return r;
3681
3682 r = sd_bus_call_method(
3683 bus,
3684 "org.freedesktop.systemd1",
3685 "/org/freedesktop/systemd1",
3686 "org.freedesktop.systemd1.Manager",
3687 "SetExitCode",
3688 &error,
3689 NULL,
3690 "y", code);
3691 if (r < 0)
af3d8113 3692 return log_error_errno(r, "Failed to set exit code: %s", bus_error_message(&error, r));
57ab9006
LP
3693
3694 return 0;
3695}
3696
e449de87 3697static int start_special(int argc, char *argv[], void *userdata) {
4c80c73c 3698 enum action a;
983d9c90 3699 int r;
2b0f4e6f
ZJS
3700 bool termination_action; /* an action that terminates the manager,
3701 * can be performed also by signal. */
983d9c90 3702
e449de87 3703 assert(argv);
514f4ef5 3704
e449de87 3705 a = verb_to_action(argv[0]);
4c80c73c 3706
4fbd7192 3707 r = logind_check_inhibitors(a);
748ebafa
LP
3708 if (r < 0)
3709 return r;
3710
fba868fa
LP
3711 if (arg_force >= 2) {
3712 r = must_be_root();
3713 if (r < 0)
3714 return r;
c32b90de
LP
3715 }
3716
4fbd7192 3717 r = prepare_firmware_setup();
a4921cf4
JJ
3718 if (r < 0)
3719 return r;
5bdf2243 3720
97af80c5
LP
3721 r = prepare_boot_loader_menu();
3722 if (r < 0)
3723 return r;
3724
3725 r = prepare_boot_loader_entry();
3726 if (r < 0)
3727 return r;
3728
e449de87 3729 if (a == ACTION_REBOOT && argc > 1) {
27c06cb5 3730 r = update_reboot_parameter_and_warn(argv[1]);
b986229e
SW
3731 if (r < 0)
3732 return r;
57ab9006 3733
4bb2e9d4
ZJS
3734 } else if (a == ACTION_KEXEC) {
3735 r = load_kexec_kernel();
d23b5ce2
ZJS
3736 if (r < 0 && arg_force >= 1)
3737 log_notice("Failed to load kexec kernel, continuing without.");
3738 else if (r < 0)
4bb2e9d4
ZJS
3739 return r;
3740
e449de87 3741 } else if (a == ACTION_EXIT && argc > 1) {
7bbb5359 3742 uint8_t code;
287419c1 3743
57ab9006
LP
3744 /* If the exit code is not given on the command line,
3745 * don't reset it to zero: just keep it as it might
3746 * have been set previously. */
287419c1 3747
e449de87 3748 r = safe_atou8(argv[1], &code);
4fbd7192 3749 if (r < 0)
57ab9006 3750 return log_error_errno(r, "Invalid exit code.");
4fbd7192 3751
57ab9006 3752 r = set_exit_code(code);
691395d8 3753 if (r < 0)
57ab9006 3754 return r;
b986229e
SW
3755 }
3756
2b0f4e6f
ZJS
3757 termination_action = IN_SET(a,
3758 ACTION_HALT,
3759 ACTION_POWEROFF,
3760 ACTION_REBOOT);
3761 if (termination_action && arg_force >= 2)
477def80 3762 return halt_now(a);
e606bb61 3763
7e59bfcb 3764 if (arg_force >= 1 &&
5955df2c 3765 (termination_action || IN_SET(a, ACTION_KEXEC, ACTION_EXIT)))
2b0f4e6f
ZJS
3766 r = trivial_method(argc, argv, userdata);
3767 else {
3768 /* First try logind, to allow authentication with polkit */
3769 if (IN_SET(a,
3770 ACTION_POWEROFF,
3771 ACTION_REBOOT,
36b69c31 3772 ACTION_HALT,
2b0f4e6f
ZJS
3773 ACTION_SUSPEND,
3774 ACTION_HIBERNATE,
c58493c0 3775 ACTION_HYBRID_SLEEP,
e68c79db 3776 ACTION_SUSPEND_THEN_HIBERNATE)) {
2b0f4e6f
ZJS
3777
3778 r = logind_reboot(a);
3779 if (r >= 0)
3780 return r;
3781 if (IN_SET(r, -EOPNOTSUPP, -EINPROGRESS))
3782 /* requested operation is not supported or already in progress */
3783 return r;
20b09ca7 3784
130246d2
LP
3785 /* On all other errors, try low-level operation. In order to minimize the difference between
3786 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3787 * logind's shutdown operations are always non-blocking. */
3788
3789 arg_no_block = true;
3790
3791 } else if (IN_SET(a, ACTION_EXIT, ACTION_KEXEC))
3792 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3793 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3794 arg_no_block = true;
7089051f 3795
2b0f4e6f 3796 r = start_unit(argc, argv, userdata);
4c80c73c 3797 }
983d9c90 3798
2b0f4e6f
ZJS
3799 if (termination_action && arg_force < 2 &&
3800 IN_SET(r, -ENOENT, -ETIMEDOUT))
cc7de2ba 3801 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
2b0f4e6f
ZJS
3802
3803 return r;
514f4ef5
LP
3804}
3805
988b3b17
ZJS
3806static int start_system_special(int argc, char *argv[], void *userdata) {
3807 /* Like start_special above, but raises an error when running in user mode */
3808
baaa35ad
ZJS
3809 if (arg_scope != UNIT_FILE_SYSTEM)
3810 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3811 "Bad action for %s mode.",
3812 arg_scope == UNIT_FILE_GLOBAL ? "--global" : "--user");
988b3b17
ZJS
3813
3814 return start_special(argc, argv, userdata);
3815}
3816
fa0d5878 3817static int check_unit_generic(int code, const UnitActiveState good_states[], int nb_states, char **args) {
e3e0314b 3818 _cleanup_strv_free_ char **names = NULL;
fa0d5878 3819 UnitActiveState active_state;
4fbd7192 3820 sd_bus *bus;
729e3769 3821 char **name;
fa0d5878 3822 int r, i;
d60f6ad0 3823 bool found = false;
0183528f 3824
4fbd7192
LP
3825 r = acquire_bus(BUS_MANAGER, &bus);
3826 if (r < 0)
3827 return r;
3828
e3e0314b 3829 r = expand_names(bus, args, NULL, &names);
f647962d
MS
3830 if (r < 0)
3831 return log_error_errno(r, "Failed to expand names: %m");
e3e0314b
ZJS
3832
3833 STRV_FOREACH(name, names) {
fa0d5878
BR
3834 r = get_state_one_unit(bus, *name, &active_state);
3835 if (r < 0)
3836 return r;
3837
3838 if (!arg_quiet)
3839 puts(unit_active_state_to_string(active_state));
60f9ba0b 3840
fa0d5878
BR
3841 for (i = 0; i < nb_states; ++i)
3842 if (good_states[i] == active_state)
3843 found = true;
1a0fce45
TA
3844 }
3845
d60f6ad0
LN
3846 /* use the given return code for the case that we won't find
3847 * any unit which matches the list */
3848 return found ? 0 : code;
1a0fce45
TA
3849}
3850
e449de87 3851static int check_unit_active(int argc, char *argv[], void *userdata) {
9897b09b
LP
3852 static const UnitActiveState states[] = {
3853 UNIT_ACTIVE,
3854 UNIT_RELOADING,
3855 };
3856
e3e0314b 3857 /* According to LSB: 3, "program is not running" */
b613907e 3858 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING, states, ELEMENTSOF(states), strv_skip(argv, 1));
e3e0314b 3859}
0183528f 3860
e449de87 3861static int check_unit_failed(int argc, char *argv[], void *userdata) {
9897b09b
LP
3862 static const UnitActiveState states[] = {
3863 UNIT_FAILED,
3864 };
3865
b613907e 3866 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS, states, ELEMENTSOF(states), strv_skip(argv, 1));
48220598
LP
3867}
3868
e449de87 3869static int kill_unit(int argc, char *argv[], void *userdata) {
e3e0314b 3870 _cleanup_strv_free_ char **names = NULL;
ac5e3a50 3871 char *kill_who = NULL, **name;
4fbd7192 3872 sd_bus *bus;
e3e0314b 3873 int r, q;
8a0867d6 3874
4fbd7192
LP
3875 r = acquire_bus(BUS_MANAGER, &bus);
3876 if (r < 0)
3877 return r;
3878
8a4b13c5 3879 polkit_agent_open_maybe();
d2ad7e1b 3880
8a0867d6
LP
3881 if (!arg_kill_who)
3882 arg_kill_who = "all";
3883
ac5e3a50
JS
3884 /* --fail was specified */
3885 if (streq(arg_job_mode, "fail"))
81d62103 3886 kill_who = strjoina(arg_kill_who, "-fail");
ac5e3a50 3887
e449de87 3888 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
e3e0314b 3889 if (r < 0)
691395d8 3890 return log_error_errno(r, "Failed to expand names: %m");
60f9ba0b 3891
e3e0314b 3892 STRV_FOREACH(name, names) {
4afd3348 3893 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
342641fb 3894
6e646d22 3895 q = sd_bus_call_method(
f22f08cd 3896 bus,
b0193f1c
LP
3897 "org.freedesktop.systemd1",
3898 "/org/freedesktop/systemd1",
3899 "org.freedesktop.systemd1.Manager",
6e646d22
LP
3900 "KillUnit",
3901 &error,
3902 NULL,
169d7fb6 3903 "ssi", *name, kill_who ? kill_who : arg_kill_who, arg_signal);
e3e0314b 3904 if (q < 0) {
169d7fb6 3905 log_error_errno(q, "Failed to kill unit %s: %s", *name, bus_error_message(&error, q));
e3e0314b
ZJS
3906 if (r == 0)
3907 r = q;
f459b602 3908 }
8a0867d6 3909 }
f459b602 3910
e3e0314b 3911 return r;
8a0867d6
LP
3912}
3913
582a507f 3914typedef struct ExecStatusInfo {
0129173a
LP
3915 char *name;
3916
582a507f
LP
3917 char *path;
3918 char **argv;
3919
b708e7ce
LP
3920 bool ignore;
3921
582a507f
LP
3922 usec_t start_timestamp;
3923 usec_t exit_timestamp;
3924 pid_t pid;
3925 int code;
3926 int status;
3927
3928 LIST_FIELDS(struct ExecStatusInfo, exec);
3929} ExecStatusInfo;
3930
3931static void exec_status_info_free(ExecStatusInfo *i) {
3932 assert(i);
3933
0129173a 3934 free(i->name);
582a507f
LP
3935 free(i->path);
3936 strv_free(i->argv);
3937 free(i);
3938}
3939
f459b602 3940static int exec_status_info_deserialize(sd_bus_message *m, ExecStatusInfo *i) {
b21a0ef8 3941 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
f459b602 3942 const char *path;
582a507f
LP
3943 uint32_t pid;
3944 int32_t code, status;
f459b602 3945 int ignore, r;
582a507f 3946
f459b602 3947 assert(m);
582a507f 3948 assert(i);
582a507f 3949
f459b602
MAP
3950 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_STRUCT, "sasbttttuii");
3951 if (r < 0)
3952 return bus_log_parse_error(r);
3953 else if (r == 0)
3954 return 0;
582a507f 3955
f459b602
MAP
3956 r = sd_bus_message_read(m, "s", &path);
3957 if (r < 0)
3958 return bus_log_parse_error(r);
582a507f 3959
f84190d8
LP
3960 i->path = strdup(path);
3961 if (!i->path)
f459b602 3962 return log_oom();
582a507f 3963
f459b602
MAP
3964 r = sd_bus_message_read_strv(m, &i->argv);
3965 if (r < 0)
3966 return bus_log_parse_error(r);
3967
3968 r = sd_bus_message_read(m,
3969 "bttttuii",
3970 &ignore,
3971 &start_timestamp, &start_timestamp_monotonic,
3972 &exit_timestamp, &exit_timestamp_monotonic,
3973 &pid,
3974 &code, &status);
3975 if (r < 0)
3976 return bus_log_parse_error(r);
582a507f 3977
b708e7ce 3978 i->ignore = ignore;
582a507f
LP
3979 i->start_timestamp = (usec_t) start_timestamp;
3980 i->exit_timestamp = (usec_t) exit_timestamp;
3981 i->pid = (pid_t) pid;
3982 i->code = code;
3983 i->status = status;
3984
f459b602
MAP
3985 r = sd_bus_message_exit_container(m);
3986 if (r < 0)
3987 return bus_log_parse_error(r);
3988
3989 return 1;
582a507f
LP
3990}
3991
d5db7fe6
WC
3992typedef struct UnitCondition {
3993 char *name;
b1ed76ae 3994 char *param;
d5db7fe6
WC
3995 bool trigger;
3996 bool negate;
d5db7fe6
WC
3997 int tristate;
3998
b1ed76ae 3999 LIST_FIELDS(struct UnitCondition, conditions);
d5db7fe6
WC
4000} UnitCondition;
4001
4002static void unit_condition_free(UnitCondition *c) {
9bb71940
ZJS
4003 if (!c)
4004 return;
d5db7fe6
WC
4005
4006 free(c->name);
4007 free(c->param);
4008 free(c);
4009}
4010
9bb71940
ZJS
4011DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition*, unit_condition_free);
4012
61cbdc4b
LP
4013typedef struct UnitStatusInfo {
4014 const char *id;
4015 const char *load_state;
4016 const char *active_state;
4017 const char *sub_state;
a4375746 4018 const char *unit_file_state;
d2dc52db 4019 const char *unit_file_preset;
61cbdc4b
LP
4020
4021 const char *description;
4a9e2fff 4022 const char *following;
61cbdc4b 4023
49dbfa7b
LP
4024 char **documentation;
4025
1b64d026
LP
4026 const char *fragment_path;
4027 const char *source_path;
4ad49000 4028 const char *control_group;
61cbdc4b 4029
76d14b87
OS
4030 char **dropin_paths;
4031
9f39404c 4032 const char *load_error;
f42806df 4033 const char *result;
9f39404c 4034
584be568 4035 usec_t inactive_exit_timestamp;
df50185b 4036 usec_t inactive_exit_timestamp_monotonic;
584be568
LP
4037 usec_t active_enter_timestamp;
4038 usec_t active_exit_timestamp;
4039 usec_t inactive_enter_timestamp;
4040
45fb0699 4041 bool need_daemon_reload;
055ef36b 4042 bool transient;
45fb0699 4043
61cbdc4b
LP
4044 /* Service */
4045 pid_t main_pid;
4046 pid_t control_pid;
4047 const char *status_text;
175728c4 4048 const char *pid_file;
d06dacd0 4049 bool running:1;
b4af5a80 4050 int status_errno;
61cbdc4b
LP
4051
4052 usec_t start_timestamp;
4053 usec_t exit_timestamp;
4054
4055 int exit_code, exit_status;
4056
90bbc946
LP
4057 usec_t condition_timestamp;
4058 bool condition_result;
b1ed76ae 4059 LIST_HEAD(UnitCondition, conditions);
59fccdc5
LP
4060
4061 usec_t assert_timestamp;
4062 bool assert_result;
4063 bool failed_assert_trigger;
4064 bool failed_assert_negate;
4065 const char *failed_assert;
4066 const char *failed_assert_parameter;
601b0842
GS
4067 usec_t next_elapse_real;
4068 usec_t next_elapse_monotonic;
90bbc946 4069
61cbdc4b
LP
4070 /* Socket */
4071 unsigned n_accepted;
4072 unsigned n_connections;
a98f7575 4073 unsigned n_refused;
b8131a87 4074 bool accept;
61cbdc4b 4075
13160134 4076 /* Pairs of type, path */
67419600
OS
4077 char **listen;
4078
61cbdc4b
LP
4079 /* Device */
4080 const char *sysfs_path;
4081
4082 /* Mount, Automount */
4083 const char *where;
4084
4085 /* Swap */
4086 const char *what;
582a507f 4087
934277fe
LP
4088 /* CGroup */
4089 uint64_t memory_current;
48422635 4090 uint64_t memory_min;
da4d897e
TH
4091 uint64_t memory_low;
4092 uint64_t memory_high;
4093 uint64_t memory_max;
96e131ea 4094 uint64_t memory_swap_max;
934277fe 4095 uint64_t memory_limit;
5ad096b3 4096 uint64_t cpu_usage_nsec;
03a7b521
LP
4097 uint64_t tasks_current;
4098 uint64_t tasks_max;
934277fe 4099
0e97c93f
DM
4100 uint64_t ip_ingress_bytes;
4101 uint64_t ip_egress_bytes;
4102
582a507f 4103 LIST_HEAD(ExecStatusInfo, exec);
61cbdc4b
LP
4104} UnitStatusInfo;
4105
a7335518
ZJS
4106static void unit_status_info_free(UnitStatusInfo *info) {
4107 ExecStatusInfo *p;
4108 UnitCondition *c;
4109
4110 strv_free(info->documentation);
4111 strv_free(info->dropin_paths);
4112 strv_free(info->listen);
4113
4114 while ((c = info->conditions)) {
4115 LIST_REMOVE(conditions, info->conditions, c);
4116 unit_condition_free(c);
4117 }
4118
4119 while ((p = info->exec)) {
4120 LIST_REMOVE(exec, info->exec, p);
4121 exec_status_info_free(p);
4122 }
4123}
4124
f459b602 4125static void print_status_info(
291d565a 4126 sd_bus *bus,
f459b602
MAP
4127 UnitStatusInfo *i,
4128 bool *ellipsized) {
4129
4d9685be
ZJS
4130 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX];
4131 const char *s1, *s2, *active_on, *active_off, *on, *off, *ss;
c7080257
LP
4132 _cleanup_free_ char *formatted_path = NULL;
4133 ExecStatusInfo *p;
584be568 4134 usec_t timestamp;
1b64d026 4135 const char *path;
13160134 4136 char **t, **t2;
291d565a 4137 int r;
582a507f 4138
61cbdc4b
LP
4139 assert(i);
4140
4141 /* This shows pretty information about a unit. See
4142 * print_property() for a low-level property printer */
4143
b0d14c69
LP
4144 if (streq_ptr(i->active_state, "failed")) {
4145 active_on = ansi_highlight_red();
1fc464f6 4146 active_off = ansi_normal();
1cf03a4f 4147 } else if (STRPTR_IN_SET(i->active_state, "active", "reloading")) {
b0d14c69 4148 active_on = ansi_highlight_green();
1fc464f6 4149 active_off = ansi_normal();
b0d14c69
LP
4150 } else
4151 active_on = active_off = "";
4152
9a6f746f 4153 printf("%s%s%s %s", active_on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), active_off, strna(i->id));
61cbdc4b
LP
4154
4155 if (i->description && !streq_ptr(i->id, i->description))
4156 printf(" - %s", i->description);
4157
4158 printf("\n");
4159
4a9e2fff 4160 if (i->following)
856323c9 4161 printf(" Follow: unit currently follows state of %s\n", i->following);
4a9e2fff 4162
c4555ad8 4163 if (STRPTR_IN_SET(i->load_state, "error", "not-found", "bad-setting")) {
0b5a519c 4164 on = ansi_highlight_red();
1fc464f6 4165 off = ansi_normal();
c31b4423
LP
4166 } else
4167 on = off = "";
4168
c7080257
LP
4169 path = i->source_path ?: i->fragment_path;
4170 if (path && terminal_urlify_path(path, NULL, &formatted_path) >= 0)
4171 path = formatted_path;
1b64d026 4172
9a0abfa8 4173 if (!isempty(i->load_error))
856323c9
ZJS
4174 printf(" Loaded: %s%s%s (Reason: %s)\n",
4175 on, strna(i->load_state), off, i->load_error);
15ce1647
LP
4176 else if (path && !isempty(i->unit_file_state) && !isempty(i->unit_file_preset) &&
4177 !STR_IN_SET(i->unit_file_state, "generated", "transient"))
d2dc52db
LP
4178 printf(" Loaded: %s%s%s (%s; %s; vendor preset: %s)\n",
4179 on, strna(i->load_state), off, path, i->unit_file_state, i->unit_file_preset);
4180 else if (path && !isempty(i->unit_file_state))
856323c9
ZJS
4181 printf(" Loaded: %s%s%s (%s; %s)\n",
4182 on, strna(i->load_state), off, path, i->unit_file_state);
1b64d026 4183 else if (path)
856323c9
ZJS
4184 printf(" Loaded: %s%s%s (%s)\n",
4185 on, strna(i->load_state), off, path);
61cbdc4b 4186 else
856323c9
ZJS
4187 printf(" Loaded: %s%s%s\n",
4188 on, strna(i->load_state), off);
61cbdc4b 4189
055ef36b
LP
4190 if (i->transient)
4191 printf("Transient: yes\n");
4192
76d14b87 4193 if (!strv_isempty(i->dropin_paths)) {
f459b602 4194 _cleanup_free_ char *dir = NULL;
76d14b87 4195 bool last = false;
f459b602 4196 char ** dropin;
76d14b87
OS
4197
4198 STRV_FOREACH(dropin, i->dropin_paths) {
c7080257
LP
4199 _cleanup_free_ char *dropin_formatted = NULL;
4200 const char *df;
4201
eb2c3192
LP
4202 if (!dir || last) {
4203 printf(dir ? " " :
4204 " Drop-In: ");
76d14b87 4205
97b11eed 4206 dir = mfree(dir);
76d14b87 4207
5f311f8c
LP
4208 dir = dirname_malloc(*dropin);
4209 if (!dir) {
76d14b87
OS
4210 log_oom();
4211 return;
4212 }
4213
eb2c3192
LP
4214 printf("%s\n"
4215 " %s", dir,
9a6f746f 4216 special_glyph(SPECIAL_GLYPH_TREE_RIGHT));
76d14b87
OS
4217 }
4218
4219 last = ! (*(dropin + 1) && startswith(*(dropin + 1), dir));
4220
c7080257
LP
4221 if (terminal_urlify_path(*dropin, basename(*dropin), &dropin_formatted) >= 0)
4222 df = dropin_formatted;
4223 else
4224 df = *dropin;
4225
4226 printf("%s%s", df, last ? "\n" : ", ");
76d14b87 4227 }
76d14b87
OS
4228 }
4229
2ee68f72 4230 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2ee68f72 4231 if (ss)
856323c9 4232 printf(" Active: %s%s (%s)%s",
b0d14c69 4233 active_on, strna(i->active_state), ss, active_off);
2ee68f72 4234 else
856323c9 4235 printf(" Active: %s%s%s",
b0d14c69 4236 active_on, strna(i->active_state), active_off);
61cbdc4b 4237
f42806df
LP
4238 if (!isempty(i->result) && !streq(i->result, "success"))
4239 printf(" (Result: %s)", i->result);
4240
1cf03a4f
ZJS
4241 timestamp = STRPTR_IN_SET(i->active_state, "active", "reloading") ? i->active_enter_timestamp :
4242 STRPTR_IN_SET(i->active_state, "inactive", "failed") ? i->inactive_enter_timestamp :
4243 STRPTR_IN_SET(i->active_state, "activating") ? i->inactive_exit_timestamp :
4244 i->active_exit_timestamp;
584be568 4245
bbb8486e 4246 s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
584be568
LP
4247 s2 = format_timestamp(since2, sizeof(since2), timestamp);
4248
4249 if (s1)
538da63d 4250 printf(" since %s; %s\n", s2, s1);
584be568 4251 else if (s2)
538da63d 4252 printf(" since %s\n", s2);
584be568
LP
4253 else
4254 printf("\n");
4255
601b0842
GS
4256 if (endswith(i->id, ".timer")) {
4257 char tstamp1[FORMAT_TIMESTAMP_RELATIVE_MAX],
4258 tstamp2[FORMAT_TIMESTAMP_MAX];
4d9685be 4259 const char *next_rel_time, *next_time;
601b0842
GS
4260 dual_timestamp nw, next = {i->next_elapse_real,
4261 i->next_elapse_monotonic};
4262 usec_t next_elapse;
4263
4264 printf(" Trigger: ");
4265
4266 dual_timestamp_get(&nw);
4267 next_elapse = calc_next_elapse(&nw, &next);
4d9685be
ZJS
4268 next_rel_time = format_timestamp_relative(tstamp1, sizeof tstamp1, next_elapse);
4269 next_time = format_timestamp(tstamp2, sizeof tstamp2, next_elapse);
601b0842
GS
4270
4271 if (next_time && next_rel_time)
4272 printf("%s; %s\n", next_time, next_rel_time);
4273 else
4274 printf("n/a\n");
4275 }
4276
90bbc946 4277 if (!i->condition_result && i->condition_timestamp > 0) {
d5db7fe6
WC
4278 UnitCondition *c;
4279 int n = 0;
4280
bbb8486e 4281 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
90bbc946
LP
4282 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
4283
59fccdc5 4284 printf("Condition: start %scondition failed%s at %s%s%s\n",
1fc464f6 4285 ansi_highlight_yellow(), ansi_normal(),
5cfee414 4286 s2, s1 ? "; " : "", strempty(s1));
d5db7fe6 4287
b1ed76ae 4288 LIST_FOREACH(conditions, c, i->conditions)
d5db7fe6
WC
4289 if (c->tristate < 0)
4290 n++;
d5db7fe6 4291
b1ed76ae
ZJS
4292 LIST_FOREACH(conditions, c, i->conditions)
4293 if (c->tristate < 0)
4294 printf(" %s %s=%s%s%s was not met\n",
9a6f746f 4295 --n ? special_glyph(SPECIAL_GLYPH_TREE_BRANCH) : special_glyph(SPECIAL_GLYPH_TREE_RIGHT),
b1ed76ae
ZJS
4296 c->name,
4297 c->trigger ? "|" : "",
4298 c->negate ? "!" : "",
4299 c->param);
59fccdc5
LP
4300 }
4301
4302 if (!i->assert_result && i->assert_timestamp > 0) {
4303 s1 = format_timestamp_relative(since1, sizeof(since1), i->assert_timestamp);
4304 s2 = format_timestamp(since2, sizeof(since2), i->assert_timestamp);
4305
4306 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
1fc464f6 4307 ansi_highlight_red(), ansi_normal(),
5cfee414 4308 s2, s1 ? "; " : "", strempty(s1));
59fccdc5
LP
4309 if (i->failed_assert_trigger)
4310 printf(" none of the trigger assertions were met\n");
4311 else if (i->failed_assert)
4312 printf(" %s=%s%s was not met\n",
4313 i->failed_assert,
4314 i->failed_assert_negate ? "!" : "",
4315 i->failed_assert_parameter);
90bbc946
LP
4316 }
4317
61cbdc4b 4318 if (i->sysfs_path)
856323c9 4319 printf(" Device: %s\n", i->sysfs_path);
9feeba4b 4320 if (i->where)
856323c9 4321 printf(" Where: %s\n", i->where);
9feeba4b 4322 if (i->what)
856323c9 4323 printf(" What: %s\n", i->what);
49dbfa7b 4324
78c7d20e
LP
4325 STRV_FOREACH(t, i->documentation) {
4326 _cleanup_free_ char *formatted = NULL;
4327 const char *q;
4328
4329 if (terminal_urlify(*t, NULL, &formatted) >= 0)
4330 q = formatted;
4331 else
4332 q = *t;
4333
4334 printf(" %*s %s\n", 9, t == i->documentation ? "Docs:" : "", q);
4335 }
49dbfa7b 4336
13160134 4337 STRV_FOREACH_PAIR(t, t2, i->listen)
856323c9 4338 printf(" %*s %s (%s)\n", 9, t == i->listen ? "Listen:" : "", *t2, *t);
67419600 4339
a98f7575
MM
4340 if (i->accept) {
4341 printf(" Accepted: %u; Connected: %u;", i->n_accepted, i->n_connections);
4342 if (i->n_refused)
4343 printf(" Refused: %u", i->n_refused);
4344 printf("\n");
4345 }
4346
582a507f 4347 LIST_FOREACH(exec, p, i->exec) {
13160134 4348 _cleanup_free_ char *argv = NULL;
9a57c629 4349 bool good;
582a507f
LP
4350
4351 /* Only show exited processes here */
4352 if (p->code == 0)
4353 continue;
4354
13160134 4355 argv = strv_join(p->argv, " ");
1fa2f38f 4356 printf(" Process: "PID_FMT" %s=%s ", p->pid, p->name, strna(argv));
582a507f 4357
1f0958f6 4358 good = is_clean_exit(p->code, p->status, EXIT_CLEAN_DAEMON, NULL);
9a57c629 4359 if (!good) {
0b5a519c 4360 on = ansi_highlight_red();
1fc464f6 4361 off = ansi_normal();
9a57c629
LP
4362 } else
4363 on = off = "";
4364
4365 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
4366
d06dacd0
LP
4367 if (p->code == CLD_EXITED) {
4368 const char *c;
4369
582a507f 4370 printf("status=%i", p->status);
d06dacd0 4371
1b64d026
LP
4372 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
4373 if (c)
d06dacd0
LP
4374 printf("/%s", c);
4375
4376 } else
582a507f 4377 printf("signal=%s", signal_to_string(p->status));
9a57c629
LP
4378
4379 printf(")%s\n", off);
4380
582a507f
LP
4381 if (i->main_pid == p->pid &&
4382 i->start_timestamp == p->start_timestamp &&
4383 i->exit_timestamp == p->start_timestamp)
4384 /* Let's not show this twice */
4385 i->main_pid = 0;
4386
4387 if (p->pid == i->control_pid)
4388 i->control_pid = 0;
4389 }
4390
61cbdc4b 4391 if (i->main_pid > 0 || i->control_pid > 0) {
61cbdc4b 4392 if (i->main_pid > 0) {
8c06592f 4393 printf(" Main PID: "PID_FMT, i->main_pid);
61cbdc4b
LP
4394
4395 if (i->running) {
a081b9ce
LP
4396
4397 if (arg_transport == BUS_TRANSPORT_LOCAL) {
4398 _cleanup_free_ char *comm = NULL;
4399
4400 (void) get_process_comm(i->main_pid, &comm);
4401 if (comm)
4402 printf(" (%s)", comm);
4403 }
4404
6d4fc029 4405 } else if (i->exit_code > 0) {
61cbdc4b
LP
4406 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
4407
d06dacd0
LP
4408 if (i->exit_code == CLD_EXITED) {
4409 const char *c;
4410
61cbdc4b 4411 printf("status=%i", i->exit_status);
d06dacd0 4412
1b64d026
LP
4413 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
4414 if (c)
d06dacd0
LP
4415 printf("/%s", c);
4416
4417 } else
582a507f 4418 printf("signal=%s", signal_to_string(i->exit_status));
6d4fc029
LP
4419 printf(")");
4420 }
13160134 4421 }
61cbdc4b
LP
4422
4423 if (i->control_pid > 0) {
13160134 4424 _cleanup_free_ char *c = NULL;
61cbdc4b 4425
1089dcd4
LP
4426 if (i->main_pid > 0)
4427 fputs("; Control PID: ", stdout);
4428 else
4429 fputs("Cntrl PID: ", stdout); /* if first in column, abbreviated so it fits alignment */
4430
4431 printf(PID_FMT, i->control_pid);
61cbdc4b 4432
a081b9ce
LP
4433 if (arg_transport == BUS_TRANSPORT_LOCAL) {
4434 (void) get_process_comm(i->control_pid, &c);
4435 if (c)
4436 printf(" (%s)", c);
4437 }
61cbdc4b
LP
4438 }
4439
4440 printf("\n");
4441 }
4442
17bb7382 4443 if (i->status_text)
856323c9 4444 printf(" Status: \"%s\"\n", i->status_text);
b4af5a80
LP
4445 if (i->status_errno > 0)
4446 printf(" Error: %i (%s)\n", i->status_errno, strerror(i->status_errno));
17bb7382 4447
0e97c93f
DM
4448 if (i->ip_ingress_bytes != (uint64_t) -1 && i->ip_egress_bytes != (uint64_t) -1) {
4449 char buf_in[FORMAT_BYTES_MAX], buf_out[FORMAT_BYTES_MAX];
4450
4451 printf(" IP: %s in, %s out\n",
4452 format_bytes(buf_in, sizeof(buf_in), i->ip_ingress_bytes),
4453 format_bytes(buf_out, sizeof(buf_out), i->ip_egress_bytes));
4454 }
4455
03a7b521
LP
4456 if (i->tasks_current != (uint64_t) -1) {
4457 printf(" Tasks: %" PRIu64, i->tasks_current);
4458
4459 if (i->tasks_max != (uint64_t) -1)
2a6736dd 4460 printf(" (limit: %" PRIu64 ")\n", i->tasks_max);
03a7b521
LP
4461 else
4462 printf("\n");
4463 }
4464
934277fe
LP
4465 if (i->memory_current != (uint64_t) -1) {
4466 char buf[FORMAT_BYTES_MAX];
4467
4468 printf(" Memory: %s", format_bytes(buf, sizeof(buf), i->memory_current));
4469
48422635
TH
4470 if (i->memory_min > 0 || i->memory_low > 0 ||
4471 i->memory_high != CGROUP_LIMIT_MAX || i->memory_max != CGROUP_LIMIT_MAX ||
4472 i->memory_swap_max != CGROUP_LIMIT_MAX ||
da4d897e
TH
4473 i->memory_limit != CGROUP_LIMIT_MAX) {
4474 const char *prefix = "";
4475
4476 printf(" (");
48422635
TH
4477 if (i->memory_min > 0) {
4478 printf("%smin: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_min));
4479 prefix = " ";
4480 }
da4d897e
TH
4481 if (i->memory_low > 0) {
4482 printf("%slow: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_low));
4483 prefix = " ";
4484 }
4485 if (i->memory_high != CGROUP_LIMIT_MAX) {
4486 printf("%shigh: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_high));
4487 prefix = " ";
4488 }
4489 if (i->memory_max != CGROUP_LIMIT_MAX) {
4490 printf("%smax: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_max));
4491 prefix = " ";
4492 }
96e131ea
WC
4493 if (i->memory_swap_max != CGROUP_LIMIT_MAX) {
4494 printf("%sswap max: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_swap_max));
4495 prefix = " ";
4496 }
da4d897e
TH
4497 if (i->memory_limit != CGROUP_LIMIT_MAX) {
4498 printf("%slimit: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_limit));
4499 prefix = " ";
4500 }
4501 printf(")");
4502 }
4503 printf("\n");
934277fe
LP
4504 }
4505
5ad096b3
LP
4506 if (i->cpu_usage_nsec != (uint64_t) -1) {
4507 char buf[FORMAT_TIMESPAN_MAX];
4508 printf(" CPU: %s\n", format_timespan(buf, sizeof(buf), i->cpu_usage_nsec / NSEC_PER_USEC, USEC_PER_MSEC));
4509 }
4510
51e22f88 4511 if (i->control_group) {
291d565a
LP
4512 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4513 static const char prefix[] = " ";
ab35fb1b
LP
4514 unsigned c;
4515
51e22f88
LP
4516 printf(" CGroup: %s\n", i->control_group);
4517
291d565a
LP
4518 c = columns();
4519 if (c > sizeof(prefix) - 1)
4520 c -= sizeof(prefix) - 1;
4521 else
4522 c = 0;
ab35fb1b 4523
291d565a
LP
4524 r = unit_show_processes(bus, i->id, i->control_group, prefix, c, get_output_flags(), &error);
4525 if (r == -EBADR) {
b69d29ce
LP
4526 unsigned k = 0;
4527 pid_t extra[2];
4528
291d565a 4529 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
ab35fb1b 4530
b69d29ce
LP
4531 if (i->main_pid > 0)
4532 extra[k++] = i->main_pid;
4533
4534 if (i->control_pid > 0)
4535 extra[k++] = i->control_pid;
4536
0ff308c8 4537 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER, i->control_group, prefix, c, extra, k, get_output_flags());
291d565a 4538 } else if (r < 0)
950d6889 4539 log_warning_errno(r, "Failed to dump process list for '%s', ignoring: %s", i->id, bus_error_message(&error, r));
c59760ee 4540 }
45fb0699 4541
ece174c5 4542 if (i->id && arg_transport == BUS_TRANSPORT_LOCAL)
3c756001
LP
4543 show_journal_by_unit(
4544 stdout,
4545 i->id,
4546 arg_output,
4547 0,
4548 i->inactive_exit_timestamp_monotonic,
4549 arg_lines,
4550 getuid(),
4551 get_output_flags() | OUTPUT_BEGIN_NEWLINE,
4552 SD_JOURNAL_LOCAL_ONLY,
4553 arg_scope == UNIT_FILE_SYSTEM,
4554 ellipsized);
86aa7ba4 4555
45fb0699 4556 if (i->need_daemon_reload)
3f36991e 4557 warn_unit_file_changed(i->id);
61cbdc4b
LP
4558}
4559
b43f208f 4560static void show_unit_help(UnitStatusInfo *i) {
256425cc
LP
4561 char **p;
4562
4563 assert(i);
4564
4565 if (!i->documentation) {
4566 log_info("Documentation for %s not known.", i->id);
4567 return;
4568 }
4569
78002a67
ZJS
4570 STRV_FOREACH(p, i->documentation)
4571 if (startswith(*p, "man:"))
4572 show_man_page(*p + 4, false);
4573 else
0315fe37 4574 log_info("Can't show: %s", *p);
256425cc
LP
4575}
4576
4679a8c3
YW
4577static int map_main_pid(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4578 UnitStatusInfo *i = userdata;
4579 uint32_t u;
f459b602 4580 int r;
61cbdc4b 4581
4679a8c3
YW
4582 r = sd_bus_message_read(m, "u", &u);
4583 if (r < 0)
4584 return r;
61cbdc4b 4585
4679a8c3
YW
4586 i->main_pid = (pid_t) u;
4587 i->running = u > 0;
b8131a87 4588
4679a8c3
YW
4589 return 0;
4590}
b8131a87 4591
4679a8c3 4592static int map_load_error(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
31d99bd1 4593 const char *message, **p = userdata;
4679a8c3 4594 int r;
b8131a87 4595
31d99bd1 4596 r = sd_bus_message_read(m, "(ss)", NULL, &message);
4679a8c3
YW
4597 if (r < 0)
4598 return r;
b8131a87 4599
4679a8c3
YW
4600 if (!isempty(message))
4601 *p = message;
61cbdc4b 4602
4679a8c3
YW
4603 return 0;
4604}
61cbdc4b 4605
4679a8c3
YW
4606static int map_listen(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4607 const char *type, *path;
4608 char ***p = userdata;
4609 int r;
61cbdc4b 4610
4679a8c3
YW
4611 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4612 if (r < 0)
4613 return r;
61cbdc4b 4614
4679a8c3 4615 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0) {
61cbdc4b 4616
4679a8c3 4617 r = strv_extend(p, type);
f459b602 4618 if (r < 0)
4679a8c3 4619 return r;
61cbdc4b 4620
4679a8c3 4621 r = strv_extend(p, path);
f459b602 4622 if (r < 0)
4679a8c3 4623 return r;
61cbdc4b 4624 }
4679a8c3
YW
4625 if (r < 0)
4626 return r;
582a507f 4627
4679a8c3
YW
4628 r = sd_bus_message_exit_container(m);
4629 if (r < 0)
4630 return r;
49dbfa7b 4631
4679a8c3
YW
4632 return 0;
4633}
52990c2e 4634
4679a8c3
YW
4635static int map_conditions(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4636 UnitStatusInfo *i = userdata;
4637 const char *cond, *param;
4638 int trigger, negate;
4639 int32_t state;
4640 int r;
52990c2e 4641
4679a8c3
YW
4642 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sbbsi)");
4643 if (r < 0)
4644 return r;
f459b602 4645
4679a8c3
YW
4646 while ((r = sd_bus_message_read(m, "(sbbsi)", &cond, &trigger, &negate, &param, &state)) > 0) {
4647 _cleanup_(unit_condition_freep) UnitCondition *c = NULL;
d5db7fe6 4648
4679a8c3
YW
4649 c = new0(UnitCondition, 1);
4650 if (!c)
4651 return -ENOMEM;
d5db7fe6 4652
4679a8c3
YW
4653 c->name = strdup(cond);
4654 c->param = strdup(param);
4655 if (!c->name || !c->param)
4656 return -ENOMEM;
d5db7fe6 4657
4679a8c3
YW
4658 c->trigger = trigger;
4659 c->negate = negate;
4660 c->tristate = state;
d5db7fe6 4661
4679a8c3
YW
4662 LIST_PREPEND(conditions, i->conditions, c);
4663 c = NULL;
4664 }
4665 if (r < 0)
4666 return r;
d5db7fe6 4667
4679a8c3
YW
4668 r = sd_bus_message_exit_container(m);
4669 if (r < 0)
4670 return r;
59fccdc5 4671
4679a8c3
YW
4672 return 0;
4673}
59fccdc5 4674
4679a8c3
YW
4675static int map_asserts(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4676 UnitStatusInfo *i = userdata;
4677 const char *cond, *param;
4678 int trigger, negate;
4679 int32_t state;
4680 int r;
59fccdc5 4681
4679a8c3
YW
4682 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sbbsi)");
4683 if (r < 0)
4684 return r;
59fccdc5 4685
4679a8c3
YW
4686 while ((r = sd_bus_message_read(m, "(sbbsi)", &cond, &trigger, &negate, &param, &state)) > 0) {
4687 if (state < 0 && (!trigger || !i->failed_assert)) {
4688 i->failed_assert = cond;
4689 i->failed_assert_trigger = trigger;
4690 i->failed_assert_negate = negate;
4691 i->failed_assert_parameter = param;
4692 }
4693 }
4694 if (r < 0)
4695 return r;
f459b602 4696
4679a8c3
YW
4697 r = sd_bus_message_exit_container(m);
4698 if (r < 0)
4699 return r;
f459b602 4700
4679a8c3
YW
4701 return 0;
4702}
582a507f 4703
4679a8c3
YW
4704static int map_exec(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4705 _cleanup_free_ ExecStatusInfo *info = NULL;
3e14d36a 4706 ExecStatusInfo *last;
4679a8c3
YW
4707 UnitStatusInfo *i = userdata;
4708 int r;
9f39404c 4709
4679a8c3
YW
4710 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sasbttttuii)");
4711 if (r < 0)
4712 return r;
9f39404c 4713
4679a8c3
YW
4714 info = new0(ExecStatusInfo, 1);
4715 if (!info)
4716 return -ENOMEM;
9f39404c 4717
3e14d36a
LP
4718 LIST_FIND_TAIL(exec, i->exec, last);
4719
4679a8c3 4720 while ((r = exec_status_info_deserialize(m, info)) > 0) {
9f39404c 4721
4679a8c3
YW
4722 info->name = strdup(member);
4723 if (!info->name)
4724 return -ENOMEM;
9f39404c 4725
3e14d36a
LP
4726 LIST_INSERT_AFTER(exec, i->exec, last, info);
4727 last = info;
f459b602 4728
4679a8c3
YW
4729 info = new0(ExecStatusInfo, 1);
4730 if (!info)
4731 return -ENOMEM;
9f39404c 4732 }
4679a8c3
YW
4733 if (r < 0)
4734 return r;
f459b602 4735
4679a8c3 4736 r = sd_bus_message_exit_container(m);
f459b602 4737 if (r < 0)
4679a8c3 4738 return r;
61cbdc4b
LP
4739
4740 return 0;
4741}
4742
eda19357 4743static int print_property(const char *name, const char *expected_value, sd_bus_message *m, bool value, bool all) {
07636114
YW
4744 char bus_type;
4745 const char *contents;
f459b602
MAP
4746 int r;
4747
48220598 4748 assert(name);
f459b602 4749 assert(m);
48220598 4750
61cbdc4b
LP
4751 /* This is a low-level property printer, see
4752 * print_status_info() for the nicer output */
4753
07636114
YW
4754 r = sd_bus_message_peek_type(m, &bus_type, &contents);
4755 if (r < 0)
852c1b4d 4756 return r;
48220598 4757
07636114 4758 switch (bus_type) {
48220598 4759
a3ddd457
YW
4760 case SD_BUS_TYPE_INT32:
4761 if (endswith(name, "ActionExitStatus")) {
4762 int32_t i;
4763
4764 r = sd_bus_message_read_basic(m, bus_type, &i);
4765 if (r < 0)
4766 return r;
4767
4768 if (i >= 0 && i <= 255)
4769 bus_print_property_valuef(name, expected_value, value, "%"PRIi32, i);
4770 else if (all)
4771 bus_print_property_value(name, expected_value, value, "[not set]");
4772
4773 return 1;
4774 }
4775 break;
4776
07636114 4777 case SD_BUS_TYPE_STRUCT:
48220598 4778
07636114 4779 if (contents[0] == SD_BUS_TYPE_UINT32 && streq(name, "Job")) {
48220598
LP
4780 uint32_t u;
4781
f459b602
MAP
4782 r = sd_bus_message_read(m, "(uo)", &u, NULL);
4783 if (r < 0)
4784 return bus_log_parse_error(r);
48220598 4785
f459b602 4786 if (u > 0)
102b0214 4787 bus_print_property_valuef(name, expected_value, value, "%"PRIu32, u);
07636114 4788 else if (all)
102b0214 4789 bus_print_property_value(name, expected_value, value, "");
48220598 4790
07636114 4791 return 1;
f459b602 4792
07636114 4793 } else if (contents[0] == SD_BUS_TYPE_STRING && streq(name, "Unit")) {
48220598
LP
4794 const char *s;
4795
f459b602
MAP
4796 r = sd_bus_message_read(m, "(so)", &s, NULL);
4797 if (r < 0)
4798 return bus_log_parse_error(r);
48220598 4799
07636114 4800 if (all || !isempty(s))
102b0214 4801 bus_print_property_value(name, expected_value, value, s);
48220598 4802
07636114 4803 return 1;
f459b602 4804
07636114 4805 } else if (contents[0] == SD_BUS_TYPE_STRING && streq(name, "LoadError")) {
9f39404c
LP
4806 const char *a = NULL, *b = NULL;
4807
f459b602
MAP
4808 r = sd_bus_message_read(m, "(ss)", &a, &b);
4809 if (r < 0)
4810 return bus_log_parse_error(r);
9f39404c 4811
48d3358d 4812 if (!isempty(a) || !isempty(b))
102b0214 4813 bus_print_property_valuef(name, expected_value, value, "%s \"%s\"", strempty(a), strempty(b));
48d3358d
YW
4814 else if (all)
4815 bus_print_property_value(name, expected_value, value, "");
f786e80d 4816
07636114 4817 return 1;
04749e40
YW
4818
4819 } else if (STR_IN_SET(name, "SystemCallFilter", "RestrictAddressFamilies")) {
57183d11
LP
4820 _cleanup_strv_free_ char **l = NULL;
4821 int whitelist;
4822
4823 r = sd_bus_message_enter_container(m, 'r', "bas");
4824 if (r < 0)
4825 return bus_log_parse_error(r);
4826
4827 r = sd_bus_message_read(m, "b", &whitelist);
4828 if (r < 0)
4829 return bus_log_parse_error(r);
4830
4831 r = sd_bus_message_read_strv(m, &l);
4832 if (r < 0)
4833 return bus_log_parse_error(r);
4834
4835 r = sd_bus_message_exit_container(m);
4836 if (r < 0)
4837 return bus_log_parse_error(r);
4838
07636114 4839 if (all || whitelist || !strv_isempty(l)) {
57183d11
LP
4840 bool first = true;
4841 char **i;
4842
07636114 4843 if (!value) {
4f9a9105
ZJS
4844 fputs(name, stdout);
4845 fputc('=', stdout);
4846 }
57183d11
LP
4847
4848 if (!whitelist)
4849 fputc('~', stdout);
4850
4851 STRV_FOREACH(i, l) {
4852 if (first)
4853 first = false;
4854 else
4855 fputc(' ', stdout);
4856
4857 fputs(*i, stdout);
4858 }
4859 fputc('\n', stdout);
4860 }
4861
c7bb2fec 4862 return 1;
102b0214 4863
c7bb2fec
IP
4864 } else if (STR_IN_SET(name, "SELinuxContext", "AppArmorProfile", "SmackProcessLabel")) {
4865 int ignore;
4866 const char *s;
4867
4868 r = sd_bus_message_read(m, "(bs)", &ignore, &s);
4869 if (r < 0)
4870 return bus_log_parse_error(r);
4871
4872 if (!isempty(s))
102b0214 4873 bus_print_property_valuef(name, expected_value, value, "%s%s", ignore ? "-" : "", s);
c7bb2fec 4874 else if (all)
102b0214 4875 bus_print_property_value(name, expected_value, value, "");
c7bb2fec 4876
07636114 4877 return 1;
4a220712
YW
4878
4879 } else if (endswith(name, "ExitStatus") && streq(contents, "aiai")) {
4880 const int32_t *status, *signal;
4881 size_t sz_status, sz_signal, i;
4882
4883 r = sd_bus_message_enter_container(m, 'r', "aiai");
4884 if (r < 0)
4885 return bus_log_parse_error(r);
4886
4887 r = sd_bus_message_read_array(m, 'i', (const void **) &status, &sz_status);
4888 if (r < 0)
4889 return bus_log_parse_error(r);
4890
4891 r = sd_bus_message_read_array(m, 'i', (const void **) &signal, &sz_signal);
4892 if (r < 0)
4893 return bus_log_parse_error(r);
4894
4895 r = sd_bus_message_exit_container(m);
4896 if (r < 0)
4897 return bus_log_parse_error(r);
4898
4899 sz_status /= sizeof(int32_t);
4900 sz_signal /= sizeof(int32_t);
4901
4902 if (all || sz_status > 0 || sz_signal > 0) {
4903 bool first = true;
4904
4905 if (!value) {
4906 fputs(name, stdout);
4907 fputc('=', stdout);
4908 }
4909
4910 for (i = 0; i < sz_status; i++) {
4911 if (status[i] < 0 || status[i] > 255)
4912 continue;
4913
4914 if (first)
4915 first = false;
4916 else
4917 fputc(' ', stdout);
4918
4919 printf("%"PRIi32, status[i]);
4920 }
4921
4922 for (i = 0; i < sz_signal; i++) {
4923 const char *str;
4924
4925 str = signal_to_string((int) signal[i]);
4926 if (!str)
4927 continue;
4928
4929 if (first)
4930 first = false;
4931 else
4932 fputc(' ', stdout);
4933
4934 fputs(str, stdout);
4935 }
4936
4937 fputc('\n', stdout);
4938 }
4939 return 1;
48220598
LP
4940 }
4941
4942 break;
48220598 4943
f459b602 4944 case SD_BUS_TYPE_ARRAY:
48220598 4945
07636114 4946 if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "EnvironmentFiles")) {
f459b602
MAP
4947 const char *path;
4948 int ignore;
8c7be95e 4949
f459b602
MAP
4950 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sb)");
4951 if (r < 0)
4952 return bus_log_parse_error(r);
8c7be95e 4953
f459b602 4954 while ((r = sd_bus_message_read(m, "(sb)", &path, &ignore)) > 0)
102b0214 4955 bus_print_property_valuef(name, expected_value, value, "%s (ignore_errors=%s)", path, yes_no(ignore));
8c7be95e 4956
f459b602
MAP
4957 if (r < 0)
4958 return bus_log_parse_error(r);
8c7be95e 4959
f459b602
MAP
4960 r = sd_bus_message_exit_container(m);
4961 if (r < 0)
4962 return bus_log_parse_error(r);
8c7be95e 4963
07636114 4964 return 1;
8c7be95e 4965
07636114 4966 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Paths")) {
f459b602 4967 const char *type, *path;
67419600 4968
f459b602
MAP
4969 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4970 if (r < 0)
4971 return bus_log_parse_error(r);
ebf57b80 4972
f459b602 4973 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
102b0214 4974 bus_print_property_valuef(name, expected_value, value, "%s (%s)", path, type);
f459b602
MAP
4975 if (r < 0)
4976 return bus_log_parse_error(r);
ebf57b80 4977
f459b602
MAP
4978 r = sd_bus_message_exit_container(m);
4979 if (r < 0)
4980 return bus_log_parse_error(r);
ebf57b80 4981
07636114 4982 return 1;
582a507f 4983
07636114 4984 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Listen")) {
f459b602 4985 const char *type, *path;
67419600 4986
f459b602
MAP
4987 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4988 if (r < 0)
4989 return bus_log_parse_error(r);
67419600 4990
f459b602 4991 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
102b0214 4992 bus_print_property_valuef(name, expected_value, value, "%s (%s)", path, type);
f459b602
MAP
4993 if (r < 0)
4994 return bus_log_parse_error(r);
67419600 4995
f459b602
MAP
4996 r = sd_bus_message_exit_container(m);
4997 if (r < 0)
4998 return bus_log_parse_error(r);
67419600 4999
07636114 5000 return 1;
67419600 5001
07636114 5002 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "TimersMonotonic")) {
f459b602 5003 const char *base;
07636114 5004 uint64_t v, next_elapse;
707e5e52 5005
f459b602
MAP
5006 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(stt)");
5007 if (r < 0)
5008 return bus_log_parse_error(r);
552e4331 5009
07636114 5010 while ((r = sd_bus_message_read(m, "(stt)", &base, &v, &next_elapse)) > 0) {
f459b602 5011 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
fe68089d 5012
102b0214
YW
5013 bus_print_property_valuef(name, expected_value, value, "{ %s=%s ; next_elapse=%s }", base,
5014 format_timespan(timespan1, sizeof(timespan1), v, 0),
5015 format_timespan(timespan2, sizeof(timespan2), next_elapse, 0));
fe68089d 5016 }
f459b602
MAP
5017 if (r < 0)
5018 return bus_log_parse_error(r);
5019
5020 r = sd_bus_message_exit_container(m);
5021 if (r < 0)
5022 return bus_log_parse_error(r);
fe68089d 5023
07636114 5024 return 1;
fe68089d 5025
07636114 5026 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "TimersCalendar")) {
fa6dee52
YW
5027 const char *base, *spec;
5028 uint64_t next_elapse;
5029
5030 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sst)");
5031 if (r < 0)
5032 return bus_log_parse_error(r);
5033
5034 while ((r = sd_bus_message_read(m, "(sst)", &base, &spec, &next_elapse)) > 0) {
5035 char timestamp[FORMAT_TIMESTAMP_MAX];
5036
102b0214
YW
5037 bus_print_property_valuef(name, expected_value, value, "{ %s=%s ; next_elapse=%s }", base, spec,
5038 format_timestamp(timestamp, sizeof(timestamp), next_elapse));
fa6dee52
YW
5039 }
5040 if (r < 0)
5041 return bus_log_parse_error(r);
5042
5043 r = sd_bus_message_exit_container(m);
5044 if (r < 0)
5045 return bus_log_parse_error(r);
5046
07636114 5047 return 1;
fa6dee52 5048
07636114 5049 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && startswith(name, "Exec")) {
f459b602
MAP
5050 ExecStatusInfo info = {};
5051
5052 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sasbttttuii)");
5053 if (r < 0)
5054 return bus_log_parse_error(r);
5055
5056 while ((r = exec_status_info_deserialize(m, &info)) > 0) {
5057 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
5058 _cleanup_free_ char *tt;
5059
5060 tt = strv_join(info.argv, " ");
5061
102b0214
YW
5062 bus_print_property_valuef(name, expected_value, value,
5063 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT" ; code=%s ; status=%i%s%s }",
5064 strna(info.path),
5065 strna(tt),
5066 yes_no(info.ignore),
5067 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
5068 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
5069 info.pid,
5070 sigchld_code_to_string(info.code),
5071 info.status,
5072 info.code == CLD_EXITED ? "" : "/",
5073 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
fe68089d 5074
582a507f
LP
5075 free(info.path);
5076 strv_free(info.argv);
f459b602 5077 zero(info);
707e5e52
LP
5078 }
5079
f459b602
MAP
5080 r = sd_bus_message_exit_container(m);
5081 if (r < 0)
5082 return bus_log_parse_error(r);
5083
07636114 5084 return 1;
4ad49000 5085
07636114 5086 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "DeviceAllow")) {
f459b602 5087 const char *path, *rwm;
4ad49000 5088
f459b602
MAP
5089 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
5090 if (r < 0)
5091 return bus_log_parse_error(r);
4ad49000 5092
f459b602 5093 while ((r = sd_bus_message_read(m, "(ss)", &path, &rwm)) > 0)
102b0214 5094 bus_print_property_valuef(name, expected_value, value, "%s %s", strna(path), strna(rwm));
f459b602
MAP
5095 if (r < 0)
5096 return bus_log_parse_error(r);
4ad49000 5097
f459b602
MAP
5098 r = sd_bus_message_exit_container(m);
5099 if (r < 0)
5100 return bus_log_parse_error(r);
4ad49000 5101
07636114 5102 return 1;
4ad49000 5103
07636114 5104 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
72240b52 5105 STR_IN_SET(name, "IODeviceWeight", "BlockIODeviceWeight")) {
f459b602
MAP
5106 const char *path;
5107 uint64_t weight;
b8ab2dc6 5108
f459b602
MAP
5109 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
5110 if (r < 0)
5111 return bus_log_parse_error(r);
b8ab2dc6 5112
f459b602 5113 while ((r = sd_bus_message_read(m, "(st)", &path, &weight)) > 0)
102b0214 5114 bus_print_property_valuef(name, expected_value, value, "%s %"PRIu64, strna(path), weight);
f459b602
MAP
5115 if (r < 0)
5116 return bus_log_parse_error(r);
b8ab2dc6 5117
f459b602
MAP
5118 r = sd_bus_message_exit_container(m);
5119 if (r < 0)
5120 return bus_log_parse_error(r);
b8ab2dc6 5121
07636114 5122 return 1;
b8ab2dc6 5123
07636114 5124 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
72240b52
ZJS
5125 (cgroup_io_limit_type_from_string(name) >= 0 ||
5126 STR_IN_SET(name, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
f459b602
MAP
5127 const char *path;
5128 uint64_t bandwidth;
4ad49000 5129
f459b602
MAP
5130 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
5131 if (r < 0)
5132 return bus_log_parse_error(r);
4ad49000 5133
f459b602 5134 while ((r = sd_bus_message_read(m, "(st)", &path, &bandwidth)) > 0)
102b0214 5135 bus_print_property_valuef(name, expected_value, value, "%s %"PRIu64, strna(path), bandwidth);
f459b602
MAP
5136 if (r < 0)
5137 return bus_log_parse_error(r);
4ad49000 5138
f459b602
MAP
5139 r = sd_bus_message_exit_container(m);
5140 if (r < 0)
5141 return bus_log_parse_error(r);
4ad49000 5142
07636114 5143 return 1;
6ae4283c
TH
5144
5145 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
5146 streq(name, "IODeviceLatencyTargetUSec")) {
5147 char ts[FORMAT_TIMESPAN_MAX];
5148 const char *path;
5149 uint64_t target;
5150
5151 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
5152 if (r < 0)
5153 return bus_log_parse_error(r);
5154
5155 while ((r = sd_bus_message_read(m, "(st)", &path, &target)) > 0)
102b0214
YW
5156 bus_print_property_valuef(name, expected_value, value, "%s %s", strna(path),
5157 format_timespan(ts, sizeof(ts), target, 1));
6ae4283c
TH
5158 if (r < 0)
5159 return bus_log_parse_error(r);
5160
5161 r = sd_bus_message_exit_container(m);
5162 if (r < 0)
5163 return bus_log_parse_error(r);
5164
5165 return 1;
08f3be7a 5166
07636114 5167 } else if (contents[0] == SD_BUS_TYPE_BYTE && streq(name, "StandardInputData")) {
08f3be7a
LP
5168 _cleanup_free_ char *h = NULL;
5169 const void *p;
5170 size_t sz;
5171 ssize_t n;
5172
5173 r = sd_bus_message_read_array(m, 'y', &p, &sz);
5174 if (r < 0)
5175 return bus_log_parse_error(r);
5176
5177 n = base64mem(p, sz, &h);
5178 if (n < 0)
5179 return log_oom();
5180
102b0214 5181 bus_print_property_value(name, expected_value, value, h);
08f3be7a 5182
07636114 5183 return 1;
9c1f9465
YW
5184
5185 } else if (STR_IN_SET(name, "IPAddressAllow", "IPAddressDeny")) {
5186 _cleanup_free_ char *addresses = NULL;
5187
5188 r = sd_bus_message_enter_container(m, 'a', "(iayu)");
5189 if (r < 0)
5190 return bus_log_parse_error(r);
5191
5192 for (;;) {
5193 _cleanup_free_ char *str = NULL;
5194 uint32_t prefixlen;
5195 int32_t family;
5196 const void *ap;
5197 size_t an;
5198
5199 r = sd_bus_message_enter_container(m, 'r', "iayu");
5200 if (r < 0)
5201 return bus_log_parse_error(r);
5202 if (r == 0)
5203 break;
5204
5205 r = sd_bus_message_read(m, "i", &family);
5206 if (r < 0)
5207 return bus_log_parse_error(r);
5208
5209 r = sd_bus_message_read_array(m, 'y', &ap, &an);
5210 if (r < 0)
5211 return bus_log_parse_error(r);
5212
5213 r = sd_bus_message_read(m, "u", &prefixlen);
5214 if (r < 0)
5215 return bus_log_parse_error(r);
5216
5217 r = sd_bus_message_exit_container(m);
5218 if (r < 0)
5219 return bus_log_parse_error(r);
5220
5221 if (!IN_SET(family, AF_INET, AF_INET6))
5222 continue;
5223
5224 if (an != FAMILY_ADDRESS_SIZE(family))
5225 continue;
5226
5227 if (prefixlen > FAMILY_ADDRESS_SIZE(family) * 8)
5228 continue;
5229
5230 if (in_addr_prefix_to_string(family, (union in_addr_union *) ap, prefixlen, &str) < 0)
5231 continue;
5232
5233 if (!strextend_with_separator(&addresses, " ", str, NULL))
5234 return log_oom();
5235 }
5236
5237 r = sd_bus_message_exit_container(m);
5238 if (r < 0)
5239 return bus_log_parse_error(r);
5240
5241 if (all || !isempty(addresses))
5242 bus_print_property_value(name, expected_value, value, strempty(addresses));
5243
5244 return 1;
4c787df7
YW
5245
5246 } else if (STR_IN_SET(name, "BindPaths", "BindReadOnlyPaths")) {
5247 _cleanup_free_ char *paths = NULL;
5248 const char *source, *dest;
5249 int ignore_enoent;
5250 uint64_t rbind;
5251
5252 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ssbt)");
5253 if (r < 0)
5254 return bus_log_parse_error(r);
5255
5256 while ((r = sd_bus_message_read(m, "(ssbt)", &source, &dest, &ignore_enoent, &rbind)) > 0) {
5257 _cleanup_free_ char *str = NULL;
5258
5259 if (isempty(source))
5260 continue;
5261
5262 if (asprintf(&str, "%s%s%s%s%s",
5263 ignore_enoent ? "-" : "",
5264 source,
5265 isempty(dest) ? "" : ":",
5266 strempty(dest),
5267 rbind == MS_REC ? ":rbind" : "") < 0)
5268 return log_oom();
5269
5270 if (!strextend_with_separator(&paths, " ", str, NULL))
5271 return log_oom();
5272 }
5273 if (r < 0)
5274 return bus_log_parse_error(r);
5275
5276 r = sd_bus_message_exit_container(m);
5277 if (r < 0)
5278 return bus_log_parse_error(r);
5279
5280 if (all || !isempty(paths))
5281 bus_print_property_value(name, expected_value, value, strempty(paths));
5282
5283 return 1;
5284
5285 } else if (streq(name, "TemporaryFileSystem")) {
5286 _cleanup_free_ char *paths = NULL;
5287 const char *target, *option;
5288
5289 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
5290 if (r < 0)
5291 return bus_log_parse_error(r);
5292
5293 while ((r = sd_bus_message_read(m, "(ss)", &target, &option)) > 0) {
5294 _cleanup_free_ char *str = NULL;
5295
5296 if (isempty(target))
5297 continue;
5298
5299 if (asprintf(&str, "%s%s%s", target, isempty(option) ? "" : ":", strempty(option)) < 0)
5300 return log_oom();
5301
5302 if (!strextend_with_separator(&paths, " ", str, NULL))
5303 return log_oom();
5304 }
5305 if (r < 0)
5306 return bus_log_parse_error(r);
5307
5308 r = sd_bus_message_exit_container(m);
5309 if (r < 0)
5310 return bus_log_parse_error(r);
5311
5312 if (all || !isempty(paths))
5313 bus_print_property_value(name, expected_value, value, strempty(paths));
5314
5315 return 1;
305a2850
YW
5316
5317 } else if (streq(name, "LogExtraFields")) {
5318 _cleanup_free_ char *fields = NULL;
5319 const void *p;
5320 size_t sz;
5321
5322 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "ay");
5323 if (r < 0)
5324 return bus_log_parse_error(r);
5325
5326 while ((r = sd_bus_message_read_array(m, 'y', &p, &sz)) > 0) {
5327 _cleanup_free_ char *str = NULL;
5328 const char *eq;
5329
5330 if (memchr(p, 0, sz))
5331 continue;
5332
5333 eq = memchr(p, '=', sz);
5334 if (!eq)
5335 continue;
5336
5337 if (!journal_field_valid(p, eq - (const char*) p, false))
5338 continue;
5339
5340 str = malloc(sz + 1);
5341 if (!str)
5342 return log_oom();
5343
5344 memcpy(str, p, sz);
5345 str[sz] = '\0';
5346
5347 if (!utf8_is_valid(str))
5348 continue;
5349
5350 if (!strextend_with_separator(&fields, " ", str, NULL))
5351 return log_oom();
5352 }
5353 if (r < 0)
5354 return bus_log_parse_error(r);
5355
5356 r = sd_bus_message_exit_container(m);
5357 if (r < 0)
5358 return bus_log_parse_error(r);
5359
5360 if (all || !isempty(fields))
5361 bus_print_property_value(name, expected_value, value, strempty(fields));
5362
5363 return 1;
48220598
LP
5364 }
5365
5366 break;
5367 }
5368
48220598
LP
5369 return 0;
5370}
5371
8559e61d
YW
5372typedef enum SystemctlShowMode{
5373 SYSTEMCTL_SHOW_PROPERTIES,
5374 SYSTEMCTL_SHOW_STATUS,
5375 SYSTEMCTL_SHOW_HELP,
5376 _SYSTEMCTL_SHOW_MODE_MAX,
5377 _SYSTEMCTL_SHOW_MODE_INVALID = -1,
5378} SystemctlShowMode;
5379
aa8d423e 5380static const char* const systemctl_show_mode_table[_SYSTEMCTL_SHOW_MODE_MAX] = {
8559e61d
YW
5381 [SYSTEMCTL_SHOW_PROPERTIES] = "show",
5382 [SYSTEMCTL_SHOW_STATUS] = "status",
5383 [SYSTEMCTL_SHOW_HELP] = "help",
5384};
5385
5386DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode, SystemctlShowMode);
5387
f459b602 5388static int show_one(
f459b602
MAP
5389 sd_bus *bus,
5390 const char *path,
3dced37b 5391 const char *unit,
8559e61d 5392 SystemctlShowMode show_mode,
f459b602
MAP
5393 bool *new_line,
5394 bool *ellipsized) {
5395
3dced37b 5396 static const struct bus_properties_map property_map[] = {
4679a8c3
YW
5397 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
5398 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
5399 { "Documentation", "as", NULL, offsetof(UnitStatusInfo, documentation) },
5400 {}
5401 }, status_map[] = {
5402 { "Id", "s", NULL, offsetof(UnitStatusInfo, id) },
5403 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
5404 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
5405 { "SubState", "s", NULL, offsetof(UnitStatusInfo, sub_state) },
5406 { "UnitFileState", "s", NULL, offsetof(UnitStatusInfo, unit_file_state) },
5407 { "UnitFilePreset", "s", NULL, offsetof(UnitStatusInfo, unit_file_preset) },
5408 { "Description", "s", NULL, offsetof(UnitStatusInfo, description) },
5409 { "Following", "s", NULL, offsetof(UnitStatusInfo, following) },
5410 { "Documentation", "as", NULL, offsetof(UnitStatusInfo, documentation) },
5411 { "FragmentPath", "s", NULL, offsetof(UnitStatusInfo, fragment_path) },
5412 { "SourcePath", "s", NULL, offsetof(UnitStatusInfo, source_path) },
5413 { "ControlGroup", "s", NULL, offsetof(UnitStatusInfo, control_group) },
5414 { "DropInPaths", "as", NULL, offsetof(UnitStatusInfo, dropin_paths) },
5415 { "LoadError", "(ss)", map_load_error, offsetof(UnitStatusInfo, load_error) },
5416 { "Result", "s", NULL, offsetof(UnitStatusInfo, result) },
5417 { "InactiveExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, inactive_exit_timestamp) },
5418 { "InactiveExitTimestampMonotonic", "t", NULL, offsetof(UnitStatusInfo, inactive_exit_timestamp_monotonic) },
5419 { "ActiveEnterTimestamp", "t", NULL, offsetof(UnitStatusInfo, active_enter_timestamp) },
5420 { "ActiveExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, active_exit_timestamp) },
5421 { "InactiveEnterTimestamp", "t", NULL, offsetof(UnitStatusInfo, inactive_enter_timestamp) },
5422 { "NeedDaemonReload", "b", NULL, offsetof(UnitStatusInfo, need_daemon_reload) },
5423 { "Transient", "b", NULL, offsetof(UnitStatusInfo, transient) },
5424 { "ExecMainPID", "u", NULL, offsetof(UnitStatusInfo, main_pid) },
5425 { "MainPID", "u", map_main_pid, 0 },
5426 { "ControlPID", "u", NULL, offsetof(UnitStatusInfo, control_pid) },
5427 { "StatusText", "s", NULL, offsetof(UnitStatusInfo, status_text) },
5428 { "PIDFile", "s", NULL, offsetof(UnitStatusInfo, pid_file) },
5429 { "StatusErrno", "i", NULL, offsetof(UnitStatusInfo, status_errno) },
5430 { "ExecMainStartTimestamp", "t", NULL, offsetof(UnitStatusInfo, start_timestamp) },
5431 { "ExecMainExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, exit_timestamp) },
5432 { "ExecMainCode", "i", NULL, offsetof(UnitStatusInfo, exit_code) },
5433 { "ExecMainStatus", "i", NULL, offsetof(UnitStatusInfo, exit_status) },
5434 { "ConditionTimestamp", "t", NULL, offsetof(UnitStatusInfo, condition_timestamp) },
5435 { "ConditionResult", "b", NULL, offsetof(UnitStatusInfo, condition_result) },
5436 { "Conditions", "a(sbbsi)", map_conditions, 0 },
5437 { "AssertTimestamp", "t", NULL, offsetof(UnitStatusInfo, assert_timestamp) },
5438 { "AssertResult", "b", NULL, offsetof(UnitStatusInfo, assert_result) },
5439 { "Asserts", "a(sbbsi)", map_asserts, 0 },
5440 { "NextElapseUSecRealtime", "t", NULL, offsetof(UnitStatusInfo, next_elapse_real) },
5441 { "NextElapseUSecMonotonic", "t", NULL, offsetof(UnitStatusInfo, next_elapse_monotonic) },
5442 { "NAccepted", "u", NULL, offsetof(UnitStatusInfo, n_accepted) },
5443 { "NConnections", "u", NULL, offsetof(UnitStatusInfo, n_connections) },
a98f7575 5444 { "NRefused", "u", NULL, offsetof(UnitStatusInfo, n_refused) },
4679a8c3
YW
5445 { "Accept", "b", NULL, offsetof(UnitStatusInfo, accept) },
5446 { "Listen", "a(ss)", map_listen, offsetof(UnitStatusInfo, listen) },
5447 { "SysFSPath", "s", NULL, offsetof(UnitStatusInfo, sysfs_path) },
5448 { "Where", "s", NULL, offsetof(UnitStatusInfo, where) },
5449 { "What", "s", NULL, offsetof(UnitStatusInfo, what) },
5450 { "MemoryCurrent", "t", NULL, offsetof(UnitStatusInfo, memory_current) },
48422635 5451 { "MemoryMin", "t", NULL, offsetof(UnitStatusInfo, memory_min) },
4679a8c3
YW
5452 { "MemoryLow", "t", NULL, offsetof(UnitStatusInfo, memory_low) },
5453 { "MemoryHigh", "t", NULL, offsetof(UnitStatusInfo, memory_high) },
5454 { "MemoryMax", "t", NULL, offsetof(UnitStatusInfo, memory_max) },
5455 { "MemorySwapMax", "t", NULL, offsetof(UnitStatusInfo, memory_swap_max) },
5456 { "MemoryLimit", "t", NULL, offsetof(UnitStatusInfo, memory_limit) },
5457 { "CPUUsageNSec", "t", NULL, offsetof(UnitStatusInfo, cpu_usage_nsec) },
5458 { "TasksCurrent", "t", NULL, offsetof(UnitStatusInfo, tasks_current) },
5459 { "TasksMax", "t", NULL, offsetof(UnitStatusInfo, tasks_max) },
5460 { "IPIngressBytes", "t", NULL, offsetof(UnitStatusInfo, ip_ingress_bytes) },
5461 { "IPEgressBytes", "t", NULL, offsetof(UnitStatusInfo, ip_egress_bytes) },
5462 { "ExecStartPre", "a(sasbttttuii)", map_exec, 0 },
5463 { "ExecStart", "a(sasbttttuii)", map_exec, 0 },
5464 { "ExecStartPost", "a(sasbttttuii)", map_exec, 0 },
5465 { "ExecReload", "a(sasbttttuii)", map_exec, 0 },
5466 { "ExecStopPre", "a(sasbttttuii)", map_exec, 0 },
5467 { "ExecStop", "a(sasbttttuii)", map_exec, 0 },
5468 { "ExecStopPost", "a(sasbttttuii)", map_exec, 0 },
3dced37b
LP
5469 {}
5470 };
5471
4afd3348
LP
5472 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
5473 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3dced37b 5474 _cleanup_set_free_ Set *found_properties = NULL;
a7335518 5475 _cleanup_(unit_status_info_free) UnitStatusInfo info = {
934277fe 5476 .memory_current = (uint64_t) -1,
da4d897e
TH
5477 .memory_high = CGROUP_LIMIT_MAX,
5478 .memory_max = CGROUP_LIMIT_MAX,
96e131ea 5479 .memory_swap_max = CGROUP_LIMIT_MAX,
934277fe 5480 .memory_limit = (uint64_t) -1,
5ad096b3 5481 .cpu_usage_nsec = (uint64_t) -1,
03a7b521
LP
5482 .tasks_current = (uint64_t) -1,
5483 .tasks_max = (uint64_t) -1,
0e97c93f
DM
5484 .ip_ingress_bytes = (uint64_t) -1,
5485 .ip_egress_bytes = (uint64_t) -1,
934277fe 5486 };
4679a8c3 5487 char **pp;
f459b602 5488 int r;
48220598 5489
48220598 5490 assert(path);
61cbdc4b 5491 assert(new_line);
48220598 5492
e3e0314b
ZJS
5493 log_debug("Showing one %s", path);
5494
4679a8c3 5495 r = bus_map_all_properties(
f22f08cd
SP
5496 bus,
5497 "org.freedesktop.systemd1",
5498 path,
4679a8c3 5499 show_mode == SYSTEMCTL_SHOW_STATUS ? status_map : property_map,
a7e4861c 5500 BUS_MAP_BOOLEAN_AS_BOOL,
f459b602 5501 &error,
f22f08cd 5502 &reply,
4679a8c3 5503 &info);
4c3e8e39
LP
5504 if (r < 0)
5505 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
48220598 5506
4679a8c3
YW
5507 if (unit && streq_ptr(info.load_state, "not-found") && streq_ptr(info.active_state, "inactive")) {
5508 log_full(show_mode == SYSTEMCTL_SHOW_STATUS ? LOG_ERR : LOG_DEBUG,
5509 "Unit %s could not be found.", unit);
e33a06a1 5510
4679a8c3
YW
5511 if (show_mode == SYSTEMCTL_SHOW_STATUS)
5512 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN;
5513 else if (show_mode == SYSTEMCTL_SHOW_HELP)
5514 return -ENOENT;
5515 }
e33a06a1 5516
4679a8c3
YW
5517 if (*new_line)
5518 printf("\n");
3dced37b 5519
4679a8c3
YW
5520 *new_line = true;
5521
5522 if (show_mode == SYSTEMCTL_SHOW_STATUS) {
5523 print_status_info(bus, &info, ellipsized);
5524
5525 if (info.active_state && !STR_IN_SET(info.active_state, "active", "reloading"))
5526 return EXIT_PROGRAM_NOT_RUNNING;
5527
5528 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK;
5529
5530 } else if (show_mode == SYSTEMCTL_SHOW_HELP) {
5531 show_unit_help(&info);
5532 return 0;
3dced37b 5533 }
e33a06a1 5534
4679a8c3
YW
5535 r = sd_bus_message_rewind(reply, true);
5536 if (r < 0)
5537 return log_error_errno(r, "Failed to rewind: %s", bus_error_message(&error, r));
5538
07636114 5539 r = bus_message_print_all_properties(reply, print_property, arg_properties, arg_value, arg_all, &found_properties);
f459b602
MAP
5540 if (r < 0)
5541 return bus_log_parse_error(r);
48220598 5542
4679a8c3
YW
5543 STRV_FOREACH(pp, arg_properties)
5544 if (!set_contains(found_properties, *pp))
5545 log_debug("Property %s does not exist.", *pp);
3dced37b 5546
4679a8c3 5547 return 0;
48220598
LP
5548}
5549
f74294c1 5550static int get_unit_dbus_path_by_pid(
f459b602
MAP
5551 sd_bus *bus,
5552 uint32_t pid,
f74294c1 5553 char **unit) {
f459b602 5554
4afd3348
LP
5555 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5556 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
373d32c9 5557 char *u;
a223b325
MS
5558 int r;
5559
f459b602 5560 r = sd_bus_call_method(
f22f08cd
SP
5561 bus,
5562 "org.freedesktop.systemd1",
5563 "/org/freedesktop/systemd1",
5564 "org.freedesktop.systemd1.Manager",
5565 "GetUnitByPID",
f459b602 5566 &error,
f22f08cd 5567 &reply,
f459b602 5568 "u", pid);
691395d8
LP
5569 if (r < 0)
5570 return log_error_errno(r, "Failed to get unit for PID %"PRIu32": %s", pid, bus_error_message(&error, r));
a223b325 5571
373d32c9 5572 r = sd_bus_message_read(reply, "o", &u);
f459b602
MAP
5573 if (r < 0)
5574 return bus_log_parse_error(r);
5575
373d32c9
LP
5576 u = strdup(u);
5577 if (!u)
5578 return log_oom();
5579
5580 *unit = u;
f74294c1 5581 return 0;
a223b325
MS
5582}
5583
f459b602 5584static int show_all(
f459b602 5585 sd_bus *bus,
f459b602
MAP
5586 bool *new_line,
5587 bool *ellipsized) {
5588
4afd3348 5589 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602
MAP
5590 _cleanup_free_ UnitInfo *unit_infos = NULL;
5591 const UnitInfo *u;
5592 unsigned c;
5bb75bc7 5593 int r, ret = 0;
265a7a2a 5594
1238ee09 5595 r = get_unit_list(bus, NULL, NULL, &unit_infos, 0, &reply);
265a7a2a
ZJS
5596 if (r < 0)
5597 return r;
5598
0221d68a 5599 (void) pager_open(arg_pager_flags);
dbed408b 5600
f459b602
MAP
5601 c = (unsigned) r;
5602
93bab288 5603 typesafe_qsort(unit_infos, c, compare_unit_info);
991f2a39 5604
265a7a2a 5605 for (u = unit_infos; u < unit_infos + c; u++) {
7fd1b19b 5606 _cleanup_free_ char *p = NULL;
265a7a2a 5607
265a7a2a
ZJS
5608 p = unit_dbus_path_from_name(u->id);
5609 if (!p)
5610 return log_oom();
5611
8559e61d 5612 r = show_one(bus, p, u->id, SYSTEMCTL_SHOW_STATUS, new_line, ellipsized);
3df538da 5613 if (r < 0)
265a7a2a 5614 return r;
5bb75bc7
ZJS
5615 else if (r > 0 && ret == 0)
5616 ret = r;
265a7a2a
ZJS
5617 }
5618
5bb75bc7 5619 return ret;
265a7a2a
ZJS
5620}
5621
8fcf784d
LP
5622static int show_system_status(sd_bus *bus) {
5623 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX];
f9e0eefc 5624 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
e7e55dbd 5625 _cleanup_(machine_info_clear) struct machine_info mi = {};
f9e0eefc 5626 _cleanup_free_ char *hn = NULL;
8fcf784d
LP
5627 const char *on, *off;
5628 int r;
5629
5630 hn = gethostname_malloc();
5631 if (!hn)
5632 return log_oom();
5633
a7e4861c
YW
5634 r = bus_map_all_properties(
5635 bus,
5636 "org.freedesktop.systemd1",
5637 "/org/freedesktop/systemd1",
5638 machine_info_property_map,
5639 BUS_MAP_STRDUP,
5640 &error,
5641 NULL,
5642 &mi);
f647962d 5643 if (r < 0)
f9e0eefc 5644 return log_error_errno(r, "Failed to read server status: %s", bus_error_message(&error, r));
8fcf784d 5645
8fcf784d
LP
5646 if (streq_ptr(mi.state, "degraded")) {
5647 on = ansi_highlight_red();
1fc464f6 5648 off = ansi_normal();
92f34a9c
JR
5649 } else if (streq_ptr(mi.state, "running")) {
5650 on = ansi_highlight_green();
5651 off = ansi_normal();
5652 } else {
8fcf784d 5653 on = ansi_highlight_yellow();
1fc464f6 5654 off = ansi_normal();
92f34a9c 5655 }
8fcf784d 5656
9a6f746f 5657 printf("%s%s%s %s\n", on, special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE), off, arg_host ? arg_host : hn);
b0d14c69 5658
8fcf784d
LP
5659 printf(" State: %s%s%s\n",
5660 on, strna(mi.state), off);
5661
c6ba5b80
MP
5662 printf(" Jobs: %" PRIu32 " queued\n", mi.n_jobs);
5663 printf(" Failed: %" PRIu32 " units\n", mi.n_failed_units);
8fcf784d
LP
5664
5665 printf(" Since: %s; %s\n",
5666 format_timestamp(since2, sizeof(since2), mi.timestamp),
5667 format_timestamp_relative(since1, sizeof(since1), mi.timestamp));
5668
5669 printf(" CGroup: %s\n", mi.control_group ?: "/");
4c315c2c
IS
5670 if (IN_SET(arg_transport,
5671 BUS_TRANSPORT_LOCAL,
5672 BUS_TRANSPORT_MACHINE)) {
8fcf784d
LP
5673 static const char prefix[] = " ";
5674 unsigned c;
5675
5676 c = columns();
5677 if (c > sizeof(prefix) - 1)
5678 c -= sizeof(prefix) - 1;
5679 else
5680 c = 0;
5681
0ff308c8 5682 show_cgroup(SYSTEMD_CGROUP_CONTROLLER, strempty(mi.control_group), prefix, c, get_output_flags());
8fcf784d
LP
5683 }
5684
8fcf784d
LP
5685 return 0;
5686}
5687
e449de87 5688static int show(int argc, char *argv[], void *userdata) {
8559e61d
YW
5689 bool new_line = false, ellipsized = false;
5690 SystemctlShowMode show_mode;
e3e0314b 5691 int r, ret = 0;
4fbd7192 5692 sd_bus *bus;
48220598 5693
e449de87 5694 assert(argv);
48220598 5695
8559e61d 5696 show_mode = systemctl_show_mode_from_string(argv[0]);
baaa35ad
ZJS
5697 if (show_mode < 0)
5698 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5699 "Invalid argument.");
e449de87 5700
baaa35ad
ZJS
5701 if (show_mode == SYSTEMCTL_SHOW_HELP && argc <= 1)
5702 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
5703 "This command expects one or more unit names. Did you mean --help?");
61cbdc4b 5704
d2ad7e1b
ZJS
5705 r = acquire_bus(BUS_MANAGER, &bus);
5706 if (r < 0)
5707 return r;
5708
0221d68a 5709 (void) pager_open(arg_pager_flags);
ec14911e 5710
4fbd7192 5711 /* If no argument is specified inspect the manager itself */
8559e61d
YW
5712 if (show_mode == SYSTEMCTL_SHOW_PROPERTIES && argc <= 1)
5713 return show_one(bus, "/org/freedesktop/systemd1", NULL, show_mode, &new_line, &ellipsized);
48220598 5714
8559e61d 5715 if (show_mode == SYSTEMCTL_SHOW_STATUS && argc <= 1) {
8fcf784d 5716
8fcf784d
LP
5717 show_system_status(bus);
5718 new_line = true;
5719
5720 if (arg_all)
8559e61d 5721 ret = show_all(bus, &new_line, &ellipsized);
8fcf784d 5722 } else {
e3e0314b
ZJS
5723 _cleanup_free_ char **patterns = NULL;
5724 char **name;
5725
e449de87 5726 STRV_FOREACH(name, strv_skip(argv, 1)) {
3dced37b 5727 _cleanup_free_ char *path = NULL, *unit = NULL;
94e0bd7d 5728 uint32_t id;
48220598 5729
94e0bd7d 5730 if (safe_atou32(*name, &id) < 0) {
e3e0314b 5731 if (strv_push(&patterns, *name) < 0)
94e0bd7d 5732 return log_oom();
48220598 5733
e3e0314b 5734 continue;
8559e61d 5735 } else if (show_mode == SYSTEMCTL_SHOW_PROPERTIES) {
94e0bd7d 5736 /* Interpret as job id */
3dced37b 5737 if (asprintf(&path, "/org/freedesktop/systemd1/job/%u", id) < 0)
94e0bd7d 5738 return log_oom();
48220598 5739
94e0bd7d
ZJS
5740 } else {
5741 /* Interpret as PID */
3dced37b 5742 r = get_unit_dbus_path_by_pid(bus, id, &path);
373d32c9 5743 if (r < 0) {
94e0bd7d 5744 ret = r;
373d32c9
LP
5745 continue;
5746 }
3dced37b
LP
5747
5748 r = unit_name_from_dbus_path(path, &unit);
5749 if (r < 0)
5750 return log_oom();
94e0bd7d 5751 }
f74294c1 5752
8559e61d 5753 r = show_one(bus, path, unit, show_mode, &new_line, &ellipsized);
5bb75bc7
ZJS
5754 if (r < 0)
5755 return r;
5756 else if (r > 0 && ret == 0)
5757 ret = r;
48220598 5758 }
94e0bd7d 5759
e3e0314b
ZJS
5760 if (!strv_isempty(patterns)) {
5761 _cleanup_strv_free_ char **names = NULL;
5762
5763 r = expand_names(bus, patterns, NULL, &names);
5764 if (r < 0)
691395d8 5765 return log_error_errno(r, "Failed to expand names: %m");
e3e0314b
ZJS
5766
5767 STRV_FOREACH(name, names) {
3dced37b 5768 _cleanup_free_ char *path;
e3e0314b 5769
3dced37b
LP
5770 path = unit_dbus_path_from_name(*name);
5771 if (!path)
e3e0314b
ZJS
5772 return log_oom();
5773
8559e61d 5774 r = show_one(bus, path, *name, show_mode, &new_line, &ellipsized);
5bb75bc7
ZJS
5775 if (r < 0)
5776 return r;
3dced37b 5777 if (r > 0 && ret == 0)
5bb75bc7 5778 ret = r;
e3e0314b
ZJS
5779 }
5780 }
5781 }
5782
94e0bd7d
ZJS
5783 if (ellipsized && !arg_quiet)
5784 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
48220598 5785
22f4096c 5786 return ret;
0183528f
LP
5787}
5788
e449de87 5789static int cat(int argc, char *argv[], void *userdata) {
8e766630 5790 _cleanup_(lookup_paths_free) LookupPaths lp = {};
15ef1144
LP
5791 _cleanup_strv_free_ char **names = NULL;
5792 char **name;
4fbd7192
LP
5793 sd_bus *bus;
5794 bool first = true;
25586912 5795 int r;
15ef1144 5796
3e7eed84 5797 if (arg_transport != BUS_TRANSPORT_LOCAL) {
4fbd7192 5798 log_error("Cannot remotely cat units.");
3e495a66
ZJS
5799 return -EINVAL;
5800 }
5801
4943d143 5802 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
ad2a0358 5803 if (r < 0)
c51932be 5804 return log_error_errno(r, "Failed to determine unit paths: %m");
ad2a0358 5805
4fbd7192 5806 r = acquire_bus(BUS_MANAGER, &bus);
15ef1144 5807 if (r < 0)
4fbd7192 5808 return r;
15ef1144 5809
e449de87 5810 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
4fbd7192
LP
5811 if (r < 0)
5812 return log_error_errno(r, "Failed to expand names: %m");
ad2a0358 5813
0221d68a 5814 (void) pager_open(arg_pager_flags);
15ef1144
LP
5815
5816 STRV_FOREACH(name, names) {
ad2a0358 5817 _cleanup_free_ char *fragment_path = NULL;
15ef1144 5818 _cleanup_strv_free_ char **dropin_paths = NULL;
15ef1144 5819
02a126a3 5820 r = unit_find_paths(bus, *name, &lp, false, &fragment_path, &dropin_paths);
86f004fb 5821 if (r == -ERFKILL) {
02a126a3
LP
5822 printf("%s# Unit %s is masked%s.\n",
5823 ansi_highlight_magenta(),
5824 *name,
5825 ansi_normal());
5826 continue;
5827 }
5828 if (r == -EKEYREJECTED) {
5829 printf("%s# Unit %s could not be loaded.%s\n",
86f004fb
ZJS
5830 ansi_highlight_magenta(),
5831 *name,
5832 ansi_normal());
5833 continue;
5834 }
ad2a0358
ZJS
5835 if (r < 0)
5836 return r;
02a126a3 5837 if (r == 0)
b5e6a600 5838 return -ENOENT;
15ef1144
LP
5839
5840 if (first)
5841 first = false;
5842 else
5843 puts("");
5844
5b9635d1 5845 if (need_daemon_reload(bus, *name) > 0) /* ignore errors (<0), this is informational output */
e100155d
LW
5846 fprintf(stderr,
5847 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
5848 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
5849 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
5850 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
5851 ansi_highlight_red(),
5852 *name,
5853 ansi_highlight_red(),
5854 ansi_highlight_red(),
5855 ansi_highlight_red(),
5856 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user",
5857 ansi_normal());
5858
854a42fb 5859 r = cat_files(fragment_path, dropin_paths, 0);
81f5e513
ZJS
5860 if (r < 0)
5861 return r;
15ef1144
LP
5862 }
5863
25586912 5864 return 0;
15ef1144
LP
5865}
5866
e449de87 5867static int set_property(int argc, char *argv[], void *userdata) {
4afd3348
LP
5868 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5869 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
68372da6 5870 _cleanup_free_ char *n = NULL;
89ada3ba 5871 UnitType t;
4fbd7192 5872 sd_bus *bus;
8e2af478
LP
5873 int r;
5874
4fbd7192
LP
5875 r = acquire_bus(BUS_MANAGER, &bus);
5876 if (r < 0)
5877 return r;
5878
8a4b13c5 5879 polkit_agent_open_maybe();
d2ad7e1b 5880
f459b602
MAP
5881 r = sd_bus_message_new_method_call(
5882 bus,
151b9b96 5883 &m,
8e2af478
LP
5884 "org.freedesktop.systemd1",
5885 "/org/freedesktop/systemd1",
5886 "org.freedesktop.systemd1.Manager",
151b9b96 5887 "SetUnitProperties");
f459b602
MAP
5888 if (r < 0)
5889 return bus_log_create_error(r);
8e2af478 5890
37cbc1d5 5891 r = unit_name_mangle(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, &n);
7410616c
LP
5892 if (r < 0)
5893 return log_error_errno(r, "Failed to mangle unit name: %m");
68372da6 5894
89ada3ba
YW
5895 t = unit_name_to_type(n);
5896 if (t < 0) {
5897 log_error("Invalid unit type: %s", n);
5898 return -EINVAL;
5899 }
5900
f459b602
MAP
5901 r = sd_bus_message_append(m, "sb", n, arg_runtime);
5902 if (r < 0)
5903 return bus_log_create_error(r);
8e2af478 5904
f459b602
MAP
5905 r = sd_bus_message_open_container(m, SD_BUS_TYPE_ARRAY, "(sv)");
5906 if (r < 0)
5907 return bus_log_create_error(r);
8e2af478 5908
89ada3ba 5909 r = bus_append_unit_property_assignment_many(m, t, strv_skip(argv, 2));
8673cf13
LP
5910 if (r < 0)
5911 return r;
8e2af478 5912
f459b602
MAP
5913 r = sd_bus_message_close_container(m);
5914 if (r < 0)
5915 return bus_log_create_error(r);
8e2af478 5916
c49b30a2 5917 r = sd_bus_call(bus, m, 0, &error, NULL);
691395d8
LP
5918 if (r < 0)
5919 return log_error_errno(r, "Failed to set unit properties on %s: %s", n, bus_error_message(&error, r));
8e2af478
LP
5920
5921 return 0;
5922}
5923
e449de87 5924static int daemon_reload(int argc, char *argv[], void *userdata) {
4afd3348 5925 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2853b60a 5926 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
7e4249b9 5927 const char *method;
4fbd7192 5928 sd_bus *bus;
f459b602 5929 int r;
7e4249b9 5930
4fbd7192
LP
5931 r = acquire_bus(BUS_MANAGER, &bus);
5932 if (r < 0)
5933 return r;
5934
8a4b13c5 5935 polkit_agent_open_maybe();
d2ad7e1b 5936
2853b60a
LP
5937 switch (arg_action) {
5938
5939 case ACTION_RELOAD:
e4b61340 5940 method = "Reload";
2853b60a
LP
5941 break;
5942
5943 case ACTION_REEXEC:
e4b61340 5944 method = "Reexecute";
2853b60a
LP
5945 break;
5946
5947 case ACTION_SYSTEMCTL:
5948 method = streq(argv[0], "daemon-reexec") ? "Reexecute" :
5949 /* "daemon-reload" */ "Reload";
5950 break;
e4b61340 5951
2853b60a
LP
5952 default:
5953 assert_not_reached("Unexpected action");
e4b61340 5954 }
7e4249b9 5955
2853b60a
LP
5956 r = sd_bus_message_new_method_call(
5957 bus,
5958 &m,
5959 "org.freedesktop.systemd1",
5960 "/org/freedesktop/systemd1",
5961 "org.freedesktop.systemd1.Manager",
5962 method);
5963 if (r < 0)
5964 return bus_log_create_error(r);
5965
5966 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
5967 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
5968 * their timeout, and for everything else there's the same time budget in place. */
5969
5970 r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC * 2, &error, NULL);
5971
5972 /* On reexecution, we expect a disconnect, not a reply */
5973 if (IN_SET(r, -ETIMEDOUT, -ECONNRESET) && streq(method, "Reexecute"))
5974 r = 0;
5975
5976 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
5977 return log_error_errno(r, "Failed to reload daemon: %s", bus_error_message(&error, r));
5978
5979 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
5980 * old ways of doing things, hence don't log any error in that case here. */
5981
5982 return r < 0 ? r : 0;
5983}
5984
5985static int trivial_method(int argc, char *argv[], void *userdata) {
5986 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5987 const char *method;
5988 sd_bus *bus;
5989 int r;
5990
1ae17672
ZJS
5991 if (arg_dry_run)
5992 return 0;
5993
2853b60a
LP
5994 r = acquire_bus(BUS_MANAGER, &bus);
5995 if (r < 0)
5996 return r;
5997
8a4b13c5 5998 polkit_agent_open_maybe();
d2ad7e1b 5999
2853b60a
LP
6000 method =
6001 streq(argv[0], "clear-jobs") ||
6002 streq(argv[0], "cancel") ? "ClearJobs" :
6003 streq(argv[0], "reset-failed") ? "ResetFailed" :
6004 streq(argv[0], "halt") ? "Halt" :
6005 streq(argv[0], "reboot") ? "Reboot" :
6006 streq(argv[0], "kexec") ? "KExec" :
6007 streq(argv[0], "exit") ? "Exit" :
6008 /* poweroff */ "PowerOff";
6009
6e646d22 6010 r = sd_bus_call_method(
f22f08cd
SP
6011 bus,
6012 "org.freedesktop.systemd1",
6013 "/org/freedesktop/systemd1",
6014 "org.freedesktop.systemd1.Manager",
6e646d22
LP
6015 method,
6016 &error,
6017 NULL,
6018 NULL);
2853b60a
LP
6019 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
6020 return log_error_errno(r, "Failed to execute operation: %s", bus_error_message(&error, r));
6021
6022 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
6023 * old ways of doing things, hence don't log any error in that case here. */
7e4249b9 6024
0a9776c2 6025 return r < 0 ? r : 0;
7e4249b9
LP
6026}
6027
e449de87 6028static int reset_failed(int argc, char *argv[], void *userdata) {
e3e0314b 6029 _cleanup_strv_free_ char **names = NULL;
4fbd7192 6030 sd_bus *bus;
f84190d8 6031 char **name;
e3e0314b 6032 int r, q;
5632e374 6033
e449de87 6034 if (argc <= 1)
2853b60a 6035 return trivial_method(argc, argv, userdata);
5632e374 6036
4fbd7192
LP
6037 r = acquire_bus(BUS_MANAGER, &bus);
6038 if (r < 0)
6039 return r;
6040
8a4b13c5 6041 polkit_agent_open_maybe();
d2ad7e1b 6042
e449de87 6043 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
e3e0314b 6044 if (r < 0)
691395d8 6045 return log_error_errno(r, "Failed to expand names: %m");
f84190d8 6046
e3e0314b 6047 STRV_FOREACH(name, names) {
4afd3348 6048 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
342641fb 6049
6e646d22 6050 q = sd_bus_call_method(
f22f08cd 6051 bus,
b0193f1c
LP
6052 "org.freedesktop.systemd1",
6053 "/org/freedesktop/systemd1",
6054 "org.freedesktop.systemd1.Manager",
6e646d22
LP
6055 "ResetFailedUnit",
6056 &error,
6057 NULL,
6058 "s", *name);
e3e0314b 6059 if (q < 0) {
691395d8 6060 log_error_errno(q, "Failed to reset failed state of unit %s: %s", *name, bus_error_message(&error, q));
e3e0314b
ZJS
6061 if (r == 0)
6062 r = q;
f459b602 6063 }
5632e374
LP
6064 }
6065
e3e0314b 6066 return r;
5632e374
LP
6067}
6068
804ee07c
ZJS
6069static int print_variable(const char *s) {
6070 const char *sep;
6071 _cleanup_free_ char *esc = NULL;
6072
6073 sep = strchr(s, '=');
baaa35ad
ZJS
6074 if (!sep)
6075 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN),
6076 "Invalid environment block");
804ee07c
ZJS
6077
6078 esc = shell_maybe_quote(sep + 1, ESCAPE_POSIX);
6079 if (!esc)
6080 return log_oom();
6081
6082 printf("%.*s=%s\n", (int)(sep-s), s, esc);
6083 return 0;
6084}
6085
e449de87 6086static int show_environment(int argc, char *argv[], void *userdata) {
4afd3348
LP
6087 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6088 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602 6089 const char *text;
4fbd7192 6090 sd_bus *bus;
7e4249b9 6091 int r;
7e4249b9 6092
4fbd7192
LP
6093 r = acquire_bus(BUS_MANAGER, &bus);
6094 if (r < 0)
6095 return r;
6096
0221d68a 6097 (void) pager_open(arg_pager_flags);
d2ad7e1b 6098
f459b602 6099 r = sd_bus_get_property(
f22f08cd
SP
6100 bus,
6101 "org.freedesktop.systemd1",
6102 "/org/freedesktop/systemd1",
f459b602
MAP
6103 "org.freedesktop.systemd1.Manager",
6104 "Environment",
6105 &error,
f22f08cd 6106 &reply,
f459b602 6107 "as");
691395d8
LP
6108 if (r < 0)
6109 return log_error_errno(r, "Failed to get environment: %s", bus_error_message(&error, r));
7e4249b9 6110
f459b602
MAP
6111 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
6112 if (r < 0)
6113 return bus_log_parse_error(r);
7e4249b9 6114
804ee07c
ZJS
6115 while ((r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &text)) > 0) {
6116 r = print_variable(text);
6117 if (r < 0)
6118 return r;
6119 }
f459b602
MAP
6120 if (r < 0)
6121 return bus_log_parse_error(r);
7e4249b9 6122
f459b602
MAP
6123 r = sd_bus_message_exit_container(reply);
6124 if (r < 0)
6125 return bus_log_parse_error(r);
7e4249b9 6126
f84190d8 6127 return 0;
7e4249b9
LP
6128}
6129
e449de87 6130static int switch_root(int argc, char *argv[], void *userdata) {
4afd3348 6131 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
f39d4a08
HH
6132 _cleanup_free_ char *cmdline_init = NULL;
6133 const char *root, *init;
4fbd7192 6134 sd_bus *bus;
f459b602 6135 int r;
957eb8ca 6136
4fbd7192
LP
6137 if (arg_transport != BUS_TRANSPORT_LOCAL) {
6138 log_error("Cannot switch root remotely.");
6139 return -EINVAL;
6140 }
6141
e449de87 6142 if (argc < 2 || argc > 3) {
957eb8ca
LP
6143 log_error("Wrong number of arguments.");
6144 return -EINVAL;
6145 }
6146
e449de87 6147 root = argv[1];
13068da8 6148
e449de87
LP
6149 if (argc >= 3)
6150 init = argv[2];
13068da8 6151 else {
01771226 6152 r = proc_cmdline_get_key("init", 0, &cmdline_init);
f39d4a08 6153 if (r < 0)
da927ba9 6154 log_debug_errno(r, "Failed to parse /proc/cmdline: %m");
13068da8 6155
f39d4a08 6156 init = cmdline_init;
13068da8 6157 }
f459b602 6158
3c6f7c34 6159 init = empty_to_null(init);
f39d4a08
HH
6160 if (init) {
6161 const char *root_systemd_path = NULL, *root_init_path = NULL;
6162
63c372cb
LP
6163 root_systemd_path = strjoina(root, "/" SYSTEMD_BINARY_PATH);
6164 root_init_path = strjoina(root, "/", init);
f39d4a08
HH
6165
6166 /* If the passed init is actually the same as the
6167 * systemd binary, then let's suppress it. */
e3f791a2 6168 if (files_same(root_init_path, root_systemd_path, 0) > 0)
f39d4a08
HH
6169 init = NULL;
6170 }
13068da8 6171
acc28e2e 6172 /* Instruct PID1 to exclude us from its killing spree applied during
b3ad0ff4
ZJS
6173 * the transition. Otherwise we would exit with a failure status even
6174 * though the switch to the new root has succeed. */
6175 argv_cmdline[0] = '@';
acc28e2e 6176
4fbd7192
LP
6177 r = acquire_bus(BUS_MANAGER, &bus);
6178 if (r < 0)
6179 return r;
6180
8a7a9cea
ZJS
6181 /* If we are slow to exit after the root switch, the new systemd instance
6182 * will send us a signal to terminate. Just ignore it and exit normally.
6183 * This way the unit does not end up as failed.
6184 */
6185 r = ignore_signals(SIGTERM, -1);
6186 if (r < 0)
6187 log_warning_errno(r, "Failed to change disposition of SIGTERM to ignore: %m");
6188
f39d4a08 6189 log_debug("Switching root - root: %s; init: %s", root, strna(init));
957eb8ca 6190
f459b602 6191 r = sd_bus_call_method(
f22f08cd 6192 bus,
957eb8ca
LP
6193 "org.freedesktop.systemd1",
6194 "/org/freedesktop/systemd1",
6195 "org.freedesktop.systemd1.Manager",
f22f08cd 6196 "SwitchRoot",
f459b602 6197 &error,
f22f08cd 6198 NULL,
f459b602 6199 "ss", root, init);
8a7a9cea
ZJS
6200 if (r < 0) {
6201 (void) default_signals(SIGTERM, -1);
6202
691395d8 6203 return log_error_errno(r, "Failed to switch root: %s", bus_error_message(&error, r));
8a7a9cea 6204 }
f459b602
MAP
6205
6206 return 0;
957eb8ca
LP
6207}
6208
e449de87 6209static int set_environment(int argc, char *argv[], void *userdata) {
4afd3348
LP
6210 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6211 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
7e4249b9 6212 const char *method;
4fbd7192 6213 sd_bus *bus;
31e767f7
LP
6214 int r;
6215
e449de87
LP
6216 assert(argc > 1);
6217 assert(argv);
7e4249b9 6218
4fbd7192
LP
6219 r = acquire_bus(BUS_MANAGER, &bus);
6220 if (r < 0)
6221 return r;
6222
8a4b13c5 6223 polkit_agent_open_maybe();
d2ad7e1b 6224
e449de87 6225 method = streq(argv[0], "set-environment")
7e4249b9
LP
6226 ? "SetEnvironment"
6227 : "UnsetEnvironment";
6228
f459b602
MAP
6229 r = sd_bus_message_new_method_call(
6230 bus,
151b9b96 6231 &m,
31e767f7
LP
6232 "org.freedesktop.systemd1",
6233 "/org/freedesktop/systemd1",
6234 "org.freedesktop.systemd1.Manager",
151b9b96 6235 method);
f459b602
MAP
6236 if (r < 0)
6237 return bus_log_create_error(r);
7e4249b9 6238
e449de87 6239 r = sd_bus_message_append_strv(m, strv_skip(argv, 1));
31e767f7 6240 if (r < 0)
f459b602 6241 return bus_log_create_error(r);
7e4249b9 6242
c49b30a2 6243 r = sd_bus_call(bus, m, 0, &error, NULL);
691395d8
LP
6244 if (r < 0)
6245 return log_error_errno(r, "Failed to set environment: %s", bus_error_message(&error, r));
7e4249b9 6246
f84190d8 6247 return 0;
7e4249b9
LP
6248}
6249
e449de87 6250static int import_environment(int argc, char *argv[], void *userdata) {
4afd3348
LP
6251 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6252 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
4fbd7192 6253 sd_bus *bus;
ac3efa8a
LP
6254 int r;
6255
4fbd7192
LP
6256 r = acquire_bus(BUS_MANAGER, &bus);
6257 if (r < 0)
6258 return r;
6259
8a4b13c5 6260 polkit_agent_open_maybe();
d2ad7e1b 6261
ac3efa8a
LP
6262 r = sd_bus_message_new_method_call(
6263 bus,
151b9b96 6264 &m,
ac3efa8a
LP
6265 "org.freedesktop.systemd1",
6266 "/org/freedesktop/systemd1",
6267 "org.freedesktop.systemd1.Manager",
151b9b96 6268 "SetEnvironment");
ac3efa8a
LP
6269 if (r < 0)
6270 return bus_log_create_error(r);
6271
e449de87 6272 if (argc < 2)
ac3efa8a
LP
6273 r = sd_bus_message_append_strv(m, environ);
6274 else {
6275 char **a, **b;
6276
6277 r = sd_bus_message_open_container(m, 'a', "s");
6278 if (r < 0)
6279 return bus_log_create_error(r);
6280
e449de87 6281 STRV_FOREACH(a, strv_skip(argv, 1)) {
ac3efa8a
LP
6282
6283 if (!env_name_is_valid(*a)) {
6284 log_error("Not a valid environment variable name: %s", *a);
6285 return -EINVAL;
6286 }
6287
6288 STRV_FOREACH(b, environ) {
6289 const char *eq;
6290
6291 eq = startswith(*b, *a);
6292 if (eq && *eq == '=') {
6293
6294 r = sd_bus_message_append(m, "s", *b);
6295 if (r < 0)
6296 return bus_log_create_error(r);
6297
6298 break;
6299 }
6300 }
6301 }
6302
6303 r = sd_bus_message_close_container(m);
6304 }
6305 if (r < 0)
6306 return bus_log_create_error(r);
6307
6308 r = sd_bus_call(bus, m, 0, &error, NULL);
691395d8
LP
6309 if (r < 0)
6310 return log_error_errno(r, "Failed to import environment: %s", bus_error_message(&error, r));
ac3efa8a
LP
6311
6312 return 0;
6313}
6314
cbb13b2a 6315static int enable_sysv_units(const char *verb, char **args) {
729e3769 6316 int r = 0;
ee5762e3 6317
349cc4a5 6318#if HAVE_SYSV_COMPAT
8e766630 6319 _cleanup_(lookup_paths_free) LookupPaths paths = {};
e735decc
LP
6320 unsigned f = 0;
6321
6322 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
ee5762e3 6323
729e3769
LP
6324 if (arg_scope != UNIT_FILE_SYSTEM)
6325 return 0;
ee5762e3 6326
b41b9d2a
LP
6327 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
6328 return 0;
6329
4c315c2c
IS
6330 if (!STR_IN_SET(verb,
6331 "enable",
6332 "disable",
6333 "is-enabled"))
729e3769 6334 return 0;
ee5762e3 6335
4943d143 6336 r = lookup_paths_init(&paths, arg_scope, LOOKUP_PATHS_EXCLUDE_GENERATED, arg_root);
729e3769
LP
6337 if (r < 0)
6338 return r;
ee5762e3 6339
729e3769 6340 r = 0;
a644abed 6341 while (args[f]) {
e735decc
LP
6342
6343 const char *argv[] = {
6344 ROOTLIBEXECDIR "/systemd-sysv-install",
6345 NULL,
6346 NULL,
6347 NULL,
6348 NULL,
6349 };
6350
05cae7f3 6351 _cleanup_free_ char *p = NULL, *q = NULL, *l = NULL;
729e3769 6352 bool found_native = false, found_sysv;
e735decc 6353 const char *name;
729e3769 6354 unsigned c = 1;
729e3769 6355 pid_t pid;
e735decc 6356 int j;
ee5762e3 6357
a644abed 6358 name = args[f++];
ee5762e3 6359
729e3769
LP
6360 if (!endswith(name, ".service"))
6361 continue;
ee5762e3 6362
729e3769
LP
6363 if (path_is_absolute(name))
6364 continue;
ee5762e3 6365
e735decc 6366 j = unit_file_exists(arg_scope, &paths, name);
76ec966f 6367 if (j < 0 && !IN_SET(j, -ELOOP, -ERFKILL, -EADDRNOTAVAIL))
e735decc 6368 return log_error_errno(j, "Failed to lookup unit file state: %m");
3c6d8e57 6369 found_native = j != 0;
ee5762e3 6370
e735decc
LP
6371 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
6372 * prefer the native unit */
355ff449 6373 if (found_native && streq(verb, "is-enabled"))
729e3769 6374 continue;
ee5762e3 6375
652ef298 6376 p = path_join(arg_root, SYSTEM_SYSVINIT_PATH, name);
0c6ea3a4 6377 if (!p)
60731f32 6378 return log_oom();
ee5762e3 6379
fbd0b64f 6380 p[strlen(p) - STRLEN(".service")] = 0;
729e3769 6381 found_sysv = access(p, F_OK) >= 0;
4b6756a8 6382 if (!found_sysv)
729e3769 6383 continue;
71fad675 6384
689e4e6a
CR
6385 if (!arg_quiet) {
6386 if (found_native)
6387 log_info("Synchronizing state of %s with SysV service script with %s.", name, argv[0]);
6388 else
6389 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name);
6390 }
ee5762e3 6391
729e3769
LP
6392 if (!isempty(arg_root))
6393 argv[c++] = q = strappend("--root=", arg_root);
ee5762e3 6394
0f0467e6 6395 argv[c++] = verb;
2b6bf07d 6396 argv[c++] = basename(p);
729e3769 6397 argv[c] = NULL;
ee5762e3 6398
729e3769 6399 l = strv_join((char**)argv, " ");
60731f32
ZJS
6400 if (!l)
6401 return log_oom();
ee5762e3 6402
8ecc68f4
LP
6403 if (!arg_quiet)
6404 log_info("Executing: %s", l);
ee5762e3 6405
0672e2c6 6406 j = safe_fork("(sysv-install)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid);
4c253ed1 6407 if (j < 0)
b6e1fff1 6408 return j;
4c253ed1 6409 if (j == 0) {
729e3769 6410 /* Child */
729e3769 6411 execv(argv[0], (char**) argv);
cc7cb0ca 6412 log_error_errno(errno, "Failed to execute %s: %m", argv[0]);
729e3769
LP
6413 _exit(EXIT_FAILURE);
6414 }
ee5762e3 6415
2e87a1fd 6416 j = wait_for_terminate_and_check("sysv-install", pid, WAIT_LOG_ABNORMAL);
d710aaf7 6417 if (j < 0)
2e87a1fd
LP
6418 return j;
6419 if (streq(verb, "is-enabled")) {
b4a34311 6420 if (j == EXIT_SUCCESS) {
2e87a1fd
LP
6421 if (!arg_quiet)
6422 puts("enabled");
6423 r = 1;
6424 } else {
6425 if (!arg_quiet)
6426 puts("disabled");
6427 }
ee5762e3 6428
b4a34311 6429 } else if (j != EXIT_SUCCESS)
2e87a1fd 6430 return -EBADE; /* We don't warn here, under the assumption the script already showed an explanation */
ee5762e3 6431
355ff449
MP
6432 if (found_native)
6433 continue;
6434
a644abed 6435 /* Remove this entry, so that we don't try enabling it as native unit */
aba84331
LP
6436 assert(f > 0);
6437 f--;
6438 assert(args[f] == name);
6439 strv_remove(args, name);
729e3769 6440 }
ee5762e3 6441
729e3769
LP
6442#endif
6443 return r;
6444}
ee5762e3 6445
37370d0c 6446static int mangle_names(char **original_names, char ***mangled_names) {
a33fdebb 6447 char **i, **l, **name;
7410616c 6448 int r;
37370d0c 6449
7410616c 6450 l = i = new(char*, strv_length(original_names) + 1);
a33fdebb 6451 if (!l)
37370d0c
VP
6452 return log_oom();
6453
37370d0c 6454 STRV_FOREACH(name, original_names) {
44386fc1
LN
6455
6456 /* When enabling units qualified path names are OK,
6457 * too, hence allow them explicitly. */
6458
7410616c 6459 if (is_path(*name)) {
44386fc1 6460 *i = strdup(*name);
7410616c
LP
6461 if (!*i) {
6462 strv_free(l);
6463 return log_oom();
6464 }
6465 } else {
37cbc1d5 6466 r = unit_name_mangle(*name, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, i);
7410616c 6467 if (r < 0) {
523f8cde 6468 *i = NULL;
7410616c
LP
6469 strv_free(l);
6470 return log_error_errno(r, "Failed to mangle unit name: %m");
6471 }
a33fdebb
LP
6472 }
6473
6474 i++;
37370d0c 6475 }
a33fdebb
LP
6476
6477 *i = NULL;
6478 *mangled_names = l;
37370d0c
VP
6479
6480 return 0;
6481}
6482
decd7982
JR
6483static int normalize_filenames(char **names) {
6484 char **u;
6485 int r;
6486
6487 STRV_FOREACH(u, names)
6488 if (!path_is_absolute(*u)) {
6489 char* normalized_path;
6490
baaa35ad
ZJS
6491 if (!isempty(arg_root))
6492 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
6493 "Non-absolute paths are not allowed when --root is used: %s",
6494 *u);
decd7982 6495
baaa35ad
ZJS
6496 if (!strchr(*u,'/'))
6497 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
6498 "Link argument does contain at least one directory separator: %s",
6499 *u);
decd7982
JR
6500
6501 r = path_make_absolute_cwd(*u, &normalized_path);
6502 if (r < 0)
6503 return r;
6504
6505 free_and_replace(*u, normalized_path);
6506 }
6507
6508 return 0;
6509}
6510
1d3c86c0
MS
6511static int normalize_names(char **names, bool warn_if_path) {
6512 char **u;
6513 bool was_path = false;
6514
6515 STRV_FOREACH(u, names) {
6516 int r;
6517
6518 if (!is_path(*u))
6519 continue;
6520
6521 r = free_and_strdup(u, basename(*u));
6522 if (r < 0)
6523 return log_error_errno(r, "Failed to normalize unit file path: %m");
6524
6525 was_path = true;
6526 }
6527
6528 if (warn_if_path && was_path)
6529 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6530
6531 return 0;
6532}
6533
173471b7 6534static int unit_exists(LookupPaths *lp, const char *unit) {
d6568222 6535 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
f37f8a61 6536 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
d6568222
SS
6537 _cleanup_free_ char *path = NULL;
6538 static const struct bus_properties_map property_map[] = {
f37f8a61
YW
6539 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
6540 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state)},
d6568222
SS
6541 {},
6542 };
6543 UnitStatusInfo info = {};
6544 sd_bus *bus;
6545 int r;
6546
173471b7
ZJS
6547 if (unit_name_is_valid(unit, UNIT_NAME_TEMPLATE))
6548 return unit_find_template_path(unit, lp, NULL, NULL);
6549
d6568222
SS
6550 path = unit_dbus_path_from_name(unit);
6551 if (!path)
6552 return log_oom();
6553
6554 r = acquire_bus(BUS_MANAGER, &bus);
6555 if (r < 0)
6556 return r;
6557
a7e4861c 6558 r = bus_map_all_properties(bus, "org.freedesktop.systemd1", path, property_map, 0, &error, &m, &info);
d6568222
SS
6559 if (r < 0)
6560 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
6561
d6568222
SS
6562 return !streq_ptr(info.load_state, "not-found") || !streq_ptr(info.active_state, "inactive");
6563}
6564
e449de87 6565static int enable_unit(int argc, char *argv[], void *userdata) {
e3e0314b 6566 _cleanup_strv_free_ char **names = NULL;
e449de87 6567 const char *verb = argv[0];
729e3769 6568 UnitFileChange *changes = NULL;
da6053d0 6569 size_t n_changes = 0;
729e3769 6570 int carries_install_info = -1;
35b132e8 6571 bool ignore_carries_install_info = arg_quiet;
729e3769 6572 int r;
ee5762e3 6573
e449de87 6574 if (!argv[1])
ab5919fa
MS
6575 return 0;
6576
e449de87 6577 r = mangle_names(strv_skip(argv, 1), &names);
3a05c0f9 6578 if (r < 0)
cbb13b2a
VP
6579 return r;
6580
e3e0314b 6581 r = enable_sysv_units(verb, names);
cbb13b2a
VP
6582 if (r < 0)
6583 return r;
3a05c0f9 6584
c61b443d 6585 /* If the operation was fully executed by the SysV compat, let's finish early */
823e5fab
FB
6586 if (strv_isempty(names)) {
6587 if (arg_no_reload || install_client_side())
6588 return 0;
6589 return daemon_reload(argc, argv, userdata);
6590 }
67d66210 6591
1d3c86c0
MS
6592 if (streq(verb, "disable")) {
6593 r = normalize_names(names, true);
6594 if (r < 0)
6595 return r;
6596 }
6597
decd7982
JR
6598 if (streq(verb, "link")) {
6599 r = normalize_filenames(names);
6600 if (r < 0)
6601 return r;
6602 }
6603
4fbd7192 6604 if (install_client_side()) {
b3796dd8
JS
6605 UnitFileFlags flags;
6606
6607 flags = args_to_flags();
729e3769 6608 if (streq(verb, "enable")) {
b3796dd8 6609 r = unit_file_enable(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769
LP
6610 carries_install_info = r;
6611 } else if (streq(verb, "disable"))
b3796dd8 6612 r = unit_file_disable(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769 6613 else if (streq(verb, "reenable")) {
b3796dd8 6614 r = unit_file_reenable(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769
LP
6615 carries_install_info = r;
6616 } else if (streq(verb, "link"))
b3796dd8 6617 r = unit_file_link(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769 6618 else if (streq(verb, "preset")) {
b3796dd8 6619 r = unit_file_preset(arg_scope, flags, arg_root, names, arg_preset_mode, &changes, &n_changes);
729e3769 6620 } else if (streq(verb, "mask"))
b3796dd8 6621 r = unit_file_mask(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769 6622 else if (streq(verb, "unmask"))
b3796dd8 6623 r = unit_file_unmask(arg_scope, flags, arg_root, names, &changes, &n_changes);
344ca755
LP
6624 else if (streq(verb, "revert"))
6625 r = unit_file_revert(arg_scope, arg_root, names, &changes, &n_changes);
729e3769
LP
6626 else
6627 assert_not_reached("Unknown verb");
ee5762e3 6628
af3d8113 6629 unit_file_dump_changes(r, verb, changes, n_changes, arg_quiet);
d073dea0 6630 if (r < 0)
85b78539 6631 goto finish;
df77cdf0 6632 r = 0;
729e3769 6633 } else {
4afd3348
LP
6634 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
6635 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
39207373 6636 bool expect_carries_install_info = false;
344ca755 6637 bool send_runtime = true, send_force = true, send_preset_mode = false;
718db961 6638 const char *method;
4fbd7192 6639 sd_bus *bus;
729e3769 6640
d6568222 6641 if (STR_IN_SET(verb, "mask", "unmask")) {
f8d6cb48 6642 char **name;
8e766630 6643 _cleanup_(lookup_paths_free) LookupPaths lp = {};
173471b7
ZJS
6644
6645 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
d6568222
SS
6646 if (r < 0)
6647 return r;
f8d6cb48
ZJS
6648
6649 STRV_FOREACH(name, names) {
173471b7 6650 r = unit_exists(&lp, *name);
f8d6cb48
ZJS
6651 if (r < 0)
6652 return r;
6653 if (r == 0)
25c59b5d 6654 log_notice("Unit %s does not exist, proceeding anyway.", *name);
f8d6cb48 6655 }
d6568222
SS
6656 }
6657
4fbd7192
LP
6658 r = acquire_bus(BUS_MANAGER, &bus);
6659 if (r < 0)
6660 return r;
6661
8a4b13c5 6662 polkit_agent_open_maybe();
d2ad7e1b 6663
729e3769
LP
6664 if (streq(verb, "enable")) {
6665 method = "EnableUnitFiles";
6666 expect_carries_install_info = true;
6667 } else if (streq(verb, "disable")) {
6668 method = "DisableUnitFiles";
6669 send_force = false;
6670 } else if (streq(verb, "reenable")) {
6671 method = "ReenableUnitFiles";
6672 expect_carries_install_info = true;
6673 } else if (streq(verb, "link"))
6674 method = "LinkUnitFiles";
6675 else if (streq(verb, "preset")) {
d309c1c3
LP
6676
6677 if (arg_preset_mode != UNIT_FILE_PRESET_FULL) {
6678 method = "PresetUnitFilesWithMode";
6679 send_preset_mode = true;
6680 } else
6681 method = "PresetUnitFiles";
6682
729e3769 6683 expect_carries_install_info = true;
39207373 6684 ignore_carries_install_info = true;
729e3769
LP
6685 } else if (streq(verb, "mask"))
6686 method = "MaskUnitFiles";
6687 else if (streq(verb, "unmask")) {
6688 method = "UnmaskUnitFiles";
6689 send_force = false;
344ca755
LP
6690 } else if (streq(verb, "revert")) {
6691 method = "RevertUnitFiles";
6692 send_runtime = send_force = false;
729e3769
LP
6693 } else
6694 assert_not_reached("Unknown verb");
6695
f459b602
MAP
6696 r = sd_bus_message_new_method_call(
6697 bus,
151b9b96 6698 &m,
729e3769
LP
6699 "org.freedesktop.systemd1",
6700 "/org/freedesktop/systemd1",
6701 "org.freedesktop.systemd1.Manager",
151b9b96 6702 method);
f459b602
MAP
6703 if (r < 0)
6704 return bus_log_create_error(r);
ee5762e3 6705
e3e0314b 6706 r = sd_bus_message_append_strv(m, names);
f459b602
MAP
6707 if (r < 0)
6708 return bus_log_create_error(r);
ee5762e3 6709
d309c1c3
LP
6710 if (send_preset_mode) {
6711 r = sd_bus_message_append(m, "s", unit_file_preset_mode_to_string(arg_preset_mode));
6712 if (r < 0)
6713 return bus_log_create_error(r);
6714 }
6715
344ca755
LP
6716 if (send_runtime) {
6717 r = sd_bus_message_append(m, "b", arg_runtime);
6718 if (r < 0)
6719 return bus_log_create_error(r);
6720 }
ee5762e3 6721
729e3769 6722 if (send_force) {
f459b602
MAP
6723 r = sd_bus_message_append(m, "b", arg_force);
6724 if (r < 0)
6725 return bus_log_create_error(r);
ee5762e3
LP
6726 }
6727
c49b30a2 6728 r = sd_bus_call(bus, m, 0, &error, &reply);
691395d8 6729 if (r < 0)
af3d8113 6730 return log_error_errno(r, "Failed to %s unit: %s", verb, bus_error_message(&error, r));
be394c48 6731
729e3769 6732 if (expect_carries_install_info) {
f459b602
MAP
6733 r = sd_bus_message_read(reply, "b", &carries_install_info);
6734 if (r < 0)
6735 return bus_log_parse_error(r);
ee5762e3
LP
6736 }
6737
57ab2eab 6738 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
f459b602 6739 if (r < 0)
85b78539 6740 goto finish;
b77398f7 6741
93c941e3 6742 /* Try to reload if enabled */
d6cb60c7 6743 if (!arg_no_reload)
e449de87 6744 r = daemon_reload(argc, argv, userdata);
f459b602
MAP
6745 else
6746 r = 0;
b647f10d 6747 }
3d3961f2 6748
39207373 6749 if (carries_install_info == 0 && !ignore_carries_install_info)
46efc978
LP
6750 log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, Also=,\n"
6751 "Alias= settings in the [Install] section, and DefaultInstance= for template\n"
2811184a
ZJS
6752 "units). This means they are not meant to be enabled using systemctl.\n"
6753 " \n" /* trick: the space is needed so that the line does not get stripped from output */
46efc978 6754 "Possible reasons for having this kind of units are:\n"
18c93ee3
LP
6755 "%1$s A unit may be statically enabled by being symlinked from another unit's\n"
6756 " .wants/ or .requires/ directory.\n"
6757 "%1$s A unit's purpose may be to act as a helper for some other unit which has\n"
6758 " a requirement dependency on it.\n"
6759 "%1$s A unit may be started when needed via activation (socket, path, timer,\n"
6760 " D-Bus, udev, scripted systemctl call, ...).\n"
6761 "%1$s In case of template units, the unit is meant to be enabled with some\n"
6762 " instance name specified.",
9a6f746f 6763 special_glyph(SPECIAL_GLYPH_BULLET));
ee5762e3 6764
6bc30691 6765 if (arg_now && STR_IN_SET(argv[0], "enable", "disable", "mask")) {
4fbd7192 6766 sd_bus *bus;
da6053d0 6767 size_t len, i;
57ab2eab 6768
4fbd7192
LP
6769 r = acquire_bus(BUS_MANAGER, &bus);
6770 if (r < 0)
d073dea0 6771 goto finish;
4fbd7192 6772
6bc30691
JS
6773 len = strv_length(names);
6774 {
6775 char *new_args[len + 2];
57ab2eab 6776
6bc30691
JS
6777 new_args[0] = (char*) (streq(argv[0], "enable") ? "start" : "stop");
6778 for (i = 0; i < len; i++)
6779 new_args[i + 1] = basename(names[i]);
6780 new_args[i + 1] = NULL;
6781
6782 r = start_unit(len + 1, new_args, userdata);
6783 }
57ab2eab
JS
6784 }
6785
729e3769 6786finish:
729e3769 6787 unit_file_changes_free(changes, n_changes);
ee5762e3 6788
729e3769 6789 return r;
ee5762e3
LP
6790}
6791
e449de87 6792static int add_dependency(int argc, char *argv[], void *userdata) {
e94937df
LN
6793 _cleanup_strv_free_ char **names = NULL;
6794 _cleanup_free_ char *target = NULL;
e449de87 6795 const char *verb = argv[0];
acc0269c 6796 UnitFileChange *changes = NULL;
da6053d0 6797 size_t n_changes = 0;
e94937df
LN
6798 UnitDependency dep;
6799 int r = 0;
6800
e449de87 6801 if (!argv[1])
e94937df
LN
6802 return 0;
6803
37cbc1d5 6804 r = unit_name_mangle_with_suffix(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".target", &target);
7410616c
LP
6805 if (r < 0)
6806 return log_error_errno(r, "Failed to mangle unit name: %m");
e94937df 6807
e449de87 6808 r = mangle_names(strv_skip(argv, 2), &names);
e94937df
LN
6809 if (r < 0)
6810 return r;
6811
6812 if (streq(verb, "add-wants"))
6813 dep = UNIT_WANTS;
6814 else if (streq(verb, "add-requires"))
6815 dep = UNIT_REQUIRES;
6816 else
6817 assert_not_reached("Unknown verb");
6818
4fbd7192 6819 if (install_client_side()) {
b3796dd8 6820 r = unit_file_add_dependency(arg_scope, args_to_flags(), arg_root, names, target, dep, &changes, &n_changes);
af3d8113 6821 unit_file_dump_changes(r, "add dependency on", changes, n_changes, arg_quiet);
5f056378
CH
6822
6823 if (r > 0)
6824 r = 0;
e94937df 6825 } else {
4afd3348
LP
6826 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
6827 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 6828 sd_bus *bus;
e94937df 6829
4fbd7192
LP
6830 r = acquire_bus(BUS_MANAGER, &bus);
6831 if (r < 0)
6832 return r;
6833
8a4b13c5 6834 polkit_agent_open_maybe();
d2ad7e1b 6835
e94937df
LN
6836 r = sd_bus_message_new_method_call(
6837 bus,
6838 &m,
6839 "org.freedesktop.systemd1",
6840 "/org/freedesktop/systemd1",
6841 "org.freedesktop.systemd1.Manager",
6842 "AddDependencyUnitFiles");
6843 if (r < 0)
6844 return bus_log_create_error(r);
6845
342641fb 6846 r = sd_bus_message_append_strv(m, names);
e94937df
LN
6847 if (r < 0)
6848 return bus_log_create_error(r);
6849
342641fb 6850 r = sd_bus_message_append(m, "ssbb", target, unit_dependency_to_string(dep), arg_runtime, arg_force);
e94937df
LN
6851 if (r < 0)
6852 return bus_log_create_error(r);
6853
6854 r = sd_bus_call(bus, m, 0, &error, &reply);
691395d8 6855 if (r < 0)
af3d8113 6856 return log_error_errno(r, "Failed to add dependency: %s", bus_error_message(&error, r));
e94937df 6857
acc0269c 6858 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
e94937df 6859 if (r < 0)
acc0269c 6860 goto finish;
e94937df 6861
acc0269c
CH
6862 if (arg_no_reload) {
6863 r = 0;
6864 goto finish;
6865 }
6866
6867 r = daemon_reload(argc, argv, userdata);
e94937df 6868 }
acc0269c
CH
6869
6870finish:
6871 unit_file_changes_free(changes, n_changes);
6872
6873 return r;
e94937df
LN
6874}
6875
e449de87 6876static int preset_all(int argc, char *argv[], void *userdata) {
acc0269c 6877 UnitFileChange *changes = NULL;
da6053d0 6878 size_t n_changes = 0;
d309c1c3
LP
6879 int r;
6880
4fbd7192 6881 if (install_client_side()) {
b3796dd8 6882 r = unit_file_preset_all(arg_scope, args_to_flags(), arg_root, arg_preset_mode, &changes, &n_changes);
af3d8113 6883 unit_file_dump_changes(r, "preset", changes, n_changes, arg_quiet);
5f056378
CH
6884
6885 if (r > 0)
6886 r = 0;
d309c1c3 6887 } else {
4afd3348
LP
6888 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6889 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
4fbd7192 6890 sd_bus *bus;
d309c1c3 6891
4fbd7192
LP
6892 r = acquire_bus(BUS_MANAGER, &bus);
6893 if (r < 0)
6894 return r;
6895
8a4b13c5 6896 polkit_agent_open_maybe();
d2ad7e1b 6897
6e646d22 6898 r = sd_bus_call_method(
d309c1c3
LP
6899 bus,
6900 "org.freedesktop.systemd1",
6901 "/org/freedesktop/systemd1",
6902 "org.freedesktop.systemd1.Manager",
6e646d22
LP
6903 "PresetAllUnitFiles",
6904 &error,
6905 &reply,
d309c1c3
LP
6906 "sbb",
6907 unit_file_preset_mode_to_string(arg_preset_mode),
6908 arg_runtime,
6909 arg_force);
691395d8 6910 if (r < 0)
af3d8113 6911 return log_error_errno(r, "Failed to preset all units: %s", bus_error_message(&error, r));
d309c1c3 6912
acc0269c 6913 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
d309c1c3 6914 if (r < 0)
acc0269c 6915 goto finish;
d309c1c3 6916
acc0269c
CH
6917 if (arg_no_reload) {
6918 r = 0;
6919 goto finish;
6920 }
6921
6922 r = daemon_reload(argc, argv, userdata);
d309c1c3 6923 }
acc0269c
CH
6924
6925finish:
6926 unit_file_changes_free(changes, n_changes);
6927
6928 return r;
d309c1c3
LP
6929}
6930
3b3557c4
JS
6931static int show_installation_targets_client_side(const char *name) {
6932 UnitFileChange *changes = NULL;
da6053d0 6933 size_t n_changes = 0, i;
3b3557c4
JS
6934 UnitFileFlags flags;
6935 char **p;
6936 int r;
6937
6938 p = STRV_MAKE(name);
6939 flags = UNIT_FILE_DRY_RUN |
6940 (arg_runtime ? UNIT_FILE_RUNTIME : 0);
6941
6942 r = unit_file_disable(UNIT_FILE_SYSTEM, flags, NULL, p, &changes, &n_changes);
6943 if (r < 0)
6944 return log_error_errno(r, "Failed to get file links for %s: %m", name);
6945
6946 for (i = 0; i < n_changes; i++)
6947 if (changes[i].type == UNIT_FILE_UNLINK)
6948 printf(" %s\n", changes[i].path);
6949
6950 return 0;
6951}
6952
6953static int show_installation_targets(sd_bus *bus, const char *name) {
6954 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
6955 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6956 const char *link;
6957 int r;
6958
6959 r = sd_bus_call_method(
6960 bus,
6961 "org.freedesktop.systemd1",
6962 "/org/freedesktop/systemd1",
6963 "org.freedesktop.systemd1.Manager",
6964 "GetUnitFileLinks",
6965 &error,
6966 &reply,
6967 "sb", name, arg_runtime);
6968 if (r < 0)
6969 return log_error_errno(r, "Failed to get unit file links for %s: %s", name, bus_error_message(&error, r));
6970
6971 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
6972 if (r < 0)
6973 return bus_log_parse_error(r);
6974
6975 while ((r = sd_bus_message_read(reply, "s", &link)) > 0)
6976 printf(" %s\n", link);
6977
6978 if (r < 0)
6979 return bus_log_parse_error(r);
6980
6981 r = sd_bus_message_exit_container(reply);
6982 if (r < 0)
6983 return bus_log_parse_error(r);
6984
6985 return 0;
6986}
6987
e449de87 6988static int unit_is_enabled(int argc, char *argv[], void *userdata) {
e3e0314b 6989 _cleanup_strv_free_ char **names = NULL;
729e3769
LP
6990 bool enabled;
6991 char **name;
f459b602 6992 int r;
ee5762e3 6993
e449de87 6994 r = mangle_names(strv_skip(argv, 1), &names);
cbb13b2a
VP
6995 if (r < 0)
6996 return r;
6997
e449de87 6998 r = enable_sysv_units(argv[0], names);
729e3769
LP
6999 if (r < 0)
7000 return r;
ee5762e3 7001
729e3769 7002 enabled = r > 0;
ee5762e3 7003
4fbd7192 7004 if (install_client_side()) {
e3e0314b 7005 STRV_FOREACH(name, names) {
729e3769 7006 UnitFileState state;
ee5762e3 7007
0ec0deaa
LP
7008 r = unit_file_get_state(arg_scope, arg_root, *name, &state);
7009 if (r < 0)
c5024cd0 7010 return log_error_errno(r, "Failed to get unit file state for %s: %m", *name);
ee5762e3 7011
4c315c2c
IS
7012 if (IN_SET(state,
7013 UNIT_FILE_ENABLED,
7014 UNIT_FILE_ENABLED_RUNTIME,
7015 UNIT_FILE_STATIC,
f4139308
LP
7016 UNIT_FILE_INDIRECT,
7017 UNIT_FILE_GENERATED))
729e3769
LP
7018 enabled = true;
7019
3b3557c4 7020 if (!arg_quiet) {
729e3769 7021 puts(unit_file_state_to_string(state));
3b3557c4
JS
7022 if (arg_full) {
7023 r = show_installation_targets_client_side(*name);
7024 if (r < 0)
7025 return r;
7026 }
7027 }
71fad675 7028 }
ee5762e3 7029
5f056378 7030 r = 0;
729e3769 7031 } else {
4afd3348 7032 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192
LP
7033 sd_bus *bus;
7034
7035 r = acquire_bus(BUS_MANAGER, &bus);
7036 if (r < 0)
7037 return r;
7038
e3e0314b 7039 STRV_FOREACH(name, names) {
4afd3348 7040 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
729e3769 7041 const char *s;
63a723f3 7042
f459b602 7043 r = sd_bus_call_method(
f22f08cd 7044 bus,
729e3769
LP
7045 "org.freedesktop.systemd1",
7046 "/org/freedesktop/systemd1",
7047 "org.freedesktop.systemd1.Manager",
f22f08cd 7048 "GetUnitFileState",
f459b602 7049 &error,
f22f08cd 7050 &reply,
04504f93 7051 "s", *name);
691395d8
LP
7052 if (r < 0)
7053 return log_error_errno(r, "Failed to get unit file state for %s: %s", *name, bus_error_message(&error, r));
ee5762e3 7054
f459b602
MAP
7055 r = sd_bus_message_read(reply, "s", &s);
7056 if (r < 0)
7057 return bus_log_parse_error(r);
ee5762e3 7058
f4139308 7059 if (STR_IN_SET(s, "enabled", "enabled-runtime", "static", "indirect", "generated"))
729e3769
LP
7060 enabled = true;
7061
3b3557c4 7062 if (!arg_quiet) {
729e3769 7063 puts(s);
3b3557c4
JS
7064 if (arg_full) {
7065 r = show_installation_targets(bus, *name);
7066 if (r < 0)
7067 return r;
7068 }
7069 }
560d8f23 7070 }
ee5762e3
LP
7071 }
7072
f4139308 7073 return enabled ? EXIT_SUCCESS : EXIT_FAILURE;
ee5762e3
LP
7074}
7075
adb6cd9b
FB
7076static int match_startup_finished(sd_bus_message *m, void *userdata, sd_bus_error *error) {
7077 char **state = userdata;
7078 int r;
7079
7080 assert(state);
7081
7082 r = sd_bus_get_property_string(
7083 sd_bus_message_get_bus(m),
7084 "org.freedesktop.systemd1",
7085 "/org/freedesktop/systemd1",
7086 "org.freedesktop.systemd1.Manager",
7087 "SystemState",
7088 NULL,
7089 state);
7090
7091 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), r);
7092 return 0;
7093}
7094
e449de87 7095static int is_system_running(int argc, char *argv[], void *userdata) {
e686a616 7096 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
adb6cd9b
FB
7097 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot_startup_finished = NULL;
7098 _cleanup_(sd_event_unrefp) sd_event* event = NULL;
99813a19 7099 _cleanup_free_ char *state = NULL;
4fbd7192 7100 sd_bus *bus;
99813a19
LP
7101 int r;
7102
040524b4 7103 if (running_in_chroot() > 0 || (arg_transport == BUS_TRANSPORT_LOCAL && !sd_booted())) {
94f099d8
LP
7104 if (!arg_quiet)
7105 puts("offline");
7106 return EXIT_FAILURE;
7107 }
7108
4fbd7192
LP
7109 r = acquire_bus(BUS_MANAGER, &bus);
7110 if (r < 0)
7111 return r;
7112
adb6cd9b
FB
7113 if (arg_wait) {
7114 r = sd_event_default(&event);
7115 if (r >= 0)
7116 r = sd_bus_attach_event(bus, event, 0);
7117 if (r >= 0)
7118 r = sd_bus_match_signal_async(
7119 bus,
7120 &slot_startup_finished,
7121 "org.freedesktop.systemd1",
7122 "/org/freedesktop/systemd1",
7123 "org.freedesktop.systemd1.Manager",
7124 "StartupFinished",
7125 match_startup_finished, NULL, &state);
7126 if (r < 0) {
7127 log_warning_errno(r, "Failed to request match for StartupFinished: %m");
7128 arg_wait = false;
7129 }
7130 }
7131
99813a19
LP
7132 r = sd_bus_get_property_string(
7133 bus,
7134 "org.freedesktop.systemd1",
7135 "/org/freedesktop/systemd1",
7136 "org.freedesktop.systemd1.Manager",
7137 "SystemState",
e686a616 7138 &error,
99813a19
LP
7139 &state);
7140 if (r < 0) {
adb6cd9b 7141 log_warning_errno(r, "Failed to query system state: %s", bus_error_message(&error, r));
e686a616 7142
99813a19
LP
7143 if (!arg_quiet)
7144 puts("unknown");
bfeec178 7145 return EXIT_FAILURE;
99813a19
LP
7146 }
7147
adb6cd9b
FB
7148 if (arg_wait && STR_IN_SET(state, "initializing", "starting")) {
7149 r = sd_event_loop(event);
7150 if (r < 0) {
7151 log_warning_errno(r, "Failed to get property from event loop: %m");
7152 if (!arg_quiet)
7153 puts("unknown");
7154 return EXIT_FAILURE;
7155 }
7156 }
7157
99813a19
LP
7158 if (!arg_quiet)
7159 puts(state);
7160
7161 return streq(state, "running") ? EXIT_SUCCESS : EXIT_FAILURE;
7162}
7163
7d4fb3b1 7164static int create_edit_temp_file(const char *new_path, const char *original_path, char **ret_tmp_fn) {
45519fd6 7165 _cleanup_free_ char *t = NULL;
ae6c3cc0 7166 int r;
7d4fb3b1
RC
7167
7168 assert(new_path);
7169 assert(original_path);
7170 assert(ret_tmp_fn);
7171
14bcf25c 7172 r = tempfn_random(new_path, NULL, &t);
ae6c3cc0 7173 if (r < 0)
029009d4 7174 return log_error_errno(r, "Failed to determine temporary filename for \"%s\": %m", new_path);
7d4fb3b1
RC
7175
7176 r = mkdir_parents(new_path, 0755);
45519fd6 7177 if (r < 0)
691395d8 7178 return log_error_errno(r, "Failed to create directories for \"%s\": %m", new_path);
7d4fb3b1 7179
1c876927 7180 r = copy_file(original_path, t, 0, 0644, 0, COPY_REFLINK);
7d4fb3b1 7181 if (r == -ENOENT) {
45519fd6 7182
7d4fb3b1 7183 r = touch(t);
45519fd6
LP
7184 if (r < 0)
7185 return log_error_errno(r, "Failed to create temporary file \"%s\": %m", t);
7186
7187 } else if (r < 0)
39c38ce1 7188 return log_error_errno(r, "Failed to create temporary file for \"%s\": %m", new_path);
7d4fb3b1 7189
ae2a15bc 7190 *ret_tmp_fn = TAKE_PTR(t);
7d4fb3b1
RC
7191
7192 return 0;
7193}
7194
c51932be
LP
7195static int get_file_to_edit(
7196 const LookupPaths *paths,
7197 const char *name,
7198 char **ret_path) {
7199
7200 _cleanup_free_ char *path = NULL, *run = NULL;
7d4fb3b1 7201
45519fd6
LP
7202 assert(name);
7203 assert(ret_path);
7204
605405c6 7205 path = strjoin(paths->persistent_config, "/", name);
c51932be 7206 if (!path)
7d4fb3b1
RC
7207 return log_oom();
7208
c51932be 7209 if (arg_runtime) {
605405c6 7210 run = strjoin(paths->runtime_config, "/", name);
c51932be
LP
7211 if (!run)
7212 return log_oom();
7213 }
7214
bc854dc7 7215 if (arg_runtime) {
baaa35ad
ZJS
7216 if (access(path, F_OK) >= 0)
7217 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
7218 "Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.",
7219 run, path);
691395d8 7220
ae2a15bc
LP
7221 *ret_path = TAKE_PTR(run);
7222 } else
7223 *ret_path = TAKE_PTR(path);
7d4fb3b1
RC
7224
7225 return 0;
7226}
7227
39c38ce1 7228static int unit_file_create_new(
c51932be
LP
7229 const LookupPaths *paths,
7230 const char *unit_name,
39c38ce1 7231 const char *suffix,
c51932be
LP
7232 char **ret_new_path,
7233 char **ret_tmp_path) {
7234
919d2720
LP
7235 _cleanup_free_ char *new_path = NULL, *tmp_path = NULL;
7236 const char *ending;
7d4fb3b1
RC
7237 int r;
7238
7239 assert(unit_name);
7240 assert(ret_new_path);
7241 assert(ret_tmp_path);
7242
39c38ce1 7243 ending = strjoina(unit_name, suffix);
919d2720 7244 r = get_file_to_edit(paths, ending, &new_path);
7d4fb3b1
RC
7245 if (r < 0)
7246 return r;
7247
919d2720
LP
7248 r = create_edit_temp_file(new_path, new_path, &tmp_path);
7249 if (r < 0)
7d4fb3b1 7250 return r;
7d4fb3b1 7251
919d2720
LP
7252 *ret_new_path = TAKE_PTR(new_path);
7253 *ret_tmp_path = TAKE_PTR(tmp_path);
7d4fb3b1
RC
7254
7255 return 0;
7256}
7257
1cfa9a4c 7258static int unit_file_create_copy(
c51932be 7259 const LookupPaths *paths,
1cfa9a4c
LP
7260 const char *unit_name,
7261 const char *fragment_path,
1cfa9a4c
LP
7262 char **ret_new_path,
7263 char **ret_tmp_path) {
7264
92d6b0bf 7265 _cleanup_free_ char *new_path = NULL, *tmp_path = NULL;
7d4fb3b1
RC
7266 int r;
7267
7268 assert(fragment_path);
7269 assert(unit_name);
7270 assert(ret_new_path);
7271 assert(ret_tmp_path);
7272
92d6b0bf 7273 r = get_file_to_edit(paths, unit_name, &new_path);
7d4fb3b1
RC
7274 if (r < 0)
7275 return r;
7276
92d6b0bf 7277 if (!path_equal(fragment_path, new_path) && access(new_path, F_OK) >= 0) {
7d4fb3b1
RC
7278 char response;
7279
92d6b0bf
LP
7280 r = ask_char(&response, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", new_path, fragment_path);
7281 if (r < 0)
7d4fb3b1 7282 return r;
5daacba2
LP
7283 if (response != 'y')
7284 return log_warning_errno(SYNTHETIC_ERRNO(EKEYREJECTED), "%s skipped.", unit_name);
7d4fb3b1
RC
7285 }
7286
92d6b0bf
LP
7287 r = create_edit_temp_file(new_path, fragment_path, &tmp_path);
7288 if (r < 0)
7d4fb3b1 7289 return r;
7d4fb3b1 7290
92d6b0bf
LP
7291 *ret_new_path = TAKE_PTR(new_path);
7292 *ret_tmp_path = TAKE_PTR(tmp_path);
7d4fb3b1
RC
7293
7294 return 0;
7295}
7296
7297static int run_editor(char **paths) {
7d4fb3b1
RC
7298 int r;
7299
7300 assert(paths);
7301
0672e2c6 7302 r = safe_fork("(editor)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG|FORK_WAIT, NULL);
4c253ed1 7303 if (r < 0)
b6e1fff1 7304 return r;
4c253ed1 7305 if (r == 0) {
b2238e38 7306 char **editor_args = NULL, **tmp_path, **original_path;
70d6e5bd 7307 size_t n_editor_args = 0, i = 1, argc;
b2238e38 7308 const char **args, *editor, *p;
7d4fb3b1
RC
7309
7310 argc = strv_length(paths)/2 + 1;
7d4fb3b1
RC
7311
7312 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
7313 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
7314 * we try to execute well known editors
7315 */
7316 editor = getenv("SYSTEMD_EDITOR");
7317 if (!editor)
7318 editor = getenv("EDITOR");
7319 if (!editor)
7320 editor = getenv("VISUAL");
7321
7322 if (!isempty(editor)) {
9ef5d8f2
JS
7323 editor_args = strv_split(editor, WHITESPACE);
7324 if (!editor_args) {
7325 (void) log_oom();
7326 _exit(EXIT_FAILURE);
7327 }
7328 n_editor_args = strv_length(editor_args);
7329 argc += n_editor_args - 1;
7330 }
02a126a3 7331
9ef5d8f2
JS
7332 args = newa(const char*, argc + 1);
7333
7334 if (n_editor_args > 0) {
7335 args[0] = editor_args[0];
7336 for (; i < n_editor_args; i++)
7337 args[i] = editor_args[i];
7338 }
7339
df79fdab
LP
7340 STRV_FOREACH_PAIR(original_path, tmp_path, paths)
7341 args[i++] = *tmp_path;
9ef5d8f2
JS
7342 args[i] = NULL;
7343
7344 if (n_editor_args > 0)
7345 execvp(args[0], (char* const*) args);
7d4fb3b1 7346
9391a1c3 7347 FOREACH_STRING(p, "editor", "nano", "vim", "vi") {
1cfa9a4c
LP
7348 args[0] = p;
7349 execvp(p, (char* const*) args);
7d4fb3b1
RC
7350 /* We do not fail if the editor doesn't exist
7351 * because we want to try each one of them before
7352 * failing.
7353 */
7354 if (errno != ENOENT) {
691395d8 7355 log_error_errno(errno, "Failed to execute %s: %m", editor);
7d4fb3b1
RC
7356 _exit(EXIT_FAILURE);
7357 }
7358 }
7359
1cfa9a4c 7360 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7d4fb3b1
RC
7361 _exit(EXIT_FAILURE);
7362 }
7363
45519fd6 7364 return 0;
7d4fb3b1
RC
7365}
7366
7367static int find_paths_to_edit(sd_bus *bus, char **names, char ***paths) {
8e766630 7368 _cleanup_(lookup_paths_free) LookupPaths lp = {};
7d4fb3b1
RC
7369 char **name;
7370 int r;
7371
7372 assert(names);
7373 assert(paths);
7374
4943d143 7375 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
5b013a2f 7376 if (r < 0)
8df18507 7377 return r;
7d4fb3b1 7378
e9e310f8 7379 STRV_FOREACH(name, names) {
b74df547
ZJS
7380 _cleanup_free_ char *path = NULL, *new_path = NULL, *tmp_path = NULL, *tmp_name = NULL;
7381 const char *unit_name;
7d4fb3b1 7382
02a126a3
LP
7383 r = unit_find_paths(bus, *name, &lp, false, &path, NULL);
7384 if (r == -EKEYREJECTED) {
7385 /* If loading of the unit failed server side complete, then the server won't tell us the unit
7386 * file path. In that case, find the file client side. */
7387 log_debug_errno(r, "Unit '%s' was not loaded correctly, retrying client-side.", *name);
7388 r = unit_find_paths(bus, *name, &lp, true, &path, NULL);
7389 }
7390 if (r == -ERFKILL)
7391 return log_error_errno(r, "Unit '%s' masked, cannot edit.", *name);
e9e310f8
RC
7392 if (r < 0)
7393 return r;
b3734d98
ZJS
7394
7395 if (r == 0) {
7396 assert(!path);
7397
7398 if (!arg_force) {
85163756
LP
7399 log_info("Run 'systemctl edit%s --force --full %s' to create a new unit.",
7400 arg_scope == UNIT_FILE_GLOBAL ? " --global" :
7401 arg_scope == UNIT_FILE_USER ? " --user" : "",
7402 *name);
39c38ce1
DC
7403 return -ENOENT;
7404 }
39c38ce1 7405
b3734d98
ZJS
7406 /* Create a new unit from scratch */
7407 unit_name = *name;
7408 r = unit_file_create_new(&lp, unit_name,
7409 arg_full ? NULL : ".d/override.conf",
7410 &new_path, &tmp_path);
7411 } else {
7412 assert(path);
b74df547 7413
b3734d98
ZJS
7414 unit_name = basename(path);
7415 /* We follow unit aliases, but we need to propagate the instance */
7416 if (unit_name_is_valid(*name, UNIT_NAME_INSTANCE) &&
7417 unit_name_is_valid(unit_name, UNIT_NAME_TEMPLATE)) {
7418 _cleanup_free_ char *instance = NULL;
b74df547 7419
b3734d98
ZJS
7420 r = unit_name_to_instance(*name, &instance);
7421 if (r < 0)
7422 return r;
b74df547 7423
b3734d98
ZJS
7424 r = unit_name_replace_instance(unit_name, instance, &tmp_name);
7425 if (r < 0)
7426 return r;
7427
7428 unit_name = tmp_name;
7429 }
b74df547 7430
39c38ce1 7431 if (arg_full)
b74df547 7432 r = unit_file_create_copy(&lp, unit_name, path, &new_path, &tmp_path);
39c38ce1 7433 else
b74df547 7434 r = unit_file_create_new(&lp, unit_name, ".d/override.conf", &new_path, &tmp_path);
b3734d98 7435 }
e9e310f8 7436 if (r < 0)
ad2a0358 7437 return r;
7d4fb3b1 7438
e9e310f8
RC
7439 r = strv_push_pair(paths, new_path, tmp_path);
7440 if (r < 0)
7441 return log_oom();
02a126a3 7442
78df0edc 7443 new_path = tmp_path = NULL;
7d4fb3b1
RC
7444 }
7445
7446 return 0;
7447}
7448
e449de87 7449static int edit(int argc, char *argv[], void *userdata) {
86f004fb 7450 _cleanup_(lookup_paths_free) LookupPaths lp = {};
7d4fb3b1
RC
7451 _cleanup_strv_free_ char **names = NULL;
7452 _cleanup_strv_free_ char **paths = NULL;
7453 char **original, **tmp;
4fbd7192 7454 sd_bus *bus;
7d4fb3b1
RC
7455 int r;
7456
7d4fb3b1 7457 if (!on_tty()) {
4fbd7192 7458 log_error("Cannot edit units if not on a tty.");
7d4fb3b1
RC
7459 return -EINVAL;
7460 }
7461
7462 if (arg_transport != BUS_TRANSPORT_LOCAL) {
4fbd7192 7463 log_error("Cannot edit units remotely.");
7d4fb3b1
RC
7464 return -EINVAL;
7465 }
7466
86f004fb
ZJS
7467 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
7468 if (r < 0)
7469 return log_error_errno(r, "Failed to determine unit paths: %m");
7470
4fbd7192
LP
7471 r = acquire_bus(BUS_MANAGER, &bus);
7472 if (r < 0)
7473 return r;
7474
e449de87 7475 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
7d4fb3b1
RC
7476 if (r < 0)
7477 return log_error_errno(r, "Failed to expand names: %m");
7478
9d9dd746 7479 STRV_FOREACH(tmp, names) {
86f004fb 7480 r = unit_is_masked(bus, &lp, *tmp);
9d9dd746
ZJS
7481 if (r < 0)
7482 return r;
9d9dd746
ZJS
7483 if (r > 0) {
7484 log_error("Cannot edit %s: unit is masked.", *tmp);
7485 return -EINVAL;
7486 }
7487 }
7488
7d4fb3b1
RC
7489 r = find_paths_to_edit(bus, names, &paths);
7490 if (r < 0)
7491 return r;
7492
b5e6a600 7493 if (strv_isempty(paths))
7d4fb3b1 7494 return -ENOENT;
7d4fb3b1
RC
7495
7496 r = run_editor(paths);
7497 if (r < 0)
7498 goto end;
7499
7500 STRV_FOREACH_PAIR(original, tmp, paths) {
9d9dd746
ZJS
7501 /* If the temporary file is empty we ignore it.
7502 * This allows the user to cancel the modification.
7d4fb3b1
RC
7503 */
7504 if (null_or_empty_path(*tmp)) {
45519fd6 7505 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original);
7d4fb3b1
RC
7506 continue;
7507 }
45519fd6 7508
7d4fb3b1
RC
7509 r = rename(*tmp, *original);
7510 if (r < 0) {
029009d4 7511 r = log_error_errno(errno, "Failed to rename \"%s\" to \"%s\": %m", *tmp, *original);
7d4fb3b1
RC
7512 goto end;
7513 }
7514 }
7515
45519fd6
LP
7516 r = 0;
7517
7518 if (!arg_no_reload && !install_client_side())
e449de87 7519 r = daemon_reload(argc, argv, userdata);
7d4fb3b1
RC
7520
7521end:
5f18271e 7522 STRV_FOREACH_PAIR(original, tmp, paths) {
45519fd6 7523 (void) unlink(*tmp);
7d4fb3b1 7524
5f18271e
RC
7525 /* Removing empty dropin dirs */
7526 if (!arg_full) {
043717f9
RC
7527 _cleanup_free_ char *dir;
7528
7529 dir = dirname_malloc(*original);
7530 if (!dir)
7531 return log_oom();
7532
5f18271e
RC
7533 /* no need to check if the dir is empty, rmdir
7534 * does nothing if it is not the case.
7535 */
7536 (void) rmdir(dir);
7537 }
7538 }
7539
7d4fb3b1
RC
7540 return r;
7541}
7542
37ec0fdd
LP
7543static int systemctl_help(void) {
7544 _cleanup_free_ char *link = NULL;
7545 int r;
7546
0221d68a 7547 (void) pager_open(arg_pager_flags);
729e3769 7548
37ec0fdd
LP
7549 r = terminal_urlify_man("systemctl", "1", &link);
7550 if (r < 0)
7551 return log_oom();
7552
2e33c433 7553 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
729e3769 7554 "Query or send control commands to the systemd manager.\n\n"
8a0867d6
LP
7555 " -h --help Show this help\n"
7556 " --version Show package version\n"
f459b602
MAP
7557 " --system Connect to system manager\n"
7558 " --user Connect to user service manager\n"
7559 " -H --host=[USER@]HOST\n"
7560 " Operate on remote host\n"
7561 " -M --machine=CONTAINER\n"
7562 " Operate on local container\n"
3fb90db2
ZJS
7563 " -t --type=TYPE List units of a particular type\n"
7564 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
8a0867d6 7565 " -p --property=NAME Show only properties by this name\n"
2cdbbc9a
LP
7566 " -a --all Show all properties/all units currently in memory,\n"
7567 " including dead/empty ones. To list all units installed on\n"
7568 " the system, use the 'list-unit-files' command instead.\n"
bef19548 7569 " --failed Same as --state=failed\n"
98a6e132 7570 " -l --full Don't ellipsize unit names on output\n"
1238ee09 7571 " -r --recursive Show unit list of host and local containers\n"
4dc5b821
LP
7572 " --reverse Show reverse dependencies with 'list-dependencies'\n"
7573 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7574 " queueing a new job\n"
a521ae4a 7575 " --show-types When showing sockets, explicitly show their type\n"
4f9a9105 7576 " --value When showing properties, only print the value\n"
b37844d3
LP
7577 " -i --ignore-inhibitors\n"
7578 " When shutting down or sleeping, ignore inhibitors\n"
a8f11321
LP
7579 " --kill-who=WHO Who to send signal to\n"
7580 " -s --signal=SIGNAL Which signal to send\n"
57ab2eab 7581 " --now Start or stop unit in addition to enabling or disabling it\n"
1ae17672 7582 " --dry-run Only print what would be done\n"
8a0867d6 7583 " -q --quiet Suppress output\n"
93a08841 7584 " --wait For (re)start, wait until service stopped again\n"
adb6cd9b 7585 " For is-system-running, wait until startup is completed\n"
8a0867d6 7586 " --no-block Do not wait until operation finished\n"
8a0867d6 7587 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3fb90db2 7588 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
ebed32bf 7589 " --no-legend Do not print a legend (column headers and hints)\n"
69fc152f 7590 " --no-pager Do not pipe output into a pager\n"
501fc174
LP
7591 " --no-ask-password\n"
7592 " Do not ask for system passwords\n"
4e93d369
LR
7593 " --global Enable/disable/mask unit files globally\n"
7594 " --runtime Enable/disable/mask unit files temporarily until next\n"
7595 " reboot\n"
8a0867d6
LP
7596 " -f --force When enabling unit files, override existing symlinks\n"
7597 " When shutting down, execute action immediately\n"
3fb90db2 7598 " --preset-mode= Apply only enable, only disable, or all presets\n"
4e93d369
LR
7599 " --root=PATH Enable/disable/mask unit files in the specified root\n"
7600 " directory\n"
76fdc966 7601 " -n --lines=INTEGER Number of journal entries to show\n"
584c6e70 7602 " -o --output=STRING Change journal output mode (short, short-precise,\n"
7e563bfc
IW
7603 " short-iso, short-iso-precise, short-full,\n"
7604 " short-monotonic, short-unix,\n"
584c6e70 7605 " verbose, export, json, json-pretty, json-sse, cat)\n"
5bdf2243 7606 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
97af80c5
LP
7607 " --boot-loader-menu=TIME\n"
7608 " Boot into boot loader menu on next boot\n"
7609 " --boot-loader-entry=NAME\n"
7610 " Boot into a specific boot loader entry on next boot\n"
815ebc54 7611 " --plain Print unit dependencies as a list instead of a tree\n\n"
34c4b47b 7612 "Unit Commands:\n"
fbf3283b
ZJS
7613 " list-units [PATTERN...] List units currently in memory\n"
7614 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7615 " ordered by address\n"
7616 " list-timers [PATTERN...] List timer units currently in memory,\n"
7617 " ordered by next elapse\n"
7618 " start UNIT... Start (activate) one or more units\n"
7619 " stop UNIT... Stop (deactivate) one or more units\n"
7620 " reload UNIT... Reload one or more units\n"
7621 " restart UNIT... Start or restart one or more units\n"
7622 " try-restart UNIT... Restart one or more units if active\n"
7623 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7624 " otherwise start or restart\n"
7625 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7626 " if supported, otherwise restart\n"
7627 " isolate UNIT Start one unit and stop all others\n"
7628 " kill UNIT... Send signal to processes of a unit\n"
7629 " is-active PATTERN... Check whether units are active\n"
7630 " is-failed PATTERN... Check whether units are failed\n"
7631 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7632 " show [PATTERN...|JOB...] Show properties of one or more\n"
7633 " units/jobs or the manager\n"
7634 " cat PATTERN... Show files and drop-ins of specified units\n"
7635 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7636 " help PATTERN...|PID... Show manual for one or more units\n"
7637 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7638 " units\n"
7639 " list-dependencies [UNIT] Recursively show units which are required\n"
7640 " or wanted by this unit or by which this\n"
7641 " unit is required or wanted\n\n"
34c4b47b 7642 "Unit File Commands:\n"
fbf3283b
ZJS
7643 " list-unit-files [PATTERN...] List installed unit files\n"
7644 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7645 " disable UNIT... Disable one or more unit files\n"
7646 " reenable UNIT... Reenable one or more unit files\n"
7647 " preset UNIT... Enable/disable one or more unit files\n"
7648 " based on preset configuration\n"
7649 " preset-all Enable/disable all unit files based on\n"
7650 " preset configuration\n"
7651 " is-enabled UNIT... Check whether unit files are enabled\n"
7652 " mask UNIT... Mask one or more units\n"
7653 " unmask UNIT... Unmask one or more units\n"
7654 " link PATH... Link one or more units files into\n"
7655 " the search path\n"
7656 " revert UNIT... Revert one or more unit files to vendor\n"
7657 " version\n"
7658 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7659 " on specified one or more units\n"
7660 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7661 " on specified one or more units\n"
7662 " edit UNIT... Edit one or more unit files\n"
7663 " get-default Get the name of the default target\n"
7664 " set-default TARGET Set the default target\n\n"
0d292f5e 7665 "Machine Commands:\n"
fbf3283b 7666 " list-machines [PATTERN...] List local containers and host\n\n"
34c4b47b 7667 "Job Commands:\n"
fbf3283b
ZJS
7668 " list-jobs [PATTERN...] List jobs\n"
7669 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
34c4b47b 7670 "Environment Commands:\n"
fbf3283b 7671 " show-environment Dump environment\n"
135775c1
ZJS
7672 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7673 " unset-environment VARIABLE... Unset one or more environment variables\n"
7674 " import-environment [VARIABLE...] Import all or some environment variables\n\n"
34c4b47b 7675 "Manager Lifecycle Commands:\n"
fbf3283b
ZJS
7676 " daemon-reload Reload systemd manager configuration\n"
7677 " daemon-reexec Reexecute systemd manager\n\n"
34c4b47b 7678 "System Commands:\n"
fbf3283b
ZJS
7679 " is-system-running Check whether system is fully running\n"
7680 " default Enter system default mode\n"
7681 " rescue Enter system rescue mode\n"
7682 " emergency Enter system emergency mode\n"
7683 " halt Shut down and halt the system\n"
7684 " poweroff Shut down and power-off the system\n"
7685 " reboot [ARG] Shut down and reboot the system\n"
7686 " kexec Shut down and reboot the system with kexec\n"
7687 " exit [EXIT_CODE] Request user instance or container exit\n"
7688 " switch-root ROOT [INIT] Change to a different root file system\n"
7689 " suspend Suspend the system\n"
7690 " hibernate Hibernate the system\n"
c58493c0 7691 " hybrid-sleep Hibernate and suspend the system\n"
e68c79db 7692 " suspend-then-hibernate Suspend the system, wake after a period of\n"
37ec0fdd
LP
7693 " time and put it into hibernate\n"
7694 "\nSee the %s for details.\n"
7695 , program_invocation_short_name
7696 , link
7697 );
7698
7699 return 0;
7e4249b9
LP
7700}
7701
37ec0fdd
LP
7702static int halt_help(void) {
7703 _cleanup_free_ char *link = NULL;
7704 int r;
7705
7706 r = terminal_urlify_man("halt", "8", &link);
7707 if (r < 0)
7708 return log_oom();
7709
37185ec8 7710 printf("%s [OPTIONS...]%s\n\n"
e4b61340
LP
7711 "%s the system.\n\n"
7712 " --help Show this help\n"
7713 " --halt Halt the machine\n"
7714 " -p --poweroff Switch off the machine\n"
7715 " --reboot Reboot the machine\n"
2e33c433
LP
7716 " -f --force Force immediate halt/power-off/reboot\n"
7717 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
e4b61340 7718 " -d --no-wtmp Don't write wtmp record\n"
37ec0fdd
LP
7719 " --no-wall Don't send wall message before halt/power-off/reboot\n"
7720 "\nSee the %s for details.\n"
7721 , program_invocation_short_name
7722 , arg_action == ACTION_REBOOT ? " [ARG]" : "",
7723 arg_action == ACTION_REBOOT ? "Reboot" :
7724 arg_action == ACTION_POWEROFF ? "Power off" :
7725 "Halt"
7726 , link
7727 );
7728
7729 return 0;
e4b61340
LP
7730}
7731
37ec0fdd
LP
7732static int shutdown_help(void) {
7733 _cleanup_free_ char *link = NULL;
7734 int r;
7735
7736 r = terminal_urlify_man("shutdown", "8", &link);
7737 if (r < 0)
7738 return log_oom();
7739
08e4b1c5 7740 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
e4b61340
LP
7741 "Shut down the system.\n\n"
7742 " --help Show this help\n"
7743 " -H --halt Halt the machine\n"
7744 " -P --poweroff Power-off the machine\n"
7745 " -r --reboot Reboot the machine\n"
386da858 7746 " -h Equivalent to --poweroff, overridden by --halt\n"
2e33c433 7747 " -k Don't halt/power-off/reboot, just send warnings\n"
f6144808 7748 " --no-wall Don't send wall message before halt/power-off/reboot\n"
37ec0fdd
LP
7749 " -c Cancel a pending shutdown\n"
7750 "\nSee the %s for details.\n"
7751 , program_invocation_short_name
7752 , link
7753 );
7754
7755 return 0;
e4b61340
LP
7756}
7757
37ec0fdd
LP
7758static int telinit_help(void) {
7759 _cleanup_free_ char *link = NULL;
7760 int r;
7761
7762 r = terminal_urlify_man("telinit", "8", &link);
7763 if (r < 0)
7764 return log_oom();
7765
2e33c433 7766 printf("%s [OPTIONS...] {COMMAND}\n\n"
514f4ef5
LP
7767 "Send control commands to the init daemon.\n\n"
7768 " --help Show this help\n"
2e33c433 7769 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
e4b61340
LP
7770 "Commands:\n"
7771 " 0 Power-off the machine\n"
7772 " 6 Reboot the machine\n"
514f4ef5
LP
7773 " 2, 3, 4, 5 Start runlevelX.target unit\n"
7774 " 1, s, S Enter rescue mode\n"
7775 " q, Q Reload init daemon configuration\n"
37ec0fdd
LP
7776 " u, U Reexecute init daemon\n"
7777 "\nSee the %s for details.\n"
7778 , program_invocation_short_name
7779 , link
7780 );
7781
7782 return 0;
e4b61340
LP
7783}
7784
37ec0fdd
LP
7785static int runlevel_help(void) {
7786 _cleanup_free_ char *link = NULL;
7787 int r;
7788
7789 r = terminal_urlify_man("runlevel", "8", &link);
7790 if (r < 0)
7791 return log_oom();
7792
2e33c433 7793 printf("%s [OPTIONS...]\n\n"
e4b61340 7794 "Prints the previous and current runlevel of the init system.\n\n"
37ec0fdd
LP
7795 " --help Show this help\n"
7796 "\nSee the %s for details.\n"
7797 , program_invocation_short_name
7798 , link
7799 );
7800
7801 return 0;
e4b61340
LP
7802}
7803
b93312f5 7804static void help_types(void) {
b93312f5
ZJS
7805 if (!arg_no_legend)
7806 puts("Available unit types:");
5c828e66
LP
7807
7808 DUMP_STRING_TABLE(unit_type, UnitType, _UNIT_TYPE_MAX);
e16972e6
ZJS
7809}
7810
7811static void help_states(void) {
e16972e6
ZJS
7812 if (!arg_no_legend)
7813 puts("Available unit load states:");
5c828e66 7814 DUMP_STRING_TABLE(unit_load_state, UnitLoadState, _UNIT_LOAD_STATE_MAX);
e16972e6
ZJS
7815
7816 if (!arg_no_legend)
7817 puts("\nAvailable unit active states:");
5c828e66 7818 DUMP_STRING_TABLE(unit_active_state, UnitActiveState, _UNIT_ACTIVE_STATE_MAX);
7e55de3b
ZJS
7819
7820 if (!arg_no_legend)
7821 puts("\nAvailable automount unit substates:");
5c828e66 7822 DUMP_STRING_TABLE(automount_state, AutomountState, _AUTOMOUNT_STATE_MAX);
7e55de3b 7823
7e55de3b
ZJS
7824 if (!arg_no_legend)
7825 puts("\nAvailable device unit substates:");
5c828e66 7826 DUMP_STRING_TABLE(device_state, DeviceState, _DEVICE_STATE_MAX);
7e55de3b
ZJS
7827
7828 if (!arg_no_legend)
7829 puts("\nAvailable mount unit substates:");
5c828e66 7830 DUMP_STRING_TABLE(mount_state, MountState, _MOUNT_STATE_MAX);
7e55de3b
ZJS
7831
7832 if (!arg_no_legend)
7833 puts("\nAvailable path unit substates:");
5c828e66 7834 DUMP_STRING_TABLE(path_state, PathState, _PATH_STATE_MAX);
7e55de3b
ZJS
7835
7836 if (!arg_no_legend)
7837 puts("\nAvailable scope unit substates:");
5c828e66 7838 DUMP_STRING_TABLE(scope_state, ScopeState, _SCOPE_STATE_MAX);
7e55de3b
ZJS
7839
7840 if (!arg_no_legend)
7841 puts("\nAvailable service unit substates:");
5c828e66 7842 DUMP_STRING_TABLE(service_state, ServiceState, _SERVICE_STATE_MAX);
7e55de3b
ZJS
7843
7844 if (!arg_no_legend)
7845 puts("\nAvailable slice unit substates:");
5c828e66 7846 DUMP_STRING_TABLE(slice_state, SliceState, _SLICE_STATE_MAX);
7e55de3b 7847
7e55de3b
ZJS
7848 if (!arg_no_legend)
7849 puts("\nAvailable socket unit substates:");
5c828e66 7850 DUMP_STRING_TABLE(socket_state, SocketState, _SOCKET_STATE_MAX);
7e55de3b
ZJS
7851
7852 if (!arg_no_legend)
7853 puts("\nAvailable swap unit substates:");
5c828e66 7854 DUMP_STRING_TABLE(swap_state, SwapState, _SWAP_STATE_MAX);
7e55de3b
ZJS
7855
7856 if (!arg_no_legend)
7857 puts("\nAvailable target unit substates:");
5c828e66 7858 DUMP_STRING_TABLE(target_state, TargetState, _TARGET_STATE_MAX);
7e55de3b
ZJS
7859
7860 if (!arg_no_legend)
7861 puts("\nAvailable timer unit substates:");
5c828e66 7862 DUMP_STRING_TABLE(timer_state, TimerState, _TIMER_STATE_MAX);
45c0c61d
ZJS
7863}
7864
97af80c5
LP
7865static int help_boot_loader_entry(void) {
7866 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
7867 _cleanup_free_ char **l = NULL;
7868 sd_bus *bus;
7869 char **i;
7870 int r;
7871
7872 r = acquire_bus(BUS_FULL, &bus);
7873 if (r < 0)
7874 return r;
7875
7876 r = sd_bus_get_property_strv(
7877 bus,
7878 "org.freedesktop.login1",
7879 "/org/freedesktop/login1",
7880 "org.freedesktop.login1.Manager",
7881 "BootLoaderEntries",
7882 &error,
7883 &l);
7884 if (r < 0)
7885 return log_error_errno(r, "Failed to enumerate boot loader entries: %s", bus_error_message(&error, r));
7886
7887 if (strv_isempty(l)) {
7888 log_error("No boot loader entries discovered.");
7889 return -ENODATA;
7890 }
7891
7892 STRV_FOREACH(i, l)
7893 puts(*i);
7894
7895 return 0;
7896}
7897
e4b61340 7898static int systemctl_parse_argv(int argc, char *argv[]) {
7e4249b9 7899 enum {
90d473a1 7900 ARG_FAIL = 0x100,
afba4199
ZJS
7901 ARG_REVERSE,
7902 ARG_AFTER,
7903 ARG_BEFORE,
1ae17672 7904 ARG_DRY_RUN,
991f2a39 7905 ARG_SHOW_TYPES,
23ade460 7906 ARG_IRREVERSIBLE,
e67c3609 7907 ARG_IGNORE_DEPENDENCIES,
4f9a9105 7908 ARG_VALUE,
35df8f27 7909 ARG_VERSION,
af2d49f7 7910 ARG_USER,
7e4249b9 7911 ARG_SYSTEM,
ee5762e3 7912 ARG_GLOBAL,
6e905d93 7913 ARG_NO_BLOCK,
ebed32bf 7914 ARG_NO_LEGEND,
611efaac 7915 ARG_NO_PAGER,
4445a875 7916 ARG_NO_WALL,
be394c48 7917 ARG_ROOT,
ee5762e3 7918 ARG_NO_RELOAD,
501fc174 7919 ARG_KILL_WHO,
30732560 7920 ARG_NO_ASK_PASSWORD,
729e3769 7921 ARG_FAILED,
df50185b 7922 ARG_RUNTIME,
9b9b3d36 7923 ARG_PLAIN,
4dc5b821 7924 ARG_STATE,
d309c1c3
LP
7925 ARG_JOB_MODE,
7926 ARG_PRESET_MODE,
5bdf2243 7927 ARG_FIRMWARE_SETUP,
97af80c5
LP
7928 ARG_BOOT_LOADER_MENU,
7929 ARG_BOOT_LOADER_ENTRY,
57ab2eab 7930 ARG_NOW,
9ef15026 7931 ARG_MESSAGE,
93a08841 7932 ARG_WAIT,
7e4249b9
LP
7933 };
7934
7935 static const struct option options[] = {
9ea9d4cf
LP
7936 { "help", no_argument, NULL, 'h' },
7937 { "version", no_argument, NULL, ARG_VERSION },
7938 { "type", required_argument, NULL, 't' },
7939 { "property", required_argument, NULL, 'p' },
7940 { "all", no_argument, NULL, 'a' },
7941 { "reverse", no_argument, NULL, ARG_REVERSE },
7942 { "after", no_argument, NULL, ARG_AFTER },
7943 { "before", no_argument, NULL, ARG_BEFORE },
7944 { "show-types", no_argument, NULL, ARG_SHOW_TYPES },
7945 { "failed", no_argument, NULL, ARG_FAILED }, /* compatibility only */
7946 { "full", no_argument, NULL, 'l' },
4dc5b821
LP
7947 { "job-mode", required_argument, NULL, ARG_JOB_MODE },
7948 { "fail", no_argument, NULL, ARG_FAIL }, /* compatibility only */
7949 { "irreversible", no_argument, NULL, ARG_IRREVERSIBLE }, /* compatibility only */
7950 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES }, /* compatibility only */
9ea9d4cf 7951 { "ignore-inhibitors", no_argument, NULL, 'i' },
4f9a9105 7952 { "value", no_argument, NULL, ARG_VALUE },
9ea9d4cf
LP
7953 { "user", no_argument, NULL, ARG_USER },
7954 { "system", no_argument, NULL, ARG_SYSTEM },
7955 { "global", no_argument, NULL, ARG_GLOBAL },
93a08841 7956 { "wait", no_argument, NULL, ARG_WAIT },
9ea9d4cf
LP
7957 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
7958 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
7959 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
7960 { "no-wall", no_argument, NULL, ARG_NO_WALL },
1ae17672 7961 { "dry-run", no_argument, NULL, ARG_DRY_RUN },
9ea9d4cf
LP
7962 { "quiet", no_argument, NULL, 'q' },
7963 { "root", required_argument, NULL, ARG_ROOT },
68da321f 7964 { "force", no_argument, NULL, 'f' },
9ea9d4cf
LP
7965 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
7966 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
7967 { "signal", required_argument, NULL, 's' },
7968 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
7969 { "host", required_argument, NULL, 'H' },
f459b602 7970 { "machine", required_argument, NULL, 'M' },
9ea9d4cf
LP
7971 { "runtime", no_argument, NULL, ARG_RUNTIME },
7972 { "lines", required_argument, NULL, 'n' },
7973 { "output", required_argument, NULL, 'o' },
7974 { "plain", no_argument, NULL, ARG_PLAIN },
7975 { "state", required_argument, NULL, ARG_STATE },
1238ee09 7976 { "recursive", no_argument, NULL, 'r' },
d309c1c3 7977 { "preset-mode", required_argument, NULL, ARG_PRESET_MODE },
5bdf2243 7978 { "firmware-setup", no_argument, NULL, ARG_FIRMWARE_SETUP },
97af80c5
LP
7979 { "boot-loader-menu", required_argument, NULL, ARG_BOOT_LOADER_MENU },
7980 { "boot-loader-entry", required_argument, NULL, ARG_BOOT_LOADER_ENTRY },
57ab2eab 7981 { "now", no_argument, NULL, ARG_NOW },
9ef15026 7982 { "message", required_argument, NULL, ARG_MESSAGE },
eb9da376 7983 {}
7e4249b9
LP
7984 };
7985
0f03c2a4 7986 int c, r;
7e4249b9 7987
e4b61340 7988 assert(argc >= 0);
7e4249b9
LP
7989 assert(argv);
7990
16f017fa
IS
7991 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
7992 arg_ask_password = true;
7993
2e7e19ca 7994 while ((c = getopt_long(argc, argv, "ht:p:alqfs:H:M:n:o:ir.::", options, NULL)) >= 0)
7e4249b9
LP
7995
7996 switch (c) {
7997
7998 case 'h':
37ec0fdd 7999 return systemctl_help();
35df8f27
LP
8000
8001 case ARG_VERSION:
3f6fd1ba 8002 return version();
7e4249b9 8003
20b3f379 8004 case 't': {
fb1ac50e
LP
8005 const char *p;
8006
baaa35ad
ZJS
8007 if (isempty(optarg))
8008 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8009 "--type= requires arguments.");
45c0c61d 8010
c58bd76a 8011 for (p = optarg;;) {
5ab22f33 8012 _cleanup_free_ char *type = NULL;
20b3f379 8013
5ab22f33
SS
8014 r = extract_first_word(&p, &type, ",", 0);
8015 if (r < 0)
8016 return log_error_errno(r, "Failed to parse type: %s", optarg);
5ab22f33
SS
8017 if (r == 0)
8018 break;
20b3f379
ZJS
8019
8020 if (streq(type, "help")) {
8021 help_types();
8022 return 0;
8023 }
8024
8025 if (unit_type_from_string(type) >= 0) {
96e895ef 8026 if (strv_consume(&arg_types, TAKE_PTR(type)) < 0)
20b3f379 8027 return log_oom();
20b3f379
ZJS
8028 continue;
8029 }
8030
9b9b3d36
MW
8031 /* It's much nicer to use --state= for
8032 * load states, but let's support this
8033 * in --types= too for compatibility
8034 * with old versions */
7e9d36e0 8035 if (unit_load_state_from_string(type) >= 0) {
96e895ef 8036 if (strv_consume(&arg_states, TAKE_PTR(type)) < 0)
20b3f379 8037 return log_oom();
20b3f379
ZJS
8038 continue;
8039 }
8040
ab06eef8 8041 log_error("Unknown unit type or load state '%s'.", type);
baaa35ad
ZJS
8042 return log_info_errno(SYNTHETIC_ERRNO(EINVAL),
8043 "Use -t help to see a list of allowed values.");
c147dc42 8044 }
20b3f379
ZJS
8045
8046 break;
8047 }
8048
ea4a240d 8049 case 'p': {
033a842c
ZJS
8050 /* Make sure that if the empty property list
8051 was specified, we won't show any properties. */
20b3f379 8052 if (isempty(optarg) && !arg_properties) {
cbc9fbd1 8053 arg_properties = new0(char*, 1);
20b3f379
ZJS
8054 if (!arg_properties)
8055 return log_oom();
fb1ac50e
LP
8056 } else {
8057 const char *p;
8058
c58bd76a 8059 for (p = optarg;;) {
5ab22f33 8060 _cleanup_free_ char *prop = NULL;
033a842c 8061
5ab22f33
SS
8062 r = extract_first_word(&p, &prop, ",", 0);
8063 if (r < 0)
8064 return log_error_errno(r, "Failed to parse property: %s", optarg);
5ab22f33
SS
8065 if (r == 0)
8066 break;
ea4a240d 8067
5ab22f33 8068 if (strv_push(&arg_properties, prop) < 0)
20b3f379 8069 return log_oom();
5ab22f33
SS
8070
8071 prop = NULL;
20b3f379 8072 }
fb1ac50e 8073 }
48220598
LP
8074
8075 /* If the user asked for a particular
8076 * property, show it to him, even if it is
8077 * empty. */
8078 arg_all = true;
033a842c 8079
48220598 8080 break;
ea4a240d 8081 }
48220598 8082
7e4249b9
LP
8083 case 'a':
8084 arg_all = true;
8085 break;
8086
afba4199
ZJS
8087 case ARG_REVERSE:
8088 arg_dependency = DEPENDENCY_REVERSE;
8089 break;
8090
8091 case ARG_AFTER:
8092 arg_dependency = DEPENDENCY_AFTER;
82948f6c 8093 arg_jobs_after = true;
afba4199
ZJS
8094 break;
8095
8096 case ARG_BEFORE:
8097 arg_dependency = DEPENDENCY_BEFORE;
82948f6c 8098 arg_jobs_before = true;
afba4199
ZJS
8099 break;
8100
991f2a39
ZJS
8101 case ARG_SHOW_TYPES:
8102 arg_show_types = true;
8103 break;
8104
4f9a9105
ZJS
8105 case ARG_VALUE:
8106 arg_value = true;
8107 break;
8108
4dc5b821
LP
8109 case ARG_JOB_MODE:
8110 arg_job_mode = optarg;
8111 break;
8112
90d473a1 8113 case ARG_FAIL:
e67c3609
LP
8114 arg_job_mode = "fail";
8115 break;
8116
23ade460
MS
8117 case ARG_IRREVERSIBLE:
8118 arg_job_mode = "replace-irreversibly";
8119 break;
8120
e67c3609
LP
8121 case ARG_IGNORE_DEPENDENCIES:
8122 arg_job_mode = "ignore-dependencies";
7e4249b9
LP
8123 break;
8124
af2d49f7 8125 case ARG_USER:
729e3769 8126 arg_scope = UNIT_FILE_USER;
7e4249b9
LP
8127 break;
8128
8129 case ARG_SYSTEM:
729e3769
LP
8130 arg_scope = UNIT_FILE_SYSTEM;
8131 break;
8132
8133 case ARG_GLOBAL:
8134 arg_scope = UNIT_FILE_GLOBAL;
7e4249b9
LP
8135 break;
8136
93a08841
MP
8137 case ARG_WAIT:
8138 arg_wait = true;
8139 break;
8140
6e905d93
LP
8141 case ARG_NO_BLOCK:
8142 arg_no_block = true;
7e4249b9
LP
8143 break;
8144
ebed32bf
MS
8145 case ARG_NO_LEGEND:
8146 arg_no_legend = true;
8147 break;
8148
611efaac 8149 case ARG_NO_PAGER:
0221d68a 8150 arg_pager_flags |= PAGER_DISABLE;
611efaac 8151 break;
0736af98 8152
514f4ef5
LP
8153 case ARG_NO_WALL:
8154 arg_no_wall = true;
8155 break;
8156
be394c48 8157 case ARG_ROOT:
bac75eb3 8158 r = parse_path_argument_and_warn(optarg, false, &arg_root);
0f03c2a4
LP
8159 if (r < 0)
8160 return r;
be394c48
FC
8161 break;
8162
98a6e132 8163 case 'l':
8fe914ec
LP
8164 arg_full = true;
8165 break;
8166
30732560 8167 case ARG_FAILED:
9b9b3d36
MW
8168 if (strv_extend(&arg_states, "failed") < 0)
8169 return log_oom();
8170
30732560
LP
8171 break;
8172
1ae17672
ZJS
8173 case ARG_DRY_RUN:
8174 arg_dry_run = true;
8175 break;
8176
0183528f
LP
8177 case 'q':
8178 arg_quiet = true;
8179 break;
8180
b4f27ccc 8181 case 'f':
313cefa1 8182 arg_force++;
ee5762e3
LP
8183 break;
8184
8185 case ARG_NO_RELOAD:
8186 arg_no_reload = true;
8187 break;
8188
8a0867d6
LP
8189 case ARG_KILL_WHO:
8190 arg_kill_who = optarg;
8191 break;
8192
8a0867d6 8193 case 's':
5c828e66
LP
8194 if (streq(optarg, "help")) {
8195 DUMP_STRING_TABLE(signal, int, _NSIG);
8196 return 0;
8197 }
8198
29a3db75 8199 arg_signal = signal_from_string(optarg);
baaa35ad
ZJS
8200 if (arg_signal < 0)
8201 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8202 "Failed to parse signal string %s.",
8203 optarg);
8a0867d6
LP
8204 break;
8205
501fc174
LP
8206 case ARG_NO_ASK_PASSWORD:
8207 arg_ask_password = false;
8208 break;
8209
f459b602
MAP
8210 case 'H':
8211 arg_transport = BUS_TRANSPORT_REMOTE;
8212 arg_host = optarg;
a8f11321
LP
8213 break;
8214
f459b602 8215 case 'M':
de33fc62 8216 arg_transport = BUS_TRANSPORT_MACHINE;
f459b602 8217 arg_host = optarg;
a8f11321
LP
8218 break;
8219
729e3769
LP
8220 case ARG_RUNTIME:
8221 arg_runtime = true;
8222 break;
8223
df50185b 8224 case 'n':
baaa35ad
ZJS
8225 if (safe_atou(optarg, &arg_lines) < 0)
8226 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8227 "Failed to parse lines '%s'",
8228 optarg);
df50185b
LP
8229 break;
8230
df50185b 8231 case 'o':
5c828e66
LP
8232 if (streq(optarg, "help")) {
8233 DUMP_STRING_TABLE(output_mode, OutputMode, _OUTPUT_MODE_MAX);
8234 return 0;
8235 }
8236
df50185b 8237 arg_output = output_mode_from_string(optarg);
baaa35ad
ZJS
8238 if (arg_output < 0)
8239 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8240 "Unknown output '%s'.",
8241 optarg);
df50185b
LP
8242 break;
8243
b37844d3
LP
8244 case 'i':
8245 arg_ignore_inhibitors = true;
8246 break;
8247
5d0c05e5
LN
8248 case ARG_PLAIN:
8249 arg_plain = true;
8250 break;
8251
5bdf2243
JJ
8252 case ARG_FIRMWARE_SETUP:
8253 arg_firmware_setup = true;
8254 break;
8255
97af80c5
LP
8256 case ARG_BOOT_LOADER_MENU:
8257
8258 r = parse_sec(optarg, &arg_boot_loader_menu);
8259 if (r < 0)
8260 return log_error_errno(r, "Failed to parse --boot-loader-menu= argument '%s': %m", optarg);
8261
8262 break;
8263
8264 case ARG_BOOT_LOADER_ENTRY:
8265
8266 if (streq(optarg, "help")) { /* Yes, this means, "help" is not a valid boot loader entry name we can deal with */
8267 r = help_boot_loader_entry();
8268 if (r < 0)
8269 return r;
8270
8271 return 0;
8272 }
8273
8274 arg_boot_loader_entry = empty_to_null(optarg);
8275 break;
8276
9b9b3d36 8277 case ARG_STATE: {
fb1ac50e
LP
8278 const char *p;
8279
baaa35ad
ZJS
8280 if (isempty(optarg))
8281 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8282 "--state= requires arguments.");
9b9b3d36 8283
c58bd76a 8284 for (p = optarg;;) {
bc6c18fe 8285 _cleanup_free_ char *s = NULL;
9b9b3d36 8286
5ab22f33
SS
8287 r = extract_first_word(&p, &s, ",", 0);
8288 if (r < 0)
6862111e 8289 return log_error_errno(r, "Failed to parse state: %s", optarg);
5ab22f33
SS
8290 if (r == 0)
8291 break;
9b9b3d36 8292
e16972e6
ZJS
8293 if (streq(s, "help")) {
8294 help_states();
8295 return 0;
8296 }
8297
7e9d36e0 8298 if (strv_push(&arg_states, s) < 0)
9b9b3d36 8299 return log_oom();
7e9d36e0
LP
8300
8301 s = NULL;
9b9b3d36
MW
8302 }
8303 break;
8304 }
8305
1238ee09 8306 case 'r':
baaa35ad
ZJS
8307 if (geteuid() != 0)
8308 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
8309 "--recursive requires root privileges.");
1238ee09
LP
8310
8311 arg_recursive = true;
8312 break;
8313
d309c1c3 8314 case ARG_PRESET_MODE:
5c828e66
LP
8315 if (streq(optarg, "help")) {
8316 DUMP_STRING_TABLE(unit_file_preset_mode, UnitFilePresetMode, _UNIT_FILE_PRESET_MAX);
8317 return 0;
8318 }
d309c1c3
LP
8319
8320 arg_preset_mode = unit_file_preset_mode_from_string(optarg);
baaa35ad
ZJS
8321 if (arg_preset_mode < 0)
8322 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8323 "Failed to parse preset mode: %s.", optarg);
d309c1c3
LP
8324
8325 break;
8326
57ab2eab
JS
8327 case ARG_NOW:
8328 arg_now = true;
8329 break;
8330
9ef15026
JS
8331 case ARG_MESSAGE:
8332 if (strv_extend(&arg_wall, optarg) < 0)
8333 return log_oom();
8334 break;
8335
2e7e19ca
ZJS
8336 case '.':
8337 /* Output an error mimicking getopt, and print a hint afterwards */
8338 log_error("%s: invalid option -- '.'", program_invocation_name);
8339 log_notice("Hint: to specify units starting with a dash, use \"--\":\n"
8340 " %s [OPTIONS...] {COMMAND} -- -.%s ...",
8341 program_invocation_name, optarg ?: "mount");
8342 _fallthrough_;
8343
7e4249b9
LP
8344 case '?':
8345 return -EINVAL;
8346
8347 default:
eb9da376 8348 assert_not_reached("Unhandled option");
7e4249b9 8349 }
7e4249b9 8350
baaa35ad
ZJS
8351 if (arg_transport != BUS_TRANSPORT_LOCAL && arg_scope != UNIT_FILE_SYSTEM)
8352 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8353 "Cannot access user instance remotely.");
a8f11321 8354
baaa35ad
ZJS
8355 if (arg_wait && arg_no_block)
8356 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8357 "--wait may not be combined with --no-block.");
93a08841 8358
7e4249b9
LP
8359 return 1;
8360}
8361
e4b61340 8362static int halt_parse_argv(int argc, char *argv[]) {
e4b61340
LP
8363 enum {
8364 ARG_HELP = 0x100,
8365 ARG_HALT,
514f4ef5
LP
8366 ARG_REBOOT,
8367 ARG_NO_WALL
e4b61340
LP
8368 };
8369
8370 static const struct option options[] = {
8371 { "help", no_argument, NULL, ARG_HELP },
8372 { "halt", no_argument, NULL, ARG_HALT },
8373 { "poweroff", no_argument, NULL, 'p' },
8374 { "reboot", no_argument, NULL, ARG_REBOOT },
8375 { "force", no_argument, NULL, 'f' },
8376 { "wtmp-only", no_argument, NULL, 'w' },
8377 { "no-wtmp", no_argument, NULL, 'd' },
f3f054f0 8378 { "no-sync", no_argument, NULL, 'n' },
514f4ef5 8379 { "no-wall", no_argument, NULL, ARG_NO_WALL },
eb9da376 8380 {}
e4b61340
LP
8381 };
8382
37185ec8 8383 int c, r, runlevel;
e4b61340
LP
8384
8385 assert(argc >= 0);
8386 assert(argv);
8387
8388 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4c701096 8389 if (IN_SET(runlevel, '0', '6'))
65491fd8 8390 arg_force = 2;
e4b61340 8391
601185b4 8392 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0)
e4b61340
LP
8393 switch (c) {
8394
8395 case ARG_HELP:
37ec0fdd 8396 return halt_help();
e4b61340
LP
8397
8398 case ARG_HALT:
8399 arg_action = ACTION_HALT;
8400 break;
8401
8402 case 'p':
a042efad
MS
8403 if (arg_action != ACTION_REBOOT)
8404 arg_action = ACTION_POWEROFF;
e4b61340
LP
8405 break;
8406
8407 case ARG_REBOOT:
8408 arg_action = ACTION_REBOOT;
8409 break;
8410
8411 case 'f':
65491fd8 8412 arg_force = 2;
e4b61340
LP
8413 break;
8414
8415 case 'w':
1ae17672 8416 arg_dry_run = true;
e4b61340
LP
8417 break;
8418
8419 case 'd':
8420 arg_no_wtmp = true;
8421 break;
8422
f3f054f0
TB
8423 case 'n':
8424 arg_no_sync = true;
8425 break;
8426
514f4ef5
LP
8427 case ARG_NO_WALL:
8428 arg_no_wall = true;
8429 break;
8430
e4b61340
LP
8431 case 'i':
8432 case 'h':
8433 /* Compatibility nops */
8434 break;
8435
8436 case '?':
8437 return -EINVAL;
8438
8439 default:
eb9da376 8440 assert_not_reached("Unhandled option");
e4b61340 8441 }
e4b61340 8442
c5220a94 8443 if (arg_action == ACTION_REBOOT && (argc == optind || argc == optind + 1)) {
27c06cb5 8444 r = update_reboot_parameter_and_warn(argc == optind + 1 ? argv[optind] : NULL);
c5220a94 8445 if (r < 0)
37185ec8 8446 return r;
baaa35ad
ZJS
8447 } else if (optind < argc)
8448 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8449 "Too many arguments.");
e4b61340
LP
8450
8451 return 1;
8452}
8453
2cc7b0a2 8454static int parse_shutdown_time_spec(const char *t, usec_t *_u) {
f6144808
LP
8455 assert(t);
8456 assert(_u);
8457
8458 if (streq(t, "now"))
8459 *_u = 0;
1a639877 8460 else if (!strchr(t, ':')) {
f6144808
LP
8461 uint64_t u;
8462
1a639877 8463 if (safe_atou64(t, &u) < 0)
f6144808
LP
8464 return -EINVAL;
8465
8466 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
8467 } else {
8468 char *e = NULL;
8469 long hour, minute;
b92bea5d 8470 struct tm tm = {};
f6144808
LP
8471 time_t s;
8472 usec_t n;
8473
8474 errno = 0;
8475 hour = strtol(t, &e, 10);
8333c77e 8476 if (errno > 0 || *e != ':' || hour < 0 || hour > 23)
f6144808
LP
8477 return -EINVAL;
8478
8479 minute = strtol(e+1, &e, 10);
8333c77e 8480 if (errno > 0 || *e != 0 || minute < 0 || minute > 59)
f6144808
LP
8481 return -EINVAL;
8482
8483 n = now(CLOCK_REALTIME);
08e4b1c5
LP
8484 s = (time_t) (n / USEC_PER_SEC);
8485
f6144808
LP
8486 assert_se(localtime_r(&s, &tm));
8487
8488 tm.tm_hour = (int) hour;
8489 tm.tm_min = (int) minute;
08e4b1c5 8490 tm.tm_sec = 0;
f6144808 8491
855a86a3
ZJS
8492 s = mktime(&tm);
8493 assert(s >= 0);
f6144808
LP
8494
8495 *_u = (usec_t) s * USEC_PER_SEC;
8496
8497 while (*_u <= n)
8498 *_u += USEC_PER_DAY;
8499 }
8500
8501 return 0;
8502}
8503
e4b61340 8504static int shutdown_parse_argv(int argc, char *argv[]) {
e4b61340
LP
8505 enum {
8506 ARG_HELP = 0x100,
514f4ef5 8507 ARG_NO_WALL
e4b61340
LP
8508 };
8509
8510 static const struct option options[] = {
8511 { "help", no_argument, NULL, ARG_HELP },
8512 { "halt", no_argument, NULL, 'H' },
8513 { "poweroff", no_argument, NULL, 'P' },
8514 { "reboot", no_argument, NULL, 'r' },
04ebb595 8515 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
514f4ef5 8516 { "no-wall", no_argument, NULL, ARG_NO_WALL },
eb9da376 8517 {}
e4b61340
LP
8518 };
8519
172d7abf 8520 char **wall = NULL;
f6144808 8521 int c, r;
e4b61340
LP
8522
8523 assert(argc >= 0);
8524 assert(argv);
8525
b068c6f5 8526 while ((c = getopt_long(argc, argv, "HPrhkKat:fFc", options, NULL)) >= 0)
e4b61340
LP
8527 switch (c) {
8528
8529 case ARG_HELP:
37ec0fdd 8530 return shutdown_help();
e4b61340
LP
8531
8532 case 'H':
8533 arg_action = ACTION_HALT;
8534 break;
8535
8536 case 'P':
8537 arg_action = ACTION_POWEROFF;
8538 break;
8539
8540 case 'r':
5622dde3
KS
8541 if (kexec_loaded())
8542 arg_action = ACTION_KEXEC;
8543 else
8544 arg_action = ACTION_REBOOT;
e4b61340
LP
8545 break;
8546
04ebb595
LP
8547 case 'K':
8548 arg_action = ACTION_KEXEC;
8549 break;
8550
e4b61340
LP
8551 case 'h':
8552 if (arg_action != ACTION_HALT)
8553 arg_action = ACTION_POWEROFF;
8554 break;
8555
8556 case 'k':
1ae17672 8557 arg_dry_run = true;
e4b61340
LP
8558 break;
8559
514f4ef5
LP
8560 case ARG_NO_WALL:
8561 arg_no_wall = true;
8562 break;
8563
e4b61340 8564 case 'a':
b068c6f5 8565 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
75836b9d
JS
8566 case 'f':
8567 case 'F':
e4b61340
LP
8568 /* Compatibility nops */
8569 break;
8570
f6144808
LP
8571 case 'c':
8572 arg_action = ACTION_CANCEL_SHUTDOWN;
8573 break;
8574
e4b61340
LP
8575 case '?':
8576 return -EINVAL;
8577
8578 default:
eb9da376 8579 assert_not_reached("Unhandled option");
e4b61340 8580 }
e4b61340 8581
dfcc5c33 8582 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
2cc7b0a2 8583 r = parse_shutdown_time_spec(argv[optind], &arg_when);
7e59bfcb 8584 if (r < 0) {
f6144808
LP
8585 log_error("Failed to parse time specification: %s", argv[optind]);
8586 return r;
8587 }
6b5ad000 8588 } else
08e4b1c5 8589 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
442b9094 8590
dfcc5c33
MS
8591 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
8592 /* No time argument for shutdown cancel */
172d7abf 8593 wall = argv + optind;
dfcc5c33
MS
8594 else if (argc > optind + 1)
8595 /* We skip the time argument */
172d7abf
LP
8596 wall = argv + optind + 1;
8597
8598 if (wall) {
8599 arg_wall = strv_copy(wall);
8600 if (!arg_wall)
8601 return log_oom();
8602 }
e4b61340
LP
8603
8604 optind = argc;
8605
8606 return 1;
e4b61340
LP
8607}
8608
8609static int telinit_parse_argv(int argc, char *argv[]) {
e4b61340
LP
8610 enum {
8611 ARG_HELP = 0x100,
514f4ef5 8612 ARG_NO_WALL
e4b61340
LP
8613 };
8614
8615 static const struct option options[] = {
8616 { "help", no_argument, NULL, ARG_HELP },
514f4ef5 8617 { "no-wall", no_argument, NULL, ARG_NO_WALL },
eb9da376 8618 {}
e4b61340
LP
8619 };
8620
8621 static const struct {
8622 char from;
8623 enum action to;
8624 } table[] = {
8625 { '0', ACTION_POWEROFF },
8626 { '6', ACTION_REBOOT },
ef2f1067 8627 { '1', ACTION_RESCUE },
e4b61340
LP
8628 { '2', ACTION_RUNLEVEL2 },
8629 { '3', ACTION_RUNLEVEL3 },
8630 { '4', ACTION_RUNLEVEL4 },
8631 { '5', ACTION_RUNLEVEL5 },
8632 { 's', ACTION_RESCUE },
8633 { 'S', ACTION_RESCUE },
8634 { 'q', ACTION_RELOAD },
8635 { 'Q', ACTION_RELOAD },
8636 { 'u', ACTION_REEXEC },
8637 { 'U', ACTION_REEXEC }
8638 };
8639
8640 unsigned i;
8641 int c;
8642
8643 assert(argc >= 0);
8644 assert(argv);
8645
601185b4 8646 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
e4b61340
LP
8647 switch (c) {
8648
8649 case ARG_HELP:
37ec0fdd 8650 return telinit_help();
e4b61340 8651
514f4ef5
LP
8652 case ARG_NO_WALL:
8653 arg_no_wall = true;
8654 break;
8655
e4b61340
LP
8656 case '?':
8657 return -EINVAL;
8658
8659 default:
eb9da376 8660 assert_not_reached("Unhandled option");
e4b61340 8661 }
e4b61340 8662
baaa35ad
ZJS
8663 if (optind >= argc)
8664 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8665 "%s: required argument missing.",
8666 program_invocation_short_name);
e4b61340 8667
baaa35ad
ZJS
8668 if (optind + 1 < argc)
8669 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8670 "Too many arguments.");
e4b61340 8671
baaa35ad
ZJS
8672 if (strlen(argv[optind]) != 1)
8673 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8674 "Expected single character argument.");
e4b61340
LP
8675
8676 for (i = 0; i < ELEMENTSOF(table); i++)
8677 if (table[i].from == argv[optind][0])
8678 break;
8679
baaa35ad
ZJS
8680 if (i >= ELEMENTSOF(table))
8681 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8682 "Unknown command '%s'.", argv[optind]);
e4b61340
LP
8683
8684 arg_action = table[i].to;
8685
313cefa1 8686 optind++;
e4b61340
LP
8687
8688 return 1;
8689}
8690
8691static int runlevel_parse_argv(int argc, char *argv[]) {
e4b61340
LP
8692 enum {
8693 ARG_HELP = 0x100,
8694 };
8695
8696 static const struct option options[] = {
8697 { "help", no_argument, NULL, ARG_HELP },
eb9da376 8698 {}
e4b61340
LP
8699 };
8700
8701 int c;
8702
8703 assert(argc >= 0);
8704 assert(argv);
8705
601185b4 8706 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
e4b61340
LP
8707 switch (c) {
8708
8709 case ARG_HELP:
37ec0fdd 8710 return runlevel_help();
e4b61340
LP
8711
8712 case '?':
8713 return -EINVAL;
8714
8715 default:
eb9da376 8716 assert_not_reached("Unhandled option");
e4b61340 8717 }
e4b61340 8718
baaa35ad
ZJS
8719 if (optind < argc)
8720 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8721 "Too many arguments.");
e4b61340
LP
8722
8723 return 1;
8724}
8725
8726static int parse_argv(int argc, char *argv[]) {
8727 assert(argc >= 0);
8728 assert(argv);
8729
8730 if (program_invocation_short_name) {
8731
8732 if (strstr(program_invocation_short_name, "halt")) {
8733 arg_action = ACTION_HALT;
8734 return halt_parse_argv(argc, argv);
c54819ca 8735
e4b61340
LP
8736 } else if (strstr(program_invocation_short_name, "poweroff")) {
8737 arg_action = ACTION_POWEROFF;
8738 return halt_parse_argv(argc, argv);
c54819ca 8739
e4b61340 8740 } else if (strstr(program_invocation_short_name, "reboot")) {
5622dde3
KS
8741 if (kexec_loaded())
8742 arg_action = ACTION_KEXEC;
8743 else
8744 arg_action = ACTION_REBOOT;
e4b61340 8745 return halt_parse_argv(argc, argv);
c54819ca 8746
e4b61340
LP
8747 } else if (strstr(program_invocation_short_name, "shutdown")) {
8748 arg_action = ACTION_POWEROFF;
8749 return shutdown_parse_argv(argc, argv);
c54819ca 8750
e4b61340 8751 } else if (strstr(program_invocation_short_name, "init")) {
d5ca5f11 8752
c54819ca
LP
8753 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
8754 * 1 on SysV.
8755 *
8756 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
8757 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
8758 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
8759 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
8760 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
8761 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
8762 * quick way to match both.
8763 *
8764 * Also see redirect_telinit() in src/core/main.c. */
8765
d5ca5f11 8766 if (sd_booted() > 0) {
f459b602 8767 arg_action = _ACTION_INVALID;
d5ca5f11
LP
8768 return telinit_parse_argv(argc, argv);
8769 } else {
c54819ca
LP
8770 /* Hmm, so some other init system is running, we need to forward this request to
8771 * it. For now we simply guess that it is Upstart. */
d5ca5f11 8772
595225af 8773 (void) rlimit_nofile_safe();
4ad61fd1 8774 execv(TELINIT, argv);
d5ca5f11 8775
baaa35ad
ZJS
8776 return log_error_errno(SYNTHETIC_ERRNO(EIO),
8777 "Couldn't find an alternative telinit implementation to spawn.");
d5ca5f11
LP
8778 }
8779
e4b61340
LP
8780 } else if (strstr(program_invocation_short_name, "runlevel")) {
8781 arg_action = ACTION_RUNLEVEL;
8782 return runlevel_parse_argv(argc, argv);
8783 }
8784 }
8785
8786 arg_action = ACTION_SYSTEMCTL;
8787 return systemctl_parse_argv(argc, argv);
8788}
8789
349cc4a5 8790#if HAVE_SYSV_COMPAT
44a6b1b6 8791_pure_ static int action_to_runlevel(void) {
eb22ac37
LP
8792 static const char table[_ACTION_MAX] = {
8793 [ACTION_HALT] = '0',
8794 [ACTION_POWEROFF] = '0',
8795 [ACTION_REBOOT] = '6',
8796 [ACTION_RUNLEVEL2] = '2',
8797 [ACTION_RUNLEVEL3] = '3',
8798 [ACTION_RUNLEVEL4] = '4',
8799 [ACTION_RUNLEVEL5] = '5',
8800 [ACTION_RESCUE] = '1'
8801 };
8802
78ca9099 8803 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
d55ae9e6
LP
8804
8805 return table[arg_action];
8806}
d2e79673 8807#endif
d55ae9e6 8808
d55ae9e6 8809static int talk_initctl(void) {
349cc4a5 8810#if HAVE_SYSV_COMPAT
cbc9fbd1
LP
8811 struct init_request request = {
8812 .magic = INIT_MAGIC,
8813 .sleeptime = 0,
8814 .cmd = INIT_CMD_RUNLVL
8815 };
8816
7fd1b19b 8817 _cleanup_close_ int fd = -1;
d55ae9e6 8818 char rl;
cbc9fbd1 8819 int r;
83c76e8c 8820 const char *p;
eb22ac37 8821
427b47c4
ZJS
8822 rl = action_to_runlevel();
8823 if (!rl)
eb22ac37
LP
8824 return 0;
8825
d55ae9e6
LP
8826 request.runlevel = rl;
8827
83c76e8c
MG
8828 FOREACH_STRING(p, "/run/initctl", "/dev/initctl") {
8829 fd = open(p, O_WRONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
8830 if (fd >= 0 || errno != ENOENT)
8831 break;
8832 }
427b47c4 8833 if (fd < 0) {
d55ae9e6
LP
8834 if (errno == ENOENT)
8835 return 0;
eb22ac37 8836
83c76e8c 8837 return log_error_errno(errno, "Failed to open initctl fifo: %m");
d55ae9e6 8838 }
eb22ac37 8839
553acb7b
ZJS
8840 r = loop_write(fd, &request, sizeof(request), false);
8841 if (r < 0)
83c76e8c 8842 return log_error_errno(r, "Failed to write to %s: %m", p);
eb22ac37
LP
8843
8844 return 1;
eca830be
LP
8845#else
8846 return 0;
8847#endif
e4b61340
LP
8848}
8849
e449de87 8850static int systemctl_main(int argc, char *argv[]) {
e449de87 8851 static const Verb verbs[] = {
c56d1e2c
CW
8852 { "list-units", VERB_ANY, VERB_ANY, VERB_DEFAULT|VERB_ONLINE_ONLY, list_units },
8853 { "list-unit-files", VERB_ANY, VERB_ANY, 0, list_unit_files },
8854 { "list-sockets", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_sockets },
8855 { "list-timers", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_timers },
8856 { "list-jobs", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_jobs },
8857 { "list-machines", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY|VERB_MUST_BE_ROOT, list_machines },
8858 { "clear-jobs", VERB_ANY, 1, VERB_ONLINE_ONLY, trivial_method },
8859 { "cancel", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, cancel_job },
8860 { "start", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8861 { "stop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8862 { "condstop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
8863 { "reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8864 { "restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8865 { "try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8866 { "reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8867 { "reload-or-try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatbility with old systemctl <= 228 */
8868 { "try-reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8869 { "force-reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with SysV */
8870 { "condreload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
8871 { "condrestart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with RH */
8872 { "isolate", 2, 2, VERB_ONLINE_ONLY, start_unit },
8873 { "kill", 2, VERB_ANY, VERB_ONLINE_ONLY, kill_unit },
8874 { "is-active", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active },
3e7e587d 8875 { "check", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active }, /* deprecated alias of is-active */
c56d1e2c
CW
8876 { "is-failed", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_failed },
8877 { "show", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8878 { "cat", 2, VERB_ANY, VERB_ONLINE_ONLY, cat },
8879 { "status", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8880 { "help", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8881 { "daemon-reload", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
8882 { "daemon-reexec", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
8883 { "show-environment", VERB_ANY, 1, VERB_ONLINE_ONLY, show_environment },
8884 { "set-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
8885 { "unset-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
8886 { "import-environment", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, import_environment },
8887 { "halt", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8888 { "poweroff", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8889 { "reboot", VERB_ANY, 2, VERB_ONLINE_ONLY, start_system_special },
8890 { "kexec", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8891 { "suspend", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8892 { "hibernate", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8893 { "hybrid-sleep", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
e68c79db 8894 { "suspend-then-hibernate",VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
c56d1e2c
CW
8895 { "default", VERB_ANY, 1, VERB_ONLINE_ONLY, start_special },
8896 { "rescue", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8897 { "emergency", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8898 { "exit", VERB_ANY, 2, VERB_ONLINE_ONLY, start_special },
8899 { "reset-failed", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, reset_failed },
8900 { "enable", 2, VERB_ANY, 0, enable_unit },
8901 { "disable", 2, VERB_ANY, 0, enable_unit },
8902 { "is-enabled", 2, VERB_ANY, 0, unit_is_enabled },
8903 { "reenable", 2, VERB_ANY, 0, enable_unit },
8904 { "preset", 2, VERB_ANY, 0, enable_unit },
8905 { "preset-all", VERB_ANY, 1, 0, preset_all },
8906 { "mask", 2, VERB_ANY, 0, enable_unit },
8907 { "unmask", 2, VERB_ANY, 0, enable_unit },
8908 { "link", 2, VERB_ANY, 0, enable_unit },
8909 { "revert", 2, VERB_ANY, 0, enable_unit },
8910 { "switch-root", 2, VERB_ANY, VERB_ONLINE_ONLY, switch_root },
8911 { "list-dependencies", VERB_ANY, 2, VERB_ONLINE_ONLY, list_dependencies },
8912 { "set-default", 2, 2, 0, set_default },
8913 { "get-default", VERB_ANY, 1, 0, get_default },
8914 { "set-property", 3, VERB_ANY, VERB_ONLINE_ONLY, set_property },
8915 { "is-system-running", VERB_ANY, 1, 0, is_system_running },
8916 { "add-wants", 3, VERB_ANY, 0, add_dependency },
8917 { "add-requires", 3, VERB_ANY, 0, add_dependency },
8918 { "edit", 2, VERB_ANY, VERB_ONLINE_ONLY, edit },
d08e75ed 8919 {}
e449de87 8920 };
7e4249b9 8921
e449de87 8922 return dispatch_verb(argc, argv, verbs, NULL);
e4b61340
LP
8923}
8924
4fbd7192 8925static int reload_with_fallback(void) {
4fbd7192 8926 /* First, try systemd via D-Bus. */
e449de87 8927 if (daemon_reload(0, NULL, NULL) >= 0)
4fbd7192 8928 return 0;
e4b61340
LP
8929
8930 /* Nothing else worked, so let's try signals */
2853b60a 8931 assert(IN_SET(arg_action, ACTION_RELOAD, ACTION_REEXEC));
e4b61340 8932
4a62c710
MS
8933 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0)
8934 return log_error_errno(errno, "kill() failed: %m");
e4b61340
LP
8935
8936 return 0;
8937}
8938
4fbd7192 8939static int start_with_fallback(void) {
4fbd7192 8940 /* First, try systemd via D-Bus. */
e449de87 8941 if (start_unit(0, NULL, NULL) >= 0)
4fbd7192 8942 return 0;
e4b61340 8943
2853b60a 8944 /* Nothing else worked, so let's try /dev/initctl */
fbc43921 8945 if (talk_initctl() > 0)
48ec22bc 8946 return 0;
d55ae9e6 8947
baaa35ad
ZJS
8948 return log_error_errno(SYNTHETIC_ERRNO(EIO),
8949 "Failed to talk to init daemon.");
e4b61340
LP
8950}
8951
477def80 8952static int halt_now(enum action a) {
c01dcddf 8953 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
f03ec2b1 8954 * synced explicitly in advance. */
1ae17672 8955 if (!arg_no_sync && !arg_dry_run)
f3f054f0 8956 (void) sync();
4a3ad399 8957
1ae17672
ZJS
8958 /* Make sure C-A-D is handled by the kernel from this point on... */
8959 if (!arg_dry_run)
8960 (void) reboot(RB_ENABLE_CAD);
e606bb61 8961
4c80c73c 8962 switch (a) {
e606bb61
LP
8963
8964 case ACTION_HALT:
60675884
LP
8965 if (!arg_quiet)
8966 log_info("Halting.");
1ae17672
ZJS
8967 if (arg_dry_run)
8968 return 0;
19578bb2 8969 (void) reboot(RB_HALT_SYSTEM);
477def80 8970 return -errno;
e606bb61
LP
8971
8972 case ACTION_POWEROFF:
60675884
LP
8973 if (!arg_quiet)
8974 log_info("Powering off.");
1ae17672
ZJS
8975 if (arg_dry_run)
8976 return 0;
19578bb2 8977 (void) reboot(RB_POWER_OFF);
477def80 8978 return -errno;
e606bb61 8979
98d52feb 8980 case ACTION_KEXEC:
c01dcddf
LP
8981 case ACTION_REBOOT:
8982 return reboot_with_parameter(REBOOT_FALLBACK |
8983 (arg_quiet ? 0 : REBOOT_LOG) |
8984 (arg_dry_run ? REBOOT_DRY_RUN : 0));
e606bb61 8985
477def80
LP
8986 default:
8987 assert_not_reached("Unknown action.");
8988 }
e606bb61
LP
8989}
8990
56a730fa 8991static int logind_schedule_shutdown(void) {
7f56c3d4 8992
cf9cda44 8993#if ENABLE_LOGIND
4afd3348 8994 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
56a730fa
LP
8995 char date[FORMAT_TIMESTAMP_MAX];
8996 const char *action;
4fbd7192 8997 sd_bus *bus;
56a730fa
LP
8998 int r;
8999
4fbd7192 9000 r = acquire_bus(BUS_FULL, &bus);
56a730fa 9001 if (r < 0)
4fbd7192 9002 return r;
56a730fa
LP
9003
9004 switch (arg_action) {
9005 case ACTION_HALT:
9006 action = "halt";
9007 break;
9008 case ACTION_POWEROFF:
9009 action = "poweroff";
9010 break;
9011 case ACTION_KEXEC:
9012 action = "kexec";
9013 break;
a4420f7b
LP
9014 case ACTION_EXIT:
9015 action = "exit";
9016 break;
9017 case ACTION_REBOOT:
56a730fa
LP
9018 default:
9019 action = "reboot";
9020 break;
9021 }
9022
1ae17672 9023 if (arg_dry_run)
56a730fa
LP
9024 action = strjoina("dry-", action);
9025
d2ad7e1b
ZJS
9026 (void) logind_set_wall_message();
9027
56a730fa 9028 r = sd_bus_call_method(
4fbd7192 9029 bus,
56a730fa
LP
9030 "org.freedesktop.login1",
9031 "/org/freedesktop/login1",
9032 "org.freedesktop.login1.Manager",
9033 "ScheduleShutdown",
9034 &error,
9035 NULL,
9036 "st",
9037 action,
9038 arg_when);
9039 if (r < 0)
9040 return log_warning_errno(r, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error, r));
9041
60675884
LP
9042 if (!arg_quiet)
9043 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date, sizeof(date), arg_when));
56a730fa 9044 return 0;
cf9cda44
DJL
9045#else
9046 log_error("Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
9047 return -ENOSYS;
807690fb 9048#endif
56a730fa
LP
9049}
9050
4fbd7192 9051static int halt_main(void) {
e4b61340
LP
9052 int r;
9053
4fbd7192 9054 r = logind_check_inhibitors(arg_action);
748ebafa
LP
9055 if (r < 0)
9056 return r;
b37844d3 9057
940bec70
DJL
9058 /* Delayed shutdown requested, and was successful */
9059 if (arg_when > 0 && logind_schedule_shutdown() == 0)
9060 return 0;
9061 /* no delay, or logind failed or is not at all available */
7f96539d 9062
bc8c2f5c 9063 if (geteuid() != 0) {
1ae17672 9064 if (arg_dry_run || arg_force > 0) {
fba868fa 9065 (void) must_be_root();
2ac3930f
IS
9066 return -EPERM;
9067 }
9068
7e59bfcb 9069 /* Try logind if we are a normal user and no special
d35f51ea 9070 * mode applies. Maybe polkit allows us to shutdown
7e59bfcb 9071 * the machine. */
36b69c31 9072 if (IN_SET(arg_action, ACTION_POWEROFF, ACTION_REBOOT, ACTION_HALT)) {
4fbd7192 9073 r = logind_reboot(arg_action);
4c80c73c
KS
9074 if (r >= 0)
9075 return r;
a9085ea3 9076 if (IN_SET(r, -EOPNOTSUPP, -EINPROGRESS))
7f96539d
LP
9077 /* requested operation is not
9078 * supported on the local system or
9079 * already in progress */
a9085ea3
IS
9080 return r;
9081 /* on all other errors, try low-level operation */
4c80c73c 9082 }
bc8c2f5c
LP
9083 }
9084
2955e0d4
GJ
9085 /* In order to minimize the difference between operation with and
9086 * without logind, we explicitly enable non-blocking mode for this,
9087 * as logind's shutdown operations are always non-blocking. */
9088 arg_no_block = true;
9089
1ae17672 9090 if (!arg_dry_run && !arg_force)
4fbd7192 9091 return start_with_fallback();
e4b61340 9092
2ac3930f
IS
9093 assert(geteuid() == 0);
9094
d90e1a30
LP
9095 if (!arg_no_wtmp) {
9096 if (sd_booted() > 0)
9097 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
7e59bfcb
LP
9098 else {
9099 r = utmp_put_shutdown();
9100 if (r < 0)
da927ba9 9101 log_warning_errno(r, "Failed to write utmp record: %m");
7e59bfcb 9102 }
d90e1a30 9103 }
e4b61340 9104
1ae17672 9105 if (arg_dry_run)
e4b61340
LP
9106 return 0;
9107
477def80 9108 r = halt_now(arg_action);
691395d8 9109 return log_error_errno(r, "Failed to reboot: %m");
e4b61340
LP
9110}
9111
9112static int runlevel_main(void) {
9113 int r, runlevel, previous;
9114
729e3769
LP
9115 r = utmp_get_runlevel(&runlevel, &previous);
9116 if (r < 0) {
9117 puts("unknown");
e4b61340
LP
9118 return r;
9119 }
9120
9121 printf("%c %c\n",
9122 previous <= 0 ? 'N' : previous,
9123 runlevel <= 0 ? 'N' : runlevel);
9124
9125 return 0;
9126}
9127
2cf05793 9128static int logind_cancel_shutdown(void) {
349cc4a5 9129#if ENABLE_LOGIND
4afd3348 9130 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 9131 sd_bus *bus;
949d9ce9
LP
9132 int r;
9133
4fbd7192 9134 r = acquire_bus(BUS_FULL, &bus);
949d9ce9 9135 if (r < 0)
4fbd7192 9136 return r;
949d9ce9 9137
4fbd7192 9138 (void) logind_set_wall_message();
949d9ce9
LP
9139
9140 r = sd_bus_call_method(
4fbd7192 9141 bus,
949d9ce9
LP
9142 "org.freedesktop.login1",
9143 "/org/freedesktop/login1",
9144 "org.freedesktop.login1.Manager",
9145 "CancelScheduledShutdown",
9146 &error,
9147 NULL, NULL);
9148 if (r < 0)
9149 return log_warning_errno(r, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error, r));
9150
9151 return 0;
2cf05793
LP
9152#else
9153 log_error("Not compiled with logind support, cannot cancel scheduled shutdowns.");
9154 return -ENOSYS;
9155#endif
949d9ce9
LP
9156}
9157
f2a3de01 9158static int run(int argc, char *argv[]) {
f459b602 9159 int r;
e4b61340 9160
acc28e2e
FB
9161 argv_cmdline = argv[0];
9162
a9cdc94f 9163 setlocale(LC_ALL, "");
e4b61340 9164 log_parse_environment();
2396fb04 9165 log_open();
1abaf488
LP
9166
9167 /* The journal merging logic potentially needs a lot of fds. */
9168 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
9169
592705f2 9170 sigbus_install();
e4b61340 9171
184ecaf7
DR
9172 /* Explicitly not on_tty() to avoid setting cached value.
9173 * This becomes relevant for piping output which might be
9174 * ellipsized. */
9175 original_stdout_is_tty = isatty(STDOUT_FILENO);
9176
04ebb595 9177 r = parse_argv(argc, argv);
f459b602 9178 if (r <= 0)
e4b61340 9179 goto finish;
7e4249b9 9180
040524b4 9181 if (arg_action != ACTION_SYSTEMCTL && running_in_chroot() > 0) {
60675884
LP
9182 if (!arg_quiet)
9183 log_info("Running in chroot, ignoring request.");
f459b602 9184 r = 0;
82e23ddd
LP
9185 goto finish;
9186 }
9187
41dd15e4
LP
9188 /* systemctl_main() will print an error message for the bus
9189 * connection, but only if it needs to */
e4b61340
LP
9190
9191 switch (arg_action) {
9192
22f4096c 9193 case ACTION_SYSTEMCTL:
e449de87 9194 r = systemctl_main(argc, argv);
e4b61340 9195 break;
e4b61340 9196
081dc638
AJ
9197 /* Legacy command aliases set arg_action. They provide some fallbacks,
9198 * e.g. to tell sysvinit to reboot after you have installed systemd
9199 * binaries. */
9200
e4b61340
LP
9201 case ACTION_HALT:
9202 case ACTION_POWEROFF:
9203 case ACTION_REBOOT:
5622dde3 9204 case ACTION_KEXEC:
4fbd7192 9205 r = halt_main();
e4b61340
LP
9206 break;
9207
e4b61340
LP
9208 case ACTION_RUNLEVEL2:
9209 case ACTION_RUNLEVEL3:
9210 case ACTION_RUNLEVEL4:
9211 case ACTION_RUNLEVEL5:
9212 case ACTION_RESCUE:
4fbd7192 9213 r = start_with_fallback();
e4b61340 9214 break;
7e4249b9 9215
e4b61340
LP
9216 case ACTION_RELOAD:
9217 case ACTION_REEXEC:
4fbd7192 9218 r = reload_with_fallback();
e4b61340
LP
9219 break;
9220
949d9ce9 9221 case ACTION_CANCEL_SHUTDOWN:
2cf05793 9222 r = logind_cancel_shutdown();
f6144808
LP
9223 break;
9224
eb22ac37 9225 case ACTION_RUNLEVEL:
4f16c1f4
LP
9226 r = runlevel_main();
9227 break;
9228
081dc638
AJ
9229 case ACTION_EXIT:
9230 case ACTION_SUSPEND:
9231 case ACTION_HIBERNATE:
9232 case ACTION_HYBRID_SLEEP:
e68c79db 9233 case ACTION_SUSPEND_THEN_HIBERNATE:
081dc638
AJ
9234 case ACTION_EMERGENCY:
9235 case ACTION_DEFAULT:
9236 /* systemctl verbs with no equivalent in the legacy commands.
9237 * These cannot appear in arg_action. Fall through. */
9238
f459b602 9239 case _ACTION_INVALID:
e4b61340
LP
9240 default:
9241 assert_not_reached("Unknown action");
9242 }
7e4249b9
LP
9243
9244finish:
cf647b69
LP
9245 release_busses();
9246
20b3f379 9247 strv_free(arg_types);
9b9b3d36 9248 strv_free(arg_states);
20b3f379 9249 strv_free(arg_properties);
ea4a240d 9250
172d7abf 9251 strv_free(arg_wall);
0f03c2a4 9252 free(arg_root);
172d7abf 9253
d1405af3
ZJS
9254 /* Note that we return r here, not 0, so that we can implement the LSB-like return codes */
9255 return r;
7e4249b9 9256}
d1405af3
ZJS
9257
9258DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);