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