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