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_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_runtime = false;
97 static char **arg_wall = NULL;
98 static const char *arg_kill_who = NULL;
99 static int arg_signal = SIGTERM;
100 static const char *arg_root = NULL;
101 static usec_t arg_when = 0;
123 ACTION_CANCEL_SHUTDOWN,
125 } arg_action = ACTION_SYSTEMCTL;
126 static enum transport {
130 } arg_transport = TRANSPORT_NORMAL;
131 static char *arg_host = NULL;
132 static char *arg_user = NULL;
133 static unsigned arg_lines = 10;
134 static OutputMode arg_output = OUTPUT_SHORT;
135 static bool arg_plain = false;
137 static bool private_bus = false;
139 static int daemon_reload(DBusConnection *bus, char **args);
140 static void halt_now(enum action a);
142 static void pager_open_if_enabled(void) {
150 static void ask_password_agent_open_if_enabled(void) {
152 /* Open the password agent as a child process if necessary */
154 if (!arg_ask_password)
157 if (arg_scope != UNIT_FILE_SYSTEM)
160 ask_password_agent_open();
164 static void polkit_agent_open_if_enabled(void) {
166 /* Open the polkit agent as a child process if necessary */
168 if (!arg_ask_password)
171 if (arg_scope != UNIT_FILE_SYSTEM)
178 static const char *ansi_highlight(bool b) {
183 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
186 static const char *ansi_highlight_red(bool b) {
191 return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
194 static const char *ansi_highlight_green(bool b) {
199 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
202 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
205 if (!dbus_error_is_set(error))
208 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
209 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
210 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
211 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
212 return EXIT_NOPERMISSION;
214 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
215 return EXIT_NOTINSTALLED;
217 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
218 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
219 return EXIT_NOTIMPLEMENTED;
221 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
222 return EXIT_NOTCONFIGURED;
230 static void warn_wall(enum action a) {
231 static const char *table[_ACTION_MAX] = {
232 [ACTION_HALT] = "The system is going down for system halt NOW!",
233 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
234 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
235 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
236 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
237 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!",
238 [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
245 _cleanup_free_ char *p;
247 p = strv_join(arg_wall, " ");
262 utmp_wall(table[a], NULL);
265 static bool avoid_bus(void) {
267 if (running_in_chroot() > 0)
270 if (sd_booted() <= 0)
273 if (!isempty(arg_root))
276 if (arg_scope == UNIT_FILE_GLOBAL)
282 static int compare_unit_info(const void *a, const void *b) {
284 const struct unit_info *u = a, *v = b;
286 d1 = strrchr(u->id, '.');
287 d2 = strrchr(v->id, '.');
292 r = strcasecmp(d1, d2);
297 return strcasecmp(u->id, v->id);
300 static bool output_show_unit(const struct unit_info *u) {
303 if (!strv_isempty(arg_states))
304 return strv_contains(arg_states, u->load_state) || strv_contains(arg_states, u->sub_state) || strv_contains(arg_states, u->active_state);
306 return (!arg_types || ((dot = strrchr(u->id, '.')) &&
307 strv_find(arg_types, dot+1))) &&
308 (arg_all || !(streq(u->active_state, "inactive")
309 || u->following[0]) || u->job_id > 0);
312 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
313 unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
314 const struct unit_info *u;
317 max_id_len = sizeof("UNIT")-1;
318 active_len = sizeof("ACTIVE")-1;
319 sub_len = sizeof("SUB")-1;
320 job_len = sizeof("JOB")-1;
323 for (u = unit_infos; u < unit_infos + c; u++) {
324 if (!output_show_unit(u))
327 max_id_len = MAX(max_id_len, strlen(u->id));
328 active_len = MAX(active_len, strlen(u->active_state));
329 sub_len = MAX(sub_len, strlen(u->sub_state));
330 if (u->job_id != 0) {
331 job_len = MAX(job_len, strlen(u->job_type));
338 id_len = MIN(max_id_len, 25u);
339 basic_len = 5 + id_len + 5 + active_len + sub_len;
341 basic_len += job_len + 1;
342 if (basic_len < (unsigned) columns()) {
343 unsigned extra_len, incr;
344 extra_len = columns() - basic_len;
345 /* Either UNIT already got 25, or is fully satisfied.
346 * Grant up to 25 to DESC now. */
347 incr = MIN(extra_len, 25u);
350 /* split the remaining space between UNIT and DESC,
351 * but do not give UNIT more than it needs. */
353 incr = MIN(extra_len / 2, max_id_len - id_len);
355 desc_len += extra_len - incr;
361 for (u = unit_infos; u < unit_infos + c; u++) {
362 _cleanup_free_ char *e = NULL;
363 const char *on_loaded, *off_loaded, *on = "";
364 const char *on_active, *off_active, *off = "";
366 if (!output_show_unit(u))
369 if (!n_shown && !arg_no_legend) {
370 printf("%-*s %-6s %-*s %-*s ", id_len, "UNIT", "LOAD",
371 active_len, "ACTIVE", sub_len, "SUB");
373 printf("%-*s ", job_len, "JOB");
374 if (!arg_full && arg_no_pager)
375 printf("%.*s\n", desc_len, "DESCRIPTION");
377 printf("%s\n", "DESCRIPTION");
382 if (streq(u->load_state, "error") ||
383 streq(u->load_state, "not-found")) {
384 on_loaded = on = ansi_highlight_red(true);
385 off_loaded = off = ansi_highlight_red(false);
387 on_loaded = off_loaded = "";
389 if (streq(u->active_state, "failed")) {
390 on_active = on = ansi_highlight_red(true);
391 off_active = off = ansi_highlight_red(false);
393 on_active = off_active = "";
395 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
397 printf("%s%-*s%s %s%-6s%s %s%-*s %-*s%s %-*s",
398 on, id_len, e ? e : u->id, off,
399 on_loaded, u->load_state, off_loaded,
400 on_active, active_len, u->active_state,
401 sub_len, u->sub_state, off_active,
402 job_count ? job_len + 1 : 0, u->job_id ? u->job_type : "");
403 if (!arg_full && arg_no_pager)
404 printf("%.*s\n", desc_len, u->description);
406 printf("%s\n", u->description);
409 if (!arg_no_legend) {
410 const char *on, *off;
413 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
414 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
415 "SUB = The low-level unit activation state, values depend on unit type.\n");
417 printf("JOB = Pending job for the unit.\n");
419 on = ansi_highlight(true);
420 off = ansi_highlight(false);
422 on = ansi_highlight_red(true);
423 off = ansi_highlight_red(false);
427 printf("%s%u loaded units listed.%s\n"
428 "To show all installed unit files use 'systemctl list-unit-files'.\n",
431 printf("%s%u loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
432 "To show all installed unit files use 'systemctl list-unit-files'.\n",
437 static int get_unit_list(
440 struct unit_info **unit_infos,
443 DBusMessageIter iter, sub;
451 r = bus_method_call_with_reply(
453 "org.freedesktop.systemd1",
454 "/org/freedesktop/systemd1",
455 "org.freedesktop.systemd1.Manager",
463 if (!dbus_message_iter_init(*reply, &iter) ||
464 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
465 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
466 log_error("Failed to parse reply.");
470 dbus_message_iter_recurse(&iter, &sub);
472 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
473 if (!GREEDY_REALLOC(*unit_infos, size, *c + 1))
476 bus_parse_unit_info(&sub, *unit_infos + *c);
479 dbus_message_iter_next(&sub);
485 static int list_units(DBusConnection *bus, char **args) {
486 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
487 _cleanup_free_ struct unit_info *unit_infos = NULL;
491 pager_open_if_enabled();
493 r = get_unit_list(bus, &reply, &unit_infos, &c);
497 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
499 output_units_list(unit_infos, c);
504 static int get_triggered_units(
506 const char* unit_path,
509 const char *interface = "org.freedesktop.systemd1.Unit",
510 *triggers_property = "Triggers";
511 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
512 DBusMessageIter iter, sub;
515 r = bus_method_call_with_reply(bus,
516 "org.freedesktop.systemd1",
518 "org.freedesktop.DBus.Properties",
522 DBUS_TYPE_STRING, &interface,
523 DBUS_TYPE_STRING, &triggers_property,
528 if (!dbus_message_iter_init(reply, &iter) ||
529 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
530 log_error("Failed to parse reply.");
534 dbus_message_iter_recurse(&iter, &sub);
535 dbus_message_iter_recurse(&sub, &iter);
538 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
541 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
542 log_error("Failed to parse reply.");
546 dbus_message_iter_get_basic(&sub, &unit);
547 r = strv_extend(triggered, unit);
551 dbus_message_iter_next(&sub);
557 static int get_listening(DBusConnection *bus, const char* unit_path,
558 char*** listen, unsigned *c)
560 const char *interface = "org.freedesktop.systemd1.Socket",
561 *listen_property = "Listen";
562 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
563 DBusMessageIter iter, sub;
566 r = bus_method_call_with_reply(bus,
567 "org.freedesktop.systemd1",
569 "org.freedesktop.DBus.Properties",
573 DBUS_TYPE_STRING, &interface,
574 DBUS_TYPE_STRING, &listen_property,
579 if (!dbus_message_iter_init(reply, &iter) ||
580 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
581 log_error("Failed to parse reply.");
585 dbus_message_iter_recurse(&iter, &sub);
586 dbus_message_iter_recurse(&sub, &iter);
589 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
590 DBusMessageIter sub2;
591 const char *type, *path;
593 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
594 log_error("Failed to parse reply.");
598 dbus_message_iter_recurse(&sub, &sub2);
600 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
601 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0) {
602 r = strv_extend(listen, type);
606 r = strv_extend(listen, path);
613 dbus_message_iter_next(&sub);
625 /* Note: triggered is a list here, although it almost certainly
626 * will always be one unit. Nevertheless, dbus API allows for multiple
627 * values, so let's follow that.*/
630 /* The strv above is shared. free is set only in the first one. */
634 static int socket_info_compare(struct socket_info *a, struct socket_info *b) {
635 int o = strcmp(a->path, b->path);
637 o = strcmp(a->type, b->type);
641 static int output_sockets_list(struct socket_info *socket_infos, unsigned cs) {
642 struct socket_info *s;
643 unsigned pathlen = sizeof("LISTEN") - 1,
644 typelen = (sizeof("TYPE") - 1) * arg_show_types,
645 socklen = sizeof("UNIT") - 1,
646 servlen = sizeof("ACTIVATES") - 1;
647 const char *on, *off;
649 for (s = socket_infos; s < socket_infos + cs; s++) {
653 socklen = MAX(socklen, strlen(s->id));
655 typelen = MAX(typelen, strlen(s->type));
656 pathlen = MAX(pathlen, strlen(s->path));
658 STRV_FOREACH(a, s->triggered)
659 tmp += strlen(*a) + 2*(a != s->triggered);
660 servlen = MAX(servlen, tmp);
665 printf("%-*s %-*.*s%-*s %s\n",
667 typelen + arg_show_types, typelen + arg_show_types, "TYPE ",
671 for (s = socket_infos; s < socket_infos + cs; s++) {
675 printf("%-*s %-*s %-*s",
676 pathlen, s->path, typelen, s->type, socklen, s->id);
679 pathlen, s->path, socklen, s->id);
680 STRV_FOREACH(a, s->triggered)
682 a == s->triggered ? "" : ",", *a);
686 on = ansi_highlight(true);
687 off = ansi_highlight(false);
691 on = ansi_highlight_red(true);
692 off = ansi_highlight_red(false);
695 if (!arg_no_legend) {
696 printf("%s%u sockets listed.%s\n", on, cs, off);
698 printf("Pass --all to see loaded but inactive sockets, too.\n");
704 static int list_sockets(DBusConnection *bus, char **args) {
705 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
706 _cleanup_free_ struct unit_info *unit_infos = NULL;
707 struct socket_info *socket_infos = NULL;
708 const struct unit_info *u;
709 struct socket_info *s;
710 unsigned cu = 0, cs = 0;
714 pager_open_if_enabled();
716 r = get_unit_list(bus, &reply, &unit_infos, &cu);
720 for (u = unit_infos; u < unit_infos + cu; u++) {
722 _cleanup_strv_free_ char **listen = NULL, **triggered = NULL;
725 if (!output_show_unit(u))
728 if ((dot = strrchr(u->id, '.')) && !streq(dot+1, "socket"))
731 r = get_triggered_units(bus, u->unit_path, &triggered);
735 r = get_listening(bus, u->unit_path, &listen, &c);
739 if (!GREEDY_REALLOC(socket_infos, size, cs + c)) {
744 for (i = 0; i < c; i++)
745 socket_infos[cs + i] = (struct socket_info) {
748 .path = listen[i*2 + 1],
749 .triggered = triggered,
750 .own_triggered = i==0,
753 /* from this point on we will cleanup those socket_infos */
756 listen = triggered = NULL; /* avoid cleanup */
759 qsort(socket_infos, cs, sizeof(struct socket_info),
760 (__compar_fn_t) socket_info_compare);
762 output_sockets_list(socket_infos, cs);
765 assert(cs == 0 || socket_infos);
766 for (s = socket_infos; s < socket_infos + cs; s++) {
769 if (s->own_triggered)
770 strv_free(s->triggered);
777 static int compare_unit_file_list(const void *a, const void *b) {
779 const UnitFileList *u = a, *v = b;
781 d1 = strrchr(u->path, '.');
782 d2 = strrchr(v->path, '.');
787 r = strcasecmp(d1, d2);
792 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
795 static bool output_show_unit_file(const UnitFileList *u) {
798 return !arg_types || ((dot = strrchr(u->path, '.')) && strv_find(arg_types, dot+1));
801 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
802 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
803 const UnitFileList *u;
805 max_id_len = sizeof("UNIT FILE")-1;
806 state_cols = sizeof("STATE")-1;
807 for (u = units; u < units + c; u++) {
808 if (!output_show_unit_file(u))
811 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
812 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
817 id_cols = MIN(max_id_len, 25u);
818 basic_cols = 1 + id_cols + state_cols;
819 if (basic_cols < (unsigned) columns())
820 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
822 id_cols = max_id_len;
825 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
827 for (u = units; u < units + c; u++) {
828 _cleanup_free_ char *e = NULL;
829 const char *on, *off;
832 if (!output_show_unit_file(u))
837 if (u->state == UNIT_FILE_MASKED ||
838 u->state == UNIT_FILE_MASKED_RUNTIME ||
839 u->state == UNIT_FILE_DISABLED ||
840 u->state == UNIT_FILE_INVALID) {
841 on = ansi_highlight_red(true);
842 off = ansi_highlight_red(false);
843 } else if (u->state == UNIT_FILE_ENABLED) {
844 on = ansi_highlight_green(true);
845 off = ansi_highlight_green(false);
849 id = path_get_file_name(u->path);
851 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
853 printf("%-*s %s%-*s%s\n",
855 on, state_cols, unit_file_state_to_string(u->state), off);
859 printf("\n%u unit files listed.\n", n_shown);
862 static int list_unit_files(DBusConnection *bus, char **args) {
863 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
864 _cleanup_free_ UnitFileList *units = NULL;
865 DBusMessageIter iter, sub, sub2;
866 unsigned c = 0, n_units = 0;
869 pager_open_if_enabled();
876 h = hashmap_new(string_hash_func, string_compare_func);
880 r = unit_file_get_list(arg_scope, arg_root, h);
882 unit_file_list_free(h);
883 log_error("Failed to get unit file list: %s", strerror(-r));
887 n_units = hashmap_size(h);
888 units = new(UnitFileList, n_units);
890 unit_file_list_free(h);
894 HASHMAP_FOREACH(u, h, i) {
895 memcpy(units + c++, u, sizeof(UnitFileList));
901 r = bus_method_call_with_reply(
903 "org.freedesktop.systemd1",
904 "/org/freedesktop/systemd1",
905 "org.freedesktop.systemd1.Manager",
913 if (!dbus_message_iter_init(reply, &iter) ||
914 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
915 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
916 log_error("Failed to parse reply.");
920 dbus_message_iter_recurse(&iter, &sub);
922 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
926 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT);
931 n_units = MAX(2*c, 16u);
932 w = realloc(units, sizeof(struct UnitFileList) * n_units);
941 dbus_message_iter_recurse(&sub, &sub2);
943 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
944 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
945 log_error("Failed to parse reply.");
949 u->state = unit_file_state_from_string(state);
951 dbus_message_iter_next(&sub);
957 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
958 output_unit_file_list(units, c);
964 static int list_dependencies_print(const char *name, int level, unsigned int branches, bool last) {
966 _cleanup_free_ char *n = NULL;
968 size_t max_len = MAX(columns(),20u);
971 for (i = level - 1; i >= 0; i--) {
973 if(len > max_len - 3 && !arg_full) {
974 printf("%s...\n",max_len % 2 ? "" : " ");
977 printf("%s", draw_special_char(branches & (1 << i) ? DRAW_TREE_VERT : DRAW_TREE_SPACE));
980 if(len > max_len - 3 && !arg_full) {
981 printf("%s...\n",max_len % 2 ? "" : " ");
984 printf("%s", draw_special_char(last ? DRAW_TREE_RIGHT : DRAW_TREE_BRANCH));
988 printf("%s\n", name);
992 n = ellipsize(name, max_len-len, 100);
1000 static int list_dependencies_get_dependencies(DBusConnection *bus, const char *name, char ***deps) {
1001 static const char *dependencies[] = {
1002 [DEPENDENCY_FORWARD] = "Requires\0"
1003 "RequiresOverridable\0"
1005 "RequisiteOverridable\0"
1007 [DEPENDENCY_REVERSE] = "RequiredBy\0"
1008 "RequiredByOverridable\0"
1011 [DEPENDENCY_AFTER] = "After\0",
1012 [DEPENDENCY_BEFORE] = "Before\0",
1015 _cleanup_free_ char *path;
1016 const char *interface = "org.freedesktop.systemd1.Unit";
1018 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1019 DBusMessageIter iter, sub, sub2, sub3;
1028 path = unit_dbus_path_from_name(name);
1034 r = bus_method_call_with_reply(
1036 "org.freedesktop.systemd1",
1038 "org.freedesktop.DBus.Properties",
1042 DBUS_TYPE_STRING, &interface,
1047 if (!dbus_message_iter_init(reply, &iter) ||
1048 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1049 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
1050 log_error("Failed to parse reply.");
1055 dbus_message_iter_recurse(&iter, &sub);
1057 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1060 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
1061 dbus_message_iter_recurse(&sub, &sub2);
1063 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
1064 log_error("Failed to parse reply.");
1069 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
1070 log_error("Failed to parse reply.");
1075 dbus_message_iter_recurse(&sub2, &sub3);
1076 dbus_message_iter_next(&sub);
1078 assert(arg_dependency < ELEMENTSOF(dependencies));
1079 if (!nulstr_contains(dependencies[arg_dependency], prop))
1082 if (dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_ARRAY) {
1083 if (dbus_message_iter_get_element_type(&sub3) == DBUS_TYPE_STRING) {
1084 DBusMessageIter sub4;
1085 dbus_message_iter_recurse(&sub3, &sub4);
1087 while (dbus_message_iter_get_arg_type(&sub4) != DBUS_TYPE_INVALID) {
1090 assert(dbus_message_iter_get_arg_type(&sub4) == DBUS_TYPE_STRING);
1091 dbus_message_iter_get_basic(&sub4, &s);
1093 r = strv_extend(&ret, s);
1099 dbus_message_iter_next(&sub4);
1112 static int list_dependencies_compare(const void *_a, const void *_b) {
1113 const char **a = (const char**) _a, **b = (const char**) _b;
1114 if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET)
1116 if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET)
1118 return strcasecmp(*a, *b);
1121 static int list_dependencies_one(DBusConnection *bus, const char *name, int level, char ***units, unsigned int branches) {
1122 _cleanup_strv_free_ char **deps = NULL, **u;
1126 u = strv_append(*units, name);
1130 r = list_dependencies_get_dependencies(bus, name, &deps);
1134 qsort(deps, strv_length(deps), sizeof (char*), list_dependencies_compare);
1136 STRV_FOREACH(c, deps) {
1137 if (strv_contains(u, *c)) {
1139 r = list_dependencies_print("...", level + 1, (branches << 1) | (c[1] == NULL ? 0 : 1), 1);
1146 r = list_dependencies_print(*c, level, branches, c[1] == NULL);
1150 if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) {
1151 r = list_dependencies_one(bus, *c, level + 1, &u, (branches << 1) | (c[1] == NULL ? 0 : 1));
1164 static int list_dependencies(DBusConnection *bus, char **args) {
1165 _cleanup_free_ char *unit = NULL;
1166 _cleanup_strv_free_ char **units = NULL;
1172 unit = unit_name_mangle(args[1]);
1177 u = SPECIAL_DEFAULT_TARGET;
1179 pager_open_if_enabled();
1183 return list_dependencies_one(bus, u, 0, &units, 0);
1186 static int get_default(DBusConnection *bus, char **args) {
1188 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1190 _cleanup_dbus_error_free_ DBusError error;
1192 dbus_error_init(&error);
1194 if (!bus || avoid_bus()) {
1195 r = unit_file_get_default(arg_scope, arg_root, &path);
1198 log_error("Operation failed: %s", strerror(-r));
1204 r = bus_method_call_with_reply(
1206 "org.freedesktop.systemd1",
1207 "/org/freedesktop/systemd1",
1208 "org.freedesktop.systemd1.Manager",
1215 log_error("Operation failed: %s", strerror(-r));
1219 if (!dbus_message_get_args(reply, &error,
1220 DBUS_TYPE_STRING, &path,
1221 DBUS_TYPE_INVALID)) {
1222 log_error("Failed to parse reply: %s", bus_error_message(&error));
1223 dbus_error_free(&error);
1229 printf("%s\n", path);
1232 if ((!bus || avoid_bus()) && path)
1241 char *name, *type, *state;
1244 static void list_jobs_print(struct job_info* jobs, size_t n) {
1247 const char *on, *off;
1248 bool shorten = false;
1250 assert(n == 0 || jobs);
1253 on = ansi_highlight_green(true);
1254 off = ansi_highlight_green(false);
1256 printf("%sNo jobs running.%s\n", on, off);
1260 pager_open_if_enabled();
1263 /* JOB UNIT TYPE STATE */
1264 unsigned l0 = 3, l1 = 4, l2 = 4, l3 = 5;
1266 for (i = 0, j = jobs; i < n; i++, j++) {
1267 assert(j->name && j->type && j->state);
1268 l0 = MAX(l0, DECIMAL_STR_WIDTH(j->id));
1269 l1 = MAX(l1, strlen(j->name));
1270 l2 = MAX(l2, strlen(j->type));
1271 l3 = MAX(l3, strlen(j->state));
1274 if (!arg_full && l0 + 1 + l1 + l2 + 1 + l3 > columns()) {
1275 l1 = MAX(33u, columns() - l0 - l2 - l3 - 3);
1280 printf("%*s %-*s %-*s %-*s\n",
1286 for (i = 0, j = jobs; i < n; i++, j++) {
1287 _cleanup_free_ char *e = NULL;
1289 if (streq(j->state, "running")) {
1290 on = ansi_highlight(true);
1291 off = ansi_highlight(false);
1295 e = shorten ? ellipsize(j->name, l1, 33) : NULL;
1296 printf("%*u %s%-*s%s %-*s %s%-*s%s\n",
1298 on, l1, e ? e : j->name, off,
1300 on, l3, j->state, off);
1304 on = ansi_highlight(true);
1305 off = ansi_highlight(false);
1308 printf("\n%s%zu jobs listed%s.\n", on, n, off);
1311 static int list_jobs(DBusConnection *bus, char **args) {
1312 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1313 DBusMessageIter iter, sub, sub2;
1315 struct job_info *jobs = NULL;
1316 size_t size = 0, used = 0;
1318 r = bus_method_call_with_reply(
1320 "org.freedesktop.systemd1",
1321 "/org/freedesktop/systemd1",
1322 "org.freedesktop.systemd1.Manager",
1330 if (!dbus_message_iter_init(reply, &iter) ||
1331 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1332 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1333 log_error("Failed to parse reply.");
1337 dbus_message_iter_recurse(&iter, &sub);
1339 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1340 const char *name, *type, *state, *job_path, *unit_path;
1343 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1344 log_error("Failed to parse reply.");
1348 dbus_message_iter_recurse(&sub, &sub2);
1350 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
1351 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
1352 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
1353 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
1354 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
1355 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
1356 log_error("Failed to parse reply.");
1361 if (!GREEDY_REALLOC(jobs, size, used + 1)) {
1366 jobs[used++] = (struct job_info) { id,
1370 if (!jobs[used-1].name || !jobs[used-1].type || !jobs[used-1].state) {
1375 dbus_message_iter_next(&sub);
1378 list_jobs_print(jobs, used);
1382 free(jobs[used].name);
1383 free(jobs[used].type);
1384 free(jobs[used].state);
1391 static int load_unit(DBusConnection *bus, char **args) {
1396 STRV_FOREACH(name, args+1) {
1397 _cleanup_free_ char *n = NULL;
1400 n = unit_name_mangle(*name);
1404 r = bus_method_call_with_reply(
1406 "org.freedesktop.systemd1",
1407 "/org/freedesktop/systemd1",
1408 "org.freedesktop.systemd1.Manager",
1412 DBUS_TYPE_STRING, &n,
1421 static int cancel_job(DBusConnection *bus, char **args) {
1426 if (strv_length(args) <= 1)
1427 return daemon_reload(bus, args);
1429 STRV_FOREACH(name, args+1) {
1433 r = safe_atou32(*name, &id);
1435 log_error("Failed to parse job id: %s", strerror(-r));
1439 r = bus_method_call_with_reply(
1441 "org.freedesktop.systemd1",
1442 "/org/freedesktop/systemd1",
1443 "org.freedesktop.systemd1.Manager",
1447 DBUS_TYPE_UINT32, &id,
1456 static int need_daemon_reload(DBusConnection *bus, const char *unit) {
1457 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1458 _cleanup_dbus_error_free_ DBusError error;
1459 dbus_bool_t b = FALSE;
1460 DBusMessageIter iter, sub;
1462 *interface = "org.freedesktop.systemd1.Unit",
1463 *property = "NeedDaemonReload",
1465 _cleanup_free_ char *n = NULL;
1468 dbus_error_init(&error);
1470 /* We ignore all errors here, since this is used to show a warning only */
1472 n = unit_name_mangle(unit);
1476 r = bus_method_call_with_reply(
1478 "org.freedesktop.systemd1",
1479 "/org/freedesktop/systemd1",
1480 "org.freedesktop.systemd1.Manager",
1484 DBUS_TYPE_STRING, &n,
1489 if (!dbus_message_get_args(reply, NULL,
1490 DBUS_TYPE_OBJECT_PATH, &path,
1494 dbus_message_unref(reply);
1497 r = bus_method_call_with_reply(
1499 "org.freedesktop.systemd1",
1501 "org.freedesktop.DBus.Properties",
1505 DBUS_TYPE_STRING, &interface,
1506 DBUS_TYPE_STRING, &property,
1511 if (!dbus_message_iter_init(reply, &iter) ||
1512 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1515 dbus_message_iter_recurse(&iter, &sub);
1516 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1519 dbus_message_iter_get_basic(&sub, &b);
1523 typedef struct WaitData {
1530 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1531 _cleanup_dbus_error_free_ DBusError error;
1534 dbus_error_init(&error);
1540 log_debug("Got D-Bus request: %s.%s() on %s",
1541 dbus_message_get_interface(message),
1542 dbus_message_get_member(message),
1543 dbus_message_get_path(message));
1545 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1546 log_error("Warning! D-Bus connection terminated.");
1547 dbus_connection_close(connection);
1549 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1551 const char *path, *result, *unit;
1553 if (dbus_message_get_args(message, &error,
1554 DBUS_TYPE_UINT32, &id,
1555 DBUS_TYPE_OBJECT_PATH, &path,
1556 DBUS_TYPE_STRING, &unit,
1557 DBUS_TYPE_STRING, &result,
1558 DBUS_TYPE_INVALID)) {
1560 free(set_remove(d->set, (char*) path));
1562 if (!isempty(result))
1563 d->result = strdup(result);
1566 d->name = strdup(unit);
1568 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1571 dbus_error_free(&error);
1572 if (dbus_message_get_args(message, &error,
1573 DBUS_TYPE_UINT32, &id,
1574 DBUS_TYPE_OBJECT_PATH, &path,
1575 DBUS_TYPE_STRING, &result,
1576 DBUS_TYPE_INVALID)) {
1577 /* Compatibility with older systemd versions <
1578 * 183 during upgrades. This should be dropped
1580 free(set_remove(d->set, (char*) path));
1583 d->result = strdup(result);
1585 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1589 log_error("Failed to parse message: %s", bus_error_message(&error));
1592 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1595 static int enable_wait_for_jobs(DBusConnection *bus) {
1603 dbus_error_init(&error);
1604 dbus_bus_add_match(bus,
1606 "sender='org.freedesktop.systemd1',"
1607 "interface='org.freedesktop.systemd1.Manager',"
1608 "member='JobRemoved',"
1609 "path='/org/freedesktop/systemd1'",
1612 if (dbus_error_is_set(&error)) {
1613 log_error("Failed to add match: %s", bus_error_message(&error));
1614 dbus_error_free(&error);
1618 /* This is slightly dirty, since we don't undo the match registrations. */
1622 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1624 WaitData d = { .set = s };
1629 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL))
1632 while (!set_isempty(s)) {
1634 if (!dbus_connection_read_write_dispatch(bus, -1)) {
1635 log_error("Disconnected from bus.");
1636 return -ECONNREFUSED;
1643 if (streq(d.result, "timeout"))
1644 log_error("Job for %s timed out.", strna(d.name));
1645 else if (streq(d.result, "canceled"))
1646 log_error("Job for %s canceled.", strna(d.name));
1647 else if (streq(d.result, "dependency"))
1648 log_error("A dependency job for %s failed. See 'journalctl -xn' for details.", strna(d.name));
1649 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1650 log_error("Job for %s failed. See 'systemctl status %s' and 'journalctl -xn' for details.", strna(d.name), strna(d.name));
1653 if (streq_ptr(d.result, "timeout"))
1655 else if (streq_ptr(d.result, "canceled"))
1657 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1668 dbus_connection_remove_filter(bus, wait_filter, &d);
1672 static int check_one_unit(DBusConnection *bus, const char *name, char **check_states, bool quiet) {
1673 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1674 _cleanup_free_ char *n = NULL;
1675 DBusMessageIter iter, sub;
1677 *interface = "org.freedesktop.systemd1.Unit",
1678 *property = "ActiveState";
1679 const char *state, *path;
1685 dbus_error_init(&error);
1687 n = unit_name_mangle(name);
1691 r = bus_method_call_with_reply (
1693 "org.freedesktop.systemd1",
1694 "/org/freedesktop/systemd1",
1695 "org.freedesktop.systemd1.Manager",
1699 DBUS_TYPE_STRING, &n,
1702 dbus_error_free(&error);
1709 if (!dbus_message_get_args(reply, NULL,
1710 DBUS_TYPE_OBJECT_PATH, &path,
1711 DBUS_TYPE_INVALID)) {
1712 log_error("Failed to parse reply.");
1716 dbus_message_unref(reply);
1719 r = bus_method_call_with_reply(
1721 "org.freedesktop.systemd1",
1723 "org.freedesktop.DBus.Properties",
1727 DBUS_TYPE_STRING, &interface,
1728 DBUS_TYPE_STRING, &property,
1736 if (!dbus_message_iter_init(reply, &iter) ||
1737 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1738 log_error("Failed to parse reply.");
1742 dbus_message_iter_recurse(&iter, &sub);
1744 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1745 log_error("Failed to parse reply.");
1749 dbus_message_iter_get_basic(&sub, &state);
1754 return strv_find(check_states, state) ? 1 : 0;
1757 static void check_triggering_units(
1758 DBusConnection *bus,
1759 const char *unit_name) {
1761 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1762 DBusMessageIter iter, sub;
1763 const char *interface = "org.freedesktop.systemd1.Unit",
1764 *load_state_property = "LoadState",
1765 *triggered_by_property = "TriggeredBy",
1767 _cleanup_free_ char *unit_path = NULL, *n = NULL;
1768 bool print_warning_label = true;
1771 n = unit_name_mangle(unit_name);
1777 unit_path = unit_dbus_path_from_name(n);
1783 r = bus_method_call_with_reply(
1785 "org.freedesktop.systemd1",
1787 "org.freedesktop.DBus.Properties",
1791 DBUS_TYPE_STRING, &interface,
1792 DBUS_TYPE_STRING, &load_state_property,
1797 if (!dbus_message_iter_init(reply, &iter) ||
1798 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1799 log_error("Failed to parse reply.");
1803 dbus_message_iter_recurse(&iter, &sub);
1805 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1806 log_error("Failed to parse reply.");
1810 dbus_message_iter_get_basic(&sub, &state);
1812 if (streq(state, "masked"))
1815 dbus_message_unref(reply);
1818 r = bus_method_call_with_reply(
1820 "org.freedesktop.systemd1",
1822 "org.freedesktop.DBus.Properties",
1826 DBUS_TYPE_STRING, &interface,
1827 DBUS_TYPE_STRING, &triggered_by_property,
1832 if (!dbus_message_iter_init(reply, &iter) ||
1833 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1834 log_error("Failed to parse reply.");
1838 dbus_message_iter_recurse(&iter, &sub);
1839 dbus_message_iter_recurse(&sub, &iter);
1842 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1843 const char * const check_states[] = {
1848 const char *service_trigger;
1850 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1851 log_error("Failed to parse reply.");
1855 dbus_message_iter_get_basic(&sub, &service_trigger);
1857 r = check_one_unit(bus, service_trigger, (char**) check_states, true);
1861 if (print_warning_label) {
1862 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1863 print_warning_label = false;
1866 log_warning(" %s", service_trigger);
1869 dbus_message_iter_next(&sub);
1873 static int start_unit_one(
1874 DBusConnection *bus,
1881 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1882 _cleanup_free_ char *n;
1891 n = unit_name_mangle(name);
1895 r = bus_method_call_with_reply(
1897 "org.freedesktop.systemd1",
1898 "/org/freedesktop/systemd1",
1899 "org.freedesktop.systemd1.Manager",
1903 DBUS_TYPE_STRING, &n,
1904 DBUS_TYPE_STRING, &mode,
1907 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
1908 /* There's always a fallback possible for
1909 * legacy actions. */
1912 log_error("Failed to issue method call: %s", bus_error_message(error));
1917 if (!dbus_message_get_args(reply, error,
1918 DBUS_TYPE_OBJECT_PATH, &path,
1919 DBUS_TYPE_INVALID)) {
1920 log_error("Failed to parse reply: %s", bus_error_message(error));
1924 if (need_daemon_reload(bus, n) > 0)
1925 log_warning("Warning: Unit file of %s changed on disk, 'systemctl %sdaemon-reload' recommended.",
1926 n, arg_scope == UNIT_FILE_SYSTEM ? "" : "--user ");
1935 r = set_consume(s, p);
1937 log_error("Failed to add path to set.");
1945 static const struct {
1949 } action_table[_ACTION_MAX] = {
1950 [ACTION_HALT] = { SPECIAL_HALT_TARGET, "halt", "replace-irreversibly" },
1951 [ACTION_POWEROFF] = { SPECIAL_POWEROFF_TARGET, "poweroff", "replace-irreversibly" },
1952 [ACTION_REBOOT] = { SPECIAL_REBOOT_TARGET, "reboot", "replace-irreversibly" },
1953 [ACTION_KEXEC] = { SPECIAL_KEXEC_TARGET, "kexec", "replace-irreversibly" },
1954 [ACTION_RUNLEVEL2] = { SPECIAL_RUNLEVEL2_TARGET, NULL, "isolate" },
1955 [ACTION_RUNLEVEL3] = { SPECIAL_RUNLEVEL3_TARGET, NULL, "isolate" },
1956 [ACTION_RUNLEVEL4] = { SPECIAL_RUNLEVEL4_TARGET, NULL, "isolate" },
1957 [ACTION_RUNLEVEL5] = { SPECIAL_RUNLEVEL5_TARGET, NULL, "isolate" },
1958 [ACTION_RESCUE] = { SPECIAL_RESCUE_TARGET, "rescue", "isolate" },
1959 [ACTION_EMERGENCY] = { SPECIAL_EMERGENCY_TARGET, "emergency", "isolate" },
1960 [ACTION_DEFAULT] = { SPECIAL_DEFAULT_TARGET, "default", "isolate" },
1961 [ACTION_EXIT] = { SPECIAL_EXIT_TARGET, "exit", "replace-irreversibly" },
1962 [ACTION_SUSPEND] = { SPECIAL_SUSPEND_TARGET, "suspend", "replace-irreversibly" },
1963 [ACTION_HIBERNATE] = { SPECIAL_HIBERNATE_TARGET, "hibernate", "replace-irreversibly" },
1964 [ACTION_HYBRID_SLEEP] = { SPECIAL_HYBRID_SLEEP_TARGET, "hybrid-sleep", "replace-irreversibly" },
1967 static enum action verb_to_action(const char *verb) {
1970 for (i = ACTION_INVALID; i < _ACTION_MAX; i++)
1971 if (action_table[i].verb && streq(verb, action_table[i].verb))
1973 return ACTION_INVALID;
1976 static int start_unit(DBusConnection *bus, char **args) {
1979 const char *method, *mode, *one_name;
1980 _cleanup_set_free_free_ Set *s = NULL;
1981 _cleanup_dbus_error_free_ DBusError error;
1984 dbus_error_init(&error);
1988 ask_password_agent_open_if_enabled();
1990 if (arg_action == ACTION_SYSTEMCTL) {
1993 streq(args[0], "stop") ||
1994 streq(args[0], "condstop") ? "StopUnit" :
1995 streq(args[0], "reload") ? "ReloadUnit" :
1996 streq(args[0], "restart") ? "RestartUnit" :
1998 streq(args[0], "try-restart") ||
1999 streq(args[0], "condrestart") ? "TryRestartUnit" :
2001 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
2003 streq(args[0], "reload-or-try-restart") ||
2004 streq(args[0], "condreload") ||
2006 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
2008 action = verb_to_action(args[0]);
2010 mode = streq(args[0], "isolate") ? "isolate" :
2011 action_table[action].mode ?: arg_job_mode;
2013 one_name = action_table[action].target;
2016 assert(arg_action < ELEMENTSOF(action_table));
2017 assert(action_table[arg_action].target);
2019 method = "StartUnit";
2021 mode = action_table[arg_action].mode;
2022 one_name = action_table[arg_action].target;
2025 if (!arg_no_block) {
2026 ret = enable_wait_for_jobs(bus);
2028 log_error("Could not watch jobs: %s", strerror(-ret));
2032 s = set_new(string_hash_func, string_compare_func);
2038 ret = start_unit_one(bus, method, one_name, mode, &error, s);
2040 ret = translate_bus_error_to_exit_status(ret, &error);
2042 STRV_FOREACH(name, args+1) {
2043 r = start_unit_one(bus, method, *name, mode, &error, s);
2045 ret = translate_bus_error_to_exit_status(r, &error);
2046 dbus_error_free(&error);
2051 if (!arg_no_block) {
2052 r = wait_for_jobs(bus, s);
2056 /* When stopping units, warn if they can still be triggered by
2057 * another active unit (socket, path, timer) */
2058 if (!arg_quiet && streq(method, "StopUnit")) {
2060 check_triggering_units(bus, one_name);
2062 STRV_FOREACH(name, args+1)
2063 check_triggering_units(bus, *name);
2070 /* Ask systemd-logind, which might grant access to unprivileged users
2071 * through PolicyKit */
2072 static int reboot_with_logind(DBusConnection *bus, enum action a) {
2075 dbus_bool_t interactive = true;
2080 polkit_agent_open_if_enabled();
2088 case ACTION_POWEROFF:
2089 method = "PowerOff";
2092 case ACTION_SUSPEND:
2096 case ACTION_HIBERNATE:
2097 method = "Hibernate";
2100 case ACTION_HYBRID_SLEEP:
2101 method = "HybridSleep";
2108 return bus_method_call_with_reply(
2110 "org.freedesktop.login1",
2111 "/org/freedesktop/login1",
2112 "org.freedesktop.login1.Manager",
2116 DBUS_TYPE_BOOLEAN, &interactive,
2123 static int check_inhibitors(DBusConnection *bus, enum action a) {
2125 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
2126 DBusMessageIter iter, sub, sub2;
2129 _cleanup_strv_free_ char **sessions = NULL;
2135 if (arg_ignore_inhibitors || arg_force > 0)
2147 r = bus_method_call_with_reply(
2149 "org.freedesktop.login1",
2150 "/org/freedesktop/login1",
2151 "org.freedesktop.login1.Manager",
2157 /* If logind is not around, then there are no inhibitors... */
2160 if (!dbus_message_iter_init(reply, &iter) ||
2161 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2162 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
2163 log_error("Failed to parse reply.");
2167 dbus_message_iter_recurse(&iter, &sub);
2168 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2169 const char *what, *who, *why, *mode;
2171 _cleanup_strv_free_ char **sv = NULL;
2172 _cleanup_free_ char *comm = NULL, *user = NULL;
2174 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
2175 log_error("Failed to parse reply.");
2179 dbus_message_iter_recurse(&sub, &sub2);
2181 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &what, true) < 0 ||
2182 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &who, true) < 0 ||
2183 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &why, true) < 0 ||
2184 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &mode, true) < 0 ||
2185 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &uid, true) < 0 ||
2186 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, false) < 0) {
2187 log_error("Failed to parse reply.");
2191 if (!streq(mode, "block"))
2194 sv = strv_split(what, ":");
2198 if (!strv_contains(sv,
2200 a == ACTION_POWEROFF ||
2201 a == ACTION_REBOOT ||
2202 a == ACTION_KEXEC ? "shutdown" : "sleep"))
2205 get_process_comm(pid, &comm);
2206 user = uid_to_name(uid);
2207 log_warning("Operation inhibited by \"%s\" (PID %lu \"%s\", user %s), reason is \"%s\".",
2208 who, (unsigned long) pid, strna(comm), strna(user), why);
2212 dbus_message_iter_next(&sub);
2215 dbus_message_iter_recurse(&iter, &sub);
2217 /* Check for current sessions */
2218 sd_get_sessions(&sessions);
2219 STRV_FOREACH(s, sessions) {
2221 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
2223 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
2226 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
2229 if (sd_session_get_type(*s, &type) < 0 || (!streq(type, "x11") && !streq(type, "tty")))
2232 sd_session_get_tty(*s, &tty);
2233 sd_session_get_seat(*s, &seat);
2234 sd_session_get_service(*s, &service);
2235 user = uid_to_name(uid);
2237 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
2244 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
2245 action_table[a].verb);
2253 static int start_special(DBusConnection *bus, char **args) {
2259 a = verb_to_action(args[0]);
2261 r = check_inhibitors(bus, a);
2265 if (arg_force >= 2 && geteuid() != 0) {
2266 log_error("Must be root.");
2270 if (arg_force >= 2 &&
2271 (a == ACTION_HALT ||
2272 a == ACTION_POWEROFF ||
2273 a == ACTION_REBOOT))
2276 if (arg_force >= 1 &&
2277 (a == ACTION_HALT ||
2278 a == ACTION_POWEROFF ||
2279 a == ACTION_REBOOT ||
2280 a == ACTION_KEXEC ||
2282 return daemon_reload(bus, args);
2284 /* first try logind, to allow authentication with polkit */
2285 if (geteuid() != 0 &&
2286 (a == ACTION_POWEROFF ||
2287 a == ACTION_REBOOT ||
2288 a == ACTION_SUSPEND ||
2289 a == ACTION_HIBERNATE ||
2290 a == ACTION_HYBRID_SLEEP)) {
2291 r = reboot_with_logind(bus, a);
2296 r = start_unit(bus, args);
2297 if (r == EXIT_SUCCESS)
2303 static int check_unit_active(DBusConnection *bus, char **args) {
2304 const char * const check_states[] = {
2311 int r = 3; /* According to LSB: "program is not running" */
2316 STRV_FOREACH(name, args+1) {
2319 state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
2329 static int check_unit_failed(DBusConnection *bus, char **args) {
2330 const char * const check_states[] = {
2341 STRV_FOREACH(name, args+1) {
2344 state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
2354 static int kill_unit(DBusConnection *bus, char **args) {
2362 arg_kill_who = "all";
2364 STRV_FOREACH(name, args+1) {
2365 _cleanup_free_ char *n = NULL;
2367 n = unit_name_mangle(*name);
2371 r = bus_method_call_with_reply(
2373 "org.freedesktop.systemd1",
2374 "/org/freedesktop/systemd1",
2375 "org.freedesktop.systemd1.Manager",
2379 DBUS_TYPE_STRING, &n,
2380 DBUS_TYPE_STRING, &arg_kill_who,
2381 DBUS_TYPE_INT32, &arg_signal,
2389 typedef struct ExecStatusInfo {
2397 usec_t start_timestamp;
2398 usec_t exit_timestamp;
2403 LIST_FIELDS(struct ExecStatusInfo, exec);
2406 static void exec_status_info_free(ExecStatusInfo *i) {
2415 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
2416 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2417 DBusMessageIter sub2, sub3;
2421 int32_t code, status;
2427 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
2430 dbus_message_iter_recurse(sub, &sub2);
2432 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
2435 i->path = strdup(path);
2439 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
2440 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
2444 dbus_message_iter_recurse(&sub2, &sub3);
2445 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2446 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2447 dbus_message_iter_next(&sub3);
2451 i->argv = new0(char*, n+1);
2456 dbus_message_iter_recurse(&sub2, &sub3);
2457 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2460 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2461 dbus_message_iter_get_basic(&sub3, &s);
2462 dbus_message_iter_next(&sub3);
2464 i->argv[n] = strdup(s);
2471 if (!dbus_message_iter_next(&sub2) ||
2472 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
2473 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
2474 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
2475 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
2476 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
2477 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
2478 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
2479 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
2483 i->start_timestamp = (usec_t) start_timestamp;
2484 i->exit_timestamp = (usec_t) exit_timestamp;
2485 i->pid = (pid_t) pid;
2492 typedef struct UnitStatusInfo {
2494 const char *load_state;
2495 const char *active_state;
2496 const char *sub_state;
2497 const char *unit_file_state;
2499 const char *description;
2500 const char *following;
2502 char **documentation;
2504 const char *fragment_path;
2505 const char *source_path;
2506 const char *control_group;
2508 char **dropin_paths;
2510 const char *load_error;
2513 usec_t inactive_exit_timestamp;
2514 usec_t inactive_exit_timestamp_monotonic;
2515 usec_t active_enter_timestamp;
2516 usec_t active_exit_timestamp;
2517 usec_t inactive_enter_timestamp;
2519 bool need_daemon_reload;
2524 const char *status_text;
2525 const char *pid_file;
2528 usec_t start_timestamp;
2529 usec_t exit_timestamp;
2531 int exit_code, exit_status;
2533 usec_t condition_timestamp;
2534 bool condition_result;
2535 bool failed_condition_trigger;
2536 bool failed_condition_negate;
2537 const char *failed_condition;
2538 const char *failed_condition_param;
2541 unsigned n_accepted;
2542 unsigned n_connections;
2545 /* Pairs of type, path */
2549 const char *sysfs_path;
2551 /* Mount, Automount */
2557 LIST_HEAD(ExecStatusInfo, exec);
2560 static void print_status_info(UnitStatusInfo *i) {
2562 const char *on, *off, *ss;
2564 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
2565 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2568 arg_all * OUTPUT_SHOW_ALL |
2569 (!on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
2570 on_tty() * OUTPUT_COLOR |
2571 !arg_quiet * OUTPUT_WARN_CUTOFF |
2572 arg_full * OUTPUT_FULL_WIDTH;
2577 /* This shows pretty information about a unit. See
2578 * print_property() for a low-level property printer */
2580 printf("%s", strna(i->id));
2582 if (i->description && !streq_ptr(i->id, i->description))
2583 printf(" - %s", i->description);
2588 printf(" Follow: unit currently follows state of %s\n", i->following);
2590 if (streq_ptr(i->load_state, "error")) {
2591 on = ansi_highlight_red(true);
2592 off = ansi_highlight_red(false);
2596 path = i->source_path ? i->source_path : i->fragment_path;
2599 printf(" Loaded: %s%s%s (Reason: %s)\n",
2600 on, strna(i->load_state), off, i->load_error);
2601 else if (path && i->unit_file_state)
2602 printf(" Loaded: %s%s%s (%s; %s)\n",
2603 on, strna(i->load_state), off, path, i->unit_file_state);
2605 printf(" Loaded: %s%s%s (%s)\n",
2606 on, strna(i->load_state), off, path);
2608 printf(" Loaded: %s%s%s\n",
2609 on, strna(i->load_state), off);
2611 if (!strv_isempty(i->dropin_paths)) {
2616 STRV_FOREACH(dropin, i->dropin_paths) {
2617 if (! dir || last) {
2618 printf(dir ? " " : " Drop-In: ");
2622 if (path_get_parent(*dropin, &dir) < 0) {
2627 printf("%s\n %s", dir,
2628 draw_special_char(DRAW_TREE_RIGHT));
2631 last = ! (*(dropin + 1) && startswith(*(dropin + 1), dir));
2633 printf("%s%s", path_get_file_name(*dropin), last ? "\n" : ", ");
2639 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2641 if (streq_ptr(i->active_state, "failed")) {
2642 on = ansi_highlight_red(true);
2643 off = ansi_highlight_red(false);
2644 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2645 on = ansi_highlight_green(true);
2646 off = ansi_highlight_green(false);
2651 printf(" Active: %s%s (%s)%s",
2652 on, strna(i->active_state), ss, off);
2654 printf(" Active: %s%s%s",
2655 on, strna(i->active_state), off);
2657 if (!isempty(i->result) && !streq(i->result, "success"))
2658 printf(" (Result: %s)", i->result);
2660 timestamp = (streq_ptr(i->active_state, "active") ||
2661 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2662 (streq_ptr(i->active_state, "inactive") ||
2663 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2664 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2665 i->active_exit_timestamp;
2667 s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
2668 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2671 printf(" since %s; %s\n", s2, s1);
2673 printf(" since %s\n", s2);
2677 if (!i->condition_result && i->condition_timestamp > 0) {
2678 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
2679 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2681 printf(" start condition failed at %s%s%s\n",
2682 s2, s1 ? "; " : "", s1 ? s1 : "");
2683 if (i->failed_condition_trigger)
2684 printf(" none of the trigger conditions were met\n");
2685 else if (i->failed_condition)
2686 printf(" %s=%s%s was not met\n",
2687 i->failed_condition,
2688 i->failed_condition_negate ? "!" : "",
2689 i->failed_condition_param);
2693 printf(" Device: %s\n", i->sysfs_path);
2695 printf(" Where: %s\n", i->where);
2697 printf(" What: %s\n", i->what);
2699 STRV_FOREACH(t, i->documentation)
2700 printf(" %*s %s\n", 9, t == i->documentation ? "Docs:" : "", *t);
2702 STRV_FOREACH_PAIR(t, t2, i->listen)
2703 printf(" %*s %s (%s)\n", 9, t == i->listen ? "Listen:" : "", *t2, *t);
2706 printf(" Accepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2708 LIST_FOREACH(exec, p, i->exec) {
2709 _cleanup_free_ char *argv = NULL;
2712 /* Only show exited processes here */
2716 argv = strv_join(p->argv, " ");
2717 printf(" Process: %u %s=%s ", p->pid, p->name, strna(argv));
2719 good = is_clean_exit_lsb(p->code, p->status, NULL);
2721 on = ansi_highlight_red(true);
2722 off = ansi_highlight_red(false);
2726 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2728 if (p->code == CLD_EXITED) {
2731 printf("status=%i", p->status);
2733 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2738 printf("signal=%s", signal_to_string(p->status));
2740 printf(")%s\n", off);
2742 if (i->main_pid == p->pid &&
2743 i->start_timestamp == p->start_timestamp &&
2744 i->exit_timestamp == p->start_timestamp)
2745 /* Let's not show this twice */
2748 if (p->pid == i->control_pid)
2752 if (i->main_pid > 0 || i->control_pid > 0) {
2753 if (i->main_pid > 0) {
2754 printf(" Main PID: %u", (unsigned) i->main_pid);
2757 _cleanup_free_ char *comm = NULL;
2758 get_process_comm(i->main_pid, &comm);
2760 printf(" (%s)", comm);
2761 } else if (i->exit_code > 0) {
2762 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2764 if (i->exit_code == CLD_EXITED) {
2767 printf("status=%i", i->exit_status);
2769 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2774 printf("signal=%s", signal_to_string(i->exit_status));
2778 if (i->control_pid > 0)
2782 if (i->control_pid > 0) {
2783 _cleanup_free_ char *c = NULL;
2785 printf(" %8s: %u", i->main_pid ? "" : " Control", (unsigned) i->control_pid);
2787 get_process_comm(i->control_pid, &c);
2796 printf(" Status: \"%s\"\n", i->status_text);
2798 if (i->control_group &&
2799 (i->main_pid > 0 || i->control_pid > 0 || cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, i->control_group, false) == 0)) {
2802 printf(" CGroup: %s\n", i->control_group);
2804 if (arg_transport != TRANSPORT_SSH) {
2807 char prefix[] = " ";
2810 if (c > sizeof(prefix) - 1)
2811 c -= sizeof(prefix) - 1;
2815 if (i->main_pid > 0)
2816 extra[k++] = i->main_pid;
2818 if (i->control_pid > 0)
2819 extra[k++] = i->control_pid;
2821 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER, i->control_group, prefix,
2822 c, false, extra, k, flags);
2826 if (i->id && arg_transport != TRANSPORT_SSH) {
2828 show_journal_by_unit(stdout,
2832 i->inactive_exit_timestamp_monotonic,
2836 arg_scope == UNIT_FILE_SYSTEM);
2839 if (i->need_daemon_reload)
2840 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %sdaemon-reload' recommended.\n",
2841 ansi_highlight_red(true),
2842 ansi_highlight_red(false),
2843 arg_scope == UNIT_FILE_SYSTEM ? "" : "--user ");
2846 static void show_unit_help(UnitStatusInfo *i) {
2851 if (!i->documentation) {
2852 log_info("Documentation for %s not known.", i->id);
2856 STRV_FOREACH(p, i->documentation) {
2858 if (startswith(*p, "man:")) {
2861 _cleanup_free_ char *page = NULL, *section = NULL;
2862 const char *args[4] = { "man", NULL, NULL, NULL };
2867 if ((*p)[k-1] == ')')
2868 e = strrchr(*p, '(');
2871 page = strndup((*p) + 4, e - *p - 4);
2872 section = strndup(e + 1, *p + k - e - 2);
2873 if (!page || !section) {
2885 log_error("Failed to fork: %m");
2891 execvp(args[0], (char**) args);
2892 log_error("Failed to execute man: %m");
2893 _exit(EXIT_FAILURE);
2896 wait_for_terminate(pid, NULL);
2898 log_info("Can't show: %s", *p);
2902 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2908 switch (dbus_message_iter_get_arg_type(iter)) {
2910 case DBUS_TYPE_STRING: {
2913 dbus_message_iter_get_basic(iter, &s);
2916 if (streq(name, "Id"))
2918 else if (streq(name, "LoadState"))
2920 else if (streq(name, "ActiveState"))
2921 i->active_state = s;
2922 else if (streq(name, "SubState"))
2924 else if (streq(name, "Description"))
2926 else if (streq(name, "FragmentPath"))
2927 i->fragment_path = s;
2928 else if (streq(name, "SourcePath"))
2931 else if (streq(name, "DefaultControlGroup")) {
2933 e = startswith(s, SYSTEMD_CGROUP_CONTROLLER ":");
2935 i->control_group = e;
2938 else if (streq(name, "ControlGroup"))
2939 i->control_group = s;
2940 else if (streq(name, "StatusText"))
2942 else if (streq(name, "PIDFile"))
2944 else if (streq(name, "SysFSPath"))
2946 else if (streq(name, "Where"))
2948 else if (streq(name, "What"))
2950 else if (streq(name, "Following"))
2952 else if (streq(name, "UnitFileState"))
2953 i->unit_file_state = s;
2954 else if (streq(name, "Result"))
2961 case DBUS_TYPE_BOOLEAN: {
2964 dbus_message_iter_get_basic(iter, &b);
2966 if (streq(name, "Accept"))
2968 else if (streq(name, "NeedDaemonReload"))
2969 i->need_daemon_reload = b;
2970 else if (streq(name, "ConditionResult"))
2971 i->condition_result = b;
2976 case DBUS_TYPE_UINT32: {
2979 dbus_message_iter_get_basic(iter, &u);
2981 if (streq(name, "MainPID")) {
2983 i->main_pid = (pid_t) u;
2986 } else if (streq(name, "ControlPID"))
2987 i->control_pid = (pid_t) u;
2988 else if (streq(name, "ExecMainPID")) {
2990 i->main_pid = (pid_t) u;
2991 } else if (streq(name, "NAccepted"))
2993 else if (streq(name, "NConnections"))
2994 i->n_connections = u;
2999 case DBUS_TYPE_INT32: {
3002 dbus_message_iter_get_basic(iter, &j);
3004 if (streq(name, "ExecMainCode"))
3005 i->exit_code = (int) j;
3006 else if (streq(name, "ExecMainStatus"))
3007 i->exit_status = (int) j;
3012 case DBUS_TYPE_UINT64: {
3015 dbus_message_iter_get_basic(iter, &u);
3017 if (streq(name, "ExecMainStartTimestamp"))
3018 i->start_timestamp = (usec_t) u;
3019 else if (streq(name, "ExecMainExitTimestamp"))
3020 i->exit_timestamp = (usec_t) u;
3021 else if (streq(name, "ActiveEnterTimestamp"))
3022 i->active_enter_timestamp = (usec_t) u;
3023 else if (streq(name, "InactiveEnterTimestamp"))
3024 i->inactive_enter_timestamp = (usec_t) u;
3025 else if (streq(name, "InactiveExitTimestamp"))
3026 i->inactive_exit_timestamp = (usec_t) u;
3027 else if (streq(name, "InactiveExitTimestampMonotonic"))
3028 i->inactive_exit_timestamp_monotonic = (usec_t) u;
3029 else if (streq(name, "ActiveExitTimestamp"))
3030 i->active_exit_timestamp = (usec_t) u;
3031 else if (streq(name, "ConditionTimestamp"))
3032 i->condition_timestamp = (usec_t) u;
3037 case DBUS_TYPE_ARRAY: {
3039 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
3040 startswith(name, "Exec")) {
3041 DBusMessageIter sub;
3043 dbus_message_iter_recurse(iter, &sub);
3044 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3045 ExecStatusInfo *info;
3048 info = new0(ExecStatusInfo, 1);
3052 info->name = strdup(name);
3058 r = exec_status_info_deserialize(&sub, info);
3064 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
3066 dbus_message_iter_next(&sub);
3069 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
3070 streq(name, "Listen")) {
3071 DBusMessageIter sub, sub2;
3073 dbus_message_iter_recurse(iter, &sub);
3074 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3075 const char *type, *path;
3077 dbus_message_iter_recurse(&sub, &sub2);
3079 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
3080 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0) {
3083 r = strv_extend(&i->listen, type);
3086 r = strv_extend(&i->listen, path);
3091 dbus_message_iter_next(&sub);
3096 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
3097 streq(name, "DropInPaths")) {
3098 int r = bus_parse_strv_iter(iter, &i->dropin_paths);
3102 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
3103 streq(name, "Documentation")) {
3105 DBusMessageIter sub;
3107 dbus_message_iter_recurse(iter, &sub);
3108 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
3112 dbus_message_iter_get_basic(&sub, &s);
3114 r = strv_extend(&i->documentation, s);
3118 dbus_message_iter_next(&sub);
3121 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
3122 streq(name, "Conditions")) {
3123 DBusMessageIter sub, sub2;
3125 dbus_message_iter_recurse(iter, &sub);
3126 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3127 const char *cond, *param;
3128 dbus_bool_t trigger, negate;
3131 dbus_message_iter_recurse(&sub, &sub2);
3134 if(bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &cond, true) >= 0 &&
3135 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &trigger, true) >= 0 &&
3136 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &negate, true) >= 0 &&
3137 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, ¶m, true) >= 0 &&
3138 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &state, false) >= 0) {
3139 log_debug("%s %d %d %s %d", cond, trigger, negate, param, state);
3140 if (state < 0 && (!trigger || !i->failed_condition)) {
3141 i->failed_condition = cond;
3142 i->failed_condition_trigger = trigger;
3143 i->failed_condition_negate = negate;
3144 i->failed_condition_param = param;
3148 dbus_message_iter_next(&sub);
3155 case DBUS_TYPE_STRUCT: {
3157 if (streq(name, "LoadError")) {
3158 DBusMessageIter sub;
3159 const char *n, *message;
3162 dbus_message_iter_recurse(iter, &sub);
3164 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
3168 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
3172 if (!isempty(message))
3173 i->load_error = message;
3183 static int print_property(const char *name, DBusMessageIter *iter) {
3187 /* This is a low-level property printer, see
3188 * print_status_info() for the nicer output */
3190 if (arg_properties && !strv_find(arg_properties, name))
3193 switch (dbus_message_iter_get_arg_type(iter)) {
3195 case DBUS_TYPE_STRUCT: {
3196 DBusMessageIter sub;
3197 dbus_message_iter_recurse(iter, &sub);
3199 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
3202 dbus_message_iter_get_basic(&sub, &u);
3205 printf("%s=%u\n", name, (unsigned) u);
3207 printf("%s=\n", name);
3210 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
3213 dbus_message_iter_get_basic(&sub, &s);
3215 if (arg_all || s[0])
3216 printf("%s=%s\n", name, s);
3219 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
3220 const char *a = NULL, *b = NULL;
3222 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
3223 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
3225 if (arg_all || !isempty(a) || !isempty(b))
3226 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
3234 case DBUS_TYPE_ARRAY:
3236 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
3237 DBusMessageIter sub, sub2;
3239 dbus_message_iter_recurse(iter, &sub);
3240 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3244 dbus_message_iter_recurse(&sub, &sub2);
3246 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
3247 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
3248 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
3250 dbus_message_iter_next(&sub);
3255 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
3256 DBusMessageIter sub, sub2;
3258 dbus_message_iter_recurse(iter, &sub);
3260 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3261 const char *type, *path;
3263 dbus_message_iter_recurse(&sub, &sub2);
3265 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
3266 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
3267 printf("%s=%s\n", type, path);
3269 dbus_message_iter_next(&sub);
3274 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Listen")) {
3275 DBusMessageIter sub, sub2;
3277 dbus_message_iter_recurse(iter, &sub);
3278 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3279 const char *type, *path;
3281 dbus_message_iter_recurse(&sub, &sub2);
3283 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
3284 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
3285 printf("Listen%s=%s\n", type, path);
3287 dbus_message_iter_next(&sub);
3292 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
3293 DBusMessageIter sub, sub2;
3295 dbus_message_iter_recurse(iter, &sub);
3296 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3298 uint64_t value, next_elapse;
3300 dbus_message_iter_recurse(&sub, &sub2);
3302 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
3303 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
3304 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
3305 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
3307 printf("%s={ value=%s ; next_elapse=%s }\n",
3309 format_timespan(timespan1, sizeof(timespan1), value, 0),
3310 format_timespan(timespan2, sizeof(timespan2), next_elapse, 0));
3313 dbus_message_iter_next(&sub);
3318 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
3319 DBusMessageIter sub;
3321 dbus_message_iter_recurse(iter, &sub);
3322 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3323 ExecStatusInfo info = {};
3325 if (exec_status_info_deserialize(&sub, &info) >= 0) {
3326 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
3327 _cleanup_free_ char *t;
3329 t = strv_join(info.argv, " ");
3331 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
3335 yes_no(info.ignore),
3336 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
3337 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
3338 (unsigned) info. pid,
3339 sigchld_code_to_string(info.code),
3341 info.code == CLD_EXITED ? "" : "/",
3342 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
3346 strv_free(info.argv);
3348 dbus_message_iter_next(&sub);
3353 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "DeviceAllow")) {
3354 DBusMessageIter sub, sub2;
3356 dbus_message_iter_recurse(iter, &sub);
3357 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3358 const char *path, *rwm;
3360 dbus_message_iter_recurse(&sub, &sub2);
3362 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
3363 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &rwm, false) >= 0)
3364 printf("%s=%s %s\n", name, strna(path), strna(rwm));
3366 dbus_message_iter_next(&sub);
3370 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && (streq(name, "BlockIOReadBandwidth") || streq(name, "BlockIOWriteBandwidth"))) {
3371 DBusMessageIter sub, sub2;
3373 dbus_message_iter_recurse(iter, &sub);
3374 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3378 dbus_message_iter_recurse(&sub, &sub2);
3380 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
3381 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &bandwidth, false) >= 0)
3382 printf("%s=%s %" PRIu64 "\n", name, strna(path), bandwidth);
3384 dbus_message_iter_next(&sub);
3393 if (generic_print_property(name, iter, arg_all) > 0)
3397 printf("%s=[unprintable]\n", name);
3402 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
3403 _cleanup_free_ DBusMessage *reply = NULL;
3404 const char *interface = "";
3406 DBusMessageIter iter, sub, sub2, sub3;
3407 UnitStatusInfo info = {};
3413 r = bus_method_call_with_reply(
3415 "org.freedesktop.systemd1",
3417 "org.freedesktop.DBus.Properties",
3421 DBUS_TYPE_STRING, &interface,
3426 if (!dbus_message_iter_init(reply, &iter) ||
3427 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3428 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
3429 log_error("Failed to parse reply.");
3433 dbus_message_iter_recurse(&iter, &sub);
3440 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3443 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
3444 dbus_message_iter_recurse(&sub, &sub2);
3446 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
3447 dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
3448 log_error("Failed to parse reply.");
3452 dbus_message_iter_recurse(&sub2, &sub3);
3454 if (show_properties)
3455 r = print_property(name, &sub3);
3457 r = status_property(name, &sub3, &info);
3459 log_error("Failed to parse reply.");
3463 dbus_message_iter_next(&sub);
3468 if (!show_properties) {
3469 if (streq(verb, "help"))
3470 show_unit_help(&info);
3472 print_status_info(&info);
3475 strv_free(info.documentation);
3476 strv_free(info.dropin_paths);
3477 strv_free(info.listen);
3479 if (!streq_ptr(info.active_state, "active") &&
3480 !streq_ptr(info.active_state, "reloading") &&
3481 streq(verb, "status")) {
3482 /* According to LSB: "program not running" */
3483 /* 0: program is running or service is OK
3484 * 1: program is dead and /var/run pid file exists
3485 * 2: program is dead and /var/lock lock file exists
3486 * 3: program is not running
3487 * 4: program or service status is unknown
3489 if (info.pid_file && access(info.pid_file, F_OK) == 0)
3495 while ((p = info.exec)) {
3496 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
3497 exec_status_info_free(p);
3503 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
3504 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3505 const char *path = NULL;
3506 _cleanup_dbus_error_free_ DBusError error;
3509 dbus_error_init(&error);
3511 r = bus_method_call_with_reply(
3513 "org.freedesktop.systemd1",
3514 "/org/freedesktop/systemd1",
3515 "org.freedesktop.systemd1.Manager",
3519 DBUS_TYPE_UINT32, &pid,
3524 if (!dbus_message_get_args(reply, &error,
3525 DBUS_TYPE_OBJECT_PATH, &path,
3526 DBUS_TYPE_INVALID)) {
3527 log_error("Failed to parse reply: %s", bus_error_message(&error));
3531 r = show_one(verb, bus, path, false, new_line);
3535 static int show_all(const char* verb, DBusConnection *bus, bool show_properties, bool *new_line) {
3536 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3537 _cleanup_free_ struct unit_info *unit_infos = NULL;
3539 const struct unit_info *u;
3542 r = get_unit_list(bus, &reply, &unit_infos, &c);
3546 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
3548 for (u = unit_infos; u < unit_infos + c; u++) {
3549 _cleanup_free_ char *p = NULL;
3551 if (!output_show_unit(u))
3554 p = unit_dbus_path_from_name(u->id);
3558 printf("%s -> '%s'\n", u->id, p);
3560 r = show_one(verb, bus, p, show_properties, new_line);
3568 static int show(DBusConnection *bus, char **args) {
3570 bool show_properties, show_status, new_line = false;
3576 show_properties = streq(args[0], "show");
3577 show_status = streq(args[0], "status");
3579 if (show_properties)
3580 pager_open_if_enabled();
3582 /* If no argument is specified inspect the manager itself */
3584 if (show_properties && strv_length(args) <= 1)
3585 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
3587 if (show_status && strv_length(args) <= 1)
3588 return show_all(args[0], bus, false, &new_line);
3590 STRV_FOREACH(name, args+1) {
3593 if (safe_atou32(*name, &id) < 0) {
3594 _cleanup_free_ char *p = NULL, *n = NULL;
3595 /* Interpret as unit name */
3597 n = unit_name_mangle(*name);
3601 p = unit_dbus_path_from_name(n);
3605 r = show_one(args[0], bus, p, show_properties, &new_line);
3609 } else if (show_properties) {
3610 _cleanup_free_ char *p = NULL;
3612 /* Interpret as job id */
3613 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
3616 r = show_one(args[0], bus, p, show_properties, &new_line);
3621 /* Interpret as PID */
3622 r = show_one_by_pid(args[0], bus, id, &new_line);
3631 static int append_assignment(DBusMessageIter *iter, const char *assignment) {
3634 DBusMessageIter sub;
3640 eq = strchr(assignment, '=');
3642 log_error("Not an assignment: %s", assignment);
3646 field = strndupa(assignment, eq - assignment);
3649 if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &field))
3652 if (streq(field, "CPUAccounting") ||
3653 streq(field, "MemoryAccounting") ||
3654 streq(field, "BlockIOAccounting")) {
3657 r = parse_boolean(eq);
3659 log_error("Failed to parse boolean assignment %s.", assignment);
3664 if (!dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, "b", &sub) ||
3665 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_BOOLEAN, &b))
3668 } else if (streq(field, "MemoryLimit") || streq(field, "MemorySoftLimit")) {
3672 r = parse_bytes(eq, &bytes);
3674 log_error("Failed to parse bytes specification %s", assignment);
3679 if (!dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, "t", &sub) ||
3680 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_UINT64, &u))
3683 } else if (streq(field, "CPUShares") || streq(field, "BlockIOWeight")) {
3686 r = safe_atou64(eq, &u);
3688 log_error("Failed to parse %s value %s.", field, eq);
3692 if (!dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, "t", &sub) ||
3693 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_UINT64, &u))
3696 } else if (streq(field, "DevicePolicy")) {
3698 if (!dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, "s", &sub) ||
3699 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &eq))
3702 } else if (streq(field, "DeviceAllow")) {
3703 DBusMessageIter sub2;
3705 if (!dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, "a(ss)", &sub) ||
3706 !dbus_message_iter_open_container(&sub, DBUS_TYPE_ARRAY, "(ss)", &sub2))
3710 const char *path, *rwm;
3711 DBusMessageIter sub3;
3714 e = strchr(eq, ' ');
3716 path = strndupa(eq, e - eq);
3723 if (!dbus_message_iter_open_container(&sub2, DBUS_TYPE_STRUCT, NULL, &sub3) ||
3724 !dbus_message_iter_append_basic(&sub3, DBUS_TYPE_STRING, &path) ||
3725 !dbus_message_iter_append_basic(&sub3, DBUS_TYPE_STRING, &rwm) ||
3726 !dbus_message_iter_close_container(&sub2, &sub3))
3730 if (!dbus_message_iter_close_container(&sub, &sub2))
3734 log_error("Unknown assignment %s.", assignment);
3738 if (!dbus_message_iter_close_container(iter, &sub))
3744 static int set_property(DBusConnection *bus, char **args) {
3746 _cleanup_free_ DBusMessage *m = NULL, *reply = NULL;
3747 DBusMessageIter iter, sub;
3748 dbus_bool_t runtime;
3753 dbus_error_init(&error);
3755 m = dbus_message_new_method_call(
3756 "org.freedesktop.systemd1",
3757 "/org/freedesktop/systemd1",
3758 "org.freedesktop.systemd1.Manager",
3759 "SetUnitProperties");
3763 dbus_message_iter_init_append(m, &iter);
3765 runtime = arg_runtime;
3767 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &args[1]) ||
3768 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &runtime) ||
3769 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(sv)", &sub))
3772 STRV_FOREACH(i, args + 2) {
3773 DBusMessageIter sub2;
3775 if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2))
3778 r = append_assignment(&sub2, *i);
3782 if (!dbus_message_iter_close_container(&sub, &sub2))
3787 if (!dbus_message_iter_close_container(&iter, &sub))
3790 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3792 log_error("Failed to issue method call: %s", bus_error_message(&error));
3793 dbus_error_free(&error);
3800 static int snapshot(DBusConnection *bus, char **args) {
3801 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3804 dbus_bool_t cleanup = FALSE;
3805 DBusMessageIter iter, sub;
3808 *interface = "org.freedesktop.systemd1.Unit",
3810 _cleanup_free_ char *n = NULL;
3812 dbus_error_init(&error);
3814 if (strv_length(args) > 1)
3815 n = unit_name_mangle_with_suffix(args[1], ".snapshot");
3821 r = bus_method_call_with_reply(
3823 "org.freedesktop.systemd1",
3824 "/org/freedesktop/systemd1",
3825 "org.freedesktop.systemd1.Manager",
3829 DBUS_TYPE_STRING, &n,
3830 DBUS_TYPE_BOOLEAN, &cleanup,
3835 if (!dbus_message_get_args(reply, &error,
3836 DBUS_TYPE_OBJECT_PATH, &path,
3837 DBUS_TYPE_INVALID)) {
3838 log_error("Failed to parse reply: %s", bus_error_message(&error));
3839 dbus_error_free(&error);
3843 dbus_message_unref(reply);
3846 r = bus_method_call_with_reply (
3848 "org.freedesktop.systemd1",
3850 "org.freedesktop.DBus.Properties",
3854 DBUS_TYPE_STRING, &interface,
3855 DBUS_TYPE_STRING, &property,
3860 if (!dbus_message_iter_init(reply, &iter) ||
3861 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3862 log_error("Failed to parse reply.");
3866 dbus_message_iter_recurse(&iter, &sub);
3868 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3869 log_error("Failed to parse reply.");
3873 dbus_message_iter_get_basic(&sub, &id);
3881 static int delete_snapshot(DBusConnection *bus, char **args) {
3886 STRV_FOREACH(name, args+1) {
3887 _cleanup_free_ char *n = NULL;
3890 n = unit_name_mangle_with_suffix(*name, ".snapshot");
3894 r = bus_method_call_with_reply(
3896 "org.freedesktop.systemd1",
3897 "/org/freedesktop/systemd1",
3898 "org.freedesktop.systemd1.Manager",
3902 DBUS_TYPE_STRING, &n,
3911 static int daemon_reload(DBusConnection *bus, char **args) {
3916 if (arg_action == ACTION_RELOAD)
3918 else if (arg_action == ACTION_REEXEC)
3919 method = "Reexecute";
3921 assert(arg_action == ACTION_SYSTEMCTL);
3924 streq(args[0], "clear-jobs") ||
3925 streq(args[0], "cancel") ? "ClearJobs" :
3926 streq(args[0], "daemon-reexec") ? "Reexecute" :
3927 streq(args[0], "reset-failed") ? "ResetFailed" :
3928 streq(args[0], "halt") ? "Halt" :
3929 streq(args[0], "poweroff") ? "PowerOff" :
3930 streq(args[0], "reboot") ? "Reboot" :
3931 streq(args[0], "kexec") ? "KExec" :
3932 streq(args[0], "exit") ? "Exit" :
3933 /* "daemon-reload" */ "Reload";
3936 r = bus_method_call_with_reply(
3938 "org.freedesktop.systemd1",
3939 "/org/freedesktop/systemd1",
3940 "org.freedesktop.systemd1.Manager",
3946 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
3947 /* There's always a fallback possible for
3948 * legacy actions. */
3950 else if ((r == -ETIMEDOUT || r == -ECONNRESET) && streq(method, "Reexecute"))
3951 /* On reexecution, we expect a disconnect, not a
3955 log_error("Failed to issue method call: %s", bus_error_message(&error));
3957 dbus_error_free(&error);
3961 static int reset_failed(DBusConnection *bus, char **args) {
3965 if (strv_length(args) <= 1)
3966 return daemon_reload(bus, args);
3968 STRV_FOREACH(name, args+1) {
3969 _cleanup_free_ char *n;
3971 n = unit_name_mangle(*name);
3975 r = bus_method_call_with_reply(
3977 "org.freedesktop.systemd1",
3978 "/org/freedesktop/systemd1",
3979 "org.freedesktop.systemd1.Manager",
3983 DBUS_TYPE_STRING, &n,
3992 static int show_enviroment(DBusConnection *bus, char **args) {
3993 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3994 DBusMessageIter iter, sub, sub2;
3997 *interface = "org.freedesktop.systemd1.Manager",
3998 *property = "Environment";
4000 pager_open_if_enabled();
4002 r = bus_method_call_with_reply(
4004 "org.freedesktop.systemd1",
4005 "/org/freedesktop/systemd1",
4006 "org.freedesktop.DBus.Properties",
4010 DBUS_TYPE_STRING, &interface,
4011 DBUS_TYPE_STRING, &property,
4016 if (!dbus_message_iter_init(reply, &iter) ||
4017 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
4018 log_error("Failed to parse reply.");
4022 dbus_message_iter_recurse(&iter, &sub);
4024 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
4025 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
4026 log_error("Failed to parse reply.");
4030 dbus_message_iter_recurse(&sub, &sub2);
4032 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
4035 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
4036 log_error("Failed to parse reply.");
4040 dbus_message_iter_get_basic(&sub2, &text);
4043 dbus_message_iter_next(&sub2);
4049 static int switch_root(DBusConnection *bus, char **args) {
4052 _cleanup_free_ char *init = NULL;
4054 l = strv_length(args);
4055 if (l < 2 || l > 3) {
4056 log_error("Wrong number of arguments.");
4063 init = strdup(args[2]);
4065 parse_env_file("/proc/cmdline", WHITESPACE,
4075 log_debug("switching root - root: %s; init: %s", root, init);
4077 return bus_method_call_with_reply(
4079 "org.freedesktop.systemd1",
4080 "/org/freedesktop/systemd1",
4081 "org.freedesktop.systemd1.Manager",
4085 DBUS_TYPE_STRING, &root,
4086 DBUS_TYPE_STRING, &init,
4090 static int set_environment(DBusConnection *bus, char **args) {
4091 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
4094 DBusMessageIter iter;
4100 dbus_error_init(&error);
4102 method = streq(args[0], "set-environment")
4104 : "UnsetEnvironment";
4106 m = dbus_message_new_method_call(
4107 "org.freedesktop.systemd1",
4108 "/org/freedesktop/systemd1",
4109 "org.freedesktop.systemd1.Manager",
4114 dbus_message_iter_init_append(m, &iter);
4116 r = bus_append_strv_iter(&iter, args + 1);
4120 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4122 log_error("Failed to issue method call: %s", bus_error_message(&error));
4123 dbus_error_free(&error);
4130 static int enable_sysv_units(char **args) {
4133 #if defined(HAVE_SYSV_COMPAT) && defined(HAVE_CHKCONFIG)
4134 const char *verb = args[0];
4135 unsigned f = 1, t = 1;
4136 LookupPaths paths = {};
4138 if (arg_scope != UNIT_FILE_SYSTEM)
4141 if (!streq(verb, "enable") &&
4142 !streq(verb, "disable") &&
4143 !streq(verb, "is-enabled"))
4146 /* Processes all SysV units, and reshuffles the array so that
4147 * afterwards only the native units remain */
4149 r = lookup_paths_init(&paths, SYSTEMD_SYSTEM, false, NULL, NULL, NULL);
4154 for (f = 1; args[f]; f++) {
4156 _cleanup_free_ char *p = NULL, *q = NULL;
4157 bool found_native = false, found_sysv;
4159 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
4167 if (!endswith(name, ".service"))
4170 if (path_is_absolute(name))
4173 STRV_FOREACH(k, paths.unit_path) {
4174 if (!isempty(arg_root))
4175 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
4177 asprintf(&p, "%s/%s", *k, name);
4184 found_native = access(p, F_OK) >= 0;
4195 if (!isempty(arg_root))
4196 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
4198 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
4204 p[strlen(p) - sizeof(".service") + 1] = 0;
4205 found_sysv = access(p, F_OK) >= 0;
4210 /* Mark this entry, so that we don't try enabling it as native unit */
4211 args[f] = (char*) "";
4213 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
4215 if (!isempty(arg_root))
4216 argv[c++] = q = strappend("--root=", arg_root);
4218 argv[c++] = path_get_file_name(p);
4220 streq(verb, "enable") ? "on" :
4221 streq(verb, "disable") ? "off" : "--level=5";
4224 l = strv_join((char**)argv, " ");
4230 log_info("Executing %s", l);
4235 log_error("Failed to fork: %m");
4238 } else if (pid == 0) {
4241 execv(argv[0], (char**) argv);
4242 _exit(EXIT_FAILURE);
4245 j = wait_for_terminate(pid, &status);
4247 log_error("Failed to wait for child: %s", strerror(-r));
4252 if (status.si_code == CLD_EXITED) {
4253 if (streq(verb, "is-enabled")) {
4254 if (status.si_status == 0) {
4263 } else if (status.si_status != 0) {
4274 lookup_paths_free(&paths);
4276 /* Drop all SysV units */
4277 for (f = 1, t = 1; args[f]; f++) {
4279 if (isempty(args[f]))
4282 args[t++] = args[f];
4291 static int mangle_names(char **original_names, char ***mangled_names) {
4292 char **i, **l, **name;
4294 l = new(char*, strv_length(original_names) + 1);
4299 STRV_FOREACH(name, original_names) {
4301 /* When enabling units qualified path names are OK,
4302 * too, hence allow them explicitly. */
4307 *i = unit_name_mangle(*name);
4323 static int enable_unit(DBusConnection *bus, char **args) {
4324 const char *verb = args[0];
4325 UnitFileChange *changes = NULL;
4326 unsigned n_changes = 0, i;
4327 int carries_install_info = -1;
4328 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
4330 _cleanup_dbus_error_free_ DBusError error;
4331 _cleanup_strv_free_ char **mangled_names = NULL;
4333 dbus_error_init(&error);
4335 r = enable_sysv_units(args);
4342 r = mangle_names(args+1, &mangled_names);
4346 if (!bus || avoid_bus()) {
4347 if (streq(verb, "enable")) {
4348 r = unit_file_enable(arg_scope, arg_runtime, arg_root, mangled_names, arg_force, &changes, &n_changes);
4349 carries_install_info = r;
4350 } else if (streq(verb, "disable"))
4351 r = unit_file_disable(arg_scope, arg_runtime, arg_root, mangled_names, &changes, &n_changes);
4352 else if (streq(verb, "reenable")) {
4353 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, mangled_names, arg_force, &changes, &n_changes);
4354 carries_install_info = r;
4355 } else if (streq(verb, "link"))
4356 r = unit_file_link(arg_scope, arg_runtime, arg_root, mangled_names, arg_force, &changes, &n_changes);
4357 else if (streq(verb, "preset")) {
4358 r = unit_file_preset(arg_scope, arg_runtime, arg_root, mangled_names, arg_force, &changes, &n_changes);
4359 carries_install_info = r;
4360 } else if (streq(verb, "mask"))
4361 r = unit_file_mask(arg_scope, arg_runtime, arg_root, mangled_names, arg_force, &changes, &n_changes);
4362 else if (streq(verb, "unmask"))
4363 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, mangled_names, &changes, &n_changes);
4364 else if (streq(verb, "set-default"))
4365 r = unit_file_set_default(arg_scope, arg_root, args[1], &changes, &n_changes);
4367 assert_not_reached("Unknown verb");
4370 log_error("Operation failed: %s", strerror(-r));
4375 for (i = 0; i < n_changes; i++) {
4376 if (changes[i].type == UNIT_FILE_SYMLINK)
4377 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
4379 log_info("rm '%s'", changes[i].path);
4386 bool send_force = true, expect_carries_install_info = false;
4388 DBusMessageIter iter, sub, sub2;
4390 if (streq(verb, "enable")) {
4391 method = "EnableUnitFiles";
4392 expect_carries_install_info = true;
4393 } else if (streq(verb, "disable")) {
4394 method = "DisableUnitFiles";
4396 } else if (streq(verb, "reenable")) {
4397 method = "ReenableUnitFiles";
4398 expect_carries_install_info = true;
4399 } else if (streq(verb, "link"))
4400 method = "LinkUnitFiles";
4401 else if (streq(verb, "preset")) {
4402 method = "PresetUnitFiles";
4403 expect_carries_install_info = true;
4404 } else if (streq(verb, "mask"))
4405 method = "MaskUnitFiles";
4406 else if (streq(verb, "unmask")) {
4407 method = "UnmaskUnitFiles";
4409 } else if (streq(verb, "set-default")) {
4410 method = "SetDefaultTarget";
4412 assert_not_reached("Unknown verb");
4414 m = dbus_message_new_method_call(
4415 "org.freedesktop.systemd1",
4416 "/org/freedesktop/systemd1",
4417 "org.freedesktop.systemd1.Manager",
4424 dbus_message_iter_init_append(m, &iter);
4426 r = bus_append_strv_iter(&iter, mangled_names);
4428 log_error("Failed to append unit files.");
4433 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
4434 log_error("Failed to append runtime boolean.");
4442 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
4443 log_error("Failed to append force boolean.");
4449 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4451 log_error("Failed to issue method call: %s", bus_error_message(&error));
4456 if (!dbus_message_iter_init(reply, &iter)) {
4457 log_error("Failed to initialize iterator.");
4461 if (expect_carries_install_info) {
4462 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
4464 log_error("Failed to parse reply.");
4468 carries_install_info = b;
4471 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
4472 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
4473 log_error("Failed to parse reply.");
4478 dbus_message_iter_recurse(&iter, &sub);
4479 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
4480 const char *type, *path, *source;
4482 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
4483 log_error("Failed to parse reply.");
4488 dbus_message_iter_recurse(&sub, &sub2);
4490 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
4491 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
4492 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
4493 log_error("Failed to parse reply.");
4499 if (streq(type, "symlink"))
4500 log_info("ln -s '%s' '%s'", source, path);
4502 log_info("rm '%s'", path);
4505 dbus_message_iter_next(&sub);
4508 /* Try to reload if enabeld */
4510 r = daemon_reload(bus, args);
4513 if (carries_install_info == 0)
4514 log_warning("The unit files have no [Install] section. They are not meant to be enabled\n"
4515 "using systemctl.\n"
4516 "Possible reasons for having this kind of units are:\n"
4517 "1) A unit may be statically enabled by being symlinked from another unit's\n"
4518 " .wants/ or .requires/ directory.\n"
4519 "2) A unit's purpose may be to act as a helper for some other unit which has\n"
4520 " a requirement dependency on it.\n"
4521 "3) A unit may be started when needed via activation (socket, path, timer,\n"
4522 " D-Bus, udev, scripted systemctl call, ...).\n");
4525 unit_file_changes_free(changes, n_changes);
4530 static int set_log_level(DBusConnection *bus, char **args) {
4531 _cleanup_dbus_error_free_ DBusError error;
4532 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
4533 DBusMessageIter iter, sub;
4534 const char* property = "LogLevel";
4535 const char* interface = "org.freedesktop.systemd1.Manager";
4542 dbus_error_init(&error);
4544 m = dbus_message_new_method_call("org.freedesktop.systemd1",
4545 "/org/freedesktop/systemd1",
4546 "org.freedesktop.DBus.Properties",
4551 dbus_message_iter_init_append(m, &iter);
4553 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &interface) ||
4554 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &property) ||
4555 !dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, "s", &sub))
4558 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &value)) {
4559 dbus_message_iter_abandon_container(&iter, &sub);
4563 if (!dbus_message_iter_close_container(&iter, &sub))
4566 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4568 log_error("Failed to issue method call: %s", bus_error_message(&error));
4575 static int unit_is_enabled(DBusConnection *bus, char **args) {
4576 _cleanup_dbus_error_free_ DBusError error;
4578 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
4583 dbus_error_init(&error);
4585 r = enable_sysv_units(args);
4591 if (!bus || avoid_bus()) {
4593 STRV_FOREACH(name, args+1) {
4594 UnitFileState state;
4596 n = unit_name_mangle(*name);
4600 state = unit_file_get_state(arg_scope, arg_root, n);
4607 if (state == UNIT_FILE_ENABLED ||
4608 state == UNIT_FILE_ENABLED_RUNTIME ||
4609 state == UNIT_FILE_STATIC)
4613 puts(unit_file_state_to_string(state));
4617 STRV_FOREACH(name, args+1) {
4620 n = unit_name_mangle(*name);
4624 r = bus_method_call_with_reply (
4626 "org.freedesktop.systemd1",
4627 "/org/freedesktop/systemd1",
4628 "org.freedesktop.systemd1.Manager",
4632 DBUS_TYPE_STRING, &n,
4640 if (!dbus_message_get_args(reply, &error,
4641 DBUS_TYPE_STRING, &s,
4642 DBUS_TYPE_INVALID)) {
4643 log_error("Failed to parse reply: %s", bus_error_message(&error));
4647 dbus_message_unref(reply);
4650 if (streq(s, "enabled") ||
4651 streq(s, "enabled-runtime") ||
4660 return enabled ? 0 : 1;
4663 static int systemctl_help(void) {
4665 pager_open_if_enabled();
4667 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4668 "Query or send control commands to the systemd manager.\n\n"
4669 " -h --help Show this help\n"
4670 " --version Show package version\n"
4671 " -t --type=TYPE List only units of a particular type\n"
4672 " --state=STATE Show only units with particular LOAD or SUB or ACTIVE state\n"
4673 " -p --property=NAME Show only properties by this name\n"
4674 " -a --all Show all loaded units/properties, including dead/empty\n"
4675 " ones. To list all units installed on the system, use\n"
4676 " the 'list-unit-files' command instead.\n"
4677 " --reverse Show reverse dependencies with 'list-dependencies'\n"
4678 " -l --full Don't ellipsize unit names on output\n"
4679 " --fail When queueing a new job, fail if conflicting jobs are\n"
4681 " --irreversible Create jobs which cannot be implicitly cancelled\n"
4682 " --show-types When showing sockets, explicitly show their type\n"
4683 " --ignore-dependencies\n"
4684 " When queueing a new job, ignore all its dependencies\n"
4685 " -i --ignore-inhibitors\n"
4686 " When shutting down or sleeping, ignore inhibitors\n"
4687 " --kill-who=WHO Who to send signal to\n"
4688 " -s --signal=SIGNAL Which signal to send\n"
4689 " -H --host=[USER@]HOST\n"
4690 " Show information for remote host\n"
4691 " -P --privileged Acquire privileges before execution\n"
4692 " -q --quiet Suppress output\n"
4693 " --no-block Do not wait until operation finished\n"
4694 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4695 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4697 " --no-legend Do not print a legend (column headers and hints)\n"
4698 " --no-pager Do not pipe output into a pager\n"
4699 " --no-ask-password\n"
4700 " Do not ask for system passwords\n"
4701 " --system Connect to system manager\n"
4702 " --user Connect to user service manager\n"
4703 " --global Enable/disable unit files globally\n"
4704 " -f --force When enabling unit files, override existing symlinks\n"
4705 " When shutting down, execute action immediately\n"
4706 " --root=PATH Enable unit files in the specified root directory\n"
4707 " --runtime Enable unit files only temporarily until next reboot\n"
4708 " -n --lines=INTEGER Journal entries to show\n"
4709 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
4710 " verbose, export, json, json-pretty, json-sse, cat)\n\n"
4712 " list-units List loaded units\n"
4713 " list-sockets List loaded sockets ordered by address\n"
4714 " start [NAME...] Start (activate) one or more units\n"
4715 " stop [NAME...] Stop (deactivate) one or more units\n"
4716 " reload [NAME...] Reload one or more units\n"
4717 " restart [NAME...] Start or restart one or more units\n"
4718 " try-restart [NAME...] Restart one or more units if active\n"
4719 " reload-or-restart [NAME...] Reload one or more units if possible,\n"
4720 " otherwise start or restart\n"
4721 " reload-or-try-restart [NAME...] Reload one or more units if possible,\n"
4722 " otherwise restart if active\n"
4723 " isolate [NAME] Start one unit and stop all others\n"
4724 " kill [NAME...] Send signal to processes of a unit\n"
4725 " is-active [NAME...] Check whether units are active\n"
4726 " is-failed [NAME...] Check whether units are failed\n"
4727 " status [NAME...|PID...] Show runtime status of one or more units\n"
4728 " show [NAME...|JOB...] Show properties of one or more\n"
4729 " units/jobs or the manager\n"
4730 " set-property [NAME] [ASSIGNMENT...]\n"
4731 " Sets one or more properties of a unit\n"
4732 " help [NAME...|PID...] Show manual for one or more units\n"
4733 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4735 " load [NAME...] Load one or more units\n"
4736 " list-dependencies [NAME] Recursively show units which are required\n"
4737 " or wanted by this unit or by which this\n"
4738 " unit is required or wanted\n\n"
4739 "Unit File Commands:\n"
4740 " list-unit-files List installed unit files\n"
4741 " enable [NAME...] Enable one or more unit files\n"
4742 " disable [NAME...] Disable one or more unit files\n"
4743 " reenable [NAME...] Reenable one or more unit files\n"
4744 " preset [NAME...] Enable/disable one or more unit files\n"
4745 " based on preset configuration\n"
4746 " mask [NAME...] Mask one or more units\n"
4747 " unmask [NAME...] Unmask one or more units\n"
4748 " link [PATH...] Link one or more units files into\n"
4749 " the search path\n"
4750 " get-default Get the name of the default target\n"
4751 " set-default NAME Set the default target\n"
4752 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
4754 " list-jobs List jobs\n"
4755 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
4756 "Snapshot Commands:\n"
4757 " snapshot [NAME] Create a snapshot\n"
4758 " delete [NAME...] Remove one or more snapshots\n\n"
4759 "Environment Commands:\n"
4760 " show-environment Dump environment\n"
4761 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4762 " unset-environment [NAME...] Unset one or more environment variables\n"
4763 " set-log-level LEVEL Set logging threshold for systemd\n\n"
4764 "Manager Lifecycle Commands:\n"
4765 " daemon-reload Reload systemd manager configuration\n"
4766 " daemon-reexec Reexecute systemd manager\n\n"
4767 "System Commands:\n"
4768 " default Enter system default mode\n"
4769 " rescue Enter system rescue mode\n"
4770 " emergency Enter system emergency mode\n"
4771 " halt Shut down and halt the system\n"
4772 " poweroff Shut down and power-off the system\n"
4773 " reboot Shut down and reboot the system\n"
4774 " kexec Shut down and reboot the system with kexec\n"
4775 " exit Request user instance exit\n"
4776 " switch-root [ROOT] [INIT] Change to a different root file system\n"
4777 " suspend Suspend the system\n"
4778 " hibernate Hibernate the system\n"
4779 " hybrid-sleep Hibernate and suspend the system\n",
4780 program_invocation_short_name);
4785 static int halt_help(void) {
4787 printf("%s [OPTIONS...]\n\n"
4788 "%s the system.\n\n"
4789 " --help Show this help\n"
4790 " --halt Halt the machine\n"
4791 " -p --poweroff Switch off the machine\n"
4792 " --reboot Reboot the machine\n"
4793 " -f --force Force immediate halt/power-off/reboot\n"
4794 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4795 " -d --no-wtmp Don't write wtmp record\n"
4796 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4797 program_invocation_short_name,
4798 arg_action == ACTION_REBOOT ? "Reboot" :
4799 arg_action == ACTION_POWEROFF ? "Power off" :
4805 static int shutdown_help(void) {
4807 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4808 "Shut down the system.\n\n"
4809 " --help Show this help\n"
4810 " -H --halt Halt the machine\n"
4811 " -P --poweroff Power-off the machine\n"
4812 " -r --reboot Reboot the machine\n"
4813 " -h Equivalent to --poweroff, overridden by --halt\n"
4814 " -k Don't halt/power-off/reboot, just send warnings\n"
4815 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4816 " -c Cancel a pending shutdown\n",
4817 program_invocation_short_name);
4822 static int telinit_help(void) {
4824 printf("%s [OPTIONS...] {COMMAND}\n\n"
4825 "Send control commands to the init daemon.\n\n"
4826 " --help Show this help\n"
4827 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4829 " 0 Power-off the machine\n"
4830 " 6 Reboot the machine\n"
4831 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4832 " 1, s, S Enter rescue mode\n"
4833 " q, Q Reload init daemon configuration\n"
4834 " u, U Reexecute init daemon\n",
4835 program_invocation_short_name);
4840 static int runlevel_help(void) {
4842 printf("%s [OPTIONS...]\n\n"
4843 "Prints the previous and current runlevel of the init system.\n\n"
4844 " --help Show this help\n",
4845 program_invocation_short_name);
4850 static int help_types(void) {
4854 puts("Available unit types:");
4855 for(i = 0; i < _UNIT_TYPE_MAX; i++) {
4856 t = unit_type_to_string(i);
4864 static int systemctl_parse_argv(int argc, char *argv[]) {
4873 ARG_IGNORE_DEPENDENCIES,
4885 ARG_NO_ASK_PASSWORD,
4893 static const struct option options[] = {
4894 { "help", no_argument, NULL, 'h' },
4895 { "version", no_argument, NULL, ARG_VERSION },
4896 { "type", required_argument, NULL, 't' },
4897 { "property", required_argument, NULL, 'p' },
4898 { "all", no_argument, NULL, 'a' },
4899 { "reverse", no_argument, NULL, ARG_REVERSE },
4900 { "after", no_argument, NULL, ARG_AFTER },
4901 { "before", no_argument, NULL, ARG_BEFORE },
4902 { "show-types", no_argument, NULL, ARG_SHOW_TYPES },
4903 { "failed", no_argument, NULL, ARG_FAILED }, /* compatibility only */
4904 { "full", no_argument, NULL, 'l' },
4905 { "fail", no_argument, NULL, ARG_FAIL },
4906 { "irreversible", no_argument, NULL, ARG_IRREVERSIBLE },
4907 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4908 { "ignore-inhibitors", no_argument, NULL, 'i' },
4909 { "user", no_argument, NULL, ARG_USER },
4910 { "system", no_argument, NULL, ARG_SYSTEM },
4911 { "global", no_argument, NULL, ARG_GLOBAL },
4912 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4913 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4914 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4915 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4916 { "quiet", no_argument, NULL, 'q' },
4917 { "root", required_argument, NULL, ARG_ROOT },
4918 { "force", no_argument, NULL, ARG_FORCE },
4919 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4920 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4921 { "signal", required_argument, NULL, 's' },
4922 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4923 { "host", required_argument, NULL, 'H' },
4924 { "privileged", no_argument, NULL, 'P' },
4925 { "runtime", no_argument, NULL, ARG_RUNTIME },
4926 { "lines", required_argument, NULL, 'n' },
4927 { "output", required_argument, NULL, 'o' },
4928 { "plain", no_argument, NULL, ARG_PLAIN },
4929 { "state", required_argument, NULL, ARG_STATE },
4930 { NULL, 0, NULL, 0 }
4938 while ((c = getopt_long(argc, argv, "ht:p:alqfs:H:Pn:o:i", options, NULL)) >= 0) {
4947 puts(PACKAGE_STRING);
4948 puts(SYSTEMD_FEATURES);
4955 FOREACH_WORD_SEPARATOR(word, size, optarg, ",", state) {
4956 _cleanup_free_ char *type;
4958 type = strndup(word, size);
4962 if (streq(type, "help")) {
4967 if (unit_type_from_string(type) >= 0) {
4968 if (strv_push(&arg_types, type))
4974 /* It's much nicer to use --state= for
4975 * load states, but let's support this
4976 * in --types= too for compatibility
4977 * with old versions */
4978 if (unit_load_state_from_string(optarg) >= 0) {
4979 if (strv_push(&arg_states, type) < 0)
4985 log_error("Unknown unit type or load state '%s'.", type);
4986 log_info("Use -t help to see a list of allowed values.");
4994 /* Make sure that if the empty property list
4995 was specified, we won't show any properties. */
4996 if (isempty(optarg) && !arg_properties) {
4997 arg_properties = strv_new(NULL, NULL);
4998 if (!arg_properties)
5004 FOREACH_WORD_SEPARATOR(word, size, optarg, ",", state) {
5007 prop = strndup(word, size);
5011 if (strv_push(&arg_properties, prop) < 0) {
5018 /* If the user asked for a particular
5019 * property, show it to him, even if it is
5031 arg_dependency = DEPENDENCY_REVERSE;
5035 arg_dependency = DEPENDENCY_AFTER;
5039 arg_dependency = DEPENDENCY_BEFORE;
5042 case ARG_SHOW_TYPES:
5043 arg_show_types = true;
5047 arg_job_mode = "fail";
5050 case ARG_IRREVERSIBLE:
5051 arg_job_mode = "replace-irreversibly";
5054 case ARG_IGNORE_DEPENDENCIES:
5055 arg_job_mode = "ignore-dependencies";
5059 arg_scope = UNIT_FILE_USER;
5063 arg_scope = UNIT_FILE_SYSTEM;
5067 arg_scope = UNIT_FILE_GLOBAL;
5071 arg_no_block = true;
5075 arg_no_legend = true;
5079 arg_no_pager = true;
5095 if (strv_extend(&arg_states, "failed") < 0)
5113 arg_no_reload = true;
5117 arg_kill_who = optarg;
5121 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
5122 log_error("Failed to parse signal string %s.", optarg);
5127 case ARG_NO_ASK_PASSWORD:
5128 arg_ask_password = false;
5132 arg_transport = TRANSPORT_POLKIT;
5136 arg_transport = TRANSPORT_SSH;
5137 parse_user_at_host(optarg, &arg_user, &arg_host);
5145 if (safe_atou(optarg, &arg_lines) < 0) {
5146 log_error("Failed to parse lines '%s'", optarg);
5152 arg_output = output_mode_from_string(optarg);
5153 if (arg_output < 0) {
5154 log_error("Unknown output '%s'.", optarg);
5160 arg_ignore_inhibitors = true;
5171 FOREACH_WORD_SEPARATOR(word, size, optarg, ",", state) {
5174 s = strndup(word, size);
5178 if (strv_push(&arg_states, s) < 0) {
5190 log_error("Unknown option code '%c'.", c);
5195 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
5196 log_error("Cannot access user instance remotely.");
5203 static int halt_parse_argv(int argc, char *argv[]) {
5212 static const struct option options[] = {
5213 { "help", no_argument, NULL, ARG_HELP },
5214 { "halt", no_argument, NULL, ARG_HALT },
5215 { "poweroff", no_argument, NULL, 'p' },
5216 { "reboot", no_argument, NULL, ARG_REBOOT },
5217 { "force", no_argument, NULL, 'f' },
5218 { "wtmp-only", no_argument, NULL, 'w' },
5219 { "no-wtmp", no_argument, NULL, 'd' },
5220 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5221 { NULL, 0, NULL, 0 }
5229 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
5230 if (runlevel == '0' || runlevel == '6')
5233 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
5241 arg_action = ACTION_HALT;
5245 if (arg_action != ACTION_REBOOT)
5246 arg_action = ACTION_POWEROFF;
5250 arg_action = ACTION_REBOOT;
5272 /* Compatibility nops */
5279 log_error("Unknown option code '%c'.", c);
5284 if (optind < argc) {
5285 log_error("Too many arguments.");
5292 static int parse_time_spec(const char *t, usec_t *_u) {
5296 if (streq(t, "now"))
5298 else if (!strchr(t, ':')) {
5301 if (safe_atou64(t, &u) < 0)
5304 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
5313 hour = strtol(t, &e, 10);
5314 if (errno > 0 || *e != ':' || hour < 0 || hour > 23)
5317 minute = strtol(e+1, &e, 10);
5318 if (errno > 0 || *e != 0 || minute < 0 || minute > 59)
5321 n = now(CLOCK_REALTIME);
5322 s = (time_t) (n / USEC_PER_SEC);
5324 assert_se(localtime_r(&s, &tm));
5326 tm.tm_hour = (int) hour;
5327 tm.tm_min = (int) minute;
5330 assert_se(s = mktime(&tm));
5332 *_u = (usec_t) s * USEC_PER_SEC;
5335 *_u += USEC_PER_DAY;
5341 static int shutdown_parse_argv(int argc, char *argv[]) {
5348 static const struct option options[] = {
5349 { "help", no_argument, NULL, ARG_HELP },
5350 { "halt", no_argument, NULL, 'H' },
5351 { "poweroff", no_argument, NULL, 'P' },
5352 { "reboot", no_argument, NULL, 'r' },
5353 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
5354 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5355 { NULL, 0, NULL, 0 }
5363 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
5371 arg_action = ACTION_HALT;
5375 arg_action = ACTION_POWEROFF;
5380 arg_action = ACTION_KEXEC;
5382 arg_action = ACTION_REBOOT;
5386 arg_action = ACTION_KEXEC;
5390 if (arg_action != ACTION_HALT)
5391 arg_action = ACTION_POWEROFF;
5404 /* Compatibility nops */
5408 arg_action = ACTION_CANCEL_SHUTDOWN;
5415 log_error("Unknown option code '%c'.", c);
5420 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
5421 r = parse_time_spec(argv[optind], &arg_when);
5423 log_error("Failed to parse time specification: %s", argv[optind]);
5427 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
5429 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
5430 /* No time argument for shutdown cancel */
5431 arg_wall = argv + optind;
5432 else if (argc > optind + 1)
5433 /* We skip the time argument */
5434 arg_wall = argv + optind + 1;
5441 static int telinit_parse_argv(int argc, char *argv[]) {
5448 static const struct option options[] = {
5449 { "help", no_argument, NULL, ARG_HELP },
5450 { "no-wall", no_argument, NULL, ARG_NO_WALL },
5451 { NULL, 0, NULL, 0 }
5454 static const struct {
5458 { '0', ACTION_POWEROFF },
5459 { '6', ACTION_REBOOT },
5460 { '1', ACTION_RESCUE },
5461 { '2', ACTION_RUNLEVEL2 },
5462 { '3', ACTION_RUNLEVEL3 },
5463 { '4', ACTION_RUNLEVEL4 },
5464 { '5', ACTION_RUNLEVEL5 },
5465 { 's', ACTION_RESCUE },
5466 { 'S', ACTION_RESCUE },
5467 { 'q', ACTION_RELOAD },
5468 { 'Q', ACTION_RELOAD },
5469 { 'u', ACTION_REEXEC },
5470 { 'U', ACTION_REEXEC }
5479 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5494 log_error("Unknown option code '%c'.", c);
5499 if (optind >= argc) {
5504 if (optind + 1 < argc) {
5505 log_error("Too many arguments.");
5509 if (strlen(argv[optind]) != 1) {
5510 log_error("Expected single character argument.");
5514 for (i = 0; i < ELEMENTSOF(table); i++)
5515 if (table[i].from == argv[optind][0])
5518 if (i >= ELEMENTSOF(table)) {
5519 log_error("Unknown command '%s'.", argv[optind]);
5523 arg_action = table[i].to;
5530 static int runlevel_parse_argv(int argc, char *argv[]) {
5536 static const struct option options[] = {
5537 { "help", no_argument, NULL, ARG_HELP },
5538 { NULL, 0, NULL, 0 }
5546 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5557 log_error("Unknown option code '%c'.", c);
5562 if (optind < argc) {
5563 log_error("Too many arguments.");
5570 static int parse_argv(int argc, char *argv[]) {
5574 if (program_invocation_short_name) {
5576 if (strstr(program_invocation_short_name, "halt")) {
5577 arg_action = ACTION_HALT;
5578 return halt_parse_argv(argc, argv);
5579 } else if (strstr(program_invocation_short_name, "poweroff")) {
5580 arg_action = ACTION_POWEROFF;
5581 return halt_parse_argv(argc, argv);
5582 } else if (strstr(program_invocation_short_name, "reboot")) {
5584 arg_action = ACTION_KEXEC;
5586 arg_action = ACTION_REBOOT;
5587 return halt_parse_argv(argc, argv);
5588 } else if (strstr(program_invocation_short_name, "shutdown")) {
5589 arg_action = ACTION_POWEROFF;
5590 return shutdown_parse_argv(argc, argv);
5591 } else if (strstr(program_invocation_short_name, "init")) {
5593 if (sd_booted() > 0) {
5594 arg_action = ACTION_INVALID;
5595 return telinit_parse_argv(argc, argv);
5597 /* Hmm, so some other init system is
5598 * running, we need to forward this
5599 * request to it. For now we simply
5600 * guess that it is Upstart. */
5602 execv(TELINIT, argv);
5604 log_error("Couldn't find an alternative telinit implementation to spawn.");
5608 } else if (strstr(program_invocation_short_name, "runlevel")) {
5609 arg_action = ACTION_RUNLEVEL;
5610 return runlevel_parse_argv(argc, argv);
5614 arg_action = ACTION_SYSTEMCTL;
5615 return systemctl_parse_argv(argc, argv);
5618 _pure_ static int action_to_runlevel(void) {
5620 static const char table[_ACTION_MAX] = {
5621 [ACTION_HALT] = '0',
5622 [ACTION_POWEROFF] = '0',
5623 [ACTION_REBOOT] = '6',
5624 [ACTION_RUNLEVEL2] = '2',
5625 [ACTION_RUNLEVEL3] = '3',
5626 [ACTION_RUNLEVEL4] = '4',
5627 [ACTION_RUNLEVEL5] = '5',
5628 [ACTION_RESCUE] = '1'
5631 assert(arg_action < _ACTION_MAX);
5633 return table[arg_action];
5636 static int talk_upstart(void) {
5637 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
5638 _cleanup_dbus_error_free_ DBusError error;
5639 int previous, rl, r;
5641 env1_buf[] = "RUNLEVEL=X",
5642 env2_buf[] = "PREVLEVEL=X";
5643 char *env1 = env1_buf, *env2 = env2_buf;
5644 const char *emit = "runlevel";
5645 dbus_bool_t b_false = FALSE;
5646 DBusMessageIter iter, sub;
5647 DBusConnection *bus;
5649 dbus_error_init(&error);
5651 if (!(rl = action_to_runlevel()))
5654 if (utmp_get_runlevel(&previous, NULL) < 0)
5657 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5658 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5663 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5668 if ((r = bus_check_peercred(bus)) < 0) {
5669 log_error("Failed to verify owner of bus.");
5673 if (!(m = dbus_message_new_method_call(
5674 "com.ubuntu.Upstart",
5675 "/com/ubuntu/Upstart",
5676 "com.ubuntu.Upstart0_6",
5679 log_error("Could not allocate message.");
5684 dbus_message_iter_init_append(m, &iter);
5686 env1_buf[sizeof(env1_buf)-2] = rl;
5687 env2_buf[sizeof(env2_buf)-2] = previous;
5689 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5690 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5691 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5692 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5693 !dbus_message_iter_close_container(&iter, &sub) ||
5694 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5695 log_error("Could not append arguments to message.");
5700 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5702 if (bus_error_is_no_service(&error)) {
5707 log_error("Failed to issue method call: %s", bus_error_message(&error));
5716 dbus_connection_flush(bus);
5717 dbus_connection_close(bus);
5718 dbus_connection_unref(bus);
5724 static int talk_initctl(void) {
5725 struct init_request request = {};
5727 _cleanup_close_ int fd = -1;
5730 rl = action_to_runlevel();
5734 request.magic = INIT_MAGIC;
5735 request.sleeptime = 0;
5736 request.cmd = INIT_CMD_RUNLVL;
5737 request.runlevel = rl;
5739 fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY);
5741 if (errno == ENOENT)
5744 log_error("Failed to open "INIT_FIFO": %m");
5749 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5751 log_error("Failed to write to "INIT_FIFO": %m");
5752 return errno > 0 ? -errno : -EIO;
5758 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5760 static const struct {
5768 int (* const dispatch)(DBusConnection *bus, char **args);
5770 { "list-units", LESS, 1, list_units },
5771 { "list-unit-files", EQUAL, 1, list_unit_files },
5772 { "list-sockets", LESS, 1, list_sockets },
5773 { "list-jobs", EQUAL, 1, list_jobs },
5774 { "clear-jobs", EQUAL, 1, daemon_reload },
5775 { "load", MORE, 2, load_unit },
5776 { "cancel", MORE, 2, cancel_job },
5777 { "start", MORE, 2, start_unit },
5778 { "stop", MORE, 2, start_unit },
5779 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5780 { "reload", MORE, 2, start_unit },
5781 { "restart", MORE, 2, start_unit },
5782 { "try-restart", MORE, 2, start_unit },
5783 { "reload-or-restart", MORE, 2, start_unit },
5784 { "reload-or-try-restart", MORE, 2, start_unit },
5785 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5786 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5787 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5788 { "isolate", EQUAL, 2, start_unit },
5789 { "kill", MORE, 2, kill_unit },
5790 { "is-active", MORE, 2, check_unit_active },
5791 { "check", MORE, 2, check_unit_active },
5792 { "is-failed", MORE, 2, check_unit_failed },
5793 { "show", MORE, 1, show },
5794 { "status", MORE, 1, show },
5795 { "help", MORE, 2, show },
5796 { "snapshot", LESS, 2, snapshot },
5797 { "delete", MORE, 2, delete_snapshot },
5798 { "daemon-reload", EQUAL, 1, daemon_reload },
5799 { "daemon-reexec", EQUAL, 1, daemon_reload },
5800 { "show-environment", EQUAL, 1, show_enviroment },
5801 { "set-environment", MORE, 2, set_environment },
5802 { "unset-environment", MORE, 2, set_environment },
5803 { "halt", EQUAL, 1, start_special },
5804 { "poweroff", EQUAL, 1, start_special },
5805 { "reboot", EQUAL, 1, start_special },
5806 { "kexec", EQUAL, 1, start_special },
5807 { "suspend", EQUAL, 1, start_special },
5808 { "hibernate", EQUAL, 1, start_special },
5809 { "hybrid-sleep", EQUAL, 1, start_special },
5810 { "default", EQUAL, 1, start_special },
5811 { "rescue", EQUAL, 1, start_special },
5812 { "emergency", EQUAL, 1, start_special },
5813 { "exit", EQUAL, 1, start_special },
5814 { "reset-failed", MORE, 1, reset_failed },
5815 { "enable", MORE, 2, enable_unit },
5816 { "disable", MORE, 2, enable_unit },
5817 { "is-enabled", MORE, 2, unit_is_enabled },
5818 { "reenable", MORE, 2, enable_unit },
5819 { "preset", MORE, 2, enable_unit },
5820 { "mask", MORE, 2, enable_unit },
5821 { "unmask", MORE, 2, enable_unit },
5822 { "link", MORE, 2, enable_unit },
5823 { "switch-root", MORE, 2, switch_root },
5824 { "list-dependencies", LESS, 2, list_dependencies },
5825 { "set-default", EQUAL, 2, enable_unit },
5826 { "get-default", LESS, 1, get_default },
5827 { "set-log-level", EQUAL, 2, set_log_level },
5828 { "set-property", MORE, 3, set_property },
5838 left = argc - optind;
5841 /* Special rule: no arguments means "list-units" */
5844 if (streq(argv[optind], "help") && !argv[optind+1]) {
5845 log_error("This command expects one or more "
5846 "unit names. Did you mean --help?");
5850 for (i = 0; i < ELEMENTSOF(verbs); i++)
5851 if (streq(argv[optind], verbs[i].verb))
5854 if (i >= ELEMENTSOF(verbs)) {
5855 log_error("Unknown operation '%s'.", argv[optind]);
5860 switch (verbs[i].argc_cmp) {
5863 if (left != verbs[i].argc) {
5864 log_error("Invalid number of arguments.");
5871 if (left < verbs[i].argc) {
5872 log_error("Too few arguments.");
5879 if (left > verbs[i].argc) {
5880 log_error("Too many arguments.");
5887 assert_not_reached("Unknown comparison operator.");
5890 /* Require a bus connection for all operations but
5892 if (!streq(verbs[i].verb, "enable") &&
5893 !streq(verbs[i].verb, "disable") &&
5894 !streq(verbs[i].verb, "is-enabled") &&
5895 !streq(verbs[i].verb, "list-unit-files") &&
5896 !streq(verbs[i].verb, "reenable") &&
5897 !streq(verbs[i].verb, "preset") &&
5898 !streq(verbs[i].verb, "mask") &&
5899 !streq(verbs[i].verb, "unmask") &&
5900 !streq(verbs[i].verb, "link") &&
5901 !streq(verbs[i].verb, "set-default") &&
5902 !streq(verbs[i].verb, "get-default")) {
5904 if (running_in_chroot() > 0) {
5905 log_info("Running in chroot, ignoring request.");
5909 if (((!streq(verbs[i].verb, "reboot") &&
5910 !streq(verbs[i].verb, "halt") &&
5911 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5912 log_error("Failed to get D-Bus connection: %s",
5913 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5919 if (!bus && !avoid_bus()) {
5920 log_error("Failed to get D-Bus connection: %s",
5921 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5926 return verbs[i].dispatch(bus, argv + optind);
5929 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5930 _cleanup_close_ int fd;
5931 struct sd_shutdown_command c = {
5937 union sockaddr_union sockaddr = {
5938 .un.sun_family = AF_UNIX,
5939 .un.sun_path = "/run/systemd/shutdownd",
5941 struct iovec iovec[2] = {
5942 {.iov_base = (char*) &c,
5943 .iov_len = offsetof(struct sd_shutdown_command, wall_message),
5946 struct msghdr msghdr = {
5947 .msg_name = &sockaddr,
5948 .msg_namelen = offsetof(struct sockaddr_un, sun_path)
5949 + sizeof("/run/systemd/shutdownd") - 1,
5954 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5958 if (!isempty(message)) {
5959 iovec[1].iov_base = (char*) message;
5960 iovec[1].iov_len = strlen(message);
5961 msghdr.msg_iovlen++;
5964 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0)
5970 static int reload_with_fallback(DBusConnection *bus) {
5973 /* First, try systemd via D-Bus. */
5974 if (daemon_reload(bus, NULL) >= 0)
5978 /* Nothing else worked, so let's try signals */
5979 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5981 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5982 log_error("kill() failed: %m");
5989 static int start_with_fallback(DBusConnection *bus) {
5992 /* First, try systemd via D-Bus. */
5993 if (start_unit(bus, NULL) >= 0)
5997 /* Hmm, talking to systemd via D-Bus didn't work. Then
5998 * let's try to talk to Upstart via D-Bus. */
5999 if (talk_upstart() > 0)
6002 /* Nothing else worked, so let's try
6004 if (talk_initctl() > 0)
6007 log_error("Failed to talk to init daemon.");
6011 warn_wall(arg_action);
6015 static _noreturn_ void halt_now(enum action a) {
6017 /* Make sure C-A-D is handled by the kernel from this
6019 reboot(RB_ENABLE_CAD);
6024 log_info("Halting.");
6025 reboot(RB_HALT_SYSTEM);
6028 case ACTION_POWEROFF:
6029 log_info("Powering off.");
6030 reboot(RB_POWER_OFF);
6034 log_info("Rebooting.");
6035 reboot(RB_AUTOBOOT);
6039 assert_not_reached("Unknown halt action.");
6042 assert_not_reached("Uh? This shouldn't happen.");
6045 static int halt_main(DBusConnection *bus) {
6048 r = check_inhibitors(bus, arg_action);
6052 if (geteuid() != 0) {
6053 /* Try logind if we are a normal user and no special
6054 * mode applies. Maybe PolicyKit allows us to shutdown
6057 if (arg_when <= 0 &&
6060 (arg_action == ACTION_POWEROFF ||
6061 arg_action == ACTION_REBOOT)) {
6062 r = reboot_with_logind(bus, arg_action);
6067 log_error("Must be root.");
6072 _cleanup_free_ char *m;
6074 m = strv_join(arg_wall, " ");
6075 r = send_shutdownd(arg_when,
6076 arg_action == ACTION_HALT ? 'H' :
6077 arg_action == ACTION_POWEROFF ? 'P' :
6078 arg_action == ACTION_KEXEC ? 'K' :
6085 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
6087 char date[FORMAT_TIMESTAMP_MAX];
6089 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
6090 format_timestamp(date, sizeof(date), arg_when));
6095 if (!arg_dry && !arg_force)
6096 return start_with_fallback(bus);
6099 if (sd_booted() > 0)
6100 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
6102 r = utmp_put_shutdown();
6104 log_warning("Failed to write utmp record: %s", strerror(-r));
6111 halt_now(arg_action);
6112 /* We should never reach this. */
6116 static int runlevel_main(void) {
6117 int r, runlevel, previous;
6119 r = utmp_get_runlevel(&runlevel, &previous);
6126 previous <= 0 ? 'N' : previous,
6127 runlevel <= 0 ? 'N' : runlevel);
6132 int main(int argc, char*argv[]) {
6133 int r, retval = EXIT_FAILURE;
6134 DBusConnection *bus = NULL;
6135 _cleanup_dbus_error_free_ DBusError error;
6137 dbus_error_init(&error);
6139 setlocale(LC_ALL, "");
6140 log_parse_environment();
6143 r = parse_argv(argc, argv);
6147 retval = EXIT_SUCCESS;
6151 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
6152 * let's shortcut this */
6153 if (arg_action == ACTION_RUNLEVEL) {
6154 r = runlevel_main();
6155 retval = r < 0 ? EXIT_FAILURE : r;
6159 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
6160 log_info("Running in chroot, ignoring request.");
6166 if (arg_transport == TRANSPORT_NORMAL)
6167 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
6168 else if (arg_transport == TRANSPORT_POLKIT) {
6169 bus_connect_system_polkit(&bus, &error);
6170 private_bus = false;
6171 } else if (arg_transport == TRANSPORT_SSH) {
6172 bus_connect_system_ssh(arg_user, arg_host, &bus, &error);
6173 private_bus = false;
6175 assert_not_reached("Uh, invalid transport...");
6178 switch (arg_action) {
6180 case ACTION_SYSTEMCTL:
6181 r = systemctl_main(bus, argc, argv, &error);
6185 case ACTION_POWEROFF:
6191 case ACTION_RUNLEVEL2:
6192 case ACTION_RUNLEVEL3:
6193 case ACTION_RUNLEVEL4:
6194 case ACTION_RUNLEVEL5:
6196 case ACTION_EMERGENCY:
6197 case ACTION_DEFAULT:
6198 r = start_with_fallback(bus);
6203 r = reload_with_fallback(bus);
6206 case ACTION_CANCEL_SHUTDOWN: {
6210 m = strv_join(arg_wall, " ");
6212 retval = EXIT_FAILURE;
6216 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
6218 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
6223 case ACTION_INVALID:
6224 case ACTION_RUNLEVEL:
6226 assert_not_reached("Unknown action");
6229 retval = r < 0 ? EXIT_FAILURE : r;
6233 dbus_connection_flush(bus);
6234 dbus_connection_close(bus);
6235 dbus_connection_unref(bus);
6240 strv_free(arg_types);
6241 strv_free(arg_states);
6242 strv_free(arg_properties);
6245 ask_password_agent_close();
6246 polkit_agent_close();