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"
70 static const char *arg_type = NULL;
71 static const char *arg_load_state = NULL;
72 static char **arg_property = NULL;
73 static bool arg_all = false;
74 static const char *arg_job_mode = "replace";
75 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
76 static bool arg_no_block = false;
77 static bool arg_no_legend = false;
78 static bool arg_no_pager = false;
79 static bool arg_no_wtmp = false;
80 static bool arg_no_wall = false;
81 static bool arg_no_reload = false;
82 static bool arg_ignore_inhibitors = false;
83 static bool arg_dry = false;
84 static bool arg_quiet = false;
85 static bool arg_full = false;
86 static int arg_force = 0;
87 static bool arg_ask_password = true;
88 static bool arg_failed = false;
89 static bool arg_runtime = false;
90 static char **arg_wall = NULL;
91 static const char *arg_kill_who = NULL;
92 static int arg_signal = SIGTERM;
93 static const char *arg_root = NULL;
94 static usec_t arg_when = 0;
116 ACTION_CANCEL_SHUTDOWN,
118 } arg_action = ACTION_SYSTEMCTL;
124 static enum transport {
128 } arg_transport = TRANSPORT_NORMAL;
129 static const char *arg_host = NULL;
130 static unsigned arg_lines = 10;
131 static OutputMode arg_output = OUTPUT_SHORT;
133 static bool private_bus = false;
135 static int daemon_reload(DBusConnection *bus, char **args);
136 static void halt_now(enum action a);
138 static void pager_open_if_enabled(void) {
146 static void ask_password_agent_open_if_enabled(void) {
148 /* Open the password agent as a child process if necessary */
150 if (!arg_ask_password)
153 if (arg_scope != UNIT_FILE_SYSTEM)
156 ask_password_agent_open();
160 static void polkit_agent_open_if_enabled(void) {
162 /* Open the polkit agent as a child process if necessary */
164 if (!arg_ask_password)
167 if (arg_scope != UNIT_FILE_SYSTEM)
174 static const char *ansi_highlight(bool b) {
179 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
182 static const char *ansi_highlight_red(bool b) {
187 return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
190 static const char *ansi_highlight_green(bool b) {
195 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
198 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
201 if (!dbus_error_is_set(error))
204 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
205 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
206 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
207 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
208 return EXIT_NOPERMISSION;
210 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
211 return EXIT_NOTINSTALLED;
213 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
214 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
215 return EXIT_NOTIMPLEMENTED;
217 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
218 return EXIT_NOTCONFIGURED;
226 static void warn_wall(enum action a) {
227 static const char *table[_ACTION_MAX] = {
228 [ACTION_HALT] = "The system is going down for system halt NOW!",
229 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
230 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
231 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
232 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
233 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!",
234 [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
241 _cleanup_free_ char *p;
243 p = strv_join(arg_wall, " ");
258 utmp_wall(table[a], NULL);
261 static bool avoid_bus(void) {
263 if (running_in_chroot() > 0)
266 if (sd_booted() <= 0)
269 if (!isempty(arg_root))
272 if (arg_scope == UNIT_FILE_GLOBAL)
280 const char *description;
281 const char *load_state;
282 const char *active_state;
283 const char *sub_state;
284 const char *following;
285 const char *unit_path;
287 const char *job_type;
288 const char *job_path;
291 static int compare_unit_info(const void *a, const void *b) {
293 const struct unit_info *u = a, *v = b;
295 d1 = strrchr(u->id, '.');
296 d2 = strrchr(v->id, '.');
301 r = strcasecmp(d1, d2);
306 return strcasecmp(u->id, v->id);
309 static bool output_show_unit(const struct unit_info *u) {
313 return streq(u->active_state, "failed");
315 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
316 streq(dot+1, arg_type))) &&
317 (!arg_load_state || streq(u->load_state, arg_load_state)) &&
318 (arg_all || !(streq(u->active_state, "inactive")
319 || u->following[0]) || u->job_id > 0);
322 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
323 unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
324 const struct unit_info *u;
327 max_id_len = sizeof("UNIT")-1;
328 active_len = sizeof("ACTIVE")-1;
329 sub_len = sizeof("SUB")-1;
330 job_len = sizeof("JOB")-1;
333 for (u = unit_infos; u < unit_infos + c; u++) {
334 if (!output_show_unit(u))
337 max_id_len = MAX(max_id_len, strlen(u->id));
338 active_len = MAX(active_len, strlen(u->active_state));
339 sub_len = MAX(sub_len, strlen(u->sub_state));
340 if (u->job_id != 0) {
341 job_len = MAX(job_len, strlen(u->job_type));
348 id_len = MIN(max_id_len, 25);
349 basic_len = 5 + id_len + 5 + active_len + sub_len;
351 basic_len += job_len + 1;
352 if (basic_len < (unsigned) columns()) {
353 unsigned extra_len, incr;
354 extra_len = columns() - basic_len;
355 /* Either UNIT already got 25, or is fully satisfied.
356 * Grant up to 25 to DESC now. */
357 incr = MIN(extra_len, 25);
360 /* split the remaining space between UNIT and DESC,
361 * but do not give UNIT more than it needs. */
363 incr = MIN(extra_len / 2, max_id_len - id_len);
365 desc_len += extra_len - incr;
371 for (u = unit_infos; u < unit_infos + c; u++) {
373 const char *on_loaded, *off_loaded;
374 const char *on_active, *off_active;
376 if (!output_show_unit(u))
379 if (!n_shown && !arg_no_legend) {
380 printf("%-*s %-6s %-*s %-*s ", id_len, "UNIT", "LOAD",
381 active_len, "ACTIVE", sub_len, "SUB");
383 printf("%-*s ", job_len, "JOB");
384 if (!arg_full && arg_no_pager)
385 printf("%.*s\n", desc_len, "DESCRIPTION");
387 printf("%s\n", "DESCRIPTION");
392 if (streq(u->load_state, "error")) {
393 on_loaded = ansi_highlight_red(true);
394 off_loaded = ansi_highlight_red(false);
396 on_loaded = off_loaded = "";
398 if (streq(u->active_state, "failed")) {
399 on_active = ansi_highlight_red(true);
400 off_active = ansi_highlight_red(false);
402 on_active = off_active = "";
404 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
406 printf("%-*s %s%-6s%s %s%-*s %-*s%s %-*s",
407 id_len, e ? e : u->id,
408 on_loaded, u->load_state, off_loaded,
409 on_active, active_len, u->active_state,
410 sub_len, u->sub_state, off_active,
411 job_count ? job_len + 1 : 0, u->job_id ? u->job_type : "");
412 if (!arg_full && arg_no_pager)
413 printf("%.*s\n", desc_len, u->description);
415 printf("%s\n", u->description);
420 if (!arg_no_legend) {
421 const char *on, *off;
424 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
425 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
426 "SUB = The low-level unit activation state, values depend on unit type.\n");
428 printf("JOB = Pending job for the unit.\n");
430 on = ansi_highlight(true);
431 off = ansi_highlight(false);
433 on = ansi_highlight_red(true);
434 off = ansi_highlight_red(false);
438 printf("%s%u loaded units listed.%s\n"
439 "To show all installed unit files use 'systemctl list-unit-files'.\n",
442 printf("%s%u loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
443 "To show all installed unit files use 'systemctl list-unit-files'.\n",
448 static int list_units(DBusConnection *bus, char **args) {
449 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
450 _cleanup_free_ struct unit_info *unit_infos = NULL;
451 DBusMessageIter iter, sub, sub2;
452 unsigned c = 0, n_units = 0;
455 pager_open_if_enabled();
457 r = bus_method_call_with_reply(
459 "org.freedesktop.systemd1",
460 "/org/freedesktop/systemd1",
461 "org.freedesktop.systemd1.Manager",
469 if (!dbus_message_iter_init(reply, &iter) ||
470 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
471 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
472 log_error("Failed to parse reply.");
476 dbus_message_iter_recurse(&iter, &sub);
478 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
481 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT);
486 n_units = MAX(2*c, 16);
487 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
496 dbus_message_iter_recurse(&sub, &sub2);
498 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
499 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
500 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
501 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
502 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
503 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
504 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
505 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
506 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
507 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
508 log_error("Failed to parse reply.");
512 dbus_message_iter_next(&sub);
517 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
518 output_units_list(unit_infos, c);
524 static int compare_unit_file_list(const void *a, const void *b) {
526 const UnitFileList *u = a, *v = b;
528 d1 = strrchr(u->path, '.');
529 d2 = strrchr(v->path, '.');
534 r = strcasecmp(d1, d2);
539 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
542 static bool output_show_unit_file(const UnitFileList *u) {
545 return !arg_type || ((dot = strrchr(u->path, '.')) && streq(dot+1, arg_type));
548 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
549 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
550 const UnitFileList *u;
552 max_id_len = sizeof("UNIT FILE")-1;
553 state_cols = sizeof("STATE")-1;
554 for (u = units; u < units + c; u++) {
555 if (!output_show_unit_file(u))
558 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
559 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
564 id_cols = MIN(max_id_len, 25);
565 basic_cols = 1 + id_cols + state_cols;
566 if (basic_cols < (unsigned) columns())
567 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
569 id_cols = max_id_len;
572 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
574 for (u = units; u < units + c; u++) {
576 const char *on, *off;
579 if (!output_show_unit_file(u))
584 if (u->state == UNIT_FILE_MASKED ||
585 u->state == UNIT_FILE_MASKED_RUNTIME ||
586 u->state == UNIT_FILE_DISABLED ||
587 u->state == UNIT_FILE_INVALID) {
588 on = ansi_highlight_red(true);
589 off = ansi_highlight_red(false);
590 } else if (u->state == UNIT_FILE_ENABLED) {
591 on = ansi_highlight_green(true);
592 off = ansi_highlight_green(false);
596 id = path_get_file_name(u->path);
598 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
600 printf("%-*s %s%-*s%s\n",
602 on, state_cols, unit_file_state_to_string(u->state), off);
608 printf("\n%u unit files listed.\n", n_shown);
611 static int list_unit_files(DBusConnection *bus, char **args) {
612 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
613 _cleanup_free_ UnitFileList *units = NULL;
614 DBusMessageIter iter, sub, sub2;
615 unsigned c = 0, n_units = 0;
618 pager_open_if_enabled();
625 h = hashmap_new(string_hash_func, string_compare_func);
629 r = unit_file_get_list(arg_scope, arg_root, h);
631 unit_file_list_free(h);
632 log_error("Failed to get unit file list: %s", strerror(-r));
636 n_units = hashmap_size(h);
637 units = new(UnitFileList, n_units);
639 unit_file_list_free(h);
643 HASHMAP_FOREACH(u, h, i) {
644 memcpy(units + c++, u, sizeof(UnitFileList));
650 r = bus_method_call_with_reply(
652 "org.freedesktop.systemd1",
653 "/org/freedesktop/systemd1",
654 "org.freedesktop.systemd1.Manager",
662 if (!dbus_message_iter_init(reply, &iter) ||
663 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
664 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
665 log_error("Failed to parse reply.");
669 dbus_message_iter_recurse(&iter, &sub);
671 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
675 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT);
680 n_units = MAX(2*c, 16);
681 w = realloc(units, sizeof(struct UnitFileList) * n_units);
690 dbus_message_iter_recurse(&sub, &sub2);
692 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
693 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
694 log_error("Failed to parse reply.");
698 u->state = unit_file_state_from_string(state);
700 dbus_message_iter_next(&sub);
706 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
707 output_unit_file_list(units, c);
713 static int list_dependencies_print(const char *name, int level, unsigned int branches, bool last) {
715 _cleanup_free_ char *n = NULL;
717 size_t max_len = MAX(columns(),20);
719 for (i = level - 1; i >= 0; i--) {
721 if(len > max_len - 3 && !arg_full) {
722 printf("%s...\n",max_len % 2 ? "" : " ");
725 printf("%s", draw_special_char(branches & (1 << i) ? DRAW_TREE_VERT : DRAW_TREE_SPACE));
728 if(len > max_len - 3 && !arg_full) {
729 printf("%s...\n",max_len % 2 ? "" : " ");
732 printf("%s", draw_special_char(last ? DRAW_TREE_RIGHT : DRAW_TREE_BRANCH));
735 printf("%s\n", name);
739 n = ellipsize(name, max_len-len, 100);
747 static int list_dependencies_get_dependencies(DBusConnection *bus, const char *name, char ***deps) {
748 static const char dependencies[] =
750 "RequiresOverridable\0"
752 "RequisiteOverridable\0"
755 _cleanup_free_ char *path;
756 const char *interface = "org.freedesktop.systemd1.Unit";
758 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
759 DBusMessageIter iter, sub, sub2, sub3;
769 path = unit_dbus_path_from_name(name);
775 r = bus_method_call_with_reply(
777 "org.freedesktop.systemd1",
779 "org.freedesktop.DBus.Properties",
783 DBUS_TYPE_STRING, &interface,
788 if (!dbus_message_iter_init(reply, &iter) ||
789 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
790 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
791 log_error("Failed to parse reply.");
796 dbus_message_iter_recurse(&iter, &sub);
798 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
801 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
802 log_error("Failed to parse reply.");
807 dbus_message_iter_recurse(&sub, &sub2);
809 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
810 log_error("Failed to parse reply.");
815 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
816 log_error("Failed to parse reply.");
821 dbus_message_iter_recurse(&sub2, &sub3);
822 dbus_message_iter_next(&sub);
824 if (!nulstr_contains(dependencies, prop))
827 if (dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_ARRAY) {
828 if (dbus_message_iter_get_element_type(&sub3) == DBUS_TYPE_STRING) {
829 DBusMessageIter sub4;
830 dbus_message_iter_recurse(&sub3, &sub4);
832 while (dbus_message_iter_get_arg_type(&sub4) != DBUS_TYPE_INVALID) {
835 assert(dbus_message_iter_get_arg_type(&sub4) == DBUS_TYPE_STRING);
836 dbus_message_iter_get_basic(&sub4, &s);
837 c = strv_append(ret, s);
844 dbus_message_iter_next(&sub4);
856 static int list_dependencies_compare(const void *_a, const void *_b) {
857 const char **a = (const char**) _a, **b = (const char**) _b;
858 if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET)
860 if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET)
862 return strcasecmp(*a, *b);
865 static int list_dependencies_one(DBusConnection *bus, const char *name, int level, char **units, unsigned int branches) {
871 u = strv_append(units, name);
875 r = list_dependencies_get_dependencies(bus, name, &deps);
879 qsort(deps, strv_length(deps), sizeof (char*), list_dependencies_compare);
881 STRV_FOREACH(c, deps) {
882 if (strv_contains(u, *c)) {
883 r = list_dependencies_print("...", level + 1, (branches << 1) | (c[1] == NULL ? 0 : 1), 1);
889 r = list_dependencies_print(*c, level, branches, c[1] == NULL);
893 if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) {
894 r = list_dependencies_one(bus, *c, level + 1, u, (branches << 1) | (c[1] == NULL ? 0 : 1));
907 static int list_dependencies(DBusConnection *bus, char **args) {
908 _cleanup_free_ char *unit = NULL;
914 unit = unit_name_mangle(args[1]);
919 u = SPECIAL_DEFAULT_TARGET;
921 pager_open_if_enabled();
925 return list_dependencies_one(bus, u, 0, NULL, 0);
928 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
930 static const char * const colors[] = {
931 "Requires", "[color=\"black\"]",
932 "RequiresOverridable", "[color=\"black\"]",
933 "Requisite", "[color=\"darkblue\"]",
934 "RequisiteOverridable", "[color=\"darkblue\"]",
935 "Wants", "[color=\"grey66\"]",
936 "Conflicts", "[color=\"red\"]",
937 "ConflictedBy", "[color=\"red\"]",
938 "After", "[color=\"green\"]"
941 const char *c = NULL;
948 for (i = 0; i < ELEMENTSOF(colors); i += 2)
949 if (streq(colors[i], prop)) {
957 if (arg_dot != DOT_ALL)
958 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
961 switch (dbus_message_iter_get_arg_type(iter)) {
963 case DBUS_TYPE_ARRAY:
965 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
968 dbus_message_iter_recurse(iter, &sub);
970 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
973 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
974 dbus_message_iter_get_basic(&sub, &s);
975 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
977 dbus_message_iter_next(&sub);
987 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
988 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
989 const char *interface = "org.freedesktop.systemd1.Unit";
991 DBusMessageIter iter, sub, sub2, sub3;
996 r = bus_method_call_with_reply(
998 "org.freedesktop.systemd1",
1000 "org.freedesktop.DBus.Properties",
1004 DBUS_TYPE_STRING, &interface,
1009 if (!dbus_message_iter_init(reply, &iter) ||
1010 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1011 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
1012 log_error("Failed to parse reply.");
1016 dbus_message_iter_recurse(&iter, &sub);
1018 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1021 assert(dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY);
1022 dbus_message_iter_recurse(&sub, &sub2);
1024 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0 ||
1025 dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
1026 log_error("Failed to parse reply.");
1030 dbus_message_iter_recurse(&sub2, &sub3);
1031 r = dot_one_property(name, prop, &sub3);
1035 dbus_message_iter_next(&sub);
1041 static int dot(DBusConnection *bus, char **args) {
1042 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1043 DBusMessageIter iter, sub, sub2;
1046 r = bus_method_call_with_reply(
1048 "org.freedesktop.systemd1",
1049 "/org/freedesktop/systemd1",
1050 "org.freedesktop.systemd1.Manager",
1058 if (!dbus_message_iter_init(reply, &iter) ||
1059 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1060 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1061 log_error("Failed to parse reply.");
1065 printf("digraph systemd {\n");
1067 dbus_message_iter_recurse(&iter, &sub);
1068 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1069 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
1071 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1072 log_error("Failed to parse reply.");
1076 dbus_message_iter_recurse(&sub, &sub2);
1078 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
1079 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
1080 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
1081 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
1082 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
1083 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
1084 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
1085 log_error("Failed to parse reply.");
1089 r = dot_one(bus, id, unit_path);
1093 /* printf("\t\"%s\";\n", id); */
1094 dbus_message_iter_next(&sub);
1099 log_info(" Color legend: black = Requires\n"
1100 " dark blue = Requisite\n"
1101 " dark grey = Wants\n"
1102 " red = Conflicts\n"
1103 " green = After\n");
1106 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
1107 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
1112 static int list_jobs(DBusConnection *bus, char **args) {
1113 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1114 DBusMessageIter iter, sub, sub2;
1118 pager_open_if_enabled();
1120 r = bus_method_call_with_reply(
1122 "org.freedesktop.systemd1",
1123 "/org/freedesktop/systemd1",
1124 "org.freedesktop.systemd1.Manager",
1132 if (!dbus_message_iter_init(reply, &iter) ||
1133 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1134 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1135 log_error("Failed to parse reply.");
1139 dbus_message_iter_recurse(&iter, &sub);
1142 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
1144 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1145 const char *name, *type, *state, *job_path, *unit_path;
1149 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1150 log_error("Failed to parse reply.");
1154 dbus_message_iter_recurse(&sub, &sub2);
1156 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
1157 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
1158 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
1159 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
1160 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
1161 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
1162 log_error("Failed to parse reply.");
1166 e = arg_full ? NULL : ellipsize(name, 25, 33);
1167 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
1172 dbus_message_iter_next(&sub);
1176 printf("\n%u jobs listed.\n", k);
1181 static int load_unit(DBusConnection *bus, char **args) {
1186 STRV_FOREACH(name, args+1) {
1187 _cleanup_free_ char *n = NULL;
1190 n = unit_name_mangle(*name);
1194 r = bus_method_call_with_reply(
1196 "org.freedesktop.systemd1",
1197 "/org/freedesktop/systemd1",
1198 "org.freedesktop.systemd1.Manager",
1202 DBUS_TYPE_STRING, &n,
1211 static int cancel_job(DBusConnection *bus, char **args) {
1216 if (strv_length(args) <= 1)
1217 return daemon_reload(bus, args);
1219 STRV_FOREACH(name, args+1) {
1223 r = safe_atou32(*name, &id);
1225 log_error("Failed to parse job id: %s", strerror(-r));
1229 r = bus_method_call_with_reply(
1231 "org.freedesktop.systemd1",
1232 "/org/freedesktop/systemd1",
1233 "org.freedesktop.systemd1.Manager",
1237 DBUS_TYPE_UINT32, &id,
1246 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1247 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1248 dbus_bool_t b = FALSE;
1249 DBusMessageIter iter, sub;
1251 *interface = "org.freedesktop.systemd1.Unit",
1252 *property = "NeedDaemonReload",
1254 _cleanup_free_ char *n = NULL;
1257 /* We ignore all errors here, since this is used to show a warning only */
1259 n = unit_name_mangle(unit);
1263 r = bus_method_call_with_reply (
1265 "org.freedesktop.systemd1",
1266 "/org/freedesktop/systemd1",
1267 "org.freedesktop.systemd1.Manager",
1271 DBUS_TYPE_STRING, &n,
1276 if (!dbus_message_get_args(reply, NULL,
1277 DBUS_TYPE_OBJECT_PATH, &path,
1281 dbus_message_unref(reply);
1284 r = bus_method_call_with_reply(
1286 "org.freedesktop.systemd1",
1288 "org.freedesktop.DBus.Properties",
1292 DBUS_TYPE_STRING, &interface,
1293 DBUS_TYPE_STRING, &property,
1298 if (!dbus_message_iter_init(reply, &iter) ||
1299 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1302 dbus_message_iter_recurse(&iter, &sub);
1303 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1306 dbus_message_iter_get_basic(&sub, &b);
1310 typedef struct WaitData {
1317 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1325 dbus_error_init(&error);
1327 log_debug("Got D-Bus request: %s.%s() on %s",
1328 dbus_message_get_interface(message),
1329 dbus_message_get_member(message),
1330 dbus_message_get_path(message));
1332 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1333 log_error("Warning! D-Bus connection terminated.");
1334 dbus_connection_close(connection);
1336 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1338 const char *path, *result, *unit;
1340 if (dbus_message_get_args(message, &error,
1341 DBUS_TYPE_UINT32, &id,
1342 DBUS_TYPE_OBJECT_PATH, &path,
1343 DBUS_TYPE_STRING, &unit,
1344 DBUS_TYPE_STRING, &result,
1345 DBUS_TYPE_INVALID)) {
1347 free(set_remove(d->set, (char*) path));
1349 if (!isempty(result))
1350 d->result = strdup(result);
1353 d->name = strdup(unit);
1358 dbus_error_free(&error);
1359 if (dbus_message_get_args(message, &error,
1360 DBUS_TYPE_UINT32, &id,
1361 DBUS_TYPE_OBJECT_PATH, &path,
1362 DBUS_TYPE_STRING, &result,
1363 DBUS_TYPE_INVALID)) {
1364 /* Compatibility with older systemd versions <
1365 * 183 during upgrades. This should be dropped
1367 free(set_remove(d->set, (char*) path));
1370 d->result = strdup(result);
1376 log_error("Failed to parse message: %s", bus_error_message(&error));
1380 dbus_error_free(&error);
1381 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1384 static int enable_wait_for_jobs(DBusConnection *bus) {
1392 dbus_error_init(&error);
1393 dbus_bus_add_match(bus,
1395 "sender='org.freedesktop.systemd1',"
1396 "interface='org.freedesktop.systemd1.Manager',"
1397 "member='JobRemoved',"
1398 "path='/org/freedesktop/systemd1'",
1401 if (dbus_error_is_set(&error)) {
1402 log_error("Failed to add match: %s", bus_error_message(&error));
1403 dbus_error_free(&error);
1407 /* This is slightly dirty, since we don't undo the match registrations. */
1411 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1421 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL))
1424 while (!set_isempty(s)) {
1426 if (!dbus_connection_read_write_dispatch(bus, -1)) {
1427 log_error("Disconnected from bus.");
1428 return -ECONNREFUSED;
1435 if (streq(d.result, "timeout"))
1436 log_error("Job for %s timed out.", strna(d.name));
1437 else if (streq(d.result, "canceled"))
1438 log_error("Job for %s canceled.", strna(d.name));
1439 else if (streq(d.result, "dependency"))
1440 log_error("A dependency job for %s failed. See 'journalctl -xn' for details.", strna(d.name));
1441 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1442 log_error("Job for %s failed. See 'systemctl status %s' and 'journalctl -xn' for details.", strna(d.name), strna(d.name));
1445 if (streq_ptr(d.result, "timeout"))
1447 else if (streq_ptr(d.result, "canceled"))
1449 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1460 dbus_connection_remove_filter(bus, wait_filter, &d);
1464 static int check_one_unit(DBusConnection *bus, const char *name, char **check_states, bool quiet) {
1465 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1466 _cleanup_free_ char *n = NULL;
1467 DBusMessageIter iter, sub;
1469 *interface = "org.freedesktop.systemd1.Unit",
1470 *property = "ActiveState";
1471 const char *state, *path;
1477 dbus_error_init(&error);
1479 n = unit_name_mangle(name);
1483 r = bus_method_call_with_reply (
1485 "org.freedesktop.systemd1",
1486 "/org/freedesktop/systemd1",
1487 "org.freedesktop.systemd1.Manager",
1491 DBUS_TYPE_STRING, &n,
1494 dbus_error_free(&error);
1501 if (!dbus_message_get_args(reply, NULL,
1502 DBUS_TYPE_OBJECT_PATH, &path,
1503 DBUS_TYPE_INVALID)) {
1504 log_error("Failed to parse reply.");
1508 dbus_message_unref(reply);
1511 r = bus_method_call_with_reply(
1513 "org.freedesktop.systemd1",
1515 "org.freedesktop.DBus.Properties",
1519 DBUS_TYPE_STRING, &interface,
1520 DBUS_TYPE_STRING, &property,
1528 if (!dbus_message_iter_init(reply, &iter) ||
1529 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1530 log_error("Failed to parse reply.");
1534 dbus_message_iter_recurse(&iter, &sub);
1536 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1537 log_error("Failed to parse reply.");
1541 dbus_message_iter_get_basic(&sub, &state);
1546 return strv_find(check_states, state) ? 1 : 0;
1549 static void check_triggering_units(
1550 DBusConnection *bus,
1551 const char *unit_name) {
1553 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1554 DBusMessageIter iter, sub;
1555 const char *interface = "org.freedesktop.systemd1.Unit",
1556 *triggered_by_property = "TriggeredBy";
1557 char _cleanup_free_ *unit_path = NULL, *n = NULL;
1558 bool print_warning_label = true;
1561 n = unit_name_mangle(unit_name);
1567 unit_path = unit_dbus_path_from_name(n);
1573 r = bus_method_call_with_reply(
1575 "org.freedesktop.systemd1",
1577 "org.freedesktop.DBus.Properties",
1581 DBUS_TYPE_STRING, &interface,
1582 DBUS_TYPE_STRING, &triggered_by_property,
1587 if (!dbus_message_iter_init(reply, &iter) ||
1588 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1589 log_error("Failed to parse reply.");
1593 dbus_message_iter_recurse(&iter, &sub);
1594 dbus_message_iter_recurse(&sub, &iter);
1597 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1598 const char * const check_states[] = {
1603 const char *service_trigger;
1605 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1606 log_error("Failed to parse reply.");
1610 dbus_message_iter_get_basic(&sub, &service_trigger);
1612 r = check_one_unit(bus, service_trigger, (char**) check_states, true);
1616 if (print_warning_label) {
1617 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1618 print_warning_label = false;
1621 log_warning(" %s", service_trigger);
1624 dbus_message_iter_next(&sub);
1628 static int start_unit_one(
1629 DBusConnection *bus,
1636 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1637 _cleanup_free_ char *n;
1646 n = unit_name_mangle(name);
1650 r = bus_method_call_with_reply(
1652 "org.freedesktop.systemd1",
1653 "/org/freedesktop/systemd1",
1654 "org.freedesktop.systemd1.Manager",
1658 DBUS_TYPE_STRING, &n,
1659 DBUS_TYPE_STRING, &mode,
1662 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
1663 /* There's always a fallback possible for
1664 * legacy actions. */
1667 log_error("Failed to issue method call: %s", bus_error_message(error));
1672 if (!dbus_message_get_args(reply, error,
1673 DBUS_TYPE_OBJECT_PATH, &path,
1674 DBUS_TYPE_INVALID)) {
1675 log_error("Failed to parse reply: %s", bus_error_message(error));
1679 if (need_daemon_reload(bus, n))
1680 log_warning("Warning: Unit file of %s changed on disk, 'systemctl %s daemon-reload' recommended.",
1681 n, arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1693 log_error("Failed to add path to set.");
1701 static enum action verb_to_action(const char *verb) {
1702 if (streq(verb, "halt"))
1704 else if (streq(verb, "poweroff"))
1705 return ACTION_POWEROFF;
1706 else if (streq(verb, "reboot"))
1707 return ACTION_REBOOT;
1708 else if (streq(verb, "kexec"))
1709 return ACTION_KEXEC;
1710 else if (streq(verb, "rescue"))
1711 return ACTION_RESCUE;
1712 else if (streq(verb, "emergency"))
1713 return ACTION_EMERGENCY;
1714 else if (streq(verb, "default"))
1715 return ACTION_DEFAULT;
1716 else if (streq(verb, "exit"))
1718 else if (streq(verb, "suspend"))
1719 return ACTION_SUSPEND;
1720 else if (streq(verb, "hibernate"))
1721 return ACTION_HIBERNATE;
1722 else if (streq(verb, "hybrid-sleep"))
1723 return ACTION_HYBRID_SLEEP;
1725 return ACTION_INVALID;
1728 static int start_unit(DBusConnection *bus, char **args) {
1730 static const char * const table[_ACTION_MAX] = {
1731 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1732 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1733 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1734 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1735 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1736 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1737 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1738 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1739 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1740 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1741 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1742 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1743 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1744 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET,
1745 [ACTION_HYBRID_SLEEP] = SPECIAL_HYBRID_SLEEP_TARGET
1749 const char *method, *mode, *one_name;
1754 dbus_error_init(&error);
1758 ask_password_agent_open_if_enabled();
1760 if (arg_action == ACTION_SYSTEMCTL) {
1762 streq(args[0], "stop") ||
1763 streq(args[0], "condstop") ? "StopUnit" :
1764 streq(args[0], "reload") ? "ReloadUnit" :
1765 streq(args[0], "restart") ? "RestartUnit" :
1767 streq(args[0], "try-restart") ||
1768 streq(args[0], "condrestart") ? "TryRestartUnit" :
1770 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1772 streq(args[0], "reload-or-try-restart") ||
1773 streq(args[0], "condreload") ||
1775 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1779 (streq(args[0], "isolate") ||
1780 streq(args[0], "rescue") ||
1781 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1783 one_name = table[verb_to_action(args[0])];
1786 assert(arg_action < ELEMENTSOF(table));
1787 assert(table[arg_action]);
1789 method = "StartUnit";
1791 mode = (arg_action == ACTION_EMERGENCY ||
1792 arg_action == ACTION_RESCUE ||
1793 arg_action == ACTION_RUNLEVEL2 ||
1794 arg_action == ACTION_RUNLEVEL3 ||
1795 arg_action == ACTION_RUNLEVEL4 ||
1796 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1798 one_name = table[arg_action];
1801 if (!arg_no_block) {
1802 ret = enable_wait_for_jobs(bus);
1804 log_error("Could not watch jobs: %s", strerror(-ret));
1808 s = set_new(string_hash_func, string_compare_func);
1816 ret = start_unit_one(bus, method, one_name, mode, &error, s);
1818 ret = translate_bus_error_to_exit_status(ret, &error);
1820 STRV_FOREACH(name, args+1) {
1821 r = start_unit_one(bus, method, *name, mode, &error, s);
1823 ret = translate_bus_error_to_exit_status(r, &error);
1824 dbus_error_free(&error);
1829 if (!arg_no_block) {
1830 r = wait_for_jobs(bus, s);
1836 /* When stopping units, warn if they can still be triggered by
1837 * another active unit (socket, path, timer) */
1838 if (!arg_quiet && streq(method, "StopUnit")) {
1840 check_triggering_units(bus, one_name);
1842 STRV_FOREACH(name, args+1)
1843 check_triggering_units(bus, *name);
1849 dbus_error_free(&error);
1854 /* Ask systemd-logind, which might grant access to unprivileged users
1855 * through PolicyKit */
1856 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1859 dbus_bool_t interactive = true;
1864 polkit_agent_open_if_enabled();
1872 case ACTION_POWEROFF:
1873 method = "PowerOff";
1876 case ACTION_SUSPEND:
1880 case ACTION_HIBERNATE:
1881 method = "Hibernate";
1884 case ACTION_HYBRID_SLEEP:
1885 method = "HybridSleep";
1892 return bus_method_call_with_reply(
1894 "org.freedesktop.login1",
1895 "/org/freedesktop/login1",
1896 "org.freedesktop.login1.Manager",
1900 DBUS_TYPE_BOOLEAN, &interactive,
1907 static int check_inhibitors(DBusConnection *bus, enum action a) {
1909 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1910 DBusMessageIter iter, sub, sub2;
1913 _cleanup_strv_free_ char **sessions = NULL;
1919 if (arg_ignore_inhibitors || arg_force > 0)
1931 r = bus_method_call_with_reply(
1933 "org.freedesktop.login1",
1934 "/org/freedesktop/login1",
1935 "org.freedesktop.login1.Manager",
1941 /* If logind is not around, then there are no inhibitors... */
1944 if (!dbus_message_iter_init(reply, &iter) ||
1945 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1946 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1947 log_error("Failed to parse reply.");
1951 dbus_message_iter_recurse(&iter, &sub);
1952 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1953 const char *what, *who, *why, *mode;
1955 _cleanup_strv_free_ char **sv = NULL;
1956 _cleanup_free_ char *comm = NULL, *user = NULL;
1958 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1959 log_error("Failed to parse reply.");
1963 dbus_message_iter_recurse(&sub, &sub2);
1965 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &what, true) < 0 ||
1966 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &who, true) < 0 ||
1967 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &why, true) < 0 ||
1968 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &mode, true) < 0 ||
1969 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &uid, true) < 0 ||
1970 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, false) < 0) {
1971 log_error("Failed to parse reply.");
1975 if (!streq(mode, "block"))
1978 sv = strv_split(what, ":");
1982 if (!strv_contains(sv,
1984 a == ACTION_POWEROFF ||
1985 a == ACTION_REBOOT ||
1986 a == ACTION_KEXEC ? "shutdown" : "sleep"))
1989 get_process_comm(pid, &comm);
1990 user = uid_to_name(uid);
1991 log_warning("Operation inhibited by \"%s\" (PID %lu \"%s\", user %s), reason is \"%s\".",
1992 who, (unsigned long) pid, strna(comm), strna(user), why);
1996 dbus_message_iter_next(&sub);
1999 dbus_message_iter_recurse(&iter, &sub);
2001 /* Check for current sessions */
2002 sd_get_sessions(&sessions);
2003 STRV_FOREACH(s, sessions) {
2005 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
2007 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
2010 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
2013 if (sd_session_get_type(*s, &type) < 0 || (!streq(type, "x11") && !streq(type, "tty")))
2016 sd_session_get_tty(*s, &tty);
2017 sd_session_get_seat(*s, &seat);
2018 sd_session_get_service(*s, &service);
2019 user = uid_to_name(uid);
2021 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
2028 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
2029 a == ACTION_HALT ? "halt" :
2030 a == ACTION_POWEROFF ? "poweroff" :
2031 a == ACTION_REBOOT ? "reboot" :
2032 a == ACTION_KEXEC ? "kexec" :
2033 a == ACTION_SUSPEND ? "suspend" :
2034 a == ACTION_HIBERNATE ? "hibernate" : "hybrid-sleep");
2042 static int start_special(DBusConnection *bus, char **args) {
2048 a = verb_to_action(args[0]);
2050 r = check_inhibitors(bus, a);
2054 if (arg_force >= 2 && geteuid() != 0) {
2055 log_error("Must be root.");
2059 if (arg_force >= 2 &&
2060 (a == ACTION_HALT ||
2061 a == ACTION_POWEROFF ||
2062 a == ACTION_REBOOT))
2065 if (arg_force >= 1 &&
2066 (a == ACTION_HALT ||
2067 a == ACTION_POWEROFF ||
2068 a == ACTION_REBOOT ||
2069 a == ACTION_KEXEC ||
2071 return daemon_reload(bus, args);
2073 /* first try logind, to allow authentication with polkit */
2074 if (geteuid() != 0 &&
2075 (a == ACTION_POWEROFF ||
2076 a == ACTION_REBOOT ||
2077 a == ACTION_SUSPEND ||
2078 a == ACTION_HIBERNATE ||
2079 a == ACTION_HYBRID_SLEEP)) {
2080 r = reboot_with_logind(bus, a);
2085 r = start_unit(bus, args);
2092 static int check_unit_active(DBusConnection *bus, char **args) {
2093 const char * const check_states[] = {
2100 int r = 3; /* According to LSB: "program is not running" */
2105 STRV_FOREACH(name, args+1) {
2108 state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
2118 static int check_unit_failed(DBusConnection *bus, char **args) {
2119 const char * const check_states[] = {
2130 STRV_FOREACH(name, args+1) {
2133 state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
2143 static int kill_unit(DBusConnection *bus, char **args) {
2151 arg_kill_who = "all";
2153 STRV_FOREACH(name, args+1) {
2154 _cleanup_free_ char *n = NULL;
2156 n = unit_name_mangle(*name);
2160 r = bus_method_call_with_reply(
2162 "org.freedesktop.systemd1",
2163 "/org/freedesktop/systemd1",
2164 "org.freedesktop.systemd1.Manager",
2168 DBUS_TYPE_STRING, &n,
2169 DBUS_TYPE_STRING, &arg_kill_who,
2170 DBUS_TYPE_INT32, &arg_signal,
2178 static int set_cgroup(DBusConnection *bus, char **args) {
2179 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
2182 DBusMessageIter iter;
2184 _cleanup_free_ char *n = NULL;
2189 dbus_error_init(&error);
2192 streq(args[0], "set-cgroup") ? "SetUnitControlGroups" :
2193 streq(args[0], "unset-group") ? "UnsetUnitControlGroups"
2194 : "UnsetUnitControlGroupAttributes";
2196 n = unit_name_mangle(args[1]);
2200 m = dbus_message_new_method_call(
2201 "org.freedesktop.systemd1",
2202 "/org/freedesktop/systemd1",
2203 "org.freedesktop.systemd1.Manager",
2208 dbus_message_iter_init_append(m, &iter);
2209 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &n))
2212 r = bus_append_strv_iter(&iter, args + 2);
2216 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2218 log_error("Failed to issue method call: %s", bus_error_message(&error));
2219 dbus_error_free(&error);
2226 static int set_cgroup_attr(DBusConnection *bus, char **args) {
2227 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
2229 DBusMessageIter iter, sub, sub2;
2231 _cleanup_free_ char *n = NULL;
2236 dbus_error_init(&error);
2238 if (strv_length(args) % 2 != 0) {
2239 log_error("Expecting an uneven number of arguments!");
2243 n = unit_name_mangle(args[1]);
2247 m = dbus_message_new_method_call(
2248 "org.freedesktop.systemd1",
2249 "/org/freedesktop/systemd1",
2250 "org.freedesktop.systemd1.Manager",
2251 "SetUnitControlGroupAttributes");
2255 dbus_message_iter_init_append(m, &iter);
2256 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &n) ||
2257 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(ss)", &sub))
2260 STRV_FOREACH_PAIR(x, y, args + 2) {
2261 if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2) ||
2262 !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, x) ||
2263 !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, y) ||
2264 !dbus_message_iter_close_container(&sub, &sub2))
2268 if (!dbus_message_iter_close_container(&iter, &sub))
2271 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2273 log_error("Failed to issue method call: %s", bus_error_message(&error));
2274 dbus_error_free(&error);
2281 typedef struct ExecStatusInfo {
2289 usec_t start_timestamp;
2290 usec_t exit_timestamp;
2295 LIST_FIELDS(struct ExecStatusInfo, exec);
2298 static void exec_status_info_free(ExecStatusInfo *i) {
2307 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
2308 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2309 DBusMessageIter sub2, sub3;
2313 int32_t code, status;
2319 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
2322 dbus_message_iter_recurse(sub, &sub2);
2324 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
2327 i->path = strdup(path);
2331 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
2332 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
2336 dbus_message_iter_recurse(&sub2, &sub3);
2337 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2338 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2339 dbus_message_iter_next(&sub3);
2343 i->argv = new0(char*, n+1);
2348 dbus_message_iter_recurse(&sub2, &sub3);
2349 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2352 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2353 dbus_message_iter_get_basic(&sub3, &s);
2354 dbus_message_iter_next(&sub3);
2356 i->argv[n] = strdup(s);
2363 if (!dbus_message_iter_next(&sub2) ||
2364 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
2365 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
2366 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
2367 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
2368 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
2369 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
2370 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
2371 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
2375 i->start_timestamp = (usec_t) start_timestamp;
2376 i->exit_timestamp = (usec_t) exit_timestamp;
2377 i->pid = (pid_t) pid;
2384 typedef struct UnitStatusInfo {
2386 const char *load_state;
2387 const char *active_state;
2388 const char *sub_state;
2389 const char *unit_file_state;
2391 const char *description;
2392 const char *following;
2394 char **documentation;
2396 const char *fragment_path;
2397 const char *source_path;
2398 const char *default_control_group;
2400 const char *load_error;
2403 usec_t inactive_exit_timestamp;
2404 usec_t inactive_exit_timestamp_monotonic;
2405 usec_t active_enter_timestamp;
2406 usec_t active_exit_timestamp;
2407 usec_t inactive_enter_timestamp;
2409 bool need_daemon_reload;
2414 const char *status_text;
2417 usec_t start_timestamp;
2418 usec_t exit_timestamp;
2420 int exit_code, exit_status;
2422 usec_t condition_timestamp;
2423 bool condition_result;
2426 unsigned n_accepted;
2427 unsigned n_connections;
2431 const char *sysfs_path;
2433 /* Mount, Automount */
2439 LIST_HEAD(ExecStatusInfo, exec);
2442 static void print_status_info(UnitStatusInfo *i) {
2444 const char *on, *off, *ss;
2446 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
2447 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2450 arg_all * OUTPUT_SHOW_ALL |
2451 (!on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
2452 on_tty() * OUTPUT_COLOR |
2453 !arg_quiet * OUTPUT_WARN_CUTOFF |
2454 arg_full * OUTPUT_FULL_WIDTH;
2458 /* This shows pretty information about a unit. See
2459 * print_property() for a low-level property printer */
2461 printf("%s", strna(i->id));
2463 if (i->description && !streq_ptr(i->id, i->description))
2464 printf(" - %s", i->description);
2469 printf("\t Follow: unit currently follows state of %s\n", i->following);
2471 if (streq_ptr(i->load_state, "error")) {
2472 on = ansi_highlight_red(true);
2473 off = ansi_highlight_red(false);
2477 path = i->source_path ? i->source_path : i->fragment_path;
2480 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2481 else if (path && i->unit_file_state)
2482 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2484 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2486 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2488 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2490 if (streq_ptr(i->active_state, "failed")) {
2491 on = ansi_highlight_red(true);
2492 off = ansi_highlight_red(false);
2493 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2494 on = ansi_highlight_green(true);
2495 off = ansi_highlight_green(false);
2500 printf("\t Active: %s%s (%s)%s",
2502 strna(i->active_state),
2506 printf("\t Active: %s%s%s",
2508 strna(i->active_state),
2511 if (!isempty(i->result) && !streq(i->result, "success"))
2512 printf(" (Result: %s)", i->result);
2514 timestamp = (streq_ptr(i->active_state, "active") ||
2515 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2516 (streq_ptr(i->active_state, "inactive") ||
2517 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2518 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2519 i->active_exit_timestamp;
2521 s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
2522 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2525 printf(" since %s; %s\n", s2, s1);
2527 printf(" since %s\n", s2);
2531 if (!i->condition_result && i->condition_timestamp > 0) {
2532 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
2533 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2536 printf("\t start condition failed at %s; %s\n", s2, s1);
2538 printf("\t start condition failed at %s\n", s2);
2542 printf("\t Device: %s\n", i->sysfs_path);
2544 printf("\t Where: %s\n", i->where);
2546 printf("\t What: %s\n", i->what);
2548 if (!strv_isempty(i->documentation)) {
2552 STRV_FOREACH(t, i->documentation) {
2554 printf("\t Docs: %s\n", *t);
2557 printf("\t %s\n", *t);
2562 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2564 LIST_FOREACH(exec, p, i->exec) {
2565 _cleanup_free_ char *t = NULL;
2568 /* Only show exited processes here */
2572 t = strv_join(p->argv, " ");
2573 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2575 good = is_clean_exit_lsb(p->code, p->status, NULL);
2577 on = ansi_highlight_red(true);
2578 off = ansi_highlight_red(false);
2582 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2584 if (p->code == CLD_EXITED) {
2587 printf("status=%i", p->status);
2589 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2594 printf("signal=%s", signal_to_string(p->status));
2596 printf(")%s\n", off);
2598 if (i->main_pid == p->pid &&
2599 i->start_timestamp == p->start_timestamp &&
2600 i->exit_timestamp == p->start_timestamp)
2601 /* Let's not show this twice */
2604 if (p->pid == i->control_pid)
2608 if (i->main_pid > 0 || i->control_pid > 0) {
2611 if (i->main_pid > 0) {
2612 printf("Main PID: %u", (unsigned) i->main_pid);
2615 _cleanup_free_ char *t = NULL;
2616 get_process_comm(i->main_pid, &t);
2619 } else if (i->exit_code > 0) {
2620 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2622 if (i->exit_code == CLD_EXITED) {
2625 printf("status=%i", i->exit_status);
2627 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2632 printf("signal=%s", signal_to_string(i->exit_status));
2637 if (i->main_pid > 0 && i->control_pid > 0)
2640 if (i->control_pid > 0) {
2641 _cleanup_free_ char *t = NULL;
2643 printf(" Control: %u", (unsigned) i->control_pid);
2645 get_process_comm(i->control_pid, &t);
2654 printf("\t Status: \"%s\"\n", i->status_text);
2656 if (i->default_control_group &&
2657 (i->main_pid > 0 || i->control_pid > 0 || cg_is_empty_by_spec(i->default_control_group, false) == 0)) {
2660 printf("\t CGroup: %s\n", i->default_control_group);
2662 if (arg_transport != TRANSPORT_SSH) {
2672 if (i->main_pid > 0)
2673 extra[k++] = i->main_pid;
2675 if (i->control_pid > 0)
2676 extra[k++] = i->control_pid;
2678 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, extra, k, flags);
2682 if (i->id && arg_transport != TRANSPORT_SSH) {
2684 show_journal_by_unit(stdout,
2688 i->inactive_exit_timestamp_monotonic,
2693 if (i->need_daemon_reload)
2694 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2695 ansi_highlight_red(true),
2696 ansi_highlight_red(false),
2697 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2700 static void show_unit_help(UnitStatusInfo *i) {
2705 if (!i->documentation) {
2706 log_info("Documentation for %s not known.", i->id);
2710 STRV_FOREACH(p, i->documentation) {
2712 if (startswith(*p, "man:")) {
2715 char *page = NULL, *section = NULL;
2716 const char *args[4] = { "man", NULL, NULL, NULL };
2721 if ((*p)[k-1] == ')')
2722 e = strrchr(*p, '(');
2725 page = strndup((*p) + 4, e - *p - 4);
2731 section = strndup(e + 1, *p + k - e - 2);
2745 log_error("Failed to fork: %m");
2753 execvp(args[0], (char**) args);
2754 log_error("Failed to execute man: %m");
2755 _exit(EXIT_FAILURE);
2761 wait_for_terminate(pid, NULL);
2763 log_info("Can't show: %s", *p);
2767 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2773 switch (dbus_message_iter_get_arg_type(iter)) {
2775 case DBUS_TYPE_STRING: {
2778 dbus_message_iter_get_basic(iter, &s);
2781 if (streq(name, "Id"))
2783 else if (streq(name, "LoadState"))
2785 else if (streq(name, "ActiveState"))
2786 i->active_state = s;
2787 else if (streq(name, "SubState"))
2789 else if (streq(name, "Description"))
2791 else if (streq(name, "FragmentPath"))
2792 i->fragment_path = s;
2793 else if (streq(name, "SourcePath"))
2795 else if (streq(name, "DefaultControlGroup"))
2796 i->default_control_group = s;
2797 else if (streq(name, "StatusText"))
2799 else if (streq(name, "SysFSPath"))
2801 else if (streq(name, "Where"))
2803 else if (streq(name, "What"))
2805 else if (streq(name, "Following"))
2807 else if (streq(name, "UnitFileState"))
2808 i->unit_file_state = s;
2809 else if (streq(name, "Result"))
2816 case DBUS_TYPE_BOOLEAN: {
2819 dbus_message_iter_get_basic(iter, &b);
2821 if (streq(name, "Accept"))
2823 else if (streq(name, "NeedDaemonReload"))
2824 i->need_daemon_reload = b;
2825 else if (streq(name, "ConditionResult"))
2826 i->condition_result = b;
2831 case DBUS_TYPE_UINT32: {
2834 dbus_message_iter_get_basic(iter, &u);
2836 if (streq(name, "MainPID")) {
2838 i->main_pid = (pid_t) u;
2841 } else if (streq(name, "ControlPID"))
2842 i->control_pid = (pid_t) u;
2843 else if (streq(name, "ExecMainPID")) {
2845 i->main_pid = (pid_t) u;
2846 } else if (streq(name, "NAccepted"))
2848 else if (streq(name, "NConnections"))
2849 i->n_connections = u;
2854 case DBUS_TYPE_INT32: {
2857 dbus_message_iter_get_basic(iter, &j);
2859 if (streq(name, "ExecMainCode"))
2860 i->exit_code = (int) j;
2861 else if (streq(name, "ExecMainStatus"))
2862 i->exit_status = (int) j;
2867 case DBUS_TYPE_UINT64: {
2870 dbus_message_iter_get_basic(iter, &u);
2872 if (streq(name, "ExecMainStartTimestamp"))
2873 i->start_timestamp = (usec_t) u;
2874 else if (streq(name, "ExecMainExitTimestamp"))
2875 i->exit_timestamp = (usec_t) u;
2876 else if (streq(name, "ActiveEnterTimestamp"))
2877 i->active_enter_timestamp = (usec_t) u;
2878 else if (streq(name, "InactiveEnterTimestamp"))
2879 i->inactive_enter_timestamp = (usec_t) u;
2880 else if (streq(name, "InactiveExitTimestamp"))
2881 i->inactive_exit_timestamp = (usec_t) u;
2882 else if (streq(name, "InactiveExitTimestampMonotonic"))
2883 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2884 else if (streq(name, "ActiveExitTimestamp"))
2885 i->active_exit_timestamp = (usec_t) u;
2886 else if (streq(name, "ConditionTimestamp"))
2887 i->condition_timestamp = (usec_t) u;
2892 case DBUS_TYPE_ARRAY: {
2894 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2895 startswith(name, "Exec")) {
2896 DBusMessageIter sub;
2898 dbus_message_iter_recurse(iter, &sub);
2899 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2900 ExecStatusInfo *info;
2903 if (!(info = new0(ExecStatusInfo, 1)))
2906 if (!(info->name = strdup(name))) {
2911 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2916 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2918 dbus_message_iter_next(&sub);
2920 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2921 streq(name, "Documentation")) {
2923 DBusMessageIter sub;
2925 dbus_message_iter_recurse(iter, &sub);
2926 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2930 dbus_message_iter_get_basic(&sub, &s);
2932 l = strv_append(i->documentation, s);
2936 strv_free(i->documentation);
2937 i->documentation = l;
2939 dbus_message_iter_next(&sub);
2946 case DBUS_TYPE_STRUCT: {
2948 if (streq(name, "LoadError")) {
2949 DBusMessageIter sub;
2950 const char *n, *message;
2953 dbus_message_iter_recurse(iter, &sub);
2955 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2959 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2963 if (!isempty(message))
2964 i->load_error = message;
2974 static int print_property(const char *name, DBusMessageIter *iter) {
2978 /* This is a low-level property printer, see
2979 * print_status_info() for the nicer output */
2981 if (arg_property && !strv_find(arg_property, name))
2984 switch (dbus_message_iter_get_arg_type(iter)) {
2986 case DBUS_TYPE_STRUCT: {
2987 DBusMessageIter sub;
2988 dbus_message_iter_recurse(iter, &sub);
2990 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2993 dbus_message_iter_get_basic(&sub, &u);
2996 printf("%s=%u\n", name, (unsigned) u);
2998 printf("%s=\n", name);
3001 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
3004 dbus_message_iter_get_basic(&sub, &s);
3006 if (arg_all || s[0])
3007 printf("%s=%s\n", name, s);
3010 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
3011 const char *a = NULL, *b = NULL;
3013 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
3014 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
3016 if (arg_all || !isempty(a) || !isempty(b))
3017 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
3025 case DBUS_TYPE_ARRAY:
3027 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
3028 DBusMessageIter sub, sub2;
3030 dbus_message_iter_recurse(iter, &sub);
3031 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3035 dbus_message_iter_recurse(&sub, &sub2);
3037 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
3038 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
3039 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
3041 dbus_message_iter_next(&sub);
3046 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
3047 DBusMessageIter sub, sub2;
3049 dbus_message_iter_recurse(iter, &sub);
3050 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3051 const char *type, *path;
3053 dbus_message_iter_recurse(&sub, &sub2);
3055 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
3056 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
3057 printf("%s=%s\n", type, path);
3059 dbus_message_iter_next(&sub);
3064 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
3065 DBusMessageIter sub, sub2;
3067 dbus_message_iter_recurse(iter, &sub);
3068 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3070 uint64_t value, next_elapse;
3072 dbus_message_iter_recurse(&sub, &sub2);
3074 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
3075 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
3076 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
3077 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
3079 printf("%s={ value=%s ; next_elapse=%s }\n",
3081 format_timespan(timespan1, sizeof(timespan1), value),
3082 format_timespan(timespan2, sizeof(timespan2), next_elapse));
3085 dbus_message_iter_next(&sub);
3090 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
3091 DBusMessageIter sub, sub2;
3093 dbus_message_iter_recurse(iter, &sub);
3094 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3095 const char *controller, *attr, *value;
3097 dbus_message_iter_recurse(&sub, &sub2);
3099 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
3100 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
3101 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
3103 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
3109 dbus_message_iter_next(&sub);
3114 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
3115 DBusMessageIter sub;
3117 dbus_message_iter_recurse(iter, &sub);
3118 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3119 ExecStatusInfo info;
3122 if (exec_status_info_deserialize(&sub, &info) >= 0) {
3123 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
3126 t = strv_join(info.argv, " ");
3128 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
3132 yes_no(info.ignore),
3133 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
3134 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
3135 (unsigned) info. pid,
3136 sigchld_code_to_string(info.code),
3138 info.code == CLD_EXITED ? "" : "/",
3139 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
3145 strv_free(info.argv);
3147 dbus_message_iter_next(&sub);
3156 if (generic_print_property(name, iter, arg_all) > 0)
3160 printf("%s=[unprintable]\n", name);
3165 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
3166 _cleanup_free_ DBusMessage *reply = NULL;
3167 const char *interface = "";
3169 DBusMessageIter iter, sub, sub2, sub3;
3170 UnitStatusInfo info;
3178 r = bus_method_call_with_reply(
3180 "org.freedesktop.systemd1",
3182 "org.freedesktop.DBus.Properties",
3186 DBUS_TYPE_STRING, &interface,
3191 if (!dbus_message_iter_init(reply, &iter) ||
3192 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3193 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
3194 log_error("Failed to parse reply.");
3198 dbus_message_iter_recurse(&iter, &sub);
3205 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3208 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
3209 dbus_message_iter_recurse(&sub, &sub2);
3211 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
3212 dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
3213 log_error("Failed to parse reply.");
3217 dbus_message_iter_recurse(&sub2, &sub3);
3219 if (show_properties)
3220 r = print_property(name, &sub3);
3222 r = status_property(name, &sub3, &info);
3224 log_error("Failed to parse reply.");
3228 dbus_message_iter_next(&sub);
3233 if (!show_properties) {
3234 if (streq(verb, "help"))
3235 show_unit_help(&info);
3237 print_status_info(&info);
3240 strv_free(info.documentation);
3242 if (!streq_ptr(info.active_state, "active") &&
3243 !streq_ptr(info.active_state, "reloading") &&
3244 streq(verb, "status"))
3245 /* According to LSB: "program not running" */
3248 while ((p = info.exec)) {
3249 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
3250 exec_status_info_free(p);
3256 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
3257 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3258 const char *path = NULL;
3262 dbus_error_init(&error);
3264 r = bus_method_call_with_reply(
3266 "org.freedesktop.systemd1",
3267 "/org/freedesktop/systemd1",
3268 "org.freedesktop.systemd1.Manager",
3272 DBUS_TYPE_UINT32, &pid,
3277 if (!dbus_message_get_args(reply, &error,
3278 DBUS_TYPE_OBJECT_PATH, &path,
3279 DBUS_TYPE_INVALID)) {
3280 log_error("Failed to parse reply: %s", bus_error_message(&error));
3285 r = show_one(verb, bus, path, false, new_line);
3288 dbus_error_free(&error);
3293 static int show(DBusConnection *bus, char **args) {
3295 bool show_properties, new_line = false;
3301 show_properties = streq(args[0], "show");
3303 if (show_properties)
3304 pager_open_if_enabled();
3306 /* If no argument is specified inspect the manager itself */
3308 if (show_properties && strv_length(args) <= 1)
3309 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
3311 STRV_FOREACH(name, args+1) {
3314 if (safe_atou32(*name, &id) < 0) {
3315 _cleanup_free_ char *p = NULL, *n = NULL;
3316 /* Interpret as unit name */
3318 n = unit_name_mangle(*name);
3322 p = unit_dbus_path_from_name(n);
3326 r = show_one(args[0], bus, p, show_properties, &new_line);
3330 } else if (show_properties) {
3331 _cleanup_free_ char *p = NULL;
3333 /* Interpret as job id */
3334 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
3337 r = show_one(args[0], bus, p, show_properties, &new_line);
3342 /* Interpret as PID */
3343 r = show_one_by_pid(args[0], bus, id, &new_line);
3352 static int dump(DBusConnection *bus, char **args) {
3353 _cleanup_free_ DBusMessage *reply = NULL;
3358 dbus_error_init(&error);
3360 pager_open_if_enabled();
3362 r = bus_method_call_with_reply(
3364 "org.freedesktop.systemd1",
3365 "/org/freedesktop/systemd1",
3366 "org.freedesktop.systemd1.Manager",
3374 if (!dbus_message_get_args(reply, &error,
3375 DBUS_TYPE_STRING, &text,
3376 DBUS_TYPE_INVALID)) {
3377 log_error("Failed to parse reply: %s", bus_error_message(&error));
3378 dbus_error_free(&error);
3382 fputs(text, stdout);
3386 static int snapshot(DBusConnection *bus, char **args) {
3387 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3390 dbus_bool_t cleanup = FALSE;
3391 DBusMessageIter iter, sub;
3394 *interface = "org.freedesktop.systemd1.Unit",
3396 _cleanup_free_ char *n = NULL;
3398 dbus_error_init(&error);
3400 if (strv_length(args) > 1)
3401 n = snapshot_name_mangle(args[1]);
3407 r = bus_method_call_with_reply (
3409 "org.freedesktop.systemd1",
3410 "/org/freedesktop/systemd1",
3411 "org.freedesktop.systemd1.Manager",
3415 DBUS_TYPE_STRING, &n,
3416 DBUS_TYPE_BOOLEAN, &cleanup,
3421 if (!dbus_message_get_args(reply, &error,
3422 DBUS_TYPE_OBJECT_PATH, &path,
3423 DBUS_TYPE_INVALID)) {
3424 log_error("Failed to parse reply: %s", bus_error_message(&error));
3425 dbus_error_free(&error);
3429 dbus_message_unref(reply);
3432 r = bus_method_call_with_reply (
3434 "org.freedesktop.systemd1",
3436 "org.freedesktop.DBus.Properties",
3440 DBUS_TYPE_STRING, &interface,
3441 DBUS_TYPE_STRING, &property,
3446 if (!dbus_message_iter_init(reply, &iter) ||
3447 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3448 log_error("Failed to parse reply.");
3452 dbus_message_iter_recurse(&iter, &sub);
3454 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3455 log_error("Failed to parse reply.");
3459 dbus_message_iter_get_basic(&sub, &id);
3467 static int delete_snapshot(DBusConnection *bus, char **args) {
3472 STRV_FOREACH(name, args+1) {
3473 _cleanup_free_ char *n = NULL;
3476 n = snapshot_name_mangle(*name);
3480 r = bus_method_call_with_reply(
3482 "org.freedesktop.systemd1",
3483 "/org/freedesktop/systemd1",
3484 "org.freedesktop.systemd1.Manager",
3488 DBUS_TYPE_STRING, &n,
3497 static int daemon_reload(DBusConnection *bus, char **args) {
3502 if (arg_action == ACTION_RELOAD)
3504 else if (arg_action == ACTION_REEXEC)
3505 method = "Reexecute";
3507 assert(arg_action == ACTION_SYSTEMCTL);
3510 streq(args[0], "clear-jobs") ||
3511 streq(args[0], "cancel") ? "ClearJobs" :
3512 streq(args[0], "daemon-reexec") ? "Reexecute" :
3513 streq(args[0], "reset-failed") ? "ResetFailed" :
3514 streq(args[0], "halt") ? "Halt" :
3515 streq(args[0], "poweroff") ? "PowerOff" :
3516 streq(args[0], "reboot") ? "Reboot" :
3517 streq(args[0], "kexec") ? "KExec" :
3518 streq(args[0], "exit") ? "Exit" :
3519 /* "daemon-reload" */ "Reload";
3522 r = bus_method_call_with_reply(
3524 "org.freedesktop.systemd1",
3525 "/org/freedesktop/systemd1",
3526 "org.freedesktop.systemd1.Manager",
3532 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
3533 /* There's always a fallback possible for
3534 * legacy actions. */
3536 else if (r == -ETIMEDOUT && streq(method, "Reexecute"))
3537 /* On reexecution, we expect a disconnect, not
3541 log_error("Failed to issue method call: %s", bus_error_message(&error));
3543 dbus_error_free(&error);
3547 static int reset_failed(DBusConnection *bus, char **args) {
3551 if (strv_length(args) <= 1)
3552 return daemon_reload(bus, args);
3554 STRV_FOREACH(name, args+1) {
3555 _cleanup_free_ char *n;
3557 n = unit_name_mangle(*name);
3561 r = bus_method_call_with_reply(
3563 "org.freedesktop.systemd1",
3564 "/org/freedesktop/systemd1",
3565 "org.freedesktop.systemd1.Manager",
3569 DBUS_TYPE_STRING, &n,
3578 static int show_enviroment(DBusConnection *bus, char **args) {
3579 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3580 DBusMessageIter iter, sub, sub2;
3583 *interface = "org.freedesktop.systemd1.Manager",
3584 *property = "Environment";
3586 pager_open_if_enabled();
3588 r = bus_method_call_with_reply(
3590 "org.freedesktop.systemd1",
3591 "/org/freedesktop/systemd1",
3592 "org.freedesktop.DBus.Properties",
3596 DBUS_TYPE_STRING, &interface,
3597 DBUS_TYPE_STRING, &property,
3602 if (!dbus_message_iter_init(reply, &iter) ||
3603 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3604 log_error("Failed to parse reply.");
3608 dbus_message_iter_recurse(&iter, &sub);
3610 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3611 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3612 log_error("Failed to parse reply.");
3616 dbus_message_iter_recurse(&sub, &sub2);
3618 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3621 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3622 log_error("Failed to parse reply.");
3626 dbus_message_iter_get_basic(&sub2, &text);
3629 dbus_message_iter_next(&sub2);
3635 static int switch_root(DBusConnection *bus, char **args) {
3638 _cleanup_free_ char *init = NULL;
3640 l = strv_length(args);
3641 if (l < 2 || l > 3) {
3642 log_error("Wrong number of arguments.");
3649 init = strdup(args[2]);
3651 parse_env_file("/proc/cmdline", WHITESPACE,
3661 log_debug("switching root - root: %s; init: %s", root, init);
3663 return bus_method_call_with_reply(
3665 "org.freedesktop.systemd1",
3666 "/org/freedesktop/systemd1",
3667 "org.freedesktop.systemd1.Manager",
3671 DBUS_TYPE_STRING, &root,
3672 DBUS_TYPE_STRING, &init,
3676 static int set_environment(DBusConnection *bus, char **args) {
3677 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
3680 DBusMessageIter iter;
3686 dbus_error_init(&error);
3688 method = streq(args[0], "set-environment")
3690 : "UnsetEnvironment";
3692 m = dbus_message_new_method_call(
3693 "org.freedesktop.systemd1",
3694 "/org/freedesktop/systemd1",
3695 "org.freedesktop.systemd1.Manager",
3700 dbus_message_iter_init_append(m, &iter);
3702 r = bus_append_strv_iter(&iter, args + 1);
3706 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3708 log_error("Failed to issue method call: %s", bus_error_message(&error));
3709 dbus_error_free(&error);
3716 static int enable_sysv_units(char **args) {
3719 #if defined(HAVE_SYSV_COMPAT) && defined(HAVE_CHKCONFIG)
3720 const char *verb = args[0];
3721 unsigned f = 1, t = 1;
3724 if (arg_scope != UNIT_FILE_SYSTEM)
3727 if (!streq(verb, "enable") &&
3728 !streq(verb, "disable") &&
3729 !streq(verb, "is-enabled"))
3732 /* Processes all SysV units, and reshuffles the array so that
3733 * afterwards only the native units remain */
3736 r = lookup_paths_init(&paths, SYSTEMD_SYSTEM, false, NULL, NULL, NULL);
3741 for (f = 1; args[f]; f++) {
3744 bool found_native = false, found_sysv;
3746 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3747 char **k, *l, *q = NULL;
3754 if (!endswith(name, ".service"))
3757 if (path_is_absolute(name))
3760 STRV_FOREACH(k, paths.unit_path) {
3763 if (!isempty(arg_root))
3764 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3766 asprintf(&p, "%s/%s", *k, name);
3773 found_native = access(p, F_OK) >= 0;
3784 if (!isempty(arg_root))
3785 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3787 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3793 p[strlen(p) - sizeof(".service") + 1] = 0;
3794 found_sysv = access(p, F_OK) >= 0;
3801 /* Mark this entry, so that we don't try enabling it as native unit */
3802 args[f] = (char*) "";
3804 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
3806 if (!isempty(arg_root))
3807 argv[c++] = q = strappend("--root=", arg_root);
3809 argv[c++] = path_get_file_name(p);
3811 streq(verb, "enable") ? "on" :
3812 streq(verb, "disable") ? "off" : "--level=5";
3815 l = strv_join((char**)argv, " ");
3823 log_info("Executing %s", l);
3828 log_error("Failed to fork: %m");
3833 } else if (pid == 0) {
3836 execv(argv[0], (char**) argv);
3837 _exit(EXIT_FAILURE);
3843 j = wait_for_terminate(pid, &status);
3845 log_error("Failed to wait for child: %s", strerror(-r));
3850 if (status.si_code == CLD_EXITED) {
3851 if (streq(verb, "is-enabled")) {
3852 if (status.si_status == 0) {
3861 } else if (status.si_status != 0) {
3872 lookup_paths_free(&paths);
3874 /* Drop all SysV units */
3875 for (f = 1, t = 1; args[f]; f++) {
3877 if (isempty(args[f]))
3880 args[t++] = args[f];
3889 static int mangle_names(char **original_names, char ***mangled_names) {
3890 char **i, **l, **name;
3892 l = new(char*, strv_length(original_names) + 1);
3897 STRV_FOREACH(name, original_names) {
3899 /* When enabling units qualified path names are OK,
3900 * too, hence allow them explicitly. */
3905 *i = unit_name_mangle(*name);
3921 static int enable_unit(DBusConnection *bus, char **args) {
3922 const char *verb = args[0];
3923 UnitFileChange *changes = NULL;
3924 unsigned n_changes = 0, i;
3925 int carries_install_info = -1;
3926 DBusMessage *m = NULL, *reply = NULL;
3929 char **mangled_names = NULL;
3931 r = enable_sysv_units(args);
3938 dbus_error_init(&error);
3940 if (!bus || avoid_bus()) {
3941 if (streq(verb, "enable")) {
3942 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3943 carries_install_info = r;
3944 } else if (streq(verb, "disable"))
3945 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3946 else if (streq(verb, "reenable")) {
3947 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3948 carries_install_info = r;
3949 } else if (streq(verb, "link"))
3950 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3951 else if (streq(verb, "preset")) {
3952 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3953 carries_install_info = r;
3954 } else if (streq(verb, "mask"))
3955 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3956 else if (streq(verb, "unmask"))
3957 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3959 assert_not_reached("Unknown verb");
3962 log_error("Operation failed: %s", strerror(-r));
3967 for (i = 0; i < n_changes; i++) {
3968 if (changes[i].type == UNIT_FILE_SYMLINK)
3969 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
3971 log_info("rm '%s'", changes[i].path);
3978 bool send_force = true, expect_carries_install_info = false;
3980 DBusMessageIter iter, sub, sub2;
3982 if (streq(verb, "enable")) {
3983 method = "EnableUnitFiles";
3984 expect_carries_install_info = true;
3985 } else if (streq(verb, "disable")) {
3986 method = "DisableUnitFiles";
3988 } else if (streq(verb, "reenable")) {
3989 method = "ReenableUnitFiles";
3990 expect_carries_install_info = true;
3991 } else if (streq(verb, "link"))
3992 method = "LinkUnitFiles";
3993 else if (streq(verb, "preset")) {
3994 method = "PresetUnitFiles";
3995 expect_carries_install_info = true;
3996 } else if (streq(verb, "mask"))
3997 method = "MaskUnitFiles";
3998 else if (streq(verb, "unmask")) {
3999 method = "UnmaskUnitFiles";
4002 assert_not_reached("Unknown verb");
4004 m = dbus_message_new_method_call(
4005 "org.freedesktop.systemd1",
4006 "/org/freedesktop/systemd1",
4007 "org.freedesktop.systemd1.Manager",
4014 dbus_message_iter_init_append(m, &iter);
4016 r = mangle_names(args+1, &mangled_names);
4020 r = bus_append_strv_iter(&iter, mangled_names);
4022 log_error("Failed to append unit files.");
4027 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
4028 log_error("Failed to append runtime boolean.");
4036 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
4037 log_error("Failed to append force boolean.");
4043 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4045 log_error("Failed to issue method call: %s", bus_error_message(&error));
4050 if (!dbus_message_iter_init(reply, &iter)) {
4051 log_error("Failed to initialize iterator.");
4055 if (expect_carries_install_info) {
4056 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
4058 log_error("Failed to parse reply.");
4062 carries_install_info = b;
4065 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
4066 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
4067 log_error("Failed to parse reply.");
4072 dbus_message_iter_recurse(&iter, &sub);
4073 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
4074 const char *type, *path, *source;
4076 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
4077 log_error("Failed to parse reply.");
4082 dbus_message_iter_recurse(&sub, &sub2);
4084 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
4085 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
4086 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
4087 log_error("Failed to parse reply.");
4093 if (streq(type, "symlink"))
4094 log_info("ln -s '%s' '%s'", source, path);
4096 log_info("rm '%s'", path);
4099 dbus_message_iter_next(&sub);
4102 /* Try to reload if enabeld */
4104 r = daemon_reload(bus, args);
4107 if (carries_install_info == 0)
4109 "The unit files have no [Install] section. They are not meant to be enabled\n"
4110 "using systemctl.\n"
4111 "Possible reasons for having this kind of units are:\n"
4112 "1) A unit may be statically enabled by being symlinked from another unit's\n"
4113 " .wants/ or .requires/ directory.\n"
4114 "2) A unit's purpose may be to act as a helper for some other unit which has\n"
4115 " a requirement dependency on it.\n"
4116 "3) A unit may be started when needed via activation (socket, path, timer,\n"
4117 " D-Bus, udev, scripted systemctl call, ...).\n");
4121 dbus_message_unref(m);
4124 dbus_message_unref(reply);
4126 unit_file_changes_free(changes, n_changes);
4128 dbus_error_free(&error);
4130 strv_free(mangled_names);
4135 static int unit_is_enabled(DBusConnection *bus, char **args) {
4138 DBusMessage *reply = NULL;
4142 dbus_error_init(&error);
4144 r = enable_sysv_units(args);
4150 if (!bus || avoid_bus()) {
4152 STRV_FOREACH(name, args+1) {
4153 UnitFileState state;
4155 state = unit_file_get_state(arg_scope, arg_root, *name);
4161 if (state == UNIT_FILE_ENABLED ||
4162 state == UNIT_FILE_ENABLED_RUNTIME ||
4163 state == UNIT_FILE_STATIC)
4167 puts(unit_file_state_to_string(state));
4171 STRV_FOREACH(name, args+1) {
4174 r = bus_method_call_with_reply (
4176 "org.freedesktop.systemd1",
4177 "/org/freedesktop/systemd1",
4178 "org.freedesktop.systemd1.Manager",
4182 DBUS_TYPE_STRING, name,
4187 if (!dbus_message_get_args(reply, &error,
4188 DBUS_TYPE_STRING, &s,
4189 DBUS_TYPE_INVALID)) {
4190 log_error("Failed to parse reply: %s", bus_error_message(&error));
4195 dbus_message_unref(reply);
4198 if (streq(s, "enabled") ||
4199 streq(s, "enabled-runtime") ||
4208 r = enabled ? 0 : 1;
4212 dbus_message_unref(reply);
4214 dbus_error_free(&error);
4218 static int systemctl_help(void) {
4220 pager_open_if_enabled();
4222 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4223 "Query or send control commands to the systemd manager.\n\n"
4224 " -h --help Show this help\n"
4225 " --version Show package version\n"
4226 " -t --type=TYPE List only units of a particular type\n"
4227 " -p --property=NAME Show only properties by this name\n"
4228 " -a --all Show all units/properties, including dead/empty ones\n"
4229 " --failed Show only failed units\n"
4230 " --full Don't ellipsize unit names on output\n"
4231 " --fail When queueing a new job, fail if conflicting jobs are\n"
4233 " --ignore-dependencies\n"
4234 " When queueing a new job, ignore all its dependencies\n"
4235 " -i --ignore-inhibitors\n"
4236 " When shutting down or sleeping, ignore inhibitors\n"
4237 " --kill-who=WHO Who to send signal to\n"
4238 " -s --signal=SIGNAL Which signal to send\n"
4239 " -H --host=[USER@]HOST\n"
4240 " Show information for remote host\n"
4241 " -P --privileged Acquire privileges before execution\n"
4242 " -q --quiet Suppress output\n"
4243 " --no-block Do not wait until operation finished\n"
4244 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4245 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4247 " --no-legend Do not print a legend (column headers and hints)\n"
4248 " --no-pager Do not pipe output into a pager\n"
4249 " --no-ask-password\n"
4250 " Do not ask for system passwords\n"
4251 " --order When generating graph for dot, show only order\n"
4252 " --require When generating graph for dot, show only requirement\n"
4253 " --system Connect to system manager\n"
4254 " --user Connect to user service manager\n"
4255 " --global Enable/disable unit files globally\n"
4256 " -f --force When enabling unit files, override existing symlinks\n"
4257 " When shutting down, execute action immediately\n"
4258 " --root=PATH Enable unit files in the specified root directory\n"
4259 " --runtime Enable unit files only temporarily until next reboot\n"
4260 " -n --lines=INTEGER Journal entries to show\n"
4261 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
4262 " verbose, export, json, json-pretty, json-sse, cat)\n\n"
4264 " list-units List loaded units\n"
4265 " start [NAME...] Start (activate) one or more units\n"
4266 " stop [NAME...] Stop (deactivate) one or more units\n"
4267 " reload [NAME...] Reload one or more units\n"
4268 " restart [NAME...] Start or restart one or more units\n"
4269 " try-restart [NAME...] Restart one or more units if active\n"
4270 " reload-or-restart [NAME...] Reload one or more units if possible,\n"
4271 " otherwise start or restart\n"
4272 " reload-or-try-restart [NAME...] Reload one or more units if possible,\n"
4273 " otherwise restart if active\n"
4274 " isolate [NAME] Start one unit and stop all others\n"
4275 " kill [NAME...] Send signal to processes of a unit\n"
4276 " is-active [NAME...] Check whether units are active\n"
4277 " is-failed [NAME...] Check whether units are failed\n"
4278 " status [NAME...|PID...] Show runtime status of one or more units\n"
4279 " show [NAME...|JOB...] Show properties of one or more\n"
4280 " units/jobs or the manager\n"
4281 " help [NAME...|PID...] Show manual for one or more units\n"
4282 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4284 " set-cgroup [NAME] [CGROUP...] Add unit to a control group\n"
4285 " unset-cgroup [NAME] [CGROUP...] Remove unit from a control group\n"
4286 " set-cgroup-attr [NAME] [ATTR] [VALUE] ...\n"
4287 " Set control group attribute\n"
4288 " unset-cgroup-attr [NAME] [ATTR...]\n"
4289 " Unset control group attribute\n"
4290 " load [NAME...] Load one or more units\n"
4291 " list-dependencies [NAME] Recursively show units which are required\n"
4292 " or wanted by this unit\n\n"
4293 "Unit File Commands:\n"
4294 " list-unit-files List installed unit files\n"
4295 " enable [NAME...] Enable one or more unit files\n"
4296 " disable [NAME...] Disable one or more unit files\n"
4297 " reenable [NAME...] Reenable one or more unit files\n"
4298 " preset [NAME...] Enable/disable one or more unit files\n"
4299 " based on preset configuration\n"
4300 " mask [NAME...] Mask one or more units\n"
4301 " unmask [NAME...] Unmask one or more units\n"
4302 " link [PATH...] Link one or more units files into\n"
4303 " the search path\n"
4304 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
4306 " list-jobs List jobs\n"
4307 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
4308 "Status Commands:\n"
4309 " dump Dump server status\n"
4310 " dot Dump dependency graph for dot(1)\n\n"
4311 "Snapshot Commands:\n"
4312 " snapshot [NAME] Create a snapshot\n"
4313 " delete [NAME...] Remove one or more snapshots\n\n"
4314 "Environment Commands:\n"
4315 " show-environment Dump environment\n"
4316 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4317 " unset-environment [NAME...] Unset one or more environment variables\n\n"
4318 "Manager Lifecycle Commands:\n"
4319 " daemon-reload Reload systemd manager configuration\n"
4320 " daemon-reexec Reexecute systemd manager\n\n"
4321 "System Commands:\n"
4322 " default Enter system default mode\n"
4323 " rescue Enter system rescue mode\n"
4324 " emergency Enter system emergency mode\n"
4325 " halt Shut down and halt the system\n"
4326 " poweroff Shut down and power-off the system\n"
4327 " reboot Shut down and reboot the system\n"
4328 " kexec Shut down and reboot the system with kexec\n"
4329 " exit Request user instance exit\n"
4330 " switch-root [ROOT] [INIT] Change to a different root file system\n"
4331 " suspend Suspend the system\n"
4332 " hibernate Hibernate the system\n"
4333 " hybrid-sleep Hibernate and suspend the system\n",
4334 program_invocation_short_name);
4339 static int halt_help(void) {
4341 printf("%s [OPTIONS...]\n\n"
4342 "%s the system.\n\n"
4343 " --help Show this help\n"
4344 " --halt Halt the machine\n"
4345 " -p --poweroff Switch off the machine\n"
4346 " --reboot Reboot the machine\n"
4347 " -f --force Force immediate halt/power-off/reboot\n"
4348 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4349 " -d --no-wtmp Don't write wtmp record\n"
4350 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4351 program_invocation_short_name,
4352 arg_action == ACTION_REBOOT ? "Reboot" :
4353 arg_action == ACTION_POWEROFF ? "Power off" :
4359 static int shutdown_help(void) {
4361 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4362 "Shut down the system.\n\n"
4363 " --help Show this help\n"
4364 " -H --halt Halt the machine\n"
4365 " -P --poweroff Power-off the machine\n"
4366 " -r --reboot Reboot the machine\n"
4367 " -h Equivalent to --poweroff, overridden by --halt\n"
4368 " -k Don't halt/power-off/reboot, just send warnings\n"
4369 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4370 " -c Cancel a pending shutdown\n",
4371 program_invocation_short_name);
4376 static int telinit_help(void) {
4378 printf("%s [OPTIONS...] {COMMAND}\n\n"
4379 "Send control commands to the init daemon.\n\n"
4380 " --help Show this help\n"
4381 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4383 " 0 Power-off the machine\n"
4384 " 6 Reboot the machine\n"
4385 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4386 " 1, s, S Enter rescue mode\n"
4387 " q, Q Reload init daemon configuration\n"
4388 " u, U Reexecute init daemon\n",
4389 program_invocation_short_name);
4394 static int runlevel_help(void) {
4396 printf("%s [OPTIONS...]\n\n"
4397 "Prints the previous and current runlevel of the init system.\n\n"
4398 " --help Show this help\n",
4399 program_invocation_short_name);
4404 static int help_types(void) {
4407 puts("Available unit types:");
4408 for(i = UNIT_SERVICE; i < _UNIT_TYPE_MAX; i++)
4409 if (unit_type_table[i])
4410 puts(unit_type_table[i]);
4412 puts("\nAvailable unit load states: ");
4413 for(i = UNIT_STUB; i < _UNIT_LOAD_STATE_MAX; i++)
4414 if (unit_type_table[i])
4415 puts(unit_load_state_table[i]);
4420 static int systemctl_parse_argv(int argc, char *argv[]) {
4424 ARG_IGNORE_DEPENDENCIES,
4439 ARG_NO_ASK_PASSWORD,
4445 static const struct option options[] = {
4446 { "help", no_argument, NULL, 'h' },
4447 { "version", no_argument, NULL, ARG_VERSION },
4448 { "type", required_argument, NULL, 't' },
4449 { "property", required_argument, NULL, 'p' },
4450 { "all", no_argument, NULL, 'a' },
4451 { "failed", no_argument, NULL, ARG_FAILED },
4452 { "full", no_argument, NULL, ARG_FULL },
4453 { "fail", no_argument, NULL, ARG_FAIL },
4454 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4455 { "ignore-inhibitors", no_argument, NULL, 'i' },
4456 { "user", no_argument, NULL, ARG_USER },
4457 { "system", no_argument, NULL, ARG_SYSTEM },
4458 { "global", no_argument, NULL, ARG_GLOBAL },
4459 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4460 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4461 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4462 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4463 { "quiet", no_argument, NULL, 'q' },
4464 { "order", no_argument, NULL, ARG_ORDER },
4465 { "require", no_argument, NULL, ARG_REQUIRE },
4466 { "root", required_argument, NULL, ARG_ROOT },
4467 { "force", no_argument, NULL, ARG_FORCE },
4468 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4469 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4470 { "signal", required_argument, NULL, 's' },
4471 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4472 { "host", required_argument, NULL, 'H' },
4473 { "privileged",no_argument, NULL, 'P' },
4474 { "runtime", no_argument, NULL, ARG_RUNTIME },
4475 { "lines", required_argument, NULL, 'n' },
4476 { "output", required_argument, NULL, 'o' },
4477 { NULL, 0, NULL, 0 }
4485 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:i", options, NULL)) >= 0) {
4494 puts(PACKAGE_STRING);
4495 puts(SYSTEMD_FEATURES);
4499 if (streq(optarg, "help")) {
4504 if (unit_type_from_string(optarg) >= 0) {
4508 if (unit_load_state_from_string(optarg) >= 0) {
4509 arg_load_state = optarg;
4512 log_error("Unkown unit type or load state '%s'.",
4514 log_info("Use -t help to see a list of allowed values.");
4519 if (!(l = strv_append(arg_property, optarg)))
4522 strv_free(arg_property);
4525 /* If the user asked for a particular
4526 * property, show it to him, even if it is
4537 arg_job_mode = "fail";
4540 case ARG_IGNORE_DEPENDENCIES:
4541 arg_job_mode = "ignore-dependencies";
4545 arg_scope = UNIT_FILE_USER;
4549 arg_scope = UNIT_FILE_SYSTEM;
4553 arg_scope = UNIT_FILE_GLOBAL;
4557 arg_no_block = true;
4561 arg_no_legend = true;
4565 arg_no_pager = true;
4573 arg_dot = DOT_ORDER;
4577 arg_dot = DOT_REQUIRE;
4605 arg_no_reload = true;
4609 arg_kill_who = optarg;
4613 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4614 log_error("Failed to parse signal string %s.", optarg);
4619 case ARG_NO_ASK_PASSWORD:
4620 arg_ask_password = false;
4624 arg_transport = TRANSPORT_POLKIT;
4628 arg_transport = TRANSPORT_SSH;
4637 if (safe_atou(optarg, &arg_lines) < 0) {
4638 log_error("Failed to parse lines '%s'", optarg);
4644 arg_output = output_mode_from_string(optarg);
4645 if (arg_output < 0) {
4646 log_error("Unknown output '%s'.", optarg);
4652 arg_ignore_inhibitors = true;
4659 log_error("Unknown option code '%c'.", c);
4664 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4665 log_error("Cannot access user instance remotely.");
4672 static int halt_parse_argv(int argc, char *argv[]) {
4681 static const struct option options[] = {
4682 { "help", no_argument, NULL, ARG_HELP },
4683 { "halt", no_argument, NULL, ARG_HALT },
4684 { "poweroff", no_argument, NULL, 'p' },
4685 { "reboot", no_argument, NULL, ARG_REBOOT },
4686 { "force", no_argument, NULL, 'f' },
4687 { "wtmp-only", no_argument, NULL, 'w' },
4688 { "no-wtmp", no_argument, NULL, 'd' },
4689 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4690 { NULL, 0, NULL, 0 }
4698 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4699 if (runlevel == '0' || runlevel == '6')
4702 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4710 arg_action = ACTION_HALT;
4714 if (arg_action != ACTION_REBOOT)
4715 arg_action = ACTION_POWEROFF;
4719 arg_action = ACTION_REBOOT;
4741 /* Compatibility nops */
4748 log_error("Unknown option code '%c'.", c);
4753 if (optind < argc) {
4754 log_error("Too many arguments.");
4761 static int parse_time_spec(const char *t, usec_t *_u) {
4765 if (streq(t, "now"))
4767 else if (!strchr(t, ':')) {
4770 if (safe_atou64(t, &u) < 0)
4773 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4782 hour = strtol(t, &e, 10);
4783 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4786 minute = strtol(e+1, &e, 10);
4787 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4790 n = now(CLOCK_REALTIME);
4791 s = (time_t) (n / USEC_PER_SEC);
4794 assert_se(localtime_r(&s, &tm));
4796 tm.tm_hour = (int) hour;
4797 tm.tm_min = (int) minute;
4800 assert_se(s = mktime(&tm));
4802 *_u = (usec_t) s * USEC_PER_SEC;
4805 *_u += USEC_PER_DAY;
4811 static int shutdown_parse_argv(int argc, char *argv[]) {
4818 static const struct option options[] = {
4819 { "help", no_argument, NULL, ARG_HELP },
4820 { "halt", no_argument, NULL, 'H' },
4821 { "poweroff", no_argument, NULL, 'P' },
4822 { "reboot", no_argument, NULL, 'r' },
4823 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4824 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4825 { NULL, 0, NULL, 0 }
4833 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4841 arg_action = ACTION_HALT;
4845 arg_action = ACTION_POWEROFF;
4850 arg_action = ACTION_KEXEC;
4852 arg_action = ACTION_REBOOT;
4856 arg_action = ACTION_KEXEC;
4860 if (arg_action != ACTION_HALT)
4861 arg_action = ACTION_POWEROFF;
4874 /* Compatibility nops */
4878 arg_action = ACTION_CANCEL_SHUTDOWN;
4885 log_error("Unknown option code '%c'.", c);
4890 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
4891 r = parse_time_spec(argv[optind], &arg_when);
4893 log_error("Failed to parse time specification: %s", argv[optind]);
4897 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4899 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
4900 /* No time argument for shutdown cancel */
4901 arg_wall = argv + optind;
4902 else if (argc > optind + 1)
4903 /* We skip the time argument */
4904 arg_wall = argv + optind + 1;
4911 static int telinit_parse_argv(int argc, char *argv[]) {
4918 static const struct option options[] = {
4919 { "help", no_argument, NULL, ARG_HELP },
4920 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4921 { NULL, 0, NULL, 0 }
4924 static const struct {
4928 { '0', ACTION_POWEROFF },
4929 { '6', ACTION_REBOOT },
4930 { '1', ACTION_RESCUE },
4931 { '2', ACTION_RUNLEVEL2 },
4932 { '3', ACTION_RUNLEVEL3 },
4933 { '4', ACTION_RUNLEVEL4 },
4934 { '5', ACTION_RUNLEVEL5 },
4935 { 's', ACTION_RESCUE },
4936 { 'S', ACTION_RESCUE },
4937 { 'q', ACTION_RELOAD },
4938 { 'Q', ACTION_RELOAD },
4939 { 'u', ACTION_REEXEC },
4940 { 'U', ACTION_REEXEC }
4949 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4964 log_error("Unknown option code '%c'.", c);
4969 if (optind >= argc) {
4974 if (optind + 1 < argc) {
4975 log_error("Too many arguments.");
4979 if (strlen(argv[optind]) != 1) {
4980 log_error("Expected single character argument.");
4984 for (i = 0; i < ELEMENTSOF(table); i++)
4985 if (table[i].from == argv[optind][0])
4988 if (i >= ELEMENTSOF(table)) {
4989 log_error("Unknown command '%s'.", argv[optind]);
4993 arg_action = table[i].to;
5000 static int runlevel_parse_argv(int argc, char *argv[]) {
5006 static const struct option options[] = {
5007 { "help", no_argument, NULL, ARG_HELP },
5008 { NULL, 0, NULL, 0 }
5016 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5027 log_error("Unknown option code '%c'.", c);
5032 if (optind < argc) {
5033 log_error("Too many arguments.");
5040 static int parse_argv(int argc, char *argv[]) {
5044 if (program_invocation_short_name) {
5046 if (strstr(program_invocation_short_name, "halt")) {
5047 arg_action = ACTION_HALT;
5048 return halt_parse_argv(argc, argv);
5049 } else if (strstr(program_invocation_short_name, "poweroff")) {
5050 arg_action = ACTION_POWEROFF;
5051 return halt_parse_argv(argc, argv);
5052 } else if (strstr(program_invocation_short_name, "reboot")) {
5054 arg_action = ACTION_KEXEC;
5056 arg_action = ACTION_REBOOT;
5057 return halt_parse_argv(argc, argv);
5058 } else if (strstr(program_invocation_short_name, "shutdown")) {
5059 arg_action = ACTION_POWEROFF;
5060 return shutdown_parse_argv(argc, argv);
5061 } else if (strstr(program_invocation_short_name, "init")) {
5063 if (sd_booted() > 0) {
5064 arg_action = ACTION_INVALID;
5065 return telinit_parse_argv(argc, argv);
5067 /* Hmm, so some other init system is
5068 * running, we need to forward this
5069 * request to it. For now we simply
5070 * guess that it is Upstart. */
5072 execv("/lib/upstart/telinit", argv);
5074 log_error("Couldn't find an alternative telinit implementation to spawn.");
5078 } else if (strstr(program_invocation_short_name, "runlevel")) {
5079 arg_action = ACTION_RUNLEVEL;
5080 return runlevel_parse_argv(argc, argv);
5084 arg_action = ACTION_SYSTEMCTL;
5085 return systemctl_parse_argv(argc, argv);
5088 static int action_to_runlevel(void) {
5090 static const char table[_ACTION_MAX] = {
5091 [ACTION_HALT] = '0',
5092 [ACTION_POWEROFF] = '0',
5093 [ACTION_REBOOT] = '6',
5094 [ACTION_RUNLEVEL2] = '2',
5095 [ACTION_RUNLEVEL3] = '3',
5096 [ACTION_RUNLEVEL4] = '4',
5097 [ACTION_RUNLEVEL5] = '5',
5098 [ACTION_RESCUE] = '1'
5101 assert(arg_action < _ACTION_MAX);
5103 return table[arg_action];
5106 static int talk_upstart(void) {
5107 DBusMessage *m = NULL, *reply = NULL;
5109 int previous, rl, r;
5111 env1_buf[] = "RUNLEVEL=X",
5112 env2_buf[] = "PREVLEVEL=X";
5113 char *env1 = env1_buf, *env2 = env2_buf;
5114 const char *emit = "runlevel";
5115 dbus_bool_t b_false = FALSE;
5116 DBusMessageIter iter, sub;
5117 DBusConnection *bus;
5119 dbus_error_init(&error);
5121 if (!(rl = action_to_runlevel()))
5124 if (utmp_get_runlevel(&previous, NULL) < 0)
5127 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5128 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5133 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5138 if ((r = bus_check_peercred(bus)) < 0) {
5139 log_error("Failed to verify owner of bus.");
5143 if (!(m = dbus_message_new_method_call(
5144 "com.ubuntu.Upstart",
5145 "/com/ubuntu/Upstart",
5146 "com.ubuntu.Upstart0_6",
5149 log_error("Could not allocate message.");
5154 dbus_message_iter_init_append(m, &iter);
5156 env1_buf[sizeof(env1_buf)-2] = rl;
5157 env2_buf[sizeof(env2_buf)-2] = previous;
5159 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5160 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5161 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5162 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5163 !dbus_message_iter_close_container(&iter, &sub) ||
5164 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5165 log_error("Could not append arguments to message.");
5170 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5172 if (bus_error_is_no_service(&error)) {
5177 log_error("Failed to issue method call: %s", bus_error_message(&error));
5186 dbus_message_unref(m);
5189 dbus_message_unref(reply);
5192 dbus_connection_flush(bus);
5193 dbus_connection_close(bus);
5194 dbus_connection_unref(bus);
5197 dbus_error_free(&error);
5202 static int talk_initctl(void) {
5203 struct init_request request;
5207 if (!(rl = action_to_runlevel()))
5211 request.magic = INIT_MAGIC;
5212 request.sleeptime = 0;
5213 request.cmd = INIT_CMD_RUNLVL;
5214 request.runlevel = rl;
5216 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5218 if (errno == ENOENT)
5221 log_error("Failed to open "INIT_FIFO": %m");
5226 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5227 close_nointr_nofail(fd);
5230 log_error("Failed to write to "INIT_FIFO": %m");
5231 return errno ? -errno : -EIO;
5237 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5239 static const struct {
5247 int (* const dispatch)(DBusConnection *bus, char **args);
5249 { "list-units", LESS, 1, list_units },
5250 { "list-unit-files", EQUAL, 1, list_unit_files },
5251 { "list-jobs", EQUAL, 1, list_jobs },
5252 { "clear-jobs", EQUAL, 1, daemon_reload },
5253 { "load", MORE, 2, load_unit },
5254 { "cancel", MORE, 2, cancel_job },
5255 { "start", MORE, 2, start_unit },
5256 { "stop", MORE, 2, start_unit },
5257 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5258 { "reload", MORE, 2, start_unit },
5259 { "restart", MORE, 2, start_unit },
5260 { "try-restart", MORE, 2, start_unit },
5261 { "reload-or-restart", MORE, 2, start_unit },
5262 { "reload-or-try-restart", MORE, 2, start_unit },
5263 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5264 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5265 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5266 { "isolate", EQUAL, 2, start_unit },
5267 { "set-cgroup", MORE, 2, set_cgroup },
5268 { "unset-cgroup", MORE, 2, set_cgroup },
5269 { "set-cgroup-attr", MORE, 2, set_cgroup_attr },
5270 { "unset-cgroup-attr", MORE, 2, set_cgroup },
5271 { "kill", MORE, 2, kill_unit },
5272 { "is-active", MORE, 2, check_unit_active },
5273 { "check", MORE, 2, check_unit_active },
5274 { "is-failed", MORE, 2, check_unit_failed },
5275 { "show", MORE, 1, show },
5276 { "status", MORE, 2, show },
5277 { "help", MORE, 2, show },
5278 { "dump", EQUAL, 1, dump },
5279 { "dot", EQUAL, 1, dot },
5280 { "snapshot", LESS, 2, snapshot },
5281 { "delete", MORE, 2, delete_snapshot },
5282 { "daemon-reload", EQUAL, 1, daemon_reload },
5283 { "daemon-reexec", EQUAL, 1, daemon_reload },
5284 { "show-environment", EQUAL, 1, show_enviroment },
5285 { "set-environment", MORE, 2, set_environment },
5286 { "unset-environment", MORE, 2, set_environment },
5287 { "halt", EQUAL, 1, start_special },
5288 { "poweroff", EQUAL, 1, start_special },
5289 { "reboot", EQUAL, 1, start_special },
5290 { "kexec", EQUAL, 1, start_special },
5291 { "suspend", EQUAL, 1, start_special },
5292 { "hibernate", EQUAL, 1, start_special },
5293 { "hybrid-sleep", EQUAL, 1, start_special },
5294 { "default", EQUAL, 1, start_special },
5295 { "rescue", EQUAL, 1, start_special },
5296 { "emergency", EQUAL, 1, start_special },
5297 { "exit", EQUAL, 1, start_special },
5298 { "reset-failed", MORE, 1, reset_failed },
5299 { "enable", MORE, 2, enable_unit },
5300 { "disable", MORE, 2, enable_unit },
5301 { "is-enabled", MORE, 2, unit_is_enabled },
5302 { "reenable", MORE, 2, enable_unit },
5303 { "preset", MORE, 2, enable_unit },
5304 { "mask", MORE, 2, enable_unit },
5305 { "unmask", MORE, 2, enable_unit },
5306 { "link", MORE, 2, enable_unit },
5307 { "switch-root", MORE, 2, switch_root },
5308 { "list-dependencies", LESS, 2, list_dependencies },
5318 left = argc - optind;
5321 /* Special rule: no arguments means "list-units" */
5324 if (streq(argv[optind], "help") && !argv[optind+1]) {
5325 log_error("This command expects one or more "
5326 "unit names. Did you mean --help?");
5330 for (i = 0; i < ELEMENTSOF(verbs); i++)
5331 if (streq(argv[optind], verbs[i].verb))
5334 if (i >= ELEMENTSOF(verbs)) {
5335 log_error("Unknown operation '%s'.", argv[optind]);
5340 switch (verbs[i].argc_cmp) {
5343 if (left != verbs[i].argc) {
5344 log_error("Invalid number of arguments.");
5351 if (left < verbs[i].argc) {
5352 log_error("Too few arguments.");
5359 if (left > verbs[i].argc) {
5360 log_error("Too many arguments.");
5367 assert_not_reached("Unknown comparison operator.");
5370 /* Require a bus connection for all operations but
5372 if (!streq(verbs[i].verb, "enable") &&
5373 !streq(verbs[i].verb, "disable") &&
5374 !streq(verbs[i].verb, "is-enabled") &&
5375 !streq(verbs[i].verb, "list-unit-files") &&
5376 !streq(verbs[i].verb, "reenable") &&
5377 !streq(verbs[i].verb, "preset") &&
5378 !streq(verbs[i].verb, "mask") &&
5379 !streq(verbs[i].verb, "unmask") &&
5380 !streq(verbs[i].verb, "link")) {
5382 if (running_in_chroot() > 0) {
5383 log_info("Running in chroot, ignoring request.");
5387 if (((!streq(verbs[i].verb, "reboot") &&
5388 !streq(verbs[i].verb, "halt") &&
5389 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5390 log_error("Failed to get D-Bus connection: %s",
5391 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5397 if (!bus && !avoid_bus()) {
5398 log_error("Failed to get D-Bus connection: %s",
5399 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5404 return verbs[i].dispatch(bus, argv + optind);
5407 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5409 struct msghdr msghdr;
5410 struct iovec iovec[2];
5411 union sockaddr_union sockaddr;
5412 struct sd_shutdown_command c;
5414 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5421 c.dry_run = dry_run;
5425 sockaddr.sa.sa_family = AF_UNIX;
5426 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5429 msghdr.msg_name = &sockaddr;
5430 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5433 iovec[0].iov_base = (char*) &c;
5434 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5436 if (isempty(message))
5437 msghdr.msg_iovlen = 1;
5439 iovec[1].iov_base = (char*) message;
5440 iovec[1].iov_len = strlen(message);
5441 msghdr.msg_iovlen = 2;
5443 msghdr.msg_iov = iovec;
5445 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5446 close_nointr_nofail(fd);
5450 close_nointr_nofail(fd);
5454 static int reload_with_fallback(DBusConnection *bus) {
5457 /* First, try systemd via D-Bus. */
5458 if (daemon_reload(bus, NULL) >= 0)
5462 /* Nothing else worked, so let's try signals */
5463 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5465 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5466 log_error("kill() failed: %m");
5473 static int start_with_fallback(DBusConnection *bus) {
5476 /* First, try systemd via D-Bus. */
5477 if (start_unit(bus, NULL) >= 0)
5481 /* Hmm, talking to systemd via D-Bus didn't work. Then
5482 * let's try to talk to Upstart via D-Bus. */
5483 if (talk_upstart() > 0)
5486 /* Nothing else worked, so let's try
5488 if (talk_initctl() > 0)
5491 log_error("Failed to talk to init daemon.");
5495 warn_wall(arg_action);
5499 static _noreturn_ void halt_now(enum action a) {
5501 /* Make sure C-A-D is handled by the kernel from this
5503 reboot(RB_ENABLE_CAD);
5508 log_info("Halting.");
5509 reboot(RB_HALT_SYSTEM);
5512 case ACTION_POWEROFF:
5513 log_info("Powering off.");
5514 reboot(RB_POWER_OFF);
5518 log_info("Rebooting.");
5519 reboot(RB_AUTOBOOT);
5523 assert_not_reached("Unknown halt action.");
5526 assert_not_reached("Uh? This shouldn't happen.");
5529 static int halt_main(DBusConnection *bus) {
5532 r = check_inhibitors(bus, arg_action);
5536 if (geteuid() != 0) {
5537 /* Try logind if we are a normal user and no special
5538 * mode applies. Maybe PolicyKit allows us to shutdown
5541 if (arg_when <= 0 &&
5544 (arg_action == ACTION_POWEROFF ||
5545 arg_action == ACTION_REBOOT)) {
5546 r = reboot_with_logind(bus, arg_action);
5551 log_error("Must be root.");
5558 m = strv_join(arg_wall, " ");
5559 r = send_shutdownd(arg_when,
5560 arg_action == ACTION_HALT ? 'H' :
5561 arg_action == ACTION_POWEROFF ? 'P' :
5562 arg_action == ACTION_KEXEC ? 'K' :
5570 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5572 char date[FORMAT_TIMESTAMP_MAX];
5574 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5575 format_timestamp(date, sizeof(date), arg_when));
5580 if (!arg_dry && !arg_force)
5581 return start_with_fallback(bus);
5584 if (sd_booted() > 0)
5585 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5587 r = utmp_put_shutdown();
5589 log_warning("Failed to write utmp record: %s", strerror(-r));
5596 halt_now(arg_action);
5597 /* We should never reach this. */
5601 static int runlevel_main(void) {
5602 int r, runlevel, previous;
5604 r = utmp_get_runlevel(&runlevel, &previous);
5611 previous <= 0 ? 'N' : previous,
5612 runlevel <= 0 ? 'N' : runlevel);
5617 int main(int argc, char*argv[]) {
5618 int r, retval = EXIT_FAILURE;
5619 DBusConnection *bus = NULL;
5622 dbus_error_init(&error);
5624 setlocale(LC_ALL, "");
5625 log_parse_environment();
5628 r = parse_argv(argc, argv);
5632 retval = EXIT_SUCCESS;
5636 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5637 * let's shortcut this */
5638 if (arg_action == ACTION_RUNLEVEL) {
5639 r = runlevel_main();
5640 retval = r < 0 ? EXIT_FAILURE : r;
5644 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5645 log_info("Running in chroot, ignoring request.");
5651 if (arg_transport == TRANSPORT_NORMAL)
5652 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5653 else if (arg_transport == TRANSPORT_POLKIT) {
5654 bus_connect_system_polkit(&bus, &error);
5655 private_bus = false;
5656 } else if (arg_transport == TRANSPORT_SSH) {
5657 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5658 private_bus = false;
5660 assert_not_reached("Uh, invalid transport...");
5663 switch (arg_action) {
5665 case ACTION_SYSTEMCTL:
5666 r = systemctl_main(bus, argc, argv, &error);
5670 case ACTION_POWEROFF:
5676 case ACTION_RUNLEVEL2:
5677 case ACTION_RUNLEVEL3:
5678 case ACTION_RUNLEVEL4:
5679 case ACTION_RUNLEVEL5:
5681 case ACTION_EMERGENCY:
5682 case ACTION_DEFAULT:
5683 r = start_with_fallback(bus);
5688 r = reload_with_fallback(bus);
5691 case ACTION_CANCEL_SHUTDOWN: {
5695 m = strv_join(arg_wall, " ");
5697 retval = EXIT_FAILURE;
5701 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
5703 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
5708 case ACTION_INVALID:
5709 case ACTION_RUNLEVEL:
5711 assert_not_reached("Unknown action");
5714 retval = r < 0 ? EXIT_FAILURE : r;
5718 dbus_connection_flush(bus);
5719 dbus_connection_close(bus);
5720 dbus_connection_unref(bus);
5723 dbus_error_free(&error);
5727 strv_free(arg_property);
5730 ask_password_agent_close();
5731 polkit_agent_close();