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