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