1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/reboot.h>
29 #include <sys/ioctl.h>
33 #include <sys/socket.h>
36 #include <sys/prctl.h>
37 #include <dbus/dbus.h>
39 #include <systemd/sd-daemon.h>
40 #include <systemd/sd-shutdown.h>
41 #include <systemd/sd-login.h>
47 #include "utmp-wtmp.h"
50 #include "path-util.h"
52 #include "dbus-common.h"
53 #include "cgroup-show.h"
54 #include "cgroup-util.h"
56 #include "path-lookup.h"
57 #include "conf-parser.h"
58 #include "exit-status.h"
59 #include "bus-errors.h"
61 #include "unit-name.h"
63 #include "spawn-ask-password-agent.h"
64 #include "spawn-polkit-agent.h"
66 #include "logs-show.h"
67 #include "path-util.h"
68 #include "socket-util.h"
71 static char **arg_types = NULL;
72 static char **arg_load_states = NULL;
73 static char **arg_properties = NULL;
74 static bool arg_all = false;
75 static enum dependency {
80 } arg_dependency = DEPENDENCY_FORWARD;
81 static const char *arg_job_mode = "replace";
82 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
83 static bool arg_no_block = false;
84 static bool arg_no_legend = false;
85 static bool arg_no_pager = false;
86 static bool arg_no_wtmp = false;
87 static bool arg_no_wall = false;
88 static bool arg_no_reload = false;
89 static bool arg_show_types = false;
90 static bool arg_ignore_inhibitors = false;
91 static bool arg_dry = false;
92 static bool arg_quiet = false;
93 static bool arg_full = false;
94 static int arg_force = 0;
95 static bool arg_ask_password = true;
96 static bool arg_failed = false;
97 static bool arg_runtime = false;
98 static char **arg_wall = NULL;
99 static const char *arg_kill_who = NULL;
100 static int arg_signal = SIGTERM;
101 static const char *arg_root = NULL;
102 static usec_t arg_when = 0;
124 ACTION_CANCEL_SHUTDOWN,
126 } arg_action = ACTION_SYSTEMCTL;
127 static enum transport {
131 } arg_transport = TRANSPORT_NORMAL;
132 static char *arg_host = NULL;
133 static char *arg_user = NULL;
134 static unsigned arg_lines = 10;
135 static OutputMode arg_output = OUTPUT_SHORT;
136 static bool arg_plain = false;
138 static bool private_bus = false;
140 static int daemon_reload(DBusConnection *bus, char **args);
141 static void halt_now(enum action a);
143 static void pager_open_if_enabled(void) {
151 static void ask_password_agent_open_if_enabled(void) {
153 /* Open the password agent as a child process if necessary */
155 if (!arg_ask_password)
158 if (arg_scope != UNIT_FILE_SYSTEM)
161 ask_password_agent_open();
165 static void polkit_agent_open_if_enabled(void) {
167 /* Open the polkit agent as a child process if necessary */
169 if (!arg_ask_password)
172 if (arg_scope != UNIT_FILE_SYSTEM)
179 static const char *ansi_highlight(bool b) {
184 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
187 static const char *ansi_highlight_red(bool b) {
192 return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
195 static const char *ansi_highlight_green(bool b) {
200 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
203 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
206 if (!dbus_error_is_set(error))
209 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
210 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
211 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
212 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
213 return EXIT_NOPERMISSION;
215 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
216 return EXIT_NOTINSTALLED;
218 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
219 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
220 return EXIT_NOTIMPLEMENTED;
222 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
223 return EXIT_NOTCONFIGURED;
231 static void warn_wall(enum action a) {
232 static const char *table[_ACTION_MAX] = {
233 [ACTION_HALT] = "The system is going down for system halt NOW!",
234 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
235 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
236 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
237 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
238 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!",
239 [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
246 _cleanup_free_ char *p;
248 p = strv_join(arg_wall, " ");
263 utmp_wall(table[a], NULL);
266 static bool avoid_bus(void) {
268 if (running_in_chroot() > 0)
271 if (sd_booted() <= 0)
274 if (!isempty(arg_root))
277 if (arg_scope == UNIT_FILE_GLOBAL)
283 static int compare_unit_info(const void *a, const void *b) {
285 const struct unit_info *u = a, *v = b;
287 d1 = strrchr(u->id, '.');
288 d2 = strrchr(v->id, '.');
293 r = strcasecmp(d1, d2);
298 return strcasecmp(u->id, v->id);
301 static bool output_show_unit(const struct unit_info *u) {
305 return streq(u->active_state, "failed");
307 return (!arg_types || ((dot = strrchr(u->id, '.')) &&
308 strv_find(arg_types, dot+1))) &&
309 (!arg_load_states || strv_find(arg_load_states, u->load_state)) &&
310 (arg_all || !(streq(u->active_state, "inactive")
311 || u->following[0]) || u->job_id > 0);
314 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
315 unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
316 const struct unit_info *u;
319 max_id_len = sizeof("UNIT")-1;
320 active_len = sizeof("ACTIVE")-1;
321 sub_len = sizeof("SUB")-1;
322 job_len = sizeof("JOB")-1;
325 for (u = unit_infos; u < unit_infos + c; u++) {
326 if (!output_show_unit(u))
329 max_id_len = MAX(max_id_len, strlen(u->id));
330 active_len = MAX(active_len, strlen(u->active_state));
331 sub_len = MAX(sub_len, strlen(u->sub_state));
332 if (u->job_id != 0) {
333 job_len = MAX(job_len, strlen(u->job_type));
340 id_len = MIN(max_id_len, 25u);
341 basic_len = 5 + id_len + 5 + active_len + sub_len;
343 basic_len += job_len + 1;
344 if (basic_len < (unsigned) columns()) {
345 unsigned extra_len, incr;
346 extra_len = columns() - basic_len;
347 /* Either UNIT already got 25, or is fully satisfied.
348 * Grant up to 25 to DESC now. */
349 incr = MIN(extra_len, 25u);
352 /* split the remaining space between UNIT and DESC,
353 * but do not give UNIT more than it needs. */
355 incr = MIN(extra_len / 2, max_id_len - id_len);
357 desc_len += extra_len - incr;
363 for (u = unit_infos; u < unit_infos + c; u++) {
364 _cleanup_free_ char *e = NULL;
365 const char *on_loaded, *off_loaded, *on = "";
366 const char *on_active, *off_active, *off = "";
368 if (!output_show_unit(u))
371 if (!n_shown && !arg_no_legend) {
372 printf("%-*s %-6s %-*s %-*s ", id_len, "UNIT", "LOAD",
373 active_len, "ACTIVE", sub_len, "SUB");
375 printf("%-*s ", job_len, "JOB");
376 if (!arg_full && arg_no_pager)
377 printf("%.*s\n", desc_len, "DESCRIPTION");
379 printf("%s\n", "DESCRIPTION");
384 if (streq(u->load_state, "error")) {
385 on_loaded = on = ansi_highlight_red(true);
386 off_loaded = off = ansi_highlight_red(false);
388 on_loaded = off_loaded = "";
390 if (streq(u->active_state, "failed")) {
391 on_active = on = ansi_highlight_red(true);
392 off_active = off = ansi_highlight_red(false);
394 on_active = off_active = "";
396 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
398 printf("%s%-*s%s %s%-6s%s %s%-*s %-*s%s %-*s",
399 on, id_len, e ? e : u->id, off,
400 on_loaded, u->load_state, off_loaded,
401 on_active, active_len, u->active_state,
402 sub_len, u->sub_state, off_active,
403 job_count ? job_len + 1 : 0, u->job_id ? u->job_type : "");
404 if (!arg_full && arg_no_pager)
405 printf("%.*s\n", desc_len, u->description);
407 printf("%s\n", u->description);
410 if (!arg_no_legend) {
411 const char *on, *off;
414 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
415 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
416 "SUB = The low-level unit activation state, values depend on unit type.\n");
418 printf("JOB = Pending job for the unit.\n");
420 on = ansi_highlight(true);
421 off = ansi_highlight(false);
423 on = ansi_highlight_red(true);
424 off = ansi_highlight_red(false);
428 printf("%s%u loaded units listed.%s\n"
429 "To show all installed unit files use 'systemctl list-unit-files'.\n",
432 printf("%s%u loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
433 "To show all installed unit files use 'systemctl list-unit-files'.\n",
438 static int get_unit_list(DBusConnection *bus, DBusMessage **reply,
439 struct unit_info **unit_infos, unsigned *c) {
440 DBusMessageIter iter, sub;
448 r = bus_method_call_with_reply(
450 "org.freedesktop.systemd1",
451 "/org/freedesktop/systemd1",
452 "org.freedesktop.systemd1.Manager",
460 if (!dbus_message_iter_init(*reply, &iter) ||
461 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
462 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
463 log_error("Failed to parse reply.");
467 dbus_message_iter_recurse(&iter, &sub);
469 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
470 if (!GREEDY_REALLOC(*unit_infos, size, *c + 1))
473 bus_parse_unit_info(&sub, *unit_infos + *c);
476 dbus_message_iter_next(&sub);
482 static int list_units(DBusConnection *bus, char **args) {
483 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
484 _cleanup_free_ struct unit_info *unit_infos = NULL;
488 pager_open_if_enabled();
490 r = get_unit_list(bus, &reply, &unit_infos, &c);
494 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
496 output_units_list(unit_infos, c);
501 static int get_triggered_units(DBusConnection *bus, const char* unit_path,
504 const char *interface = "org.freedesktop.systemd1.Unit",
505 *triggers_property = "Triggers";
506 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
507 DBusMessageIter iter, sub;
510 r = bus_method_call_with_reply(bus,
511 "org.freedesktop.systemd1",
513 "org.freedesktop.DBus.Properties",
517 DBUS_TYPE_STRING, &interface,
518 DBUS_TYPE_STRING, &triggers_property,
523 if (!dbus_message_iter_init(reply, &iter) ||
524 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
525 log_error("Failed to parse reply.");
529 dbus_message_iter_recurse(&iter, &sub);
530 dbus_message_iter_recurse(&sub, &iter);
533 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
536 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
537 log_error("Failed to parse reply.");
541 dbus_message_iter_get_basic(&sub, &unit);
542 r = strv_extend(triggered, unit);
546 dbus_message_iter_next(&sub);
552 static int get_listening(DBusConnection *bus, const char* unit_path,
553 char*** listen, unsigned *c)
555 const char *interface = "org.freedesktop.systemd1.Socket",
556 *listen_property = "Listen";
557 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
558 DBusMessageIter iter, sub;
561 r = bus_method_call_with_reply(bus,
562 "org.freedesktop.systemd1",
564 "org.freedesktop.DBus.Properties",
568 DBUS_TYPE_STRING, &interface,
569 DBUS_TYPE_STRING, &listen_property,
574 if (!dbus_message_iter_init(reply, &iter) ||
575 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
576 log_error("Failed to parse reply.");
580 dbus_message_iter_recurse(&iter, &sub);
581 dbus_message_iter_recurse(&sub, &iter);
584 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
585 DBusMessageIter sub2;
586 const char *type, *path;
588 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
589 log_error("Failed to parse reply.");
593 dbus_message_iter_recurse(&sub, &sub2);
595 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
596 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0) {
597 r = strv_extend(listen, type);
601 r = strv_extend(listen, path);
608 dbus_message_iter_next(&sub);
620 /* Note: triggered is a list here, although it almost certainly
621 * will always be one unit. Nevertheless, dbus API allows for multiple
622 * values, so let's follow that.*/
625 /* The strv above is shared. free is set only in the first one. */
629 static int socket_info_compare(struct socket_info *a, struct socket_info *b) {
630 int o = strcmp(a->path, b->path);
632 o = strcmp(a->type, b->type);
636 static int output_sockets_list(struct socket_info *socket_infos, unsigned cs) {
637 struct socket_info *s;
638 unsigned pathlen = sizeof("LISTEN") - 1,
639 typelen = (sizeof("TYPE") - 1) * arg_show_types,
640 socklen = sizeof("UNIT") - 1,
641 servlen = sizeof("ACTIVATES") - 1;
642 const char *on, *off;
644 for (s = socket_infos; s < socket_infos + cs; s++) {
648 socklen = MAX(socklen, strlen(s->id));
650 typelen = MAX(typelen, strlen(s->type));
651 pathlen = MAX(pathlen, strlen(s->path));
653 STRV_FOREACH(a, s->triggered)
654 tmp += strlen(*a) + 2*(a != s->triggered);
655 servlen = MAX(servlen, tmp);
660 printf("%-*s %-*.*s%-*s %s\n",
662 typelen + arg_show_types, typelen + arg_show_types, "TYPE ",
666 for (s = socket_infos; s < socket_infos + cs; s++) {
670 printf("%-*s %-*s %-*s",
671 pathlen, s->path, typelen, s->type, socklen, s->id);
674 pathlen, s->path, socklen, s->id);
675 STRV_FOREACH(a, s->triggered)
677 a == s->triggered ? "" : ",", *a);
681 on = ansi_highlight(true);
682 off = ansi_highlight(false);
686 on = ansi_highlight_red(true);
687 off = ansi_highlight_red(false);
690 if (!arg_no_legend) {
691 printf("%s%u sockets listed.%s\n", on, cs, off);
693 printf("Pass --all to see loaded but inactive sockets, too.\n");
699 static int list_sockets(DBusConnection *bus, char **args) {
700 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
701 _cleanup_free_ struct unit_info *unit_infos = NULL;
702 struct socket_info *socket_infos = NULL;
703 const struct unit_info *u;
704 struct socket_info *s;
705 unsigned cu = 0, cs = 0;
709 pager_open_if_enabled();
711 r = get_unit_list(bus, &reply, &unit_infos, &cu);
715 for (u = unit_infos; u < unit_infos + cu; u++) {
717 _cleanup_strv_free_ char **listen = NULL, **triggered = NULL;
720 if (!output_show_unit(u))
723 if ((dot = strrchr(u->id, '.')) && !streq(dot+1, "socket"))
726 r = get_triggered_units(bus, u->unit_path, &triggered);
730 r = get_listening(bus, u->unit_path, &listen, &c);
734 if (!GREEDY_REALLOC(socket_infos, size, cs + c)) {
739 for (i = 0; i < c; i++)
740 socket_infos[cs + i] = (struct socket_info) {
743 .path = listen[i*2 + 1],
744 .triggered = triggered,
745 .own_triggered = i==0,
748 /* from this point on we will cleanup those socket_infos */
751 listen = triggered = NULL; /* avoid cleanup */
754 qsort(socket_infos, cs, sizeof(struct socket_info),
755 (__compar_fn_t) socket_info_compare);
757 output_sockets_list(socket_infos, cs);
760 assert(cs == 0 || socket_infos);
761 for (s = socket_infos; s < socket_infos + cs; s++) {
764 if (s->own_triggered)
765 strv_free(s->triggered);
772 static int compare_unit_file_list(const void *a, const void *b) {
774 const UnitFileList *u = a, *v = b;
776 d1 = strrchr(u->path, '.');
777 d2 = strrchr(v->path, '.');
782 r = strcasecmp(d1, d2);
787 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
790 static bool output_show_unit_file(const UnitFileList *u) {
793 return !arg_types || ((dot = strrchr(u->path, '.')) && strv_find(arg_types, dot+1));
796 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
797 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
798 const UnitFileList *u;
800 max_id_len = sizeof("UNIT FILE")-1;
801 state_cols = sizeof("STATE")-1;
802 for (u = units; u < units + c; u++) {
803 if (!output_show_unit_file(u))
806 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
807 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
812 id_cols = MIN(max_id_len, 25u);
813 basic_cols = 1 + id_cols + state_cols;
814 if (basic_cols < (unsigned) columns())
815 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
817 id_cols = max_id_len;
820 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
822 for (u = units; u < units + c; u++) {
823 _cleanup_free_ char *e = NULL;
824 const char *on, *off;
827 if (!output_show_unit_file(u))
832 if (u->state == UNIT_FILE_MASKED ||
833 u->state == UNIT_FILE_MASKED_RUNTIME ||
834 u->state == UNIT_FILE_DISABLED ||
835 u->state == UNIT_FILE_INVALID) {
836 on = ansi_highlight_red(true);
837 off = ansi_highlight_red(false);
838 } else if (u->state == UNIT_FILE_ENABLED) {
839 on = ansi_highlight_green(true);
840 off = ansi_highlight_green(false);
844 id = path_get_file_name(u->path);
846 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
848 printf("%-*s %s%-*s%s\n",
850 on, state_cols, unit_file_state_to_string(u->state), off);
854 printf("\n%u unit files listed.\n", n_shown);
857 static int list_unit_files(DBusConnection *bus, char **args) {
858 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
859 _cleanup_free_ UnitFileList *units = NULL;
860 DBusMessageIter iter, sub, sub2;
861 unsigned c = 0, n_units = 0;
864 pager_open_if_enabled();
871 h = hashmap_new(string_hash_func, string_compare_func);
875 r = unit_file_get_list(arg_scope, arg_root, h);
877 unit_file_list_free(h);
878 log_error("Failed to get unit file list: %s", strerror(-r));
882 n_units = hashmap_size(h);
883 units = new(UnitFileList, n_units);
885 unit_file_list_free(h);
889 HASHMAP_FOREACH(u, h, i) {
890 memcpy(units + c++, u, sizeof(UnitFileList));
896 r = bus_method_call_with_reply(
898 "org.freedesktop.systemd1",
899 "/org/freedesktop/systemd1",
900 "org.freedesktop.systemd1.Manager",
908 if (!dbus_message_iter_init(reply, &iter) ||
909 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
910 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
911 log_error("Failed to parse reply.");
915 dbus_message_iter_recurse(&iter, &sub);
917 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
921 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT);
926 n_units = MAX(2*c, 16u);
927 w = realloc(units, sizeof(struct UnitFileList) * n_units);
936 dbus_message_iter_recurse(&sub, &sub2);
938 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
939 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
940 log_error("Failed to parse reply.");
944 u->state = unit_file_state_from_string(state);
946 dbus_message_iter_next(&sub);
952 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
953 output_unit_file_list(units, c);
959 static int list_dependencies_print(const char *name, int level, unsigned int branches, bool last) {
961 _cleanup_free_ char *n = NULL;
963 size_t max_len = MAX(columns(),20u);
966 for (i = level - 1; i >= 0; i--) {
968 if(len > max_len - 3 && !arg_full) {
969 printf("%s...\n",max_len % 2 ? "" : " ");
972 printf("%s", draw_special_char(branches & (1 << i) ? DRAW_TREE_VERT : DRAW_TREE_SPACE));
975 if(len > max_len - 3 && !arg_full) {
976 printf("%s...\n",max_len % 2 ? "" : " ");
979 printf("%s", draw_special_char(last ? DRAW_TREE_RIGHT : DRAW_TREE_BRANCH));
983 printf("%s\n", name);
987 n = ellipsize(name, max_len-len, 100);
995 static int list_dependencies_get_dependencies(DBusConnection *bus, const char *name, char ***deps) {
996 static const char *dependencies[] = {
997 [DEPENDENCY_FORWARD] = "Requires\0"
998 "RequiresOverridable\0"
1000 "RequisiteOverridable\0"
1002 [DEPENDENCY_REVERSE] = "RequiredBy\0"
1003 "RequiredByOverridable\0"
1006 [DEPENDENCY_AFTER] = "After\0",
1007 [DEPENDENCY_BEFORE] = "Before\0",
1010 _cleanup_free_ char *path;
1011 const char *interface = "org.freedesktop.systemd1.Unit";
1013 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1014 DBusMessageIter iter, sub, sub2, sub3;
1023 path = unit_dbus_path_from_name(name);
1029 r = bus_method_call_with_reply(
1031 "org.freedesktop.systemd1",
1033 "org.freedesktop.DBus.Properties",
1037 DBUS_TYPE_STRING, &interface,
1042 if (!dbus_message_iter_init(reply, &iter) ||
1043 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1044 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
1045 log_error("Failed to parse reply.");
1050 dbus_message_iter_recurse(&iter, &sub);
1052 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1055 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
1056 dbus_message_iter_recurse(&sub, &sub2);
1058 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
1059 log_error("Failed to parse reply.");
1064 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
1065 log_error("Failed to parse reply.");
1070 dbus_message_iter_recurse(&sub2, &sub3);
1071 dbus_message_iter_next(&sub);
1073 assert(arg_dependency < ELEMENTSOF(dependencies));
1074 if (!nulstr_contains(dependencies[arg_dependency], prop))
1077 if (dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_ARRAY) {
1078 if (dbus_message_iter_get_element_type(&sub3) == DBUS_TYPE_STRING) {
1079 DBusMessageIter sub4;
1080 dbus_message_iter_recurse(&sub3, &sub4);
1082 while (dbus_message_iter_get_arg_type(&sub4) != DBUS_TYPE_INVALID) {
1085 assert(dbus_message_iter_get_arg_type(&sub4) == DBUS_TYPE_STRING);
1086 dbus_message_iter_get_basic(&sub4, &s);
1088 r = strv_extend(&ret, s);
1094 dbus_message_iter_next(&sub4);
1107 static int list_dependencies_compare(const void *_a, const void *_b) {
1108 const char **a = (const char**) _a, **b = (const char**) _b;
1109 if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET)
1111 if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET)
1113 return strcasecmp(*a, *b);
1116 static int list_dependencies_one(DBusConnection *bus, const char *name, int level, char ***units, unsigned int branches) {
1117 _cleanup_strv_free_ char **deps = NULL, **u;
1121 u = strv_append(*units, name);
1125 r = list_dependencies_get_dependencies(bus, name, &deps);
1129 qsort(deps, strv_length(deps), sizeof (char*), list_dependencies_compare);
1131 STRV_FOREACH(c, deps) {
1132 if (strv_contains(u, *c)) {
1134 r = list_dependencies_print("...", level + 1, (branches << 1) | (c[1] == NULL ? 0 : 1), 1);
1141 r = list_dependencies_print(*c, level, branches, c[1] == NULL);
1145 if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) {
1146 r = list_dependencies_one(bus, *c, level + 1, &u, (branches << 1) | (c[1] == NULL ? 0 : 1));
1159 static int list_dependencies(DBusConnection *bus, char **args) {
1160 _cleanup_free_ char *unit = NULL;
1161 _cleanup_strv_free_ char **units = NULL;
1167 unit = unit_name_mangle(args[1]);
1172 u = SPECIAL_DEFAULT_TARGET;
1174 pager_open_if_enabled();
1178 return list_dependencies_one(bus, u, 0, &units, 0);
1181 static int get_default(DBusConnection *bus, char **args) {
1183 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
1185 _cleanup_dbus_error_free_ DBusError error;
1187 dbus_error_init(&error);
1189 if (!bus || avoid_bus()) {
1190 r = unit_file_get_default(arg_scope, arg_root, &path);
1193 log_error("Operation failed: %s", strerror(-r));
1199 r = bus_method_call_with_reply(
1201 "org.freedesktop.systemd1",
1202 "/org/freedesktop/systemd1",
1203 "org.freedesktop.systemd1.Manager",
1210 log_error("Operation failed: %s", strerror(-r));
1214 if (!dbus_message_get_args(reply, &error,
1215 DBUS_TYPE_STRING, &path,
1216 DBUS_TYPE_INVALID)) {
1217 log_error("Failed to parse reply: %s", bus_error_message(&error));
1218 dbus_error_free(&error);
1224 printf("%s\n", path);
1227 if ((!bus || avoid_bus()) && path)
1236 char *name, *type, *state;
1239 static void list_jobs_print(struct job_info* jobs, size_t n) {
1242 const char *on, *off;
1243 bool shorten = false;
1245 assert(n == 0 || jobs);
1248 on = ansi_highlight_green(true);
1249 off = ansi_highlight_green(false);
1251 printf("%sNo jobs running.%s\n", on, off);
1255 pager_open_if_enabled();
1258 /* JOB UNIT TYPE STATE */
1259 unsigned l0 = 3, l1 = 4, l2 = 4, l3 = 5;
1261 for (i = 0, j = jobs; i < n; i++, j++) {
1262 assert(j->name && j->type && j->state);
1263 l0 = MAX(l0, DECIMAL_STR_WIDTH(j->id));
1264 l1 = MAX(l1, strlen(j->name));
1265 l2 = MAX(l2, strlen(j->type));
1266 l3 = MAX(l3, strlen(j->state));
1269 if (!arg_full && l0 + 1 + l1 + l2 + 1 + l3 > columns()) {
1270 l1 = MAX(33u, columns() - l0 - l2 - l3 - 3);
1275 printf("%*s %-*s %-*s %-*s\n",
1281 for (i = 0, j = jobs; i < n; i++, j++) {
1282 _cleanup_free_ char *e = NULL;
1284 if (streq(j->state, "running")) {
1285 on = ansi_highlight(true);
1286 off = ansi_highlight(false);
1290 e = shorten ? ellipsize(j->name, l1, 33) : NULL;
1291 printf("%*u %s%-*s%s %-*s %s%-*s%s\n",
1293 on, l1, e ? e : j->name, off,
1295 on, l3, j->state, off);
1299 on = ansi_highlight(true);
1300 off = ansi_highlight(false);
1303 printf("\n%s%zu jobs listed%s.\n", on, n, off);
1306 static int list_jobs(DBusConnection *bus, char **args) {
1307 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1308 DBusMessageIter iter, sub, sub2;
1310 struct job_info *jobs = NULL;
1311 size_t size = 0, used = 0;
1313 r = bus_method_call_with_reply(
1315 "org.freedesktop.systemd1",
1316 "/org/freedesktop/systemd1",
1317 "org.freedesktop.systemd1.Manager",
1325 if (!dbus_message_iter_init(reply, &iter) ||
1326 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1327 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1328 log_error("Failed to parse reply.");
1332 dbus_message_iter_recurse(&iter, &sub);
1334 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1335 const char *name, *type, *state, *job_path, *unit_path;
1338 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1339 log_error("Failed to parse reply.");
1343 dbus_message_iter_recurse(&sub, &sub2);
1345 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
1346 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
1347 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
1348 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
1349 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
1350 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
1351 log_error("Failed to parse reply.");
1356 if (!GREEDY_REALLOC(jobs, size, used + 1)) {
1361 jobs[used++] = (struct job_info) { id,
1365 if (!jobs[used-1].name || !jobs[used-1].type || !jobs[used-1].state) {
1370 dbus_message_iter_next(&sub);
1373 list_jobs_print(jobs, used);
1377 free(jobs[used].name);
1378 free(jobs[used].type);
1379 free(jobs[used].state);
1386 static int load_unit(DBusConnection *bus, char **args) {
1391 STRV_FOREACH(name, args+1) {
1392 _cleanup_free_ char *n = NULL;
1395 n = unit_name_mangle(*name);
1399 r = bus_method_call_with_reply(
1401 "org.freedesktop.systemd1",
1402 "/org/freedesktop/systemd1",
1403 "org.freedesktop.systemd1.Manager",
1407 DBUS_TYPE_STRING, &n,
1416 static int cancel_job(DBusConnection *bus, char **args) {
1421 if (strv_length(args) <= 1)
1422 return daemon_reload(bus, args);
1424 STRV_FOREACH(name, args+1) {
1428 r = safe_atou32(*name, &id);
1430 log_error("Failed to parse job id: %s", strerror(-r));
1434 r = bus_method_call_with_reply(
1436 "org.freedesktop.systemd1",
1437 "/org/freedesktop/systemd1",
1438 "org.freedesktop.systemd1.Manager",
1442 DBUS_TYPE_UINT32, &id,
1451 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1452 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1453 dbus_bool_t b = FALSE;
1454 DBusMessageIter iter, sub;
1456 *interface = "org.freedesktop.systemd1.Unit",
1457 *property = "NeedDaemonReload",
1459 _cleanup_free_ char *n = NULL;
1462 /* We ignore all errors here, since this is used to show a warning only */
1464 n = unit_name_mangle(unit);
1468 r = bus_method_call_with_reply(
1470 "org.freedesktop.systemd1",
1471 "/org/freedesktop/systemd1",
1472 "org.freedesktop.systemd1.Manager",
1476 DBUS_TYPE_STRING, &n,
1481 if (!dbus_message_get_args(reply, NULL,
1482 DBUS_TYPE_OBJECT_PATH, &path,
1486 dbus_message_unref(reply);
1489 r = bus_method_call_with_reply(
1491 "org.freedesktop.systemd1",
1493 "org.freedesktop.DBus.Properties",
1497 DBUS_TYPE_STRING, &interface,
1498 DBUS_TYPE_STRING, &property,
1503 if (!dbus_message_iter_init(reply, &iter) ||
1504 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1507 dbus_message_iter_recurse(&iter, &sub);
1508 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1511 dbus_message_iter_get_basic(&sub, &b);
1515 typedef struct WaitData {
1522 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1523 _cleanup_dbus_error_free_ DBusError error;
1526 dbus_error_init(&error);
1532 log_debug("Got D-Bus request: %s.%s() on %s",
1533 dbus_message_get_interface(message),
1534 dbus_message_get_member(message),
1535 dbus_message_get_path(message));
1537 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1538 log_error("Warning! D-Bus connection terminated.");
1539 dbus_connection_close(connection);
1541 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1543 const char *path, *result, *unit;
1545 if (dbus_message_get_args(message, &error,
1546 DBUS_TYPE_UINT32, &id,
1547 DBUS_TYPE_OBJECT_PATH, &path,
1548 DBUS_TYPE_STRING, &unit,
1549 DBUS_TYPE_STRING, &result,
1550 DBUS_TYPE_INVALID)) {
1552 free(set_remove(d->set, (char*) path));
1554 if (!isempty(result))
1555 d->result = strdup(result);
1558 d->name = strdup(unit);
1560 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1563 dbus_error_free(&error);
1564 if (dbus_message_get_args(message, &error,
1565 DBUS_TYPE_UINT32, &id,
1566 DBUS_TYPE_OBJECT_PATH, &path,
1567 DBUS_TYPE_STRING, &result,
1568 DBUS_TYPE_INVALID)) {
1569 /* Compatibility with older systemd versions <
1570 * 183 during upgrades. This should be dropped
1572 free(set_remove(d->set, (char*) path));
1575 d->result = strdup(result);
1577 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1581 log_error("Failed to parse message: %s", bus_error_message(&error));
1584 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1587 static int enable_wait_for_jobs(DBusConnection *bus) {
1595 dbus_error_init(&error);
1596 dbus_bus_add_match(bus,
1598 "sender='org.freedesktop.systemd1',"
1599 "interface='org.freedesktop.systemd1.Manager',"
1600 "member='JobRemoved',"
1601 "path='/org/freedesktop/systemd1'",
1604 if (dbus_error_is_set(&error)) {
1605 log_error("Failed to add match: %s", bus_error_message(&error));
1606 dbus_error_free(&error);
1610 /* This is slightly dirty, since we don't undo the match registrations. */
1614 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1616 WaitData d = { .set = s };
1621 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL))
1624 while (!set_isempty(s)) {
1626 if (!dbus_connection_read_write_dispatch(bus, -1)) {
1627 log_error("Disconnected from bus.");
1628 return -ECONNREFUSED;
1635 if (streq(d.result, "timeout"))
1636 log_error("Job for %s timed out.", strna(d.name));
1637 else if (streq(d.result, "canceled"))
1638 log_error("Job for %s canceled.", strna(d.name));
1639 else if (streq(d.result, "dependency"))
1640 log_error("A dependency job for %s failed. See 'journalctl -xn' for details.", strna(d.name));
1641 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1642 log_error("Job for %s failed. See 'systemctl status %s' and 'journalctl -xn' for details.", strna(d.name), strna(d.name));
1645 if (streq_ptr(d.result, "timeout"))
1647 else if (streq_ptr(d.result, "canceled"))
1649 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1660 dbus_connection_remove_filter(bus, wait_filter, &d);
1664 static int check_one_unit(DBusConnection *bus, const char *name, char **check_states, bool quiet) {
1665 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1666 _cleanup_free_ char *n = NULL;
1667 DBusMessageIter iter, sub;
1669 *interface = "org.freedesktop.systemd1.Unit",
1670 *property = "ActiveState";
1671 const char *state, *path;
1677 dbus_error_init(&error);
1679 n = unit_name_mangle(name);
1683 r = bus_method_call_with_reply (
1685 "org.freedesktop.systemd1",
1686 "/org/freedesktop/systemd1",
1687 "org.freedesktop.systemd1.Manager",
1691 DBUS_TYPE_STRING, &n,
1694 dbus_error_free(&error);
1701 if (!dbus_message_get_args(reply, NULL,
1702 DBUS_TYPE_OBJECT_PATH, &path,
1703 DBUS_TYPE_INVALID)) {
1704 log_error("Failed to parse reply.");
1708 dbus_message_unref(reply);
1711 r = bus_method_call_with_reply(
1713 "org.freedesktop.systemd1",
1715 "org.freedesktop.DBus.Properties",
1719 DBUS_TYPE_STRING, &interface,
1720 DBUS_TYPE_STRING, &property,
1728 if (!dbus_message_iter_init(reply, &iter) ||
1729 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1730 log_error("Failed to parse reply.");
1734 dbus_message_iter_recurse(&iter, &sub);
1736 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1737 log_error("Failed to parse reply.");
1741 dbus_message_iter_get_basic(&sub, &state);
1746 return strv_find(check_states, state) ? 1 : 0;
1749 static void check_triggering_units(
1750 DBusConnection *bus,
1751 const char *unit_name) {
1753 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1754 DBusMessageIter iter, sub;
1755 const char *interface = "org.freedesktop.systemd1.Unit",
1756 *load_state_property = "LoadState",
1757 *triggered_by_property = "TriggeredBy",
1759 _cleanup_free_ char *unit_path = NULL, *n = NULL;
1760 bool print_warning_label = true;
1763 n = unit_name_mangle(unit_name);
1769 unit_path = unit_dbus_path_from_name(n);
1775 r = bus_method_call_with_reply(
1777 "org.freedesktop.systemd1",
1779 "org.freedesktop.DBus.Properties",
1783 DBUS_TYPE_STRING, &interface,
1784 DBUS_TYPE_STRING, &load_state_property,
1789 if (!dbus_message_iter_init(reply, &iter) ||
1790 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1791 log_error("Failed to parse reply.");
1795 dbus_message_iter_recurse(&iter, &sub);
1797 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1798 log_error("Failed to parse reply.");
1802 dbus_message_iter_get_basic(&sub, &state);
1804 if (streq(state, "masked"))
1807 dbus_message_unref(reply);
1810 r = bus_method_call_with_reply(
1812 "org.freedesktop.systemd1",
1814 "org.freedesktop.DBus.Properties",
1818 DBUS_TYPE_STRING, &interface,
1819 DBUS_TYPE_STRING, &triggered_by_property,
1824 if (!dbus_message_iter_init(reply, &iter) ||
1825 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1826 log_error("Failed to parse reply.");
1830 dbus_message_iter_recurse(&iter, &sub);
1831 dbus_message_iter_recurse(&sub, &iter);
1834 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1835 const char * const check_states[] = {
1840 const char *service_trigger;
1842 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1843 log_error("Failed to parse reply.");
1847 dbus_message_iter_get_basic(&sub, &service_trigger);
1849 r = check_one_unit(bus, service_trigger, (char**) check_states, true);
1853 if (print_warning_label) {
1854 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1855 print_warning_label = false;
1858 log_warning(" %s", service_trigger);
1861 dbus_message_iter_next(&sub);
1865 static int start_unit_one(
1866 DBusConnection *bus,
1873 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1874 _cleanup_free_ char *n;
1883 n = unit_name_mangle(name);
1887 r = bus_method_call_with_reply(
1889 "org.freedesktop.systemd1",
1890 "/org/freedesktop/systemd1",
1891 "org.freedesktop.systemd1.Manager",
1895 DBUS_TYPE_STRING, &n,
1896 DBUS_TYPE_STRING, &mode,
1899 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
1900 /* There's always a fallback possible for
1901 * legacy actions. */
1904 log_error("Failed to issue method call: %s", bus_error_message(error));
1909 if (!dbus_message_get_args(reply, error,
1910 DBUS_TYPE_OBJECT_PATH, &path,
1911 DBUS_TYPE_INVALID)) {
1912 log_error("Failed to parse reply: %s", bus_error_message(error));
1916 if (need_daemon_reload(bus, n))
1917 log_warning("Warning: Unit file of %s changed on disk, 'systemctl %sdaemon-reload' recommended.",
1918 n, arg_scope == UNIT_FILE_SYSTEM ? "" : "--user ");
1927 r = set_consume(s, p);
1929 log_error("Failed to add path to set.");
1937 static const struct {
1941 } action_table[_ACTION_MAX] = {
1942 [ACTION_HALT] = { SPECIAL_HALT_TARGET, "halt", "replace-irreversibly" },
1943 [ACTION_POWEROFF] = { SPECIAL_POWEROFF_TARGET, "poweroff", "replace-irreversibly" },
1944 [ACTION_REBOOT] = { SPECIAL_REBOOT_TARGET, "reboot", "replace-irreversibly" },
1945 [ACTION_KEXEC] = { SPECIAL_KEXEC_TARGET, "kexec", "replace-irreversibly" },
1946 [ACTION_RUNLEVEL2] = { SPECIAL_RUNLEVEL2_TARGET, NULL, "isolate" },
1947 [ACTION_RUNLEVEL3] = { SPECIAL_RUNLEVEL3_TARGET, NULL, "isolate" },
1948 [ACTION_RUNLEVEL4] = { SPECIAL_RUNLEVEL4_TARGET, NULL, "isolate" },
1949 [ACTION_RUNLEVEL5] = { SPECIAL_RUNLEVEL5_TARGET, NULL, "isolate" },
1950 [ACTION_RESCUE] = { SPECIAL_RESCUE_TARGET, "rescue", "isolate" },
1951 [ACTION_EMERGENCY] = { SPECIAL_EMERGENCY_TARGET, "emergency", "isolate" },
1952 [ACTION_DEFAULT] = { SPECIAL_DEFAULT_TARGET, "default", "isolate" },
1953 [ACTION_EXIT] = { SPECIAL_EXIT_TARGET, "exit", "replace-irreversibly" },
1954 [ACTION_SUSPEND] = { SPECIAL_SUSPEND_TARGET, "suspend", "replace-irreversibly" },
1955 [ACTION_HIBERNATE] = { SPECIAL_HIBERNATE_TARGET, "hibernate", "replace-irreversibly" },
1956 [ACTION_HYBRID_SLEEP] = { SPECIAL_HYBRID_SLEEP_TARGET, "hybrid-sleep", "replace-irreversibly" },
1959 static enum action verb_to_action(const char *verb) {
1962 for (i = ACTION_INVALID; i < _ACTION_MAX; i++)
1963 if (action_table[i].verb && streq(verb, action_table[i].verb))
1965 return ACTION_INVALID;
1968 static int start_unit(DBusConnection *bus, char **args) {
1971 const char *method, *mode, *one_name;
1972 _cleanup_set_free_free_ Set *s = NULL;
1973 _cleanup_dbus_error_free_ DBusError error;
1976 dbus_error_init(&error);
1980 ask_password_agent_open_if_enabled();
1982 if (arg_action == ACTION_SYSTEMCTL) {
1985 streq(args[0], "stop") ||
1986 streq(args[0], "condstop") ? "StopUnit" :
1987 streq(args[0], "reload") ? "ReloadUnit" :
1988 streq(args[0], "restart") ? "RestartUnit" :
1990 streq(args[0], "try-restart") ||
1991 streq(args[0], "condrestart") ? "TryRestartUnit" :
1993 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1995 streq(args[0], "reload-or-try-restart") ||
1996 streq(args[0], "condreload") ||
1998 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
2000 action = verb_to_action(args[0]);
2002 mode = streq(args[0], "isolate") ? "isolate" :
2003 action_table[action].mode ?: arg_job_mode;
2005 one_name = action_table[action].target;
2008 assert(arg_action < ELEMENTSOF(action_table));
2009 assert(action_table[arg_action].target);
2011 method = "StartUnit";
2013 mode = action_table[arg_action].mode;
2014 one_name = action_table[arg_action].target;
2017 if (!arg_no_block) {
2018 ret = enable_wait_for_jobs(bus);
2020 log_error("Could not watch jobs: %s", strerror(-ret));
2024 s = set_new(string_hash_func, string_compare_func);
2030 ret = start_unit_one(bus, method, one_name, mode, &error, s);
2032 ret = translate_bus_error_to_exit_status(ret, &error);
2034 STRV_FOREACH(name, args+1) {
2035 r = start_unit_one(bus, method, *name, mode, &error, s);
2037 ret = translate_bus_error_to_exit_status(r, &error);
2038 dbus_error_free(&error);
2043 if (!arg_no_block) {
2044 r = wait_for_jobs(bus, s);
2048 /* When stopping units, warn if they can still be triggered by
2049 * another active unit (socket, path, timer) */
2050 if (!arg_quiet && streq(method, "StopUnit")) {
2052 check_triggering_units(bus, one_name);
2054 STRV_FOREACH(name, args+1)
2055 check_triggering_units(bus, *name);
2062 /* Ask systemd-logind, which might grant access to unprivileged users
2063 * through PolicyKit */
2064 static int reboot_with_logind(DBusConnection *bus, enum action a) {
2067 dbus_bool_t interactive = true;
2072 polkit_agent_open_if_enabled();
2080 case ACTION_POWEROFF:
2081 method = "PowerOff";
2084 case ACTION_SUSPEND:
2088 case ACTION_HIBERNATE:
2089 method = "Hibernate";
2092 case ACTION_HYBRID_SLEEP:
2093 method = "HybridSleep";
2100 return bus_method_call_with_reply(
2102 "org.freedesktop.login1",
2103 "/org/freedesktop/login1",
2104 "org.freedesktop.login1.Manager",
2108 DBUS_TYPE_BOOLEAN, &interactive,
2115 static int check_inhibitors(DBusConnection *bus, enum action a) {
2117 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
2118 DBusMessageIter iter, sub, sub2;
2121 _cleanup_strv_free_ char **sessions = NULL;
2127 if (arg_ignore_inhibitors || arg_force > 0)
2139 r = bus_method_call_with_reply(
2141 "org.freedesktop.login1",
2142 "/org/freedesktop/login1",
2143 "org.freedesktop.login1.Manager",
2149 /* If logind is not around, then there are no inhibitors... */
2152 if (!dbus_message_iter_init(reply, &iter) ||
2153 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2154 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
2155 log_error("Failed to parse reply.");
2159 dbus_message_iter_recurse(&iter, &sub);
2160 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2161 const char *what, *who, *why, *mode;
2163 _cleanup_strv_free_ char **sv = NULL;
2164 _cleanup_free_ char *comm = NULL, *user = NULL;
2166 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
2167 log_error("Failed to parse reply.");
2171 dbus_message_iter_recurse(&sub, &sub2);
2173 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &what, true) < 0 ||
2174 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &who, true) < 0 ||
2175 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &why, true) < 0 ||
2176 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &mode, true) < 0 ||
2177 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &uid, true) < 0 ||
2178 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, false) < 0) {
2179 log_error("Failed to parse reply.");
2183 if (!streq(mode, "block"))
2186 sv = strv_split(what, ":");
2190 if (!strv_contains(sv,
2192 a == ACTION_POWEROFF ||
2193 a == ACTION_REBOOT ||
2194 a == ACTION_KEXEC ? "shutdown" : "sleep"))
2197 get_process_comm(pid, &comm);
2198 user = uid_to_name(uid);
2199 log_warning("Operation inhibited by \"%s\" (PID %lu \"%s\", user %s), reason is \"%s\".",
2200 who, (unsigned long) pid, strna(comm), strna(user), why);
2204 dbus_message_iter_next(&sub);
2207 dbus_message_iter_recurse(&iter, &sub);
2209 /* Check for current sessions */
2210 sd_get_sessions(&sessions);
2211 STRV_FOREACH(s, sessions) {
2213 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
2215 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
2218 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
2221 if (sd_session_get_type(*s, &type) < 0 || (!streq(type, "x11") && !streq(type, "tty")))
2224 sd_session_get_tty(*s, &tty);
2225 sd_session_get_seat(*s, &seat);
2226 sd_session_get_service(*s, &service);
2227 user = uid_to_name(uid);
2229 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
2236 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
2237 action_table[a].verb);
2245 static int start_special(DBusConnection *bus, char **args) {
2251 a = verb_to_action(args[0]);
2253 r = check_inhibitors(bus, a);
2257 if (arg_force >= 2 && geteuid() != 0) {
2258 log_error("Must be root.");
2262 if (arg_force >= 2 &&
2263 (a == ACTION_HALT ||
2264 a == ACTION_POWEROFF ||
2265 a == ACTION_REBOOT))
2268 if (arg_force >= 1 &&
2269 (a == ACTION_HALT ||
2270 a == ACTION_POWEROFF ||
2271 a == ACTION_REBOOT ||
2272 a == ACTION_KEXEC ||
2274 return daemon_reload(bus, args);
2276 /* first try logind, to allow authentication with polkit */
2277 if (geteuid() != 0 &&
2278 (a == ACTION_POWEROFF ||
2279 a == ACTION_REBOOT ||
2280 a == ACTION_SUSPEND ||
2281 a == ACTION_HIBERNATE ||
2282 a == ACTION_HYBRID_SLEEP)) {
2283 r = reboot_with_logind(bus, a);
2288 r = start_unit(bus, args);
2289 if (r == EXIT_SUCCESS)
2295 static int check_unit_active(DBusConnection *bus, char **args) {
2296 const char * const check_states[] = {
2303 int r = 3; /* According to LSB: "program is not running" */
2308 STRV_FOREACH(name, args+1) {
2311 state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
2321 static int check_unit_failed(DBusConnection *bus, char **args) {
2322 const char * const check_states[] = {
2333 STRV_FOREACH(name, args+1) {
2336 state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
2346 static int kill_unit(DBusConnection *bus, char **args) {
2354 arg_kill_who = "all";
2356 STRV_FOREACH(name, args+1) {
2357 _cleanup_free_ char *n = NULL;
2359 n = unit_name_mangle(*name);
2363 r = bus_method_call_with_reply(
2365 "org.freedesktop.systemd1",
2366 "/org/freedesktop/systemd1",
2367 "org.freedesktop.systemd1.Manager",
2371 DBUS_TYPE_STRING, &n,
2372 DBUS_TYPE_STRING, &arg_kill_who,
2373 DBUS_TYPE_INT32, &arg_signal,
2381 typedef struct ExecStatusInfo {
2389 usec_t start_timestamp;
2390 usec_t exit_timestamp;
2395 LIST_FIELDS(struct ExecStatusInfo, exec);
2398 static void exec_status_info_free(ExecStatusInfo *i) {
2407 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
2408 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2409 DBusMessageIter sub2, sub3;
2413 int32_t code, status;
2419 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
2422 dbus_message_iter_recurse(sub, &sub2);
2424 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
2427 i->path = strdup(path);
2431 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
2432 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
2436 dbus_message_iter_recurse(&sub2, &sub3);
2437 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2438 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2439 dbus_message_iter_next(&sub3);
2443 i->argv = new0(char*, n+1);
2448 dbus_message_iter_recurse(&sub2, &sub3);
2449 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2452 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2453 dbus_message_iter_get_basic(&sub3, &s);
2454 dbus_message_iter_next(&sub3);
2456 i->argv[n] = strdup(s);
2463 if (!dbus_message_iter_next(&sub2) ||
2464 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
2465 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
2466 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
2467 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
2468 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
2469 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
2470 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
2471 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
2475 i->start_timestamp = (usec_t) start_timestamp;
2476 i->exit_timestamp = (usec_t) exit_timestamp;
2477 i->pid = (pid_t) pid;
2484 typedef struct UnitStatusInfo {
2486 const char *load_state;
2487 const char *active_state;
2488 const char *sub_state;
2489 const char *unit_file_state;
2491 const char *description;
2492 const char *following;
2494 char **documentation;
2496 const char *fragment_path;
2497 const char *source_path;
2498 const char *control_group;
2500 char **dropin_paths;
2502 const char *load_error;
2505 usec_t inactive_exit_timestamp;
2506 usec_t inactive_exit_timestamp_monotonic;
2507 usec_t active_enter_timestamp;
2508 usec_t active_exit_timestamp;
2509 usec_t inactive_enter_timestamp;
2511 bool need_daemon_reload;
2516 const char *status_text;
2517 const char *pid_file;
2520 usec_t start_timestamp;
2521 usec_t exit_timestamp;
2523 int exit_code, exit_status;
2525 usec_t condition_timestamp;
2526 bool condition_result;
2529 unsigned n_accepted;
2530 unsigned n_connections;
2533 /* Pairs of type, path */
2537 const char *sysfs_path;
2539 /* Mount, Automount */
2545 LIST_HEAD(ExecStatusInfo, exec);
2548 static void print_status_info(UnitStatusInfo *i) {
2550 const char *on, *off, *ss;
2552 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
2553 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2556 arg_all * OUTPUT_SHOW_ALL |
2557 (!on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
2558 on_tty() * OUTPUT_COLOR |
2559 !arg_quiet * OUTPUT_WARN_CUTOFF |
2560 arg_full * OUTPUT_FULL_WIDTH;
2565 /* This shows pretty information about a unit. See
2566 * print_property() for a low-level property printer */
2568 printf("%s", strna(i->id));
2570 if (i->description && !streq_ptr(i->id, i->description))
2571 printf(" - %s", i->description);
2576 printf(" Follow: unit currently follows state of %s\n", i->following);
2578 if (streq_ptr(i->load_state, "error")) {
2579 on = ansi_highlight_red(true);
2580 off = ansi_highlight_red(false);
2584 path = i->source_path ? i->source_path : i->fragment_path;
2587 printf(" Loaded: %s%s%s (Reason: %s)\n",
2588 on, strna(i->load_state), off, i->load_error);
2589 else if (path && i->unit_file_state)
2590 printf(" Loaded: %s%s%s (%s; %s)\n",
2591 on, strna(i->load_state), off, path, i->unit_file_state);
2593 printf(" Loaded: %s%s%s (%s)\n",
2594 on, strna(i->load_state), off, path);
2596 printf(" Loaded: %s%s%s\n",
2597 on, strna(i->load_state), off);
2599 if (!strv_isempty(i->dropin_paths)) {
2604 STRV_FOREACH(dropin, i->dropin_paths) {
2605 if (! dir || last) {
2606 printf(dir ? " " : " Drop-In: ");
2610 if (path_get_parent(*dropin, &dir) < 0) {
2615 printf("%s\n %s", dir,
2616 draw_special_char(DRAW_TREE_RIGHT));
2619 last = ! (*(dropin + 1) && startswith(*(dropin + 1), dir));
2621 printf("%s%s", path_get_file_name(*dropin), last ? "\n" : ", ");
2627 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2629 if (streq_ptr(i->active_state, "failed")) {
2630 on = ansi_highlight_red(true);
2631 off = ansi_highlight_red(false);
2632 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2633 on = ansi_highlight_green(true);
2634 off = ansi_highlight_green(false);
2639 printf(" Active: %s%s (%s)%s",
2640 on, strna(i->active_state), ss, off);
2642 printf(" Active: %s%s%s",
2643 on, strna(i->active_state), off);
2645 if (!isempty(i->result) && !streq(i->result, "success"))
2646 printf(" (Result: %s)", i->result);
2648 timestamp = (streq_ptr(i->active_state, "active") ||
2649 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2650 (streq_ptr(i->active_state, "inactive") ||
2651 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2652 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2653 i->active_exit_timestamp;
2655 s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
2656 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2659 printf(" since %s; %s\n", s2, s1);
2661 printf(" since %s\n", s2);
2665 if (!i->condition_result && i->condition_timestamp > 0) {
2666 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
2667 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2670 printf(" start condition failed at %s; %s\n", s2, s1);
2672 printf(" start condition failed at %s\n", s2);
2676 printf(" Device: %s\n", i->sysfs_path);
2678 printf(" Where: %s\n", i->where);
2680 printf(" What: %s\n", i->what);
2682 STRV_FOREACH(t, i->documentation)
2683 printf(" %*s %s\n", 9, t == i->documentation ? "Docs:" : "", *t);
2685 STRV_FOREACH_PAIR(t, t2, i->listen)
2686 printf(" %*s %s (%s)\n", 9, t == i->listen ? "Listen:" : "", *t2, *t);
2689 printf(" Accepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2691 LIST_FOREACH(exec, p, i->exec) {
2692 _cleanup_free_ char *argv = NULL;
2695 /* Only show exited processes here */
2699 argv = strv_join(p->argv, " ");
2700 printf(" Process: %u %s=%s ", p->pid, p->name, strna(argv));
2702 good = is_clean_exit_lsb(p->code, p->status, NULL);
2704 on = ansi_highlight_red(true);
2705 off = ansi_highlight_red(false);
2709 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2711 if (p->code == CLD_EXITED) {
2714 printf("status=%i", p->status);
2716 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2721 printf("signal=%s", signal_to_string(p->status));
2723 printf(")%s\n", off);
2725 if (i->main_pid == p->pid &&
2726 i->start_timestamp == p->start_timestamp &&
2727 i->exit_timestamp == p->start_timestamp)
2728 /* Let's not show this twice */
2731 if (p->pid == i->control_pid)
2735 if (i->main_pid > 0 || i->control_pid > 0) {
2736 if (i->main_pid > 0) {
2737 printf(" Main PID: %u", (unsigned) i->main_pid);
2740 _cleanup_free_ char *comm = NULL;
2741 get_process_comm(i->main_pid, &comm);
2743 printf(" (%s)", comm);
2744 } else if (i->exit_code > 0) {
2745 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2747 if (i->exit_code == CLD_EXITED) {
2750 printf("status=%i", i->exit_status);
2752 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2757 printf("signal=%s", signal_to_string(i->exit_status));
2761 if (i->control_pid > 0)
2765 if (i->control_pid > 0) {
2766 _cleanup_free_ char *c = NULL;
2768 printf(" %8s: %u", i->main_pid ? "" : " Control", (unsigned) i->control_pid);
2770 get_process_comm(i->control_pid, &c);
2779 printf(" Status: \"%s\"\n", i->status_text);
2781 if (i->control_group &&
2782 (i->main_pid > 0 || i->control_pid > 0 || cg_is_empty_by_spec(i->control_group, false) == 0)) {
2785 printf(" CGroup: %s\n", i->control_group);
2787 if (arg_transport != TRANSPORT_SSH) {
2790 char prefix[] = " ";
2793 if (c > sizeof(prefix) - 1)
2794 c -= sizeof(prefix) - 1;
2798 if (i->main_pid > 0)
2799 extra[k++] = i->main_pid;
2801 if (i->control_pid > 0)
2802 extra[k++] = i->control_pid;
2804 show_cgroup_and_extra_by_spec(i->control_group, prefix,
2805 c, false, extra, k, flags);
2809 if (i->id && arg_transport != TRANSPORT_SSH) {
2811 show_journal_by_unit(stdout,
2815 i->inactive_exit_timestamp_monotonic,
2819 arg_scope == UNIT_FILE_SYSTEM);
2822 if (i->need_daemon_reload)
2823 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %sdaemon-reload' recommended.\n",
2824 ansi_highlight_red(true),
2825 ansi_highlight_red(false),
2826 arg_scope == UNIT_FILE_SYSTEM ? "" : "--user ");
2829 static void show_unit_help(UnitStatusInfo *i) {
2834 if (!i->documentation) {
2835 log_info("Documentation for %s not known.", i->id);
2839 STRV_FOREACH(p, i->documentation) {
2841 if (startswith(*p, "man:")) {
2844 _cleanup_free_ char *page = NULL, *section = NULL;
2845 const char *args[4] = { "man", NULL, NULL, NULL };
2850 if ((*p)[k-1] == ')')
2851 e = strrchr(*p, '(');
2854 page = strndup((*p) + 4, e - *p - 4);
2855 section = strndup(e + 1, *p + k - e - 2);
2856 if (!page || !section) {
2868 log_error("Failed to fork: %m");
2874 execvp(args[0], (char**) args);
2875 log_error("Failed to execute man: %m");
2876 _exit(EXIT_FAILURE);
2879 wait_for_terminate(pid, NULL);
2881 log_info("Can't show: %s", *p);
2885 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2891 switch (dbus_message_iter_get_arg_type(iter)) {
2893 case DBUS_TYPE_STRING: {
2896 dbus_message_iter_get_basic(iter, &s);
2899 if (streq(name, "Id"))
2901 else if (streq(name, "LoadState"))
2903 else if (streq(name, "ActiveState"))
2904 i->active_state = s;
2905 else if (streq(name, "SubState"))
2907 else if (streq(name, "Description"))
2909 else if (streq(name, "FragmentPath"))
2910 i->fragment_path = s;
2911 else if (streq(name, "SourcePath"))
2914 else if (streq(name, "DefaultControlGroup"))
2915 i->control_group = s;
2917 else if (streq(name, "ControlGroup"))
2918 i->control_group = s;
2919 else if (streq(name, "StatusText"))
2921 else if (streq(name, "PIDFile"))
2923 else if (streq(name, "SysFSPath"))
2925 else if (streq(name, "Where"))
2927 else if (streq(name, "What"))
2929 else if (streq(name, "Following"))
2931 else if (streq(name, "UnitFileState"))
2932 i->unit_file_state = s;
2933 else if (streq(name, "Result"))
2940 case DBUS_TYPE_BOOLEAN: {
2943 dbus_message_iter_get_basic(iter, &b);
2945 if (streq(name, "Accept"))
2947 else if (streq(name, "NeedDaemonReload"))
2948 i->need_daemon_reload = b;
2949 else if (streq(name, "ConditionResult"))
2950 i->condition_result = b;
2955 case DBUS_TYPE_UINT32: {
2958 dbus_message_iter_get_basic(iter, &u);
2960 if (streq(name, "MainPID")) {
2962 i->main_pid = (pid_t) u;
2965 } else if (streq(name, "ControlPID"))
2966 i->control_pid = (pid_t) u;
2967 else if (streq(name, "ExecMainPID")) {
2969 i->main_pid = (pid_t) u;
2970 } else if (streq(name, "NAccepted"))
2972 else if (streq(name, "NConnections"))
2973 i->n_connections = u;
2978 case DBUS_TYPE_INT32: {
2981 dbus_message_iter_get_basic(iter, &j);
2983 if (streq(name, "ExecMainCode"))
2984 i->exit_code = (int) j;
2985 else if (streq(name, "ExecMainStatus"))
2986 i->exit_status = (int) j;
2991 case DBUS_TYPE_UINT64: {
2994 dbus_message_iter_get_basic(iter, &u);
2996 if (streq(name, "ExecMainStartTimestamp"))
2997 i->start_timestamp = (usec_t) u;
2998 else if (streq(name, "ExecMainExitTimestamp"))
2999 i->exit_timestamp = (usec_t) u;
3000 else if (streq(name, "ActiveEnterTimestamp"))
3001 i->active_enter_timestamp = (usec_t) u;
3002 else if (streq(name, "InactiveEnterTimestamp"))
3003 i->inactive_enter_timestamp = (usec_t) u;
3004 else if (streq(name, "InactiveExitTimestamp"))
3005 i->inactive_exit_timestamp = (usec_t) u;
3006 else if (streq(name, "InactiveExitTimestampMonotonic"))
3007 i->inactive_exit_timestamp_monotonic = (usec_t) u;
3008 else if (streq(name, "ActiveExitTimestamp"))
3009 i->active_exit_timestamp = (usec_t) u;
3010 else if (streq(name, "ConditionTimestamp"))
3011 i->condition_timestamp = (usec_t) u;
3016 case DBUS_TYPE_ARRAY: {
3018 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
3019 startswith(name, "Exec")) {
3020 DBusMessageIter sub;
3022 dbus_message_iter_recurse(iter, &sub);
3023 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3024 ExecStatusInfo *info;
3027 if (!(info = new0(ExecStatusInfo, 1)))
3030 if (!(info->name = strdup(name))) {
3035 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
3040 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
3042 dbus_message_iter_next(&sub);
3045 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Listen")) {
3046 DBusMessageIter sub, sub2;
3048 dbus_message_iter_recurse(iter, &sub);
3049 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3050 const char *type, *path;
3052 dbus_message_iter_recurse(&sub, &sub2);
3054 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
3055 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0) {
3058 r = strv_extend(&i->listen, type);
3061 r = strv_extend(&i->listen, path);
3066 dbus_message_iter_next(&sub);
3071 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING && streq(name, "DropInPaths")) {
3072 int r = bus_parse_strv_iter(iter, &i->dropin_paths);
3076 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
3077 streq(name, "Documentation")) {
3079 DBusMessageIter sub;
3081 dbus_message_iter_recurse(iter, &sub);
3082 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
3086 dbus_message_iter_get_basic(&sub, &s);
3088 r = strv_extend(&i->documentation, s);
3092 dbus_message_iter_next(&sub);
3099 case DBUS_TYPE_STRUCT: {
3101 if (streq(name, "LoadError")) {
3102 DBusMessageIter sub;
3103 const char *n, *message;
3106 dbus_message_iter_recurse(iter, &sub);
3108 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
3112 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
3116 if (!isempty(message))
3117 i->load_error = message;
3127 static int print_property(const char *name, DBusMessageIter *iter) {
3131 /* This is a low-level property printer, see
3132 * print_status_info() for the nicer output */
3134 if (arg_properties && !strv_find(arg_properties, name))
3137 switch (dbus_message_iter_get_arg_type(iter)) {
3139 case DBUS_TYPE_STRUCT: {
3140 DBusMessageIter sub;
3141 dbus_message_iter_recurse(iter, &sub);
3143 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
3146 dbus_message_iter_get_basic(&sub, &u);
3149 printf("%s=%u\n", name, (unsigned) u);
3151 printf("%s=\n", name);
3154 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
3157 dbus_message_iter_get_basic(&sub, &s);
3159 if (arg_all || s[0])
3160 printf("%s=%s\n", name, s);
3163 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
3164 const char *a = NULL, *b = NULL;
3166 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
3167 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
3169 if (arg_all || !isempty(a) || !isempty(b))
3170 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
3178 case DBUS_TYPE_ARRAY:
3180 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
3181 DBusMessageIter sub, sub2;
3183 dbus_message_iter_recurse(iter, &sub);
3184 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3188 dbus_message_iter_recurse(&sub, &sub2);
3190 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
3191 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
3192 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
3194 dbus_message_iter_next(&sub);
3199 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
3200 DBusMessageIter sub, sub2;
3202 dbus_message_iter_recurse(iter, &sub);
3204 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3205 const char *type, *path;
3207 dbus_message_iter_recurse(&sub, &sub2);
3209 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
3210 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
3211 printf("%s=%s\n", type, path);
3213 dbus_message_iter_next(&sub);
3218 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Listen")) {
3219 DBusMessageIter sub, sub2;
3221 dbus_message_iter_recurse(iter, &sub);
3222 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3223 const char *type, *path;
3225 dbus_message_iter_recurse(&sub, &sub2);
3227 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
3228 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
3229 printf("Listen%s=%s\n", type, path);
3231 dbus_message_iter_next(&sub);
3236 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
3237 DBusMessageIter sub, sub2;
3239 dbus_message_iter_recurse(iter, &sub);
3240 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3242 uint64_t value, next_elapse;
3244 dbus_message_iter_recurse(&sub, &sub2);
3246 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
3247 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
3248 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
3249 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
3251 printf("%s={ value=%s ; next_elapse=%s }\n",
3253 format_timespan(timespan1, sizeof(timespan1), value, 0),
3254 format_timespan(timespan2, sizeof(timespan2), next_elapse, 0));
3257 dbus_message_iter_next(&sub);
3262 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
3263 DBusMessageIter sub, sub2;
3265 dbus_message_iter_recurse(iter, &sub);
3266 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3267 const char *controller, *attr, *value;
3269 dbus_message_iter_recurse(&sub, &sub2);
3271 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
3272 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
3273 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
3275 printf("ControlGroupAttributes={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
3281 dbus_message_iter_next(&sub);
3286 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
3287 DBusMessageIter sub;
3289 dbus_message_iter_recurse(iter, &sub);
3290 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3291 ExecStatusInfo info = {};
3293 if (exec_status_info_deserialize(&sub, &info) >= 0) {
3294 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
3295 _cleanup_free_ char *t;
3297 t = strv_join(info.argv, " ");
3299 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
3303 yes_no(info.ignore),
3304 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
3305 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
3306 (unsigned) info. pid,
3307 sigchld_code_to_string(info.code),
3309 info.code == CLD_EXITED ? "" : "/",
3310 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
3314 strv_free(info.argv);
3316 dbus_message_iter_next(&sub);
3321 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "DeviceAllow")) {
3322 DBusMessageIter sub, sub2;
3324 dbus_message_iter_recurse(iter, &sub);
3325 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3326 const char *path, *rwm;
3328 dbus_message_iter_recurse(&sub, &sub2);
3330 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
3331 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &rwm, false) >= 0)
3332 printf("%s=%s %s\n", name, strna(path), strna(rwm));
3334 dbus_message_iter_next(&sub);
3338 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && (streq(name, "BlockIOReadBandwidth") || streq(name, "BlockIOWriteBandwidth"))) {
3339 DBusMessageIter sub, sub2;
3341 dbus_message_iter_recurse(iter, &sub);
3342 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3346 dbus_message_iter_recurse(&sub, &sub2);
3348 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
3349 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &bandwidth, false) >= 0)
3350 printf("%s=%s %" PRIu64 "\n", name, strna(path), bandwidth);
3352 dbus_message_iter_next(&sub);
3361 if (generic_print_property(name, iter, arg_all) > 0)
3365 printf("%s=[unprintable]\n", name);
3370 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
3371 _cleanup_free_ DBusMessage *reply = NULL;
3372 const char *interface = "";
3374 DBusMessageIter iter, sub, sub2, sub3;
3375 UnitStatusInfo info = {};
3381 r = bus_method_call_with_reply(
3383 "org.freedesktop.systemd1",
3385 "org.freedesktop.DBus.Properties",
3389 DBUS_TYPE_STRING, &interface,
3394 if (!dbus_message_iter_init(reply, &iter) ||
3395 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3396 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
3397 log_error("Failed to parse reply.");
3401 dbus_message_iter_recurse(&iter, &sub);
3408 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3411 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
3412 dbus_message_iter_recurse(&sub, &sub2);
3414 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
3415 dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
3416 log_error("Failed to parse reply.");
3420 dbus_message_iter_recurse(&sub2, &sub3);
3422 if (show_properties)
3423 r = print_property(name, &sub3);
3425 r = status_property(name, &sub3, &info);
3427 log_error("Failed to parse reply.");
3431 dbus_message_iter_next(&sub);
3436 if (!show_properties) {
3437 if (streq(verb, "help"))
3438 show_unit_help(&info);
3440 print_status_info(&info);
3443 strv_free(info.documentation);
3444 strv_free(info.dropin_paths);
3445 strv_free(info.listen);
3447 if (!streq_ptr(info.active_state, "active") &&
3448 !streq_ptr(info.active_state, "reloading") &&
3449 streq(verb, "status")) {
3450 /* According to LSB: "program not running" */
3451 /* 0: program is running or service is OK
3452 * 1: program is dead and /var/run pid file exists
3453 * 2: program is dead and /var/lock lock file exists
3454 * 3: program is not running
3455 * 4: program or service status is unknown
3457 if (info.pid_file && access(info.pid_file, F_OK) == 0)
3463 while ((p = info.exec)) {
3464 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
3465 exec_status_info_free(p);
3471 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
3472 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3473 const char *path = NULL;
3474 _cleanup_dbus_error_free_ DBusError error;
3477 dbus_error_init(&error);
3479 r = bus_method_call_with_reply(
3481 "org.freedesktop.systemd1",
3482 "/org/freedesktop/systemd1",
3483 "org.freedesktop.systemd1.Manager",
3487 DBUS_TYPE_UINT32, &pid,
3492 if (!dbus_message_get_args(reply, &error,
3493 DBUS_TYPE_OBJECT_PATH, &path,
3494 DBUS_TYPE_INVALID)) {
3495 log_error("Failed to parse reply: %s", bus_error_message(&error));
3499 r = show_one(verb, bus, path, false, new_line);
3503 static int show_all(const char* verb, DBusConnection *bus, bool show_properties, bool *new_line) {
3504 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3505 _cleanup_free_ struct unit_info *unit_infos = NULL;
3507 const struct unit_info *u;
3510 r = get_unit_list(bus, &reply, &unit_infos, &c);
3514 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
3516 for (u = unit_infos; u < unit_infos + c; u++) {
3517 _cleanup_free_ char *p = NULL;
3519 if (!output_show_unit(u))
3522 p = unit_dbus_path_from_name(u->id);
3526 printf("%s -> '%s'\n", u->id, p);
3528 r = show_one(verb, bus, p, show_properties, new_line);
3536 static int show(DBusConnection *bus, char **args) {
3538 bool show_properties, show_status, new_line = false;
3544 show_properties = streq(args[0], "show");
3545 show_status = streq(args[0], "status");
3547 if (show_properties)
3548 pager_open_if_enabled();
3550 /* If no argument is specified inspect the manager itself */
3552 if (show_properties && strv_length(args) <= 1)
3553 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
3555 if (show_status && strv_length(args) <= 1)
3556 return show_all(args[0], bus, false, &new_line);
3558 STRV_FOREACH(name, args+1) {
3561 if (safe_atou32(*name, &id) < 0) {
3562 _cleanup_free_ char *p = NULL, *n = NULL;
3563 /* Interpret as unit name */
3565 n = unit_name_mangle(*name);
3569 p = unit_dbus_path_from_name(n);
3573 r = show_one(args[0], bus, p, show_properties, &new_line);
3577 } else if (show_properties) {
3578 _cleanup_free_ char *p = NULL;
3580 /* Interpret as job id */
3581 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
3584 r = show_one(args[0], bus, p, show_properties, &new_line);
3589 /* Interpret as PID */
3590 r = show_one_by_pid(args[0], bus, id, &new_line);
3599 static int append_assignment(DBusMessageIter *iter, const char *assignment) {
3602 DBusMessageIter sub;
3608 eq = strchr(assignment, '=');
3610 log_error("Not an assignment: %s", assignment);
3614 field = strndupa(assignment, eq - assignment);
3617 if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &field))
3620 if (streq(field, "CPUAccounting") ||
3621 streq(field, "MemoryAccounting") ||
3622 streq(field, "BlockIOAccounting")) {
3625 r = parse_boolean(eq);
3627 log_error("Failed to parse boolean assignment %s.", assignment);
3632 if (!dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, "b", &sub) ||
3633 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_BOOLEAN, &b))
3636 } else if (streq(field, "MemoryLimit") || streq(field, "MemorySoftLimit")) {
3640 r = parse_bytes(eq, &bytes);
3642 log_error("Failed to parse bytes specification %s", assignment);
3647 if (!dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, "t", &sub) ||
3648 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_UINT64, &u))
3651 } else if (streq(field, "CPUShares") || streq(field, "BlockIOWeight")) {
3654 r = safe_atou64(eq, &u);
3656 log_error("Failed to parse %s value %s.", field, eq);
3660 if (!dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, "t", &sub) ||
3661 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_UINT64, &u))
3665 log_error("Unknown assignment %s.", assignment);
3669 if (!dbus_message_iter_close_container(iter, &sub))
3675 static int set_property(DBusConnection *bus, char **args) {
3677 _cleanup_free_ DBusMessage *m = NULL, *reply = NULL;
3678 DBusMessageIter iter, sub;
3679 dbus_bool_t runtime;
3684 dbus_error_init(&error);
3686 m = dbus_message_new_method_call(
3687 "org.freedesktop.systemd1",
3688 "/org/freedesktop/systemd1",
3689 "org.freedesktop.systemd1.Manager",
3690 "SetUnitProperties");
3694 dbus_message_iter_init_append(m, &iter);
3696 runtime = arg_runtime;
3698 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &args[1]) ||
3699 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &runtime) ||
3700 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(sv)", &sub))
3703 STRV_FOREACH(i, args + 2) {
3704 DBusMessageIter sub2;
3706 if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2))
3709 r = append_assignment(&sub2, *i);
3713 if (!dbus_message_iter_close_container(&sub, &sub2))
3718 if (!dbus_message_iter_close_container(&iter, &sub))
3721 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3723 log_error("Failed to issue method call: %s", bus_error_message(&error));
3724 dbus_error_free(&error);
3731 static int dump(DBusConnection *bus, char **args) {
3732 _cleanup_free_ DBusMessage *reply = NULL;
3737 dbus_error_init(&error);
3739 pager_open_if_enabled();
3741 r = bus_method_call_with_reply(
3743 "org.freedesktop.systemd1",
3744 "/org/freedesktop/systemd1",
3745 "org.freedesktop.systemd1.Manager",
3753 if (!dbus_message_get_args(reply, &error,
3754 DBUS_TYPE_STRING, &text,
3755 DBUS_TYPE_INVALID)) {
3756 log_error("Failed to parse reply: %s", bus_error_message(&error));
3757 dbus_error_free(&error);
3761 fputs(text, stdout);
3765 static int snapshot(DBusConnection *bus, char **args) {
3766 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3769 dbus_bool_t cleanup = FALSE;
3770 DBusMessageIter iter, sub;
3773 *interface = "org.freedesktop.systemd1.Unit",
3775 _cleanup_free_ char *n = NULL;
3777 dbus_error_init(&error);
3779 if (strv_length(args) > 1)
3780 n = unit_name_mangle_with_suffix(args[1], ".snapshot");
3786 r = bus_method_call_with_reply (
3788 "org.freedesktop.systemd1",
3789 "/org/freedesktop/systemd1",
3790 "org.freedesktop.systemd1.Manager",
3794 DBUS_TYPE_STRING, &n,
3795 DBUS_TYPE_BOOLEAN, &cleanup,
3800 if (!dbus_message_get_args(reply, &error,
3801 DBUS_TYPE_OBJECT_PATH, &path,
3802 DBUS_TYPE_INVALID)) {
3803 log_error("Failed to parse reply: %s", bus_error_message(&error));
3804 dbus_error_free(&error);
3808 dbus_message_unref(reply);
3811 r = bus_method_call_with_reply (
3813 "org.freedesktop.systemd1",
3815 "org.freedesktop.DBus.Properties",
3819 DBUS_TYPE_STRING, &interface,
3820 DBUS_TYPE_STRING, &property,
3825 if (!dbus_message_iter_init(reply, &iter) ||
3826 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3827 log_error("Failed to parse reply.");
3831 dbus_message_iter_recurse(&iter, &sub);
3833 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3834 log_error("Failed to parse reply.");
3838 dbus_message_iter_get_basic(&sub, &id);
3846 static int delete_snapshot(DBusConnection *bus, char **args) {
3851 STRV_FOREACH(name, args+1) {
3852 _cleanup_free_ char *n = NULL;
3855 n = unit_name_mangle_with_suffix(*name, ".snapshot");
3859 r = bus_method_call_with_reply(
3861 "org.freedesktop.systemd1",
3862 "/org/freedesktop/systemd1",
3863 "org.freedesktop.systemd1.Manager",
3867 DBUS_TYPE_STRING, &n,
3876 static int daemon_reload(DBusConnection *bus, char **args) {
3881 if (arg_action == ACTION_RELOAD)
3883 else if (arg_action == ACTION_REEXEC)
3884 method = "Reexecute";
3886 assert(arg_action == ACTION_SYSTEMCTL);
3889 streq(args[0], "clear-jobs") ||
3890 streq(args[0], "cancel") ? "ClearJobs" :
3891 streq(args[0], "daemon-reexec") ? "Reexecute" :
3892 streq(args[0], "reset-failed") ? "ResetFailed" :
3893 streq(args[0], "halt") ? "Halt" :
3894 streq(args[0], "poweroff") ? "PowerOff" :
3895 streq(args[0], "reboot") ? "Reboot" :
3896 streq(args[0], "kexec") ? "KExec" :
3897 streq(args[0], "exit") ? "Exit" :
3898 /* "daemon-reload" */ "Reload";
3901 r = bus_method_call_with_reply(
3903 "org.freedesktop.systemd1",
3904 "/org/freedesktop/systemd1",
3905 "org.freedesktop.systemd1.Manager",
3911 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
3912 /* There's always a fallback possible for
3913 * legacy actions. */
3915 else if (r == -ETIMEDOUT && streq(method, "Reexecute"))
3916 /* On reexecution, we expect a disconnect, not
3920 log_error("Failed to issue method call: %s", bus_error_message(&error));
3922 dbus_error_free(&error);
3926 static int reset_failed(DBusConnection *bus, char **args) {
3930 if (strv_length(args) <= 1)
3931 return daemon_reload(bus, args);
3933 STRV_FOREACH(name, args+1) {
3934 _cleanup_free_ char *n;
3936 n = unit_name_mangle(*name);
3940 r = bus_method_call_with_reply(
3942 "org.freedesktop.systemd1",
3943 "/org/freedesktop/systemd1",
3944 "org.freedesktop.systemd1.Manager",
3948 DBUS_TYPE_STRING, &n,
3957 static int show_enviroment(DBusConnection *bus, char **args) {
3958 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3959 DBusMessageIter iter, sub, sub2;
3962 *interface = "org.freedesktop.systemd1.Manager",
3963 *property = "Environment";
3965 pager_open_if_enabled();
3967 r = bus_method_call_with_reply(
3969 "org.freedesktop.systemd1",
3970 "/org/freedesktop/systemd1",
3971 "org.freedesktop.DBus.Properties",
3975 DBUS_TYPE_STRING, &interface,
3976 DBUS_TYPE_STRING, &property,
3981 if (!dbus_message_iter_init(reply, &iter) ||
3982 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3983 log_error("Failed to parse reply.");
3987 dbus_message_iter_recurse(&iter, &sub);
3989 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3990 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3991 log_error("Failed to parse reply.");
3995 dbus_message_iter_recurse(&sub, &sub2);
3997 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
4000 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
4001 log_error("Failed to parse reply.");
4005 dbus_message_iter_get_basic(&sub2, &text);
4008 dbus_message_iter_next(&sub2);
4014 static int switch_root(DBusConnection *bus, char **args) {
4017 _cleanup_free_ char *init = NULL;
4019 l = strv_length(args);
4020 if (l < 2 || l > 3) {
4021 log_error("Wrong number of arguments.");
4028 init = strdup(args[2]);
4030 parse_env_file("/proc/cmdline", WHITESPACE,
4040 log_debug("switching root - root: %s; init: %s", root, init);
4042 return bus_method_call_with_reply(
4044 "org.freedesktop.systemd1",
4045 "/org/freedesktop/systemd1",
4046 "org.freedesktop.systemd1.Manager",
4050 DBUS_TYPE_STRING, &root,
4051 DBUS_TYPE_STRING, &init,
4055 static int set_environment(DBusConnection *bus, char **args) {
4056 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
4059 DBusMessageIter iter;
4065 dbus_error_init(&error);
4067 method = streq(args[0], "set-environment")
4069 : "UnsetEnvironment";
4071 m = dbus_message_new_method_call(
4072 "org.freedesktop.systemd1",
4073 "/org/freedesktop/systemd1",
4074 "org.freedesktop.systemd1.Manager",
4079 dbus_message_iter_init_append(m, &iter);
4081 r = bus_append_strv_iter(&iter, args + 1);
4085 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4087 log_error("Failed to issue method call: %s", bus_error_message(&error));
4088 dbus_error_free(&error);
4095 static int enable_sysv_units(char **args) {
4098 #if defined(HAVE_SYSV_COMPAT) && defined(HAVE_CHKCONFIG)
4099 const char *verb = args[0];
4100 unsigned f = 1, t = 1;
4101 LookupPaths paths = {};
4103 if (arg_scope != UNIT_FILE_SYSTEM)
4106 if (!streq(verb, "enable") &&
4107 !streq(verb, "disable") &&
4108 !streq(verb, "is-enabled"))
4111 /* Processes all SysV units, and reshuffles the array so that
4112 * afterwards only the native units remain */
4114 r = lookup_paths_init(&paths, SYSTEMD_SYSTEM, false, NULL, NULL, NULL);
4119 for (f = 1; args[f]; f++) {
4121 _cleanup_free_ char *p = NULL, *q = NULL;
4122 bool found_native = false, found_sysv;
4124 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
4132 if (!endswith(name, ".service"))
4135 if (path_is_absolute(name))
4138 STRV_FOREACH(k, paths.unit_path) {
4139 if (!isempty(arg_root))
4140 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
4142 asprintf(&p, "%s/%s", *k, name);
4149 found_native = access(p, F_OK) >= 0;
4160 if (!isempty(arg_root))
4161 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
4163 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
4169 p[strlen(p) - sizeof(".service") + 1] = 0;
4170 found_sysv = access(p, F_OK) >= 0;
4175 /* Mark this entry, so that we don't try enabling it as native unit */
4176 args[f] = (char*) "";
4178 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
4180 if (!isempty(arg_root))
4181 argv[c++] = q = strappend("--root=", arg_root);
4183 argv[c++] = path_get_file_name(p);
4185 streq(verb, "enable") ? "on" :
4186 streq(verb, "disable") ? "off" : "--level=5";
4189 l = strv_join((char**)argv, " ");
4195 log_info("Executing %s", l);
4200 log_error("Failed to fork: %m");
4203 } else if (pid == 0) {
4206 execv(argv[0], (char**) argv);
4207 _exit(EXIT_FAILURE);
4210 j = wait_for_terminate(pid, &status);
4212 log_error("Failed to wait for child: %s", strerror(-r));
4217 if (status.si_code == CLD_EXITED) {
4218 if (streq(verb, "is-enabled")) {
4219 if (status.si_status == 0) {
4228 } else if (status.si_status != 0) {
4239 lookup_paths_free(&paths);
4241 /* Drop all SysV units */
4242 for (f = 1, t = 1; args[f]; f++) {
4244 if (isempty(args[f]))
4247 args[t++] = args[f];
4256 static int mangle_names(char **original_names, char ***mangled_names) {
4257 char **i, **l, **name;
4259 l = new(char*, strv_length(original_names) + 1);
4264 STRV_FOREACH(name, original_names) {
4266 /* When enabling units qualified path names are OK,
4267 * too, hence allow them explicitly. */
4272 *i = unit_name_mangle(*name);
4288 static int enable_unit(DBusConnection *bus, char **args) {
4289 const char *verb = args[0];
4290 UnitFileChange *changes = NULL;
4291 unsigned n_changes = 0, i;
4292 int carries_install_info = -1;
4293 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
4295 _cleanup_dbus_error_free_ DBusError error;
4296 _cleanup_strv_free_ char **mangled_names = NULL;
4298 dbus_error_init(&error);
4300 r = enable_sysv_units(args);
4307 r = mangle_names(args+1, &mangled_names);
4311 if (!bus || avoid_bus()) {
4312 if (streq(verb, "enable")) {
4313 r = unit_file_enable(arg_scope, arg_runtime, arg_root, mangled_names, arg_force, &changes, &n_changes);
4314 carries_install_info = r;
4315 } else if (streq(verb, "disable"))
4316 r = unit_file_disable(arg_scope, arg_runtime, arg_root, mangled_names, &changes, &n_changes);
4317 else if (streq(verb, "reenable")) {
4318 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, mangled_names, arg_force, &changes, &n_changes);
4319 carries_install_info = r;
4320 } else if (streq(verb, "link"))
4321 r = unit_file_link(arg_scope, arg_runtime, arg_root, mangled_names, arg_force, &changes, &n_changes);
4322 else if (streq(verb, "preset")) {
4323 r = unit_file_preset(arg_scope, arg_runtime, arg_root, mangled_names, arg_force, &changes, &n_changes);
4324 carries_install_info = r;
4325 } else if (streq(verb, "mask"))
4326 r = unit_file_mask(arg_scope, arg_runtime, arg_root, mangled_names, arg_force, &changes, &n_changes);
4327 else if (streq(verb, "unmask"))
4328 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, mangled_names, &changes, &n_changes);
4329 else if (streq(verb, "set-default"))
4330 r = unit_file_set_default(arg_scope, arg_root, args[1], &changes, &n_changes);
4332 assert_not_reached("Unknown verb");
4335 log_error("Operation failed: %s", strerror(-r));
4340 for (i = 0; i < n_changes; i++) {
4341 if (changes[i].type == UNIT_FILE_SYMLINK)
4342 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
4344 log_info("rm '%s'", changes[i].path);
4351 bool send_force = true, expect_carries_install_info = false;
4353 DBusMessageIter iter, sub, sub2;
4355 if (streq(verb, "enable")) {
4356 method = "EnableUnitFiles";
4357 expect_carries_install_info = true;
4358 } else if (streq(verb, "disable")) {
4359 method = "DisableUnitFiles";
4361 } else if (streq(verb, "reenable")) {
4362 method = "ReenableUnitFiles";
4363 expect_carries_install_info = true;
4364 } else if (streq(verb, "link"))
4365 method = "LinkUnitFiles";
4366 else if (streq(verb, "preset")) {
4367 method = "PresetUnitFiles";
4368 expect_carries_install_info = true;
4369 } else if (streq(verb, "mask"))
4370 method = "MaskUnitFiles";
4371 else if (streq(verb, "unmask")) {
4372 method = "UnmaskUnitFiles";
4374 } else if (streq(verb, "set-default")) {
4375 method = "SetDefaultTarget";
4377 assert_not_reached("Unknown verb");
4379 m = dbus_message_new_method_call(
4380 "org.freedesktop.systemd1",
4381 "/org/freedesktop/systemd1",
4382 "org.freedesktop.systemd1.Manager",
4389 dbus_message_iter_init_append(m, &iter);
4391 r = bus_append_strv_iter(&iter, mangled_names);
4393 log_error("Failed to append unit files.");
4398 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
4399 log_error("Failed to append runtime boolean.");
4407 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
4408 log_error("Failed to append force boolean.");
4414 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4416 log_error("Failed to issue method call: %s", bus_error_message(&error));
4421 if (!dbus_message_iter_init(reply, &iter)) {
4422 log_error("Failed to initialize iterator.");
4426 if (expect_carries_install_info) {
4427 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
4429 log_error("Failed to parse reply.");
4433 carries_install_info = b;
4436 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
4437 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
4438 log_error("Failed to parse reply.");
4443 dbus_message_iter_recurse(&iter, &sub);
4444 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
4445 const char *type, *path, *source;
4447 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
4448 log_error("Failed to parse reply.");
4453 dbus_message_iter_recurse(&sub, &sub2);
4455 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
4456 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
4457 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
4458 log_error("Failed to parse reply.");
4464 if (streq(type, "symlink"))
4465 log_info("ln -s '%s' '%s'", source, path);
4467 log_info("rm '%s'", path);
4470 dbus_message_iter_next(&sub);
4473 /* Try to reload if enabeld */
4475 r = daemon_reload(bus, args);
4478 if (carries_install_info == 0)
4479 log_warning("The unit files have no [Install] section. They are not meant to be enabled\n"
4480 "using systemctl.\n"
4481 "Possible reasons for having this kind of units are:\n"
4482 "1) A unit may be statically enabled by being symlinked from another unit's\n"
4483 " .wants/ or .requires/ directory.\n"
4484 "2) A unit's purpose may be to act as a helper for some other unit which has\n"
4485 " a requirement dependency on it.\n"
4486 "3) A unit may be started when needed via activation (socket, path, timer,\n"
4487 " D-Bus, udev, scripted systemctl call, ...).\n");
4490 unit_file_changes_free(changes, n_changes);
4495 static int set_log_level(DBusConnection *bus, char **args) {
4496 _cleanup_dbus_error_free_ DBusError error;
4497 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
4498 DBusMessageIter iter, sub;
4499 const char* property = "LogLevel";
4500 const char* interface = "org.freedesktop.systemd1.Manager";
4507 dbus_error_init(&error);
4509 m = dbus_message_new_method_call("org.freedesktop.systemd1",
4510 "/org/freedesktop/systemd1",
4511 "org.freedesktop.DBus.Properties",
4516 dbus_message_iter_init_append(m, &iter);
4518 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &interface) ||
4519 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &property) ||
4520 !dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, "s", &sub))
4523 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &value)) {
4524 dbus_message_iter_abandon_container(&iter, &sub);
4528 if (!dbus_message_iter_close_container(&iter, &sub))
4531 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4533 log_error("Failed to issue method call: %s", bus_error_message(&error));
4540 static int unit_is_enabled(DBusConnection *bus, char **args) {
4541 _cleanup_dbus_error_free_ DBusError error;
4543 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
4548 dbus_error_init(&error);
4550 r = enable_sysv_units(args);
4556 if (!bus || avoid_bus()) {
4558 STRV_FOREACH(name, args+1) {
4559 UnitFileState state;
4561 n = unit_name_mangle(*name);
4565 state = unit_file_get_state(arg_scope, arg_root, n);
4572 if (state == UNIT_FILE_ENABLED ||
4573 state == UNIT_FILE_ENABLED_RUNTIME ||
4574 state == UNIT_FILE_STATIC)
4578 puts(unit_file_state_to_string(state));
4582 STRV_FOREACH(name, args+1) {
4585 n = unit_name_mangle(*name);
4589 r = bus_method_call_with_reply (
4591 "org.freedesktop.systemd1",
4592 "/org/freedesktop/systemd1",
4593 "org.freedesktop.systemd1.Manager",
4597 DBUS_TYPE_STRING, &n,
4605 if (!dbus_message_get_args(reply, &error,
4606 DBUS_TYPE_STRING, &s,
4607 DBUS_TYPE_INVALID)) {
4608 log_error("Failed to parse reply: %s", bus_error_message(&error));
4612 dbus_message_unref(reply);
4615 if (streq(s, "enabled") ||
4616 streq(s, "enabled-runtime") ||
4625 return enabled ? 0 : 1;
4628 static int systemctl_help(void) {
4630 pager_open_if_enabled();
4632 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4633 "Query or send control commands to the systemd manager.\n\n"
4634 " -h --help Show this help\n"
4635 " --version Show package version\n"
4636 " -t --type=TYPE List only units of a particular type\n"
4637 " -p --property=NAME Show only properties by this name\n"
4638 " -a --all Show all loaded units/properties, including dead/empty\n"
4639 " ones. To list all units installed on the system, use\n"
4640 " the 'list-unit-files' command instead.\n"
4641 " --reverse Show reverse dependencies with 'list-dependencies'\n"
4642 " --failed Show only failed units\n"
4643 " -l --full Don't ellipsize unit names on output\n"
4644 " --fail When queueing a new job, fail if conflicting jobs are\n"
4646 " --irreversible Create jobs which cannot be implicitly cancelled\n"
4647 " --show-types When showing sockets, explicitly show their type\n"
4648 " --ignore-dependencies\n"
4649 " When queueing a new job, ignore all its dependencies\n"
4650 " -i --ignore-inhibitors\n"
4651 " When shutting down or sleeping, ignore inhibitors\n"
4652 " --kill-who=WHO Who to send signal to\n"
4653 " -s --signal=SIGNAL Which signal to send\n"
4654 " -H --host=[USER@]HOST\n"
4655 " Show information for remote host\n"
4656 " -P --privileged Acquire privileges before execution\n"
4657 " -q --quiet Suppress output\n"
4658 " --no-block Do not wait until operation finished\n"
4659 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4660 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4662 " --no-legend Do not print a legend (column headers and hints)\n"
4663 " --no-pager Do not pipe output into a pager\n"
4664 " --no-ask-password\n"
4665 " Do not ask for system passwords\n"
4666 " --system Connect to system manager\n"
4667 " --user Connect to user service manager\n"
4668 " --global Enable/disable unit files globally\n"
4669 " -f --force When enabling unit files, override existing symlinks\n"
4670 " When shutting down, execute action immediately\n"
4671 " --root=PATH Enable unit files in the specified root directory\n"
4672 " --runtime Enable unit files only temporarily until next reboot\n"
4673 " -n --lines=INTEGER Journal entries to show\n"
4674 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
4675 " verbose, export, json, json-pretty, json-sse, cat)\n\n"
4677 " list-units List loaded units\n"
4678 " list-sockets List loaded sockets ordered by address\n"
4679 " start [NAME...] Start (activate) one or more units\n"
4680 " stop [NAME...] Stop (deactivate) one or more units\n"
4681 " reload [NAME...] Reload one or more units\n"
4682 " restart [NAME...] Start or restart one or more units\n"
4683 " try-restart [NAME...] Restart one or more units if active\n"
4684 " reload-or-restart [NAME...] Reload one or more units if possible,\n"
4685 " otherwise start or restart\n"
4686 " reload-or-try-restart [NAME...] Reload one or more units if possible,\n"
4687 " otherwise restart if active\n"
4688 " isolate [NAME] Start one unit and stop all others\n"
4689 " kill [NAME...] Send signal to processes of a unit\n"
4690 " is-active [NAME...] Check whether units are active\n"
4691 " is-failed [NAME...] Check whether units are failed\n"
4692 " status [NAME...|PID...] Show runtime status of one or more units\n"
4693 " show [NAME...|JOB...] Show properties of one or more\n"
4694 " units/jobs or the manager\n"
4695 " set-property [NAME] [ASSIGNMENT...]\n"
4696 " Sets one or more properties of a unit\n"
4697 " help [NAME...|PID...] Show manual for one or more units\n"
4698 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4700 " load [NAME...] Load one or more units\n"
4701 " list-dependencies [NAME] Recursively show units which are required\n"
4702 " or wanted by this unit or by which this\n"
4703 " unit is required or wanted\n\n"
4704 "Unit File Commands:\n"
4705 " list-unit-files List installed unit files\n"
4706 " enable [NAME...] Enable one or more unit files\n"
4707 " disable [NAME...] Disable one or more unit files\n"
4708 " reenable [NAME...] Reenable one or more unit files\n"
4709 " preset [NAME...] Enable/disable one or more unit files\n"
4710 " based on preset configuration\n"
4711 " mask [NAME...] Mask one or more units\n"
4712 " unmask [NAME...] Unmask one or more units\n"
4713 " link [PATH...] Link one or more units files into\n"
4714 " the search path\n"
4715 " get-default Get the name of the default target\n"
4716 " set-default NAME Set the default target\n"
4717 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
4719 " list-jobs List jobs\n"
4720 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
4721 "Status Commands:\n"
4722 " dump Dump server status\n"
4723 "Snapshot Commands:\n"
4724 " snapshot [NAME] Create a snapshot\n"
4725 " delete [NAME...] Remove one or more snapshots\n\n"
4726 "Environment Commands:\n"
4727 " show-environment Dump environment\n"
4728 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4729 " unset-environment [NAME...] Unset one or more environment variables\n"
4730 " set-log-level LEVEL Set logging threshold for systemd\n\n"
4731 "Manager Lifecycle Commands:\n"
4732 " daemon-reload Reload systemd manager configuration\n"
4733 " daemon-reexec Reexecute systemd manager\n\n"
4734 "System Commands:\n"
4735 " default Enter system default mode\n"
4736 " rescue Enter system rescue mode\n"
4737 " emergency Enter system emergency mode\n"
4738 " halt Shut down and halt the system\n"
4739 " poweroff Shut down and power-off the system\n"
4740 " reboot Shut down and reboot the system\n"
4741 " kexec Shut down and reboot the system with kexec\n"
4742 " exit Request user instance exit\n"
4743 " switch-root [ROOT] [INIT] Change to a different root file system\n"
4744 " suspend Suspend the system\n"
4745 " hibernate Hibernate the system\n"
4746 " hybrid-sleep Hibernate and suspend the system\n",
4747 program_invocation_short_name);
4752 static int halt_help(void) {
4754 printf("%s [OPTIONS...]\n\n"
4755 "%s the system.\n\n"
4756 " --help Show this help\n"
4757 " --halt Halt the machine\n"
4758 " -p --poweroff Switch off the machine\n"
4759 " --reboot Reboot the machine\n"
4760 " -f --force Force immediate halt/power-off/reboot\n"
4761 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4762 " -d --no-wtmp Don't write wtmp record\n"
4763 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4764 program_invocation_short_name,
4765 arg_action == ACTION_REBOOT ? "Reboot" :
4766 arg_action == ACTION_POWEROFF ? "Power off" :
4772 static int shutdown_help(void) {
4774 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4775 "Shut down the system.\n\n"
4776 " --help Show this help\n"
4777 " -H --halt Halt the machine\n"
4778 " -P --poweroff Power-off the machine\n"
4779 " -r --reboot Reboot the machine\n"
4780 " -h Equivalent to --poweroff, overridden by --halt\n"
4781 " -k Don't halt/power-off/reboot, just send warnings\n"
4782 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4783 " -c Cancel a pending shutdown\n",
4784 program_invocation_short_name);
4789 static int telinit_help(void) {
4791 printf("%s [OPTIONS...] {COMMAND}\n\n"
4792 "Send control commands to the init daemon.\n\n"
4793 " --help Show this help\n"
4794 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4796 " 0 Power-off the machine\n"
4797 " 6 Reboot the machine\n"
4798 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4799 " 1, s, S Enter rescue mode\n"
4800 " q, Q Reload init daemon configuration\n"
4801 " u, U Reexecute init daemon\n",
4802 program_invocation_short_name);
4807 static int runlevel_help(void) {
4809 printf("%s [OPTIONS...]\n\n"
4810 "Prints the previous and current runlevel of the init system.\n\n"
4811 " --help Show this help\n",
4812 program_invocation_short_name);
4817 static int help_types(void) {
4821 puts("Available unit types:");
4822 for(i = 0; i < _UNIT_TYPE_MAX; i++) {
4823 t = unit_type_to_string(i);
4828 puts("\nAvailable unit load states: ");
4829 for(i = 0; i < _UNIT_LOAD_STATE_MAX; i++) {
4830 t = unit_load_state_to_string(i);
4838 static int systemctl_parse_argv(int argc, char *argv[]) {
4847 ARG_IGNORE_DEPENDENCIES,
4859 ARG_NO_ASK_PASSWORD,
4866 static const struct option options[] = {
4867 { "help", no_argument, NULL, 'h' },
4868 { "version", no_argument, NULL, ARG_VERSION },
4869 { "type", required_argument, NULL, 't' },
4870 { "property", required_argument, NULL, 'p' },
4871 { "all", no_argument, NULL, 'a' },
4872 { "reverse", no_argument, NULL, ARG_REVERSE },
4873 { "after", no_argument, NULL, ARG_AFTER },
4874 { "before", no_argument, NULL, ARG_BEFORE },
4875 { "show-types", no_argument, NULL, ARG_SHOW_TYPES },
4876 { "failed", no_argument, NULL, ARG_FAILED },
4877 { "full", no_argument, NULL, 'l' },
4878 { "fail", no_argument, NULL, ARG_FAIL },
4879 { "irreversible", no_argument, NULL, ARG_IRREVERSIBLE },
4880 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4881 { "ignore-inhibitors", no_argument, NULL, 'i' },
4882 { "user", no_argument, NULL, ARG_USER },
4883 { "system", no_argument, NULL, ARG_SYSTEM },
4884 { "global", no_argument, NULL, ARG_GLOBAL },
4885 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4886 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4887 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4888 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4889 { "quiet", no_argument, NULL, 'q' },
4890 { "root", required_argument, NULL, ARG_ROOT },
4891 { "force", no_argument, NULL, ARG_FORCE },
4892 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4893 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4894 { "signal", required_argument, NULL, 's' },
4895 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4896 { "host", required_argument, NULL, 'H' },
4897 { "privileged",no_argument, NULL, 'P' },
4898 { "runtime", no_argument, NULL, ARG_RUNTIME },
4899 { "lines", required_argument, NULL, 'n' },
4900 { "output", required_argument, NULL, 'o' },
4901 { "plain", no_argument, NULL, ARG_PLAIN },
4902 { NULL, 0, NULL, 0 }
4910 while ((c = getopt_long(argc, argv, "ht:p:alqfs:H:Pn:o:i", options, NULL)) >= 0) {
4919 puts(PACKAGE_STRING);
4920 puts(SYSTEMD_FEATURES);
4927 FOREACH_WORD_SEPARATOR(word, size, optarg, ",", state) {
4928 _cleanup_free_ char *type;
4930 type = strndup(word, size);
4934 if (streq(type, "help")) {
4939 if (unit_type_from_string(type) >= 0) {
4940 if (strv_push(&arg_types, type))
4946 if (unit_load_state_from_string(optarg) >= 0) {
4947 if (strv_push(&arg_load_states, type))
4953 log_error("Unknown unit type or load state '%s'.", type);
4954 log_info("Use -t help to see a list of allowed values.");
4962 /* Make sure that if the empty property list
4963 was specified, we won't show any properties. */
4964 if (isempty(optarg) && !arg_properties) {
4965 arg_properties = strv_new(NULL, NULL);
4966 if (!arg_properties)
4972 FOREACH_WORD_SEPARATOR(word, size, optarg, ",", state) {
4975 prop = strndup(word, size);
4979 if (strv_push(&arg_properties, prop)) {
4986 /* If the user asked for a particular
4987 * property, show it to him, even if it is
4999 arg_dependency = DEPENDENCY_REVERSE;
5003 arg_dependency = DEPENDENCY_AFTER;
5007 arg_dependency = DEPENDENCY_BEFORE;
5010 case ARG_SHOW_TYPES:
5011 arg_show_types = true;
5015 arg_job_mode = "fail";
5018 case ARG_IRREVERSIBLE:
5019 arg_job_mode = "replace-irreversibly";
5022 case ARG_IGNORE_DEPENDENCIES:
5023 arg_job_mode = "ignore-dependencies";
5027 arg_scope = UNIT_FILE_USER;
5031 arg_scope = UNIT_FILE_SYSTEM;
5035 arg_scope = UNIT_FILE_GLOBAL;
5039 arg_no_block = true;
5043 arg_no_legend = true;
5047 arg_no_pager = true;
5079 arg_no_reload = true;
5083 arg_kill_who = optarg;
5087 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
5088 log_error("Failed to parse signal string %s.", optarg);
5093 case ARG_NO_ASK_PASSWORD:
5094 arg_ask_password = false;
5098 arg_transport = TRANSPORT_POLKIT;
5102 arg_transport = TRANSPORT_SSH;
5103 parse_user_at_host(optarg, &arg_user, &arg_host);
5111 if (safe_atou(optarg, &arg_lines) < 0) {
5112 log_error("Failed to parse lines '%s'", optarg);
5118 arg_output = output_mode_from_string(optarg);
5119 if (arg_output < 0) {
5120 log_error("Unknown output '%s'.", optarg);
5126 arg_ignore_inhibitors = true;
5137 log_error("Unknown option code '%c'.", c);
5142 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
5143 log_error("Cannot access user instance remotely.");
5150 static int halt_parse_argv(int argc, char *argv[]) {
5159 static const struct option options[] = {
5160 { "help", no_argument, NULL, ARG_HELP },
5161 { "halt", no_argument, NULL, ARG_HALT },
5162 { "poweroff", no_argument, NULL, 'p' },
5163 { "reboot", no_argument, NULL, ARG_REBOOT },
5164 { "force", no_argument, NULL, 'f' },
5165 { "wtmp-only", no_argument, NULL, 'w' },
5166 { "no-wtmp", no_argument, NULL, 'd' },
5167 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5168 { NULL, 0, NULL, 0 }
5176 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
5177 if (runlevel == '0' || runlevel == '6')
5180 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
5188 arg_action = ACTION_HALT;
5192 if (arg_action != ACTION_REBOOT)
5193 arg_action = ACTION_POWEROFF;
5197 arg_action = ACTION_REBOOT;
5219 /* Compatibility nops */
5226 log_error("Unknown option code '%c'.", c);
5231 if (optind < argc) {
5232 log_error("Too many arguments.");
5239 static int parse_time_spec(const char *t, usec_t *_u) {
5243 if (streq(t, "now"))
5245 else if (!strchr(t, ':')) {
5248 if (safe_atou64(t, &u) < 0)
5251 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
5260 hour = strtol(t, &e, 10);
5261 if (errno > 0 || *e != ':' || hour < 0 || hour > 23)
5264 minute = strtol(e+1, &e, 10);
5265 if (errno > 0 || *e != 0 || minute < 0 || minute > 59)
5268 n = now(CLOCK_REALTIME);
5269 s = (time_t) (n / USEC_PER_SEC);
5271 assert_se(localtime_r(&s, &tm));
5273 tm.tm_hour = (int) hour;
5274 tm.tm_min = (int) minute;
5277 assert_se(s = mktime(&tm));
5279 *_u = (usec_t) s * USEC_PER_SEC;
5282 *_u += USEC_PER_DAY;
5288 static int shutdown_parse_argv(int argc, char *argv[]) {
5295 static const struct option options[] = {
5296 { "help", no_argument, NULL, ARG_HELP },
5297 { "halt", no_argument, NULL, 'H' },
5298 { "poweroff", no_argument, NULL, 'P' },
5299 { "reboot", no_argument, NULL, 'r' },
5300 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
5301 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5302 { NULL, 0, NULL, 0 }
5310 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
5318 arg_action = ACTION_HALT;
5322 arg_action = ACTION_POWEROFF;
5327 arg_action = ACTION_KEXEC;
5329 arg_action = ACTION_REBOOT;
5333 arg_action = ACTION_KEXEC;
5337 if (arg_action != ACTION_HALT)
5338 arg_action = ACTION_POWEROFF;
5351 /* Compatibility nops */
5355 arg_action = ACTION_CANCEL_SHUTDOWN;
5362 log_error("Unknown option code '%c'.", c);
5367 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
5368 r = parse_time_spec(argv[optind], &arg_when);
5370 log_error("Failed to parse time specification: %s", argv[optind]);
5374 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
5376 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
5377 /* No time argument for shutdown cancel */
5378 arg_wall = argv + optind;
5379 else if (argc > optind + 1)
5380 /* We skip the time argument */
5381 arg_wall = argv + optind + 1;
5388 static int telinit_parse_argv(int argc, char *argv[]) {
5395 static const struct option options[] = {
5396 { "help", no_argument, NULL, ARG_HELP },
5397 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5398 { NULL, 0, NULL, 0 }
5401 static const struct {
5405 { '0', ACTION_POWEROFF },
5406 { '6', ACTION_REBOOT },
5407 { '1', ACTION_RESCUE },
5408 { '2', ACTION_RUNLEVEL2 },
5409 { '3', ACTION_RUNLEVEL3 },
5410 { '4', ACTION_RUNLEVEL4 },
5411 { '5', ACTION_RUNLEVEL5 },
5412 { 's', ACTION_RESCUE },
5413 { 'S', ACTION_RESCUE },
5414 { 'q', ACTION_RELOAD },
5415 { 'Q', ACTION_RELOAD },
5416 { 'u', ACTION_REEXEC },
5417 { 'U', ACTION_REEXEC }
5426 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5441 log_error("Unknown option code '%c'.", c);
5446 if (optind >= argc) {
5451 if (optind + 1 < argc) {
5452 log_error("Too many arguments.");
5456 if (strlen(argv[optind]) != 1) {
5457 log_error("Expected single character argument.");
5461 for (i = 0; i < ELEMENTSOF(table); i++)
5462 if (table[i].from == argv[optind][0])
5465 if (i >= ELEMENTSOF(table)) {
5466 log_error("Unknown command '%s'.", argv[optind]);
5470 arg_action = table[i].to;
5477 static int runlevel_parse_argv(int argc, char *argv[]) {
5483 static const struct option options[] = {
5484 { "help", no_argument, NULL, ARG_HELP },
5485 { NULL, 0, NULL, 0 }
5493 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5504 log_error("Unknown option code '%c'.", c);
5509 if (optind < argc) {
5510 log_error("Too many arguments.");
5517 static int parse_argv(int argc, char *argv[]) {
5521 if (program_invocation_short_name) {
5523 if (strstr(program_invocation_short_name, "halt")) {
5524 arg_action = ACTION_HALT;
5525 return halt_parse_argv(argc, argv);
5526 } else if (strstr(program_invocation_short_name, "poweroff")) {
5527 arg_action = ACTION_POWEROFF;
5528 return halt_parse_argv(argc, argv);
5529 } else if (strstr(program_invocation_short_name, "reboot")) {
5531 arg_action = ACTION_KEXEC;
5533 arg_action = ACTION_REBOOT;
5534 return halt_parse_argv(argc, argv);
5535 } else if (strstr(program_invocation_short_name, "shutdown")) {
5536 arg_action = ACTION_POWEROFF;
5537 return shutdown_parse_argv(argc, argv);
5538 } else if (strstr(program_invocation_short_name, "init")) {
5540 if (sd_booted() > 0) {
5541 arg_action = ACTION_INVALID;
5542 return telinit_parse_argv(argc, argv);
5544 /* Hmm, so some other init system is
5545 * running, we need to forward this
5546 * request to it. For now we simply
5547 * guess that it is Upstart. */
5549 execv(TELINIT, argv);
5551 log_error("Couldn't find an alternative telinit implementation to spawn.");
5555 } else if (strstr(program_invocation_short_name, "runlevel")) {
5556 arg_action = ACTION_RUNLEVEL;
5557 return runlevel_parse_argv(argc, argv);
5561 arg_action = ACTION_SYSTEMCTL;
5562 return systemctl_parse_argv(argc, argv);
5565 _pure_ static int action_to_runlevel(void) {
5567 static const char table[_ACTION_MAX] = {
5568 [ACTION_HALT] = '0',
5569 [ACTION_POWEROFF] = '0',
5570 [ACTION_REBOOT] = '6',
5571 [ACTION_RUNLEVEL2] = '2',
5572 [ACTION_RUNLEVEL3] = '3',
5573 [ACTION_RUNLEVEL4] = '4',
5574 [ACTION_RUNLEVEL5] = '5',
5575 [ACTION_RESCUE] = '1'
5578 assert(arg_action < _ACTION_MAX);
5580 return table[arg_action];
5583 static int talk_upstart(void) {
5584 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
5585 _cleanup_dbus_error_free_ DBusError error;
5586 int previous, rl, r;
5588 env1_buf[] = "RUNLEVEL=X",
5589 env2_buf[] = "PREVLEVEL=X";
5590 char *env1 = env1_buf, *env2 = env2_buf;
5591 const char *emit = "runlevel";
5592 dbus_bool_t b_false = FALSE;
5593 DBusMessageIter iter, sub;
5594 DBusConnection *bus;
5596 dbus_error_init(&error);
5598 if (!(rl = action_to_runlevel()))
5601 if (utmp_get_runlevel(&previous, NULL) < 0)
5604 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5605 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5610 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5615 if ((r = bus_check_peercred(bus)) < 0) {
5616 log_error("Failed to verify owner of bus.");
5620 if (!(m = dbus_message_new_method_call(
5621 "com.ubuntu.Upstart",
5622 "/com/ubuntu/Upstart",
5623 "com.ubuntu.Upstart0_6",
5626 log_error("Could not allocate message.");
5631 dbus_message_iter_init_append(m, &iter);
5633 env1_buf[sizeof(env1_buf)-2] = rl;
5634 env2_buf[sizeof(env2_buf)-2] = previous;
5636 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5637 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5638 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5639 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5640 !dbus_message_iter_close_container(&iter, &sub) ||
5641 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5642 log_error("Could not append arguments to message.");
5647 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5649 if (bus_error_is_no_service(&error)) {
5654 log_error("Failed to issue method call: %s", bus_error_message(&error));
5663 dbus_connection_flush(bus);
5664 dbus_connection_close(bus);
5665 dbus_connection_unref(bus);
5671 static int talk_initctl(void) {
5672 struct init_request request = {};
5674 _cleanup_close_ int fd = -1;
5677 rl = action_to_runlevel();
5681 request.magic = INIT_MAGIC;
5682 request.sleeptime = 0;
5683 request.cmd = INIT_CMD_RUNLVL;
5684 request.runlevel = rl;
5686 fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY);
5688 if (errno == ENOENT)
5691 log_error("Failed to open "INIT_FIFO": %m");
5696 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5698 log_error("Failed to write to "INIT_FIFO": %m");
5699 return errno > 0 ? -errno : -EIO;
5705 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5707 static const struct {
5715 int (* const dispatch)(DBusConnection *bus, char **args);
5717 { "list-units", LESS, 1, list_units },
5718 { "list-unit-files", EQUAL, 1, list_unit_files },
5719 { "list-sockets", LESS, 1, list_sockets },
5720 { "list-jobs", EQUAL, 1, list_jobs },
5721 { "clear-jobs", EQUAL, 1, daemon_reload },
5722 { "load", MORE, 2, load_unit },
5723 { "cancel", MORE, 2, cancel_job },
5724 { "start", MORE, 2, start_unit },
5725 { "stop", MORE, 2, start_unit },
5726 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5727 { "reload", MORE, 2, start_unit },
5728 { "restart", MORE, 2, start_unit },
5729 { "try-restart", MORE, 2, start_unit },
5730 { "reload-or-restart", MORE, 2, start_unit },
5731 { "reload-or-try-restart", MORE, 2, start_unit },
5732 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5733 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5734 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5735 { "isolate", EQUAL, 2, start_unit },
5736 { "kill", MORE, 2, kill_unit },
5737 { "is-active", MORE, 2, check_unit_active },
5738 { "check", MORE, 2, check_unit_active },
5739 { "is-failed", MORE, 2, check_unit_failed },
5740 { "show", MORE, 1, show },
5741 { "status", MORE, 1, show },
5742 { "help", MORE, 2, show },
5743 { "dump", EQUAL, 1, dump },
5744 { "snapshot", LESS, 2, snapshot },
5745 { "delete", MORE, 2, delete_snapshot },
5746 { "daemon-reload", EQUAL, 1, daemon_reload },
5747 { "daemon-reexec", EQUAL, 1, daemon_reload },
5748 { "show-environment", EQUAL, 1, show_enviroment },
5749 { "set-environment", MORE, 2, set_environment },
5750 { "unset-environment", MORE, 2, set_environment },
5751 { "halt", EQUAL, 1, start_special },
5752 { "poweroff", EQUAL, 1, start_special },
5753 { "reboot", EQUAL, 1, start_special },
5754 { "kexec", EQUAL, 1, start_special },
5755 { "suspend", EQUAL, 1, start_special },
5756 { "hibernate", EQUAL, 1, start_special },
5757 { "hybrid-sleep", EQUAL, 1, start_special },
5758 { "default", EQUAL, 1, start_special },
5759 { "rescue", EQUAL, 1, start_special },
5760 { "emergency", EQUAL, 1, start_special },
5761 { "exit", EQUAL, 1, start_special },
5762 { "reset-failed", MORE, 1, reset_failed },
5763 { "enable", MORE, 2, enable_unit },
5764 { "disable", MORE, 2, enable_unit },
5765 { "is-enabled", MORE, 2, unit_is_enabled },
5766 { "reenable", MORE, 2, enable_unit },
5767 { "preset", MORE, 2, enable_unit },
5768 { "mask", MORE, 2, enable_unit },
5769 { "unmask", MORE, 2, enable_unit },
5770 { "link", MORE, 2, enable_unit },
5771 { "switch-root", MORE, 2, switch_root },
5772 { "list-dependencies", LESS, 2, list_dependencies },
5773 { "set-default", EQUAL, 2, enable_unit },
5774 { "get-default", LESS, 1, get_default },
5775 { "set-log-level", EQUAL, 2, set_log_level },
5776 { "set-property", MORE, 3, set_property },
5786 left = argc - optind;
5789 /* Special rule: no arguments means "list-units" */
5792 if (streq(argv[optind], "help") && !argv[optind+1]) {
5793 log_error("This command expects one or more "
5794 "unit names. Did you mean --help?");
5798 for (i = 0; i < ELEMENTSOF(verbs); i++)
5799 if (streq(argv[optind], verbs[i].verb))
5802 if (i >= ELEMENTSOF(verbs)) {
5803 log_error("Unknown operation '%s'.", argv[optind]);
5808 switch (verbs[i].argc_cmp) {
5811 if (left != verbs[i].argc) {
5812 log_error("Invalid number of arguments.");
5819 if (left < verbs[i].argc) {
5820 log_error("Too few arguments.");
5827 if (left > verbs[i].argc) {
5828 log_error("Too many arguments.");
5835 assert_not_reached("Unknown comparison operator.");
5838 /* Require a bus connection for all operations but
5840 if (!streq(verbs[i].verb, "enable") &&
5841 !streq(verbs[i].verb, "disable") &&
5842 !streq(verbs[i].verb, "is-enabled") &&
5843 !streq(verbs[i].verb, "list-unit-files") &&
5844 !streq(verbs[i].verb, "reenable") &&
5845 !streq(verbs[i].verb, "preset") &&
5846 !streq(verbs[i].verb, "mask") &&
5847 !streq(verbs[i].verb, "unmask") &&
5848 !streq(verbs[i].verb, "link") &&
5849 !streq(verbs[i].verb, "set-default") &&
5850 !streq(verbs[i].verb, "get-default")) {
5852 if (running_in_chroot() > 0) {
5853 log_info("Running in chroot, ignoring request.");
5857 if (((!streq(verbs[i].verb, "reboot") &&
5858 !streq(verbs[i].verb, "halt") &&
5859 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5860 log_error("Failed to get D-Bus connection: %s",
5861 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5867 if (!bus && !avoid_bus()) {
5868 log_error("Failed to get D-Bus connection: %s",
5869 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5874 return verbs[i].dispatch(bus, argv + optind);
5877 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5878 _cleanup_close_ int fd;
5879 struct sd_shutdown_command c = {
5885 union sockaddr_union sockaddr = {
5886 .un.sun_family = AF_UNIX,
5887 .un.sun_path = "/run/systemd/shutdownd",
5889 struct iovec iovec[2] = {
5890 {.iov_base = (char*) &c,
5891 .iov_len = offsetof(struct sd_shutdown_command, wall_message),
5894 struct msghdr msghdr = {
5895 .msg_name = &sockaddr,
5896 .msg_namelen = offsetof(struct sockaddr_un, sun_path)
5897 + sizeof("/run/systemd/shutdownd") - 1,
5902 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5906 if (!isempty(message)) {
5907 iovec[1].iov_base = (char*) message;
5908 iovec[1].iov_len = strlen(message);
5909 msghdr.msg_iovlen++;
5912 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0)
5918 static int reload_with_fallback(DBusConnection *bus) {
5921 /* First, try systemd via D-Bus. */
5922 if (daemon_reload(bus, NULL) >= 0)
5926 /* Nothing else worked, so let's try signals */
5927 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5929 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5930 log_error("kill() failed: %m");
5937 static int start_with_fallback(DBusConnection *bus) {
5940 /* First, try systemd via D-Bus. */
5941 if (start_unit(bus, NULL) >= 0)
5945 /* Hmm, talking to systemd via D-Bus didn't work. Then
5946 * let's try to talk to Upstart via D-Bus. */
5947 if (talk_upstart() > 0)
5950 /* Nothing else worked, so let's try
5952 if (talk_initctl() > 0)
5955 log_error("Failed to talk to init daemon.");
5959 warn_wall(arg_action);
5963 static _noreturn_ void halt_now(enum action a) {
5965 /* Make sure C-A-D is handled by the kernel from this
5967 reboot(RB_ENABLE_CAD);
5972 log_info("Halting.");
5973 reboot(RB_HALT_SYSTEM);
5976 case ACTION_POWEROFF:
5977 log_info("Powering off.");
5978 reboot(RB_POWER_OFF);
5982 log_info("Rebooting.");
5983 reboot(RB_AUTOBOOT);
5987 assert_not_reached("Unknown halt action.");
5990 assert_not_reached("Uh? This shouldn't happen.");
5993 static int halt_main(DBusConnection *bus) {
5996 r = check_inhibitors(bus, arg_action);
6000 if (geteuid() != 0) {
6001 /* Try logind if we are a normal user and no special
6002 * mode applies. Maybe PolicyKit allows us to shutdown
6005 if (arg_when <= 0 &&
6008 (arg_action == ACTION_POWEROFF ||
6009 arg_action == ACTION_REBOOT)) {
6010 r = reboot_with_logind(bus, arg_action);
6015 log_error("Must be root.");
6020 _cleanup_free_ char *m;
6022 m = strv_join(arg_wall, " ");
6023 r = send_shutdownd(arg_when,
6024 arg_action == ACTION_HALT ? 'H' :
6025 arg_action == ACTION_POWEROFF ? 'P' :
6026 arg_action == ACTION_KEXEC ? 'K' :
6033 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
6035 char date[FORMAT_TIMESTAMP_MAX];
6037 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
6038 format_timestamp(date, sizeof(date), arg_when));
6043 if (!arg_dry && !arg_force)
6044 return start_with_fallback(bus);
6047 if (sd_booted() > 0)
6048 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
6050 r = utmp_put_shutdown();
6052 log_warning("Failed to write utmp record: %s", strerror(-r));
6059 halt_now(arg_action);
6060 /* We should never reach this. */
6064 static int runlevel_main(void) {
6065 int r, runlevel, previous;
6067 r = utmp_get_runlevel(&runlevel, &previous);
6074 previous <= 0 ? 'N' : previous,
6075 runlevel <= 0 ? 'N' : runlevel);
6080 int main(int argc, char*argv[]) {
6081 int r, retval = EXIT_FAILURE;
6082 DBusConnection *bus = NULL;
6083 _cleanup_dbus_error_free_ DBusError error;
6085 dbus_error_init(&error);
6087 setlocale(LC_ALL, "");
6088 log_parse_environment();
6091 r = parse_argv(argc, argv);
6095 retval = EXIT_SUCCESS;
6099 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
6100 * let's shortcut this */
6101 if (arg_action == ACTION_RUNLEVEL) {
6102 r = runlevel_main();
6103 retval = r < 0 ? EXIT_FAILURE : r;
6107 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
6108 log_info("Running in chroot, ignoring request.");
6114 if (arg_transport == TRANSPORT_NORMAL)
6115 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
6116 else if (arg_transport == TRANSPORT_POLKIT) {
6117 bus_connect_system_polkit(&bus, &error);
6118 private_bus = false;
6119 } else if (arg_transport == TRANSPORT_SSH) {
6120 bus_connect_system_ssh(arg_user, arg_host, &bus, &error);
6121 private_bus = false;
6123 assert_not_reached("Uh, invalid transport...");
6126 switch (arg_action) {
6128 case ACTION_SYSTEMCTL:
6129 r = systemctl_main(bus, argc, argv, &error);
6133 case ACTION_POWEROFF:
6139 case ACTION_RUNLEVEL2:
6140 case ACTION_RUNLEVEL3:
6141 case ACTION_RUNLEVEL4:
6142 case ACTION_RUNLEVEL5:
6144 case ACTION_EMERGENCY:
6145 case ACTION_DEFAULT:
6146 r = start_with_fallback(bus);
6151 r = reload_with_fallback(bus);
6154 case ACTION_CANCEL_SHUTDOWN: {
6158 m = strv_join(arg_wall, " ");
6160 retval = EXIT_FAILURE;
6164 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
6166 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
6171 case ACTION_INVALID:
6172 case ACTION_RUNLEVEL:
6174 assert_not_reached("Unknown action");
6177 retval = r < 0 ? EXIT_FAILURE : r;
6181 dbus_connection_flush(bus);
6182 dbus_connection_close(bus);
6183 dbus_connection_unref(bus);
6188 strv_free(arg_types);
6189 strv_free(arg_load_states);
6190 strv_free(arg_properties);
6193 ask_password_agent_close();
6194 polkit_agent_close();