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