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