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