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