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