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;
768 path = unit_dbus_path_from_name(name);
774 r = bus_method_call_with_reply(
776 "org.freedesktop.systemd1",
778 "org.freedesktop.DBus.Properties",
782 DBUS_TYPE_STRING, &interface,
787 if (!dbus_message_iter_init(reply, &iter) ||
788 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
789 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
790 log_error("Failed to parse reply.");
795 dbus_message_iter_recurse(&iter, &sub);
797 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
800 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
801 dbus_message_iter_recurse(&sub, &sub2);
803 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
804 log_error("Failed to parse reply.");
809 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
810 log_error("Failed to parse reply.");
815 dbus_message_iter_recurse(&sub2, &sub3);
816 dbus_message_iter_next(&sub);
818 if (!nulstr_contains(dependencies, prop))
821 if (dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_ARRAY) {
822 if (dbus_message_iter_get_element_type(&sub3) == DBUS_TYPE_STRING) {
823 DBusMessageIter sub4;
824 dbus_message_iter_recurse(&sub3, &sub4);
826 while (dbus_message_iter_get_arg_type(&sub4) != DBUS_TYPE_INVALID) {
829 assert(dbus_message_iter_get_arg_type(&sub4) == DBUS_TYPE_STRING);
830 dbus_message_iter_get_basic(&sub4, &s);
832 r = strv_extend(&ret, s);
838 dbus_message_iter_next(&sub4);
851 static int list_dependencies_compare(const void *_a, const void *_b) {
852 const char **a = (const char**) _a, **b = (const char**) _b;
853 if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET)
855 if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET)
857 return strcasecmp(*a, *b);
860 static int list_dependencies_one(DBusConnection *bus, const char *name, int level, char **units, unsigned int branches) {
866 u = strv_append(units, name);
870 r = list_dependencies_get_dependencies(bus, name, &deps);
874 qsort(deps, strv_length(deps), sizeof (char*), list_dependencies_compare);
876 STRV_FOREACH(c, deps) {
877 if (strv_contains(u, *c)) {
878 r = list_dependencies_print("...", level + 1, (branches << 1) | (c[1] == NULL ? 0 : 1), 1);
884 r = list_dependencies_print(*c, level, branches, c[1] == NULL);
888 if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) {
889 r = list_dependencies_one(bus, *c, level + 1, u, (branches << 1) | (c[1] == NULL ? 0 : 1));
902 static int list_dependencies(DBusConnection *bus, char **args) {
903 _cleanup_free_ char *unit = NULL;
909 unit = unit_name_mangle(args[1]);
914 u = SPECIAL_DEFAULT_TARGET;
916 pager_open_if_enabled();
920 return list_dependencies_one(bus, u, 0, NULL, 0);
923 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
925 static const char * const colors[] = {
926 "Requires", "[color=\"black\"]",
927 "RequiresOverridable", "[color=\"black\"]",
928 "Requisite", "[color=\"darkblue\"]",
929 "RequisiteOverridable", "[color=\"darkblue\"]",
930 "Wants", "[color=\"grey66\"]",
931 "Conflicts", "[color=\"red\"]",
932 "ConflictedBy", "[color=\"red\"]",
933 "After", "[color=\"green\"]"
936 const char *c = NULL;
943 for (i = 0; i < ELEMENTSOF(colors); i += 2)
944 if (streq(colors[i], prop)) {
952 if (arg_dot != DOT_ALL)
953 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
956 switch (dbus_message_iter_get_arg_type(iter)) {
958 case DBUS_TYPE_ARRAY:
960 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
963 dbus_message_iter_recurse(iter, &sub);
965 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
968 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
969 dbus_message_iter_get_basic(&sub, &s);
970 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
972 dbus_message_iter_next(&sub);
982 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
983 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
984 const char *interface = "org.freedesktop.systemd1.Unit";
986 DBusMessageIter iter, sub, sub2, sub3;
991 r = bus_method_call_with_reply(
993 "org.freedesktop.systemd1",
995 "org.freedesktop.DBus.Properties",
999 DBUS_TYPE_STRING, &interface,
1004 if (!dbus_message_iter_init(reply, &iter) ||
1005 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1006 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
1007 log_error("Failed to parse reply.");
1011 dbus_message_iter_recurse(&iter, &sub);
1013 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1016 assert(dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY);
1017 dbus_message_iter_recurse(&sub, &sub2);
1019 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0 ||
1020 dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
1021 log_error("Failed to parse reply.");
1025 dbus_message_iter_recurse(&sub2, &sub3);
1026 r = dot_one_property(name, prop, &sub3);
1030 dbus_message_iter_next(&sub);
1036 static int dot(DBusConnection *bus, char **args) {
1037 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1038 DBusMessageIter iter, sub, sub2;
1041 r = bus_method_call_with_reply(
1043 "org.freedesktop.systemd1",
1044 "/org/freedesktop/systemd1",
1045 "org.freedesktop.systemd1.Manager",
1053 if (!dbus_message_iter_init(reply, &iter) ||
1054 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1055 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1056 log_error("Failed to parse reply.");
1060 printf("digraph systemd {\n");
1062 dbus_message_iter_recurse(&iter, &sub);
1063 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1064 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
1066 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1067 log_error("Failed to parse reply.");
1071 dbus_message_iter_recurse(&sub, &sub2);
1073 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
1074 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
1075 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
1076 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
1077 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
1078 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
1079 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
1080 log_error("Failed to parse reply.");
1084 r = dot_one(bus, id, unit_path);
1088 /* printf("\t\"%s\";\n", id); */
1089 dbus_message_iter_next(&sub);
1094 log_info(" Color legend: black = Requires\n"
1095 " dark blue = Requisite\n"
1096 " dark grey = Wants\n"
1097 " red = Conflicts\n"
1098 " green = After\n");
1101 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
1102 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
1107 static int list_jobs(DBusConnection *bus, char **args) {
1108 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1109 DBusMessageIter iter, sub, sub2;
1113 pager_open_if_enabled();
1115 r = bus_method_call_with_reply(
1117 "org.freedesktop.systemd1",
1118 "/org/freedesktop/systemd1",
1119 "org.freedesktop.systemd1.Manager",
1127 if (!dbus_message_iter_init(reply, &iter) ||
1128 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1129 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1130 log_error("Failed to parse reply.");
1134 dbus_message_iter_recurse(&iter, &sub);
1137 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
1139 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1140 const char *name, *type, *state, *job_path, *unit_path;
1144 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1145 log_error("Failed to parse reply.");
1149 dbus_message_iter_recurse(&sub, &sub2);
1151 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
1152 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
1153 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
1154 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
1155 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
1156 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
1157 log_error("Failed to parse reply.");
1161 e = arg_full ? NULL : ellipsize(name, 25, 33);
1162 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
1167 dbus_message_iter_next(&sub);
1171 printf("\n%u jobs listed.\n", k);
1176 static int load_unit(DBusConnection *bus, char **args) {
1181 STRV_FOREACH(name, args+1) {
1182 _cleanup_free_ char *n = NULL;
1185 n = unit_name_mangle(*name);
1189 r = bus_method_call_with_reply(
1191 "org.freedesktop.systemd1",
1192 "/org/freedesktop/systemd1",
1193 "org.freedesktop.systemd1.Manager",
1197 DBUS_TYPE_STRING, &n,
1206 static int cancel_job(DBusConnection *bus, char **args) {
1211 if (strv_length(args) <= 1)
1212 return daemon_reload(bus, args);
1214 STRV_FOREACH(name, args+1) {
1218 r = safe_atou32(*name, &id);
1220 log_error("Failed to parse job id: %s", strerror(-r));
1224 r = bus_method_call_with_reply(
1226 "org.freedesktop.systemd1",
1227 "/org/freedesktop/systemd1",
1228 "org.freedesktop.systemd1.Manager",
1232 DBUS_TYPE_UINT32, &id,
1241 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1242 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1243 dbus_bool_t b = FALSE;
1244 DBusMessageIter iter, sub;
1246 *interface = "org.freedesktop.systemd1.Unit",
1247 *property = "NeedDaemonReload",
1249 _cleanup_free_ char *n = NULL;
1252 /* We ignore all errors here, since this is used to show a warning only */
1254 n = unit_name_mangle(unit);
1258 r = bus_method_call_with_reply (
1260 "org.freedesktop.systemd1",
1261 "/org/freedesktop/systemd1",
1262 "org.freedesktop.systemd1.Manager",
1266 DBUS_TYPE_STRING, &n,
1271 if (!dbus_message_get_args(reply, NULL,
1272 DBUS_TYPE_OBJECT_PATH, &path,
1276 dbus_message_unref(reply);
1279 r = bus_method_call_with_reply(
1281 "org.freedesktop.systemd1",
1283 "org.freedesktop.DBus.Properties",
1287 DBUS_TYPE_STRING, &interface,
1288 DBUS_TYPE_STRING, &property,
1293 if (!dbus_message_iter_init(reply, &iter) ||
1294 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1297 dbus_message_iter_recurse(&iter, &sub);
1298 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1301 dbus_message_iter_get_basic(&sub, &b);
1305 typedef struct WaitData {
1312 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1320 dbus_error_init(&error);
1322 log_debug("Got D-Bus request: %s.%s() on %s",
1323 dbus_message_get_interface(message),
1324 dbus_message_get_member(message),
1325 dbus_message_get_path(message));
1327 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1328 log_error("Warning! D-Bus connection terminated.");
1329 dbus_connection_close(connection);
1331 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1333 const char *path, *result, *unit;
1335 if (dbus_message_get_args(message, &error,
1336 DBUS_TYPE_UINT32, &id,
1337 DBUS_TYPE_OBJECT_PATH, &path,
1338 DBUS_TYPE_STRING, &unit,
1339 DBUS_TYPE_STRING, &result,
1340 DBUS_TYPE_INVALID)) {
1342 free(set_remove(d->set, (char*) path));
1344 if (!isempty(result))
1345 d->result = strdup(result);
1348 d->name = strdup(unit);
1353 dbus_error_free(&error);
1354 if (dbus_message_get_args(message, &error,
1355 DBUS_TYPE_UINT32, &id,
1356 DBUS_TYPE_OBJECT_PATH, &path,
1357 DBUS_TYPE_STRING, &result,
1358 DBUS_TYPE_INVALID)) {
1359 /* Compatibility with older systemd versions <
1360 * 183 during upgrades. This should be dropped
1362 free(set_remove(d->set, (char*) path));
1365 d->result = strdup(result);
1371 log_error("Failed to parse message: %s", bus_error_message(&error));
1375 dbus_error_free(&error);
1376 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1379 static int enable_wait_for_jobs(DBusConnection *bus) {
1387 dbus_error_init(&error);
1388 dbus_bus_add_match(bus,
1390 "sender='org.freedesktop.systemd1',"
1391 "interface='org.freedesktop.systemd1.Manager',"
1392 "member='JobRemoved',"
1393 "path='/org/freedesktop/systemd1'",
1396 if (dbus_error_is_set(&error)) {
1397 log_error("Failed to add match: %s", bus_error_message(&error));
1398 dbus_error_free(&error);
1402 /* This is slightly dirty, since we don't undo the match registrations. */
1406 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1416 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL))
1419 while (!set_isempty(s)) {
1421 if (!dbus_connection_read_write_dispatch(bus, -1)) {
1422 log_error("Disconnected from bus.");
1423 return -ECONNREFUSED;
1430 if (streq(d.result, "timeout"))
1431 log_error("Job for %s timed out.", strna(d.name));
1432 else if (streq(d.result, "canceled"))
1433 log_error("Job for %s canceled.", strna(d.name));
1434 else if (streq(d.result, "dependency"))
1435 log_error("A dependency job for %s failed. See 'journalctl -xn' for details.", strna(d.name));
1436 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1437 log_error("Job for %s failed. See 'systemctl status %s' and 'journalctl -xn' for details.", strna(d.name), strna(d.name));
1440 if (streq_ptr(d.result, "timeout"))
1442 else if (streq_ptr(d.result, "canceled"))
1444 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1455 dbus_connection_remove_filter(bus, wait_filter, &d);
1459 static int check_one_unit(DBusConnection *bus, const char *name, char **check_states, bool quiet) {
1460 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1461 _cleanup_free_ char *n = NULL;
1462 DBusMessageIter iter, sub;
1464 *interface = "org.freedesktop.systemd1.Unit",
1465 *property = "ActiveState";
1466 const char *state, *path;
1472 dbus_error_init(&error);
1474 n = unit_name_mangle(name);
1478 r = bus_method_call_with_reply (
1480 "org.freedesktop.systemd1",
1481 "/org/freedesktop/systemd1",
1482 "org.freedesktop.systemd1.Manager",
1486 DBUS_TYPE_STRING, &n,
1489 dbus_error_free(&error);
1496 if (!dbus_message_get_args(reply, NULL,
1497 DBUS_TYPE_OBJECT_PATH, &path,
1498 DBUS_TYPE_INVALID)) {
1499 log_error("Failed to parse reply.");
1503 dbus_message_unref(reply);
1506 r = bus_method_call_with_reply(
1508 "org.freedesktop.systemd1",
1510 "org.freedesktop.DBus.Properties",
1514 DBUS_TYPE_STRING, &interface,
1515 DBUS_TYPE_STRING, &property,
1523 if (!dbus_message_iter_init(reply, &iter) ||
1524 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1525 log_error("Failed to parse reply.");
1529 dbus_message_iter_recurse(&iter, &sub);
1531 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1532 log_error("Failed to parse reply.");
1536 dbus_message_iter_get_basic(&sub, &state);
1541 return strv_find(check_states, state) ? 1 : 0;
1544 static void check_triggering_units(
1545 DBusConnection *bus,
1546 const char *unit_name) {
1548 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1549 DBusMessageIter iter, sub;
1550 const char *interface = "org.freedesktop.systemd1.Unit",
1551 *triggered_by_property = "TriggeredBy";
1552 char _cleanup_free_ *unit_path = NULL, *n = NULL;
1553 bool print_warning_label = true;
1556 n = unit_name_mangle(unit_name);
1562 unit_path = unit_dbus_path_from_name(n);
1568 r = bus_method_call_with_reply(
1570 "org.freedesktop.systemd1",
1572 "org.freedesktop.DBus.Properties",
1576 DBUS_TYPE_STRING, &interface,
1577 DBUS_TYPE_STRING, &triggered_by_property,
1582 if (!dbus_message_iter_init(reply, &iter) ||
1583 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1584 log_error("Failed to parse reply.");
1588 dbus_message_iter_recurse(&iter, &sub);
1589 dbus_message_iter_recurse(&sub, &iter);
1592 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1593 const char * const check_states[] = {
1598 const char *service_trigger;
1600 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1601 log_error("Failed to parse reply.");
1605 dbus_message_iter_get_basic(&sub, &service_trigger);
1607 r = check_one_unit(bus, service_trigger, (char**) check_states, true);
1611 if (print_warning_label) {
1612 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1613 print_warning_label = false;
1616 log_warning(" %s", service_trigger);
1619 dbus_message_iter_next(&sub);
1623 static int start_unit_one(
1624 DBusConnection *bus,
1631 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1632 _cleanup_free_ char *n;
1641 n = unit_name_mangle(name);
1645 r = bus_method_call_with_reply(
1647 "org.freedesktop.systemd1",
1648 "/org/freedesktop/systemd1",
1649 "org.freedesktop.systemd1.Manager",
1653 DBUS_TYPE_STRING, &n,
1654 DBUS_TYPE_STRING, &mode,
1657 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
1658 /* There's always a fallback possible for
1659 * legacy actions. */
1662 log_error("Failed to issue method call: %s", bus_error_message(error));
1667 if (!dbus_message_get_args(reply, error,
1668 DBUS_TYPE_OBJECT_PATH, &path,
1669 DBUS_TYPE_INVALID)) {
1670 log_error("Failed to parse reply: %s", bus_error_message(error));
1674 if (need_daemon_reload(bus, n))
1675 log_warning("Warning: Unit file of %s changed on disk, 'systemctl %s daemon-reload' recommended.",
1676 n, arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1688 log_error("Failed to add path to set.");
1696 static enum action verb_to_action(const char *verb) {
1697 if (streq(verb, "halt"))
1699 else if (streq(verb, "poweroff"))
1700 return ACTION_POWEROFF;
1701 else if (streq(verb, "reboot"))
1702 return ACTION_REBOOT;
1703 else if (streq(verb, "kexec"))
1704 return ACTION_KEXEC;
1705 else if (streq(verb, "rescue"))
1706 return ACTION_RESCUE;
1707 else if (streq(verb, "emergency"))
1708 return ACTION_EMERGENCY;
1709 else if (streq(verb, "default"))
1710 return ACTION_DEFAULT;
1711 else if (streq(verb, "exit"))
1713 else if (streq(verb, "suspend"))
1714 return ACTION_SUSPEND;
1715 else if (streq(verb, "hibernate"))
1716 return ACTION_HIBERNATE;
1717 else if (streq(verb, "hybrid-sleep"))
1718 return ACTION_HYBRID_SLEEP;
1720 return ACTION_INVALID;
1723 static int start_unit(DBusConnection *bus, char **args) {
1725 static const char * const table[_ACTION_MAX] = {
1726 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1727 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1728 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1729 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1730 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1731 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1732 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1733 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1734 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1735 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1736 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1737 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1738 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1739 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET,
1740 [ACTION_HYBRID_SLEEP] = SPECIAL_HYBRID_SLEEP_TARGET
1744 const char *method, *mode, *one_name;
1749 dbus_error_init(&error);
1753 ask_password_agent_open_if_enabled();
1755 if (arg_action == ACTION_SYSTEMCTL) {
1757 streq(args[0], "stop") ||
1758 streq(args[0], "condstop") ? "StopUnit" :
1759 streq(args[0], "reload") ? "ReloadUnit" :
1760 streq(args[0], "restart") ? "RestartUnit" :
1762 streq(args[0], "try-restart") ||
1763 streq(args[0], "condrestart") ? "TryRestartUnit" :
1765 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1767 streq(args[0], "reload-or-try-restart") ||
1768 streq(args[0], "condreload") ||
1770 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1774 (streq(args[0], "isolate") ||
1775 streq(args[0], "rescue") ||
1776 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1778 one_name = table[verb_to_action(args[0])];
1781 assert(arg_action < ELEMENTSOF(table));
1782 assert(table[arg_action]);
1784 method = "StartUnit";
1786 mode = (arg_action == ACTION_EMERGENCY ||
1787 arg_action == ACTION_RESCUE ||
1788 arg_action == ACTION_RUNLEVEL2 ||
1789 arg_action == ACTION_RUNLEVEL3 ||
1790 arg_action == ACTION_RUNLEVEL4 ||
1791 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1793 one_name = table[arg_action];
1796 if (!arg_no_block) {
1797 ret = enable_wait_for_jobs(bus);
1799 log_error("Could not watch jobs: %s", strerror(-ret));
1803 s = set_new(string_hash_func, string_compare_func);
1811 ret = start_unit_one(bus, method, one_name, mode, &error, s);
1813 ret = translate_bus_error_to_exit_status(ret, &error);
1815 STRV_FOREACH(name, args+1) {
1816 r = start_unit_one(bus, method, *name, mode, &error, s);
1818 ret = translate_bus_error_to_exit_status(r, &error);
1819 dbus_error_free(&error);
1824 if (!arg_no_block) {
1825 r = wait_for_jobs(bus, s);
1831 /* When stopping units, warn if they can still be triggered by
1832 * another active unit (socket, path, timer) */
1833 if (!arg_quiet && streq(method, "StopUnit")) {
1835 check_triggering_units(bus, one_name);
1837 STRV_FOREACH(name, args+1)
1838 check_triggering_units(bus, *name);
1844 dbus_error_free(&error);
1849 /* Ask systemd-logind, which might grant access to unprivileged users
1850 * through PolicyKit */
1851 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1854 dbus_bool_t interactive = true;
1859 polkit_agent_open_if_enabled();
1867 case ACTION_POWEROFF:
1868 method = "PowerOff";
1871 case ACTION_SUSPEND:
1875 case ACTION_HIBERNATE:
1876 method = "Hibernate";
1879 case ACTION_HYBRID_SLEEP:
1880 method = "HybridSleep";
1887 return bus_method_call_with_reply(
1889 "org.freedesktop.login1",
1890 "/org/freedesktop/login1",
1891 "org.freedesktop.login1.Manager",
1895 DBUS_TYPE_BOOLEAN, &interactive,
1902 static int check_inhibitors(DBusConnection *bus, enum action a) {
1904 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1905 DBusMessageIter iter, sub, sub2;
1908 _cleanup_strv_free_ char **sessions = NULL;
1914 if (arg_ignore_inhibitors || arg_force > 0)
1926 r = bus_method_call_with_reply(
1928 "org.freedesktop.login1",
1929 "/org/freedesktop/login1",
1930 "org.freedesktop.login1.Manager",
1936 /* If logind is not around, then there are no inhibitors... */
1939 if (!dbus_message_iter_init(reply, &iter) ||
1940 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1941 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1942 log_error("Failed to parse reply.");
1946 dbus_message_iter_recurse(&iter, &sub);
1947 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1948 const char *what, *who, *why, *mode;
1950 _cleanup_strv_free_ char **sv = NULL;
1951 _cleanup_free_ char *comm = NULL, *user = NULL;
1953 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1954 log_error("Failed to parse reply.");
1958 dbus_message_iter_recurse(&sub, &sub2);
1960 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &what, true) < 0 ||
1961 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &who, true) < 0 ||
1962 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &why, true) < 0 ||
1963 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &mode, true) < 0 ||
1964 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &uid, true) < 0 ||
1965 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, false) < 0) {
1966 log_error("Failed to parse reply.");
1970 if (!streq(mode, "block"))
1973 sv = strv_split(what, ":");
1977 if (!strv_contains(sv,
1979 a == ACTION_POWEROFF ||
1980 a == ACTION_REBOOT ||
1981 a == ACTION_KEXEC ? "shutdown" : "sleep"))
1984 get_process_comm(pid, &comm);
1985 user = uid_to_name(uid);
1986 log_warning("Operation inhibited by \"%s\" (PID %lu \"%s\", user %s), reason is \"%s\".",
1987 who, (unsigned long) pid, strna(comm), strna(user), why);
1991 dbus_message_iter_next(&sub);
1994 dbus_message_iter_recurse(&iter, &sub);
1996 /* Check for current sessions */
1997 sd_get_sessions(&sessions);
1998 STRV_FOREACH(s, sessions) {
2000 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
2002 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
2005 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
2008 if (sd_session_get_type(*s, &type) < 0 || (!streq(type, "x11") && !streq(type, "tty")))
2011 sd_session_get_tty(*s, &tty);
2012 sd_session_get_seat(*s, &seat);
2013 sd_session_get_service(*s, &service);
2014 user = uid_to_name(uid);
2016 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
2023 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
2024 a == ACTION_HALT ? "halt" :
2025 a == ACTION_POWEROFF ? "poweroff" :
2026 a == ACTION_REBOOT ? "reboot" :
2027 a == ACTION_KEXEC ? "kexec" :
2028 a == ACTION_SUSPEND ? "suspend" :
2029 a == ACTION_HIBERNATE ? "hibernate" : "hybrid-sleep");
2037 static int start_special(DBusConnection *bus, char **args) {
2043 a = verb_to_action(args[0]);
2045 r = check_inhibitors(bus, a);
2049 if (arg_force >= 2 && geteuid() != 0) {
2050 log_error("Must be root.");
2054 if (arg_force >= 2 &&
2055 (a == ACTION_HALT ||
2056 a == ACTION_POWEROFF ||
2057 a == ACTION_REBOOT))
2060 if (arg_force >= 1 &&
2061 (a == ACTION_HALT ||
2062 a == ACTION_POWEROFF ||
2063 a == ACTION_REBOOT ||
2064 a == ACTION_KEXEC ||
2066 return daemon_reload(bus, args);
2068 /* first try logind, to allow authentication with polkit */
2069 if (geteuid() != 0 &&
2070 (a == ACTION_POWEROFF ||
2071 a == ACTION_REBOOT ||
2072 a == ACTION_SUSPEND ||
2073 a == ACTION_HIBERNATE ||
2074 a == ACTION_HYBRID_SLEEP)) {
2075 r = reboot_with_logind(bus, a);
2080 r = start_unit(bus, args);
2087 static int check_unit_active(DBusConnection *bus, char **args) {
2088 const char * const check_states[] = {
2095 int r = 3; /* According to LSB: "program is not running" */
2100 STRV_FOREACH(name, args+1) {
2103 state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
2113 static int check_unit_failed(DBusConnection *bus, char **args) {
2114 const char * const check_states[] = {
2125 STRV_FOREACH(name, args+1) {
2128 state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
2138 static int kill_unit(DBusConnection *bus, char **args) {
2146 arg_kill_who = "all";
2148 STRV_FOREACH(name, args+1) {
2149 _cleanup_free_ char *n = NULL;
2151 n = unit_name_mangle(*name);
2155 r = bus_method_call_with_reply(
2157 "org.freedesktop.systemd1",
2158 "/org/freedesktop/systemd1",
2159 "org.freedesktop.systemd1.Manager",
2163 DBUS_TYPE_STRING, &n,
2164 DBUS_TYPE_STRING, &arg_kill_who,
2165 DBUS_TYPE_INT32, &arg_signal,
2173 static int set_cgroup(DBusConnection *bus, char **args) {
2174 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
2177 DBusMessageIter iter;
2179 _cleanup_free_ char *n = NULL;
2184 dbus_error_init(&error);
2187 streq(args[0], "set-cgroup") ? "SetUnitControlGroups" :
2188 streq(args[0], "unset-group") ? "UnsetUnitControlGroups"
2189 : "UnsetUnitControlGroupAttributes";
2191 n = unit_name_mangle(args[1]);
2195 m = dbus_message_new_method_call(
2196 "org.freedesktop.systemd1",
2197 "/org/freedesktop/systemd1",
2198 "org.freedesktop.systemd1.Manager",
2203 dbus_message_iter_init_append(m, &iter);
2204 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &n))
2207 r = bus_append_strv_iter(&iter, args + 2);
2211 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2213 log_error("Failed to issue method call: %s", bus_error_message(&error));
2214 dbus_error_free(&error);
2221 static int set_cgroup_attr(DBusConnection *bus, char **args) {
2222 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
2224 DBusMessageIter iter, sub, sub2;
2226 _cleanup_free_ char *n = NULL;
2231 dbus_error_init(&error);
2233 if (strv_length(args) % 2 != 0) {
2234 log_error("Expecting an uneven number of arguments!");
2238 n = unit_name_mangle(args[1]);
2242 m = dbus_message_new_method_call(
2243 "org.freedesktop.systemd1",
2244 "/org/freedesktop/systemd1",
2245 "org.freedesktop.systemd1.Manager",
2246 "SetUnitControlGroupAttributes");
2250 dbus_message_iter_init_append(m, &iter);
2251 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &n) ||
2252 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(ss)", &sub))
2255 STRV_FOREACH_PAIR(x, y, args + 2) {
2256 if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2) ||
2257 !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, x) ||
2258 !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, y) ||
2259 !dbus_message_iter_close_container(&sub, &sub2))
2263 if (!dbus_message_iter_close_container(&iter, &sub))
2266 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2268 log_error("Failed to issue method call: %s", bus_error_message(&error));
2269 dbus_error_free(&error);
2276 static int get_cgroup_attr(DBusConnection *bus, char **args) {
2277 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
2279 DBusMessageIter iter;
2281 _cleanup_free_ char *n = NULL;
2282 _cleanup_strv_free_ char **list = NULL;
2288 dbus_error_init(&error);
2290 n = unit_name_mangle(args[1]);
2294 m = dbus_message_new_method_call(
2295 "org.freedesktop.systemd1",
2296 "/org/freedesktop/systemd1",
2297 "org.freedesktop.systemd1.Manager",
2298 "GetUnitControlGroupAttributes");
2302 dbus_message_iter_init_append(m, &iter);
2303 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &n))
2306 r = bus_append_strv_iter(&iter, args + 2);
2310 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2312 log_error("Failed to issue method call: %s", bus_error_message(&error));
2313 dbus_error_free(&error);
2317 dbus_message_iter_init(reply, &iter);
2318 r = bus_parse_strv_iter(&iter, &list);
2320 log_error("Failed to parse value list.");
2324 STRV_FOREACH(a, list) {
2325 if (endswith(*a, "\n"))
2334 typedef struct ExecStatusInfo {
2342 usec_t start_timestamp;
2343 usec_t exit_timestamp;
2348 LIST_FIELDS(struct ExecStatusInfo, exec);
2351 static void exec_status_info_free(ExecStatusInfo *i) {
2360 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
2361 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2362 DBusMessageIter sub2, sub3;
2366 int32_t code, status;
2372 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
2375 dbus_message_iter_recurse(sub, &sub2);
2377 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
2380 i->path = strdup(path);
2384 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
2385 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
2389 dbus_message_iter_recurse(&sub2, &sub3);
2390 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2391 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2392 dbus_message_iter_next(&sub3);
2396 i->argv = new0(char*, n+1);
2401 dbus_message_iter_recurse(&sub2, &sub3);
2402 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2405 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2406 dbus_message_iter_get_basic(&sub3, &s);
2407 dbus_message_iter_next(&sub3);
2409 i->argv[n] = strdup(s);
2416 if (!dbus_message_iter_next(&sub2) ||
2417 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
2418 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
2419 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
2420 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
2421 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
2422 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
2423 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
2424 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
2428 i->start_timestamp = (usec_t) start_timestamp;
2429 i->exit_timestamp = (usec_t) exit_timestamp;
2430 i->pid = (pid_t) pid;
2437 typedef struct UnitStatusInfo {
2439 const char *load_state;
2440 const char *active_state;
2441 const char *sub_state;
2442 const char *unit_file_state;
2444 const char *description;
2445 const char *following;
2447 char **documentation;
2449 const char *fragment_path;
2450 const char *source_path;
2451 const char *default_control_group;
2453 const char *load_error;
2456 usec_t inactive_exit_timestamp;
2457 usec_t inactive_exit_timestamp_monotonic;
2458 usec_t active_enter_timestamp;
2459 usec_t active_exit_timestamp;
2460 usec_t inactive_enter_timestamp;
2462 bool need_daemon_reload;
2467 const char *status_text;
2470 usec_t start_timestamp;
2471 usec_t exit_timestamp;
2473 int exit_code, exit_status;
2475 usec_t condition_timestamp;
2476 bool condition_result;
2479 unsigned n_accepted;
2480 unsigned n_connections;
2484 const char *sysfs_path;
2486 /* Mount, Automount */
2492 LIST_HEAD(ExecStatusInfo, exec);
2495 static void print_status_info(UnitStatusInfo *i) {
2497 const char *on, *off, *ss;
2499 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
2500 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2503 arg_all * OUTPUT_SHOW_ALL |
2504 (!on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
2505 on_tty() * OUTPUT_COLOR |
2506 !arg_quiet * OUTPUT_WARN_CUTOFF |
2507 arg_full * OUTPUT_FULL_WIDTH;
2511 /* This shows pretty information about a unit. See
2512 * print_property() for a low-level property printer */
2514 printf("%s", strna(i->id));
2516 if (i->description && !streq_ptr(i->id, i->description))
2517 printf(" - %s", i->description);
2522 printf("\t Follow: unit currently follows state of %s\n", i->following);
2524 if (streq_ptr(i->load_state, "error")) {
2525 on = ansi_highlight_red(true);
2526 off = ansi_highlight_red(false);
2530 path = i->source_path ? i->source_path : i->fragment_path;
2533 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2534 else if (path && i->unit_file_state)
2535 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2537 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2539 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2541 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2543 if (streq_ptr(i->active_state, "failed")) {
2544 on = ansi_highlight_red(true);
2545 off = ansi_highlight_red(false);
2546 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2547 on = ansi_highlight_green(true);
2548 off = ansi_highlight_green(false);
2553 printf("\t Active: %s%s (%s)%s",
2555 strna(i->active_state),
2559 printf("\t Active: %s%s%s",
2561 strna(i->active_state),
2564 if (!isempty(i->result) && !streq(i->result, "success"))
2565 printf(" (Result: %s)", i->result);
2567 timestamp = (streq_ptr(i->active_state, "active") ||
2568 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2569 (streq_ptr(i->active_state, "inactive") ||
2570 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2571 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2572 i->active_exit_timestamp;
2574 s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
2575 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2578 printf(" since %s; %s\n", s2, s1);
2580 printf(" since %s\n", s2);
2584 if (!i->condition_result && i->condition_timestamp > 0) {
2585 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
2586 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2589 printf("\t start condition failed at %s; %s\n", s2, s1);
2591 printf("\t start condition failed at %s\n", s2);
2595 printf("\t Device: %s\n", i->sysfs_path);
2597 printf("\t Where: %s\n", i->where);
2599 printf("\t What: %s\n", i->what);
2601 if (!strv_isempty(i->documentation)) {
2605 STRV_FOREACH(t, i->documentation) {
2607 printf("\t Docs: %s\n", *t);
2610 printf("\t %s\n", *t);
2615 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2617 LIST_FOREACH(exec, p, i->exec) {
2618 _cleanup_free_ char *t = NULL;
2621 /* Only show exited processes here */
2625 t = strv_join(p->argv, " ");
2626 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2628 good = is_clean_exit_lsb(p->code, p->status, NULL);
2630 on = ansi_highlight_red(true);
2631 off = ansi_highlight_red(false);
2635 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2637 if (p->code == CLD_EXITED) {
2640 printf("status=%i", p->status);
2642 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2647 printf("signal=%s", signal_to_string(p->status));
2649 printf(")%s\n", off);
2651 if (i->main_pid == p->pid &&
2652 i->start_timestamp == p->start_timestamp &&
2653 i->exit_timestamp == p->start_timestamp)
2654 /* Let's not show this twice */
2657 if (p->pid == i->control_pid)
2661 if (i->main_pid > 0 || i->control_pid > 0) {
2664 if (i->main_pid > 0) {
2665 printf("Main PID: %u", (unsigned) i->main_pid);
2668 _cleanup_free_ char *t = NULL;
2669 get_process_comm(i->main_pid, &t);
2672 } else if (i->exit_code > 0) {
2673 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2675 if (i->exit_code == CLD_EXITED) {
2678 printf("status=%i", i->exit_status);
2680 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2685 printf("signal=%s", signal_to_string(i->exit_status));
2690 if (i->main_pid > 0 && i->control_pid > 0)
2693 if (i->control_pid > 0) {
2694 _cleanup_free_ char *t = NULL;
2696 printf(" Control: %u", (unsigned) i->control_pid);
2698 get_process_comm(i->control_pid, &t);
2707 printf("\t Status: \"%s\"\n", i->status_text);
2709 if (i->default_control_group &&
2710 (i->main_pid > 0 || i->control_pid > 0 || cg_is_empty_by_spec(i->default_control_group, false) == 0)) {
2713 printf("\t CGroup: %s\n", i->default_control_group);
2715 if (arg_transport != TRANSPORT_SSH) {
2725 if (i->main_pid > 0)
2726 extra[k++] = i->main_pid;
2728 if (i->control_pid > 0)
2729 extra[k++] = i->control_pid;
2731 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, extra, k, flags);
2735 if (i->id && arg_transport != TRANSPORT_SSH) {
2737 if(arg_scope == UNIT_FILE_SYSTEM)
2738 show_journal_by_unit(stdout,
2742 i->inactive_exit_timestamp_monotonic,
2746 show_journal_by_user_unit(stdout,
2750 i->inactive_exit_timestamp_monotonic,
2756 if (i->need_daemon_reload)
2757 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2758 ansi_highlight_red(true),
2759 ansi_highlight_red(false),
2760 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2763 static void show_unit_help(UnitStatusInfo *i) {
2768 if (!i->documentation) {
2769 log_info("Documentation for %s not known.", i->id);
2773 STRV_FOREACH(p, i->documentation) {
2775 if (startswith(*p, "man:")) {
2778 char *page = NULL, *section = NULL;
2779 const char *args[4] = { "man", NULL, NULL, NULL };
2784 if ((*p)[k-1] == ')')
2785 e = strrchr(*p, '(');
2788 page = strndup((*p) + 4, e - *p - 4);
2794 section = strndup(e + 1, *p + k - e - 2);
2808 log_error("Failed to fork: %m");
2816 execvp(args[0], (char**) args);
2817 log_error("Failed to execute man: %m");
2818 _exit(EXIT_FAILURE);
2824 wait_for_terminate(pid, NULL);
2826 log_info("Can't show: %s", *p);
2830 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2836 switch (dbus_message_iter_get_arg_type(iter)) {
2838 case DBUS_TYPE_STRING: {
2841 dbus_message_iter_get_basic(iter, &s);
2844 if (streq(name, "Id"))
2846 else if (streq(name, "LoadState"))
2848 else if (streq(name, "ActiveState"))
2849 i->active_state = s;
2850 else if (streq(name, "SubState"))
2852 else if (streq(name, "Description"))
2854 else if (streq(name, "FragmentPath"))
2855 i->fragment_path = s;
2856 else if (streq(name, "SourcePath"))
2858 else if (streq(name, "DefaultControlGroup"))
2859 i->default_control_group = s;
2860 else if (streq(name, "StatusText"))
2862 else if (streq(name, "SysFSPath"))
2864 else if (streq(name, "Where"))
2866 else if (streq(name, "What"))
2868 else if (streq(name, "Following"))
2870 else if (streq(name, "UnitFileState"))
2871 i->unit_file_state = s;
2872 else if (streq(name, "Result"))
2879 case DBUS_TYPE_BOOLEAN: {
2882 dbus_message_iter_get_basic(iter, &b);
2884 if (streq(name, "Accept"))
2886 else if (streq(name, "NeedDaemonReload"))
2887 i->need_daemon_reload = b;
2888 else if (streq(name, "ConditionResult"))
2889 i->condition_result = b;
2894 case DBUS_TYPE_UINT32: {
2897 dbus_message_iter_get_basic(iter, &u);
2899 if (streq(name, "MainPID")) {
2901 i->main_pid = (pid_t) u;
2904 } else if (streq(name, "ControlPID"))
2905 i->control_pid = (pid_t) u;
2906 else if (streq(name, "ExecMainPID")) {
2908 i->main_pid = (pid_t) u;
2909 } else if (streq(name, "NAccepted"))
2911 else if (streq(name, "NConnections"))
2912 i->n_connections = u;
2917 case DBUS_TYPE_INT32: {
2920 dbus_message_iter_get_basic(iter, &j);
2922 if (streq(name, "ExecMainCode"))
2923 i->exit_code = (int) j;
2924 else if (streq(name, "ExecMainStatus"))
2925 i->exit_status = (int) j;
2930 case DBUS_TYPE_UINT64: {
2933 dbus_message_iter_get_basic(iter, &u);
2935 if (streq(name, "ExecMainStartTimestamp"))
2936 i->start_timestamp = (usec_t) u;
2937 else if (streq(name, "ExecMainExitTimestamp"))
2938 i->exit_timestamp = (usec_t) u;
2939 else if (streq(name, "ActiveEnterTimestamp"))
2940 i->active_enter_timestamp = (usec_t) u;
2941 else if (streq(name, "InactiveEnterTimestamp"))
2942 i->inactive_enter_timestamp = (usec_t) u;
2943 else if (streq(name, "InactiveExitTimestamp"))
2944 i->inactive_exit_timestamp = (usec_t) u;
2945 else if (streq(name, "InactiveExitTimestampMonotonic"))
2946 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2947 else if (streq(name, "ActiveExitTimestamp"))
2948 i->active_exit_timestamp = (usec_t) u;
2949 else if (streq(name, "ConditionTimestamp"))
2950 i->condition_timestamp = (usec_t) u;
2955 case DBUS_TYPE_ARRAY: {
2957 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2958 startswith(name, "Exec")) {
2959 DBusMessageIter sub;
2961 dbus_message_iter_recurse(iter, &sub);
2962 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2963 ExecStatusInfo *info;
2966 if (!(info = new0(ExecStatusInfo, 1)))
2969 if (!(info->name = strdup(name))) {
2974 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2979 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2981 dbus_message_iter_next(&sub);
2983 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2984 streq(name, "Documentation")) {
2986 DBusMessageIter sub;
2988 dbus_message_iter_recurse(iter, &sub);
2989 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2993 dbus_message_iter_get_basic(&sub, &s);
2995 l = strv_append(i->documentation, s);
2999 strv_free(i->documentation);
3000 i->documentation = l;
3002 dbus_message_iter_next(&sub);
3009 case DBUS_TYPE_STRUCT: {
3011 if (streq(name, "LoadError")) {
3012 DBusMessageIter sub;
3013 const char *n, *message;
3016 dbus_message_iter_recurse(iter, &sub);
3018 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
3022 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
3026 if (!isempty(message))
3027 i->load_error = message;
3037 static int print_property(const char *name, DBusMessageIter *iter) {
3041 /* This is a low-level property printer, see
3042 * print_status_info() for the nicer output */
3044 if (arg_property && !strv_find(arg_property, name))
3047 switch (dbus_message_iter_get_arg_type(iter)) {
3049 case DBUS_TYPE_STRUCT: {
3050 DBusMessageIter sub;
3051 dbus_message_iter_recurse(iter, &sub);
3053 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
3056 dbus_message_iter_get_basic(&sub, &u);
3059 printf("%s=%u\n", name, (unsigned) u);
3061 printf("%s=\n", name);
3064 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
3067 dbus_message_iter_get_basic(&sub, &s);
3069 if (arg_all || s[0])
3070 printf("%s=%s\n", name, s);
3073 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
3074 const char *a = NULL, *b = NULL;
3076 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
3077 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
3079 if (arg_all || !isempty(a) || !isempty(b))
3080 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
3088 case DBUS_TYPE_ARRAY:
3090 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
3091 DBusMessageIter sub, sub2;
3093 dbus_message_iter_recurse(iter, &sub);
3094 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3098 dbus_message_iter_recurse(&sub, &sub2);
3100 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
3101 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
3102 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
3104 dbus_message_iter_next(&sub);
3109 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
3110 DBusMessageIter sub, sub2;
3112 dbus_message_iter_recurse(iter, &sub);
3113 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3114 const char *type, *path;
3116 dbus_message_iter_recurse(&sub, &sub2);
3118 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
3119 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
3120 printf("%s=%s\n", type, path);
3122 dbus_message_iter_next(&sub);
3127 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
3128 DBusMessageIter sub, sub2;
3130 dbus_message_iter_recurse(iter, &sub);
3131 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3133 uint64_t value, next_elapse;
3135 dbus_message_iter_recurse(&sub, &sub2);
3137 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
3138 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
3139 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
3140 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
3142 printf("%s={ value=%s ; next_elapse=%s }\n",
3144 format_timespan(timespan1, sizeof(timespan1), value),
3145 format_timespan(timespan2, sizeof(timespan2), next_elapse));
3148 dbus_message_iter_next(&sub);
3153 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
3154 DBusMessageIter sub, sub2;
3156 dbus_message_iter_recurse(iter, &sub);
3157 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3158 const char *controller, *attr, *value;
3160 dbus_message_iter_recurse(&sub, &sub2);
3162 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
3163 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
3164 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
3166 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
3172 dbus_message_iter_next(&sub);
3177 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
3178 DBusMessageIter sub;
3180 dbus_message_iter_recurse(iter, &sub);
3181 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3182 ExecStatusInfo info;
3185 if (exec_status_info_deserialize(&sub, &info) >= 0) {
3186 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
3189 t = strv_join(info.argv, " ");
3191 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
3195 yes_no(info.ignore),
3196 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
3197 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
3198 (unsigned) info. pid,
3199 sigchld_code_to_string(info.code),
3201 info.code == CLD_EXITED ? "" : "/",
3202 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
3208 strv_free(info.argv);
3210 dbus_message_iter_next(&sub);
3219 if (generic_print_property(name, iter, arg_all) > 0)
3223 printf("%s=[unprintable]\n", name);
3228 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
3229 _cleanup_free_ DBusMessage *reply = NULL;
3230 const char *interface = "";
3232 DBusMessageIter iter, sub, sub2, sub3;
3233 UnitStatusInfo info;
3241 r = bus_method_call_with_reply(
3243 "org.freedesktop.systemd1",
3245 "org.freedesktop.DBus.Properties",
3249 DBUS_TYPE_STRING, &interface,
3254 if (!dbus_message_iter_init(reply, &iter) ||
3255 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3256 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
3257 log_error("Failed to parse reply.");
3261 dbus_message_iter_recurse(&iter, &sub);
3268 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3271 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
3272 dbus_message_iter_recurse(&sub, &sub2);
3274 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
3275 dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
3276 log_error("Failed to parse reply.");
3280 dbus_message_iter_recurse(&sub2, &sub3);
3282 if (show_properties)
3283 r = print_property(name, &sub3);
3285 r = status_property(name, &sub3, &info);
3287 log_error("Failed to parse reply.");
3291 dbus_message_iter_next(&sub);
3296 if (!show_properties) {
3297 if (streq(verb, "help"))
3298 show_unit_help(&info);
3300 print_status_info(&info);
3303 strv_free(info.documentation);
3305 if (!streq_ptr(info.active_state, "active") &&
3306 !streq_ptr(info.active_state, "reloading") &&
3307 streq(verb, "status"))
3308 /* According to LSB: "program not running" */
3311 while ((p = info.exec)) {
3312 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
3313 exec_status_info_free(p);
3319 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
3320 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3321 const char *path = NULL;
3325 dbus_error_init(&error);
3327 r = bus_method_call_with_reply(
3329 "org.freedesktop.systemd1",
3330 "/org/freedesktop/systemd1",
3331 "org.freedesktop.systemd1.Manager",
3335 DBUS_TYPE_UINT32, &pid,
3340 if (!dbus_message_get_args(reply, &error,
3341 DBUS_TYPE_OBJECT_PATH, &path,
3342 DBUS_TYPE_INVALID)) {
3343 log_error("Failed to parse reply: %s", bus_error_message(&error));
3348 r = show_one(verb, bus, path, false, new_line);
3351 dbus_error_free(&error);
3356 static int show(DBusConnection *bus, char **args) {
3358 bool show_properties, new_line = false;
3364 show_properties = streq(args[0], "show");
3366 if (show_properties)
3367 pager_open_if_enabled();
3369 /* If no argument is specified inspect the manager itself */
3371 if (show_properties && strv_length(args) <= 1)
3372 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
3374 STRV_FOREACH(name, args+1) {
3377 if (safe_atou32(*name, &id) < 0) {
3378 _cleanup_free_ char *p = NULL, *n = NULL;
3379 /* Interpret as unit name */
3381 n = unit_name_mangle(*name);
3385 p = unit_dbus_path_from_name(n);
3389 r = show_one(args[0], bus, p, show_properties, &new_line);
3393 } else if (show_properties) {
3394 _cleanup_free_ char *p = NULL;
3396 /* Interpret as job id */
3397 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
3400 r = show_one(args[0], bus, p, show_properties, &new_line);
3405 /* Interpret as PID */
3406 r = show_one_by_pid(args[0], bus, id, &new_line);
3415 static int dump(DBusConnection *bus, char **args) {
3416 _cleanup_free_ DBusMessage *reply = NULL;
3421 dbus_error_init(&error);
3423 pager_open_if_enabled();
3425 r = bus_method_call_with_reply(
3427 "org.freedesktop.systemd1",
3428 "/org/freedesktop/systemd1",
3429 "org.freedesktop.systemd1.Manager",
3437 if (!dbus_message_get_args(reply, &error,
3438 DBUS_TYPE_STRING, &text,
3439 DBUS_TYPE_INVALID)) {
3440 log_error("Failed to parse reply: %s", bus_error_message(&error));
3441 dbus_error_free(&error);
3445 fputs(text, stdout);
3449 static int snapshot(DBusConnection *bus, char **args) {
3450 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3453 dbus_bool_t cleanup = FALSE;
3454 DBusMessageIter iter, sub;
3457 *interface = "org.freedesktop.systemd1.Unit",
3459 _cleanup_free_ char *n = NULL;
3461 dbus_error_init(&error);
3463 if (strv_length(args) > 1)
3464 n = snapshot_name_mangle(args[1]);
3470 r = bus_method_call_with_reply (
3472 "org.freedesktop.systemd1",
3473 "/org/freedesktop/systemd1",
3474 "org.freedesktop.systemd1.Manager",
3478 DBUS_TYPE_STRING, &n,
3479 DBUS_TYPE_BOOLEAN, &cleanup,
3484 if (!dbus_message_get_args(reply, &error,
3485 DBUS_TYPE_OBJECT_PATH, &path,
3486 DBUS_TYPE_INVALID)) {
3487 log_error("Failed to parse reply: %s", bus_error_message(&error));
3488 dbus_error_free(&error);
3492 dbus_message_unref(reply);
3495 r = bus_method_call_with_reply (
3497 "org.freedesktop.systemd1",
3499 "org.freedesktop.DBus.Properties",
3503 DBUS_TYPE_STRING, &interface,
3504 DBUS_TYPE_STRING, &property,
3509 if (!dbus_message_iter_init(reply, &iter) ||
3510 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3511 log_error("Failed to parse reply.");
3515 dbus_message_iter_recurse(&iter, &sub);
3517 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3518 log_error("Failed to parse reply.");
3522 dbus_message_iter_get_basic(&sub, &id);
3530 static int delete_snapshot(DBusConnection *bus, char **args) {
3535 STRV_FOREACH(name, args+1) {
3536 _cleanup_free_ char *n = NULL;
3539 n = snapshot_name_mangle(*name);
3543 r = bus_method_call_with_reply(
3545 "org.freedesktop.systemd1",
3546 "/org/freedesktop/systemd1",
3547 "org.freedesktop.systemd1.Manager",
3551 DBUS_TYPE_STRING, &n,
3560 static int daemon_reload(DBusConnection *bus, char **args) {
3565 if (arg_action == ACTION_RELOAD)
3567 else if (arg_action == ACTION_REEXEC)
3568 method = "Reexecute";
3570 assert(arg_action == ACTION_SYSTEMCTL);
3573 streq(args[0], "clear-jobs") ||
3574 streq(args[0], "cancel") ? "ClearJobs" :
3575 streq(args[0], "daemon-reexec") ? "Reexecute" :
3576 streq(args[0], "reset-failed") ? "ResetFailed" :
3577 streq(args[0], "halt") ? "Halt" :
3578 streq(args[0], "poweroff") ? "PowerOff" :
3579 streq(args[0], "reboot") ? "Reboot" :
3580 streq(args[0], "kexec") ? "KExec" :
3581 streq(args[0], "exit") ? "Exit" :
3582 /* "daemon-reload" */ "Reload";
3585 r = bus_method_call_with_reply(
3587 "org.freedesktop.systemd1",
3588 "/org/freedesktop/systemd1",
3589 "org.freedesktop.systemd1.Manager",
3595 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
3596 /* There's always a fallback possible for
3597 * legacy actions. */
3599 else if (r == -ETIMEDOUT && streq(method, "Reexecute"))
3600 /* On reexecution, we expect a disconnect, not
3604 log_error("Failed to issue method call: %s", bus_error_message(&error));
3606 dbus_error_free(&error);
3610 static int reset_failed(DBusConnection *bus, char **args) {
3614 if (strv_length(args) <= 1)
3615 return daemon_reload(bus, args);
3617 STRV_FOREACH(name, args+1) {
3618 _cleanup_free_ char *n;
3620 n = unit_name_mangle(*name);
3624 r = bus_method_call_with_reply(
3626 "org.freedesktop.systemd1",
3627 "/org/freedesktop/systemd1",
3628 "org.freedesktop.systemd1.Manager",
3632 DBUS_TYPE_STRING, &n,
3641 static int show_enviroment(DBusConnection *bus, char **args) {
3642 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3643 DBusMessageIter iter, sub, sub2;
3646 *interface = "org.freedesktop.systemd1.Manager",
3647 *property = "Environment";
3649 pager_open_if_enabled();
3651 r = bus_method_call_with_reply(
3653 "org.freedesktop.systemd1",
3654 "/org/freedesktop/systemd1",
3655 "org.freedesktop.DBus.Properties",
3659 DBUS_TYPE_STRING, &interface,
3660 DBUS_TYPE_STRING, &property,
3665 if (!dbus_message_iter_init(reply, &iter) ||
3666 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3667 log_error("Failed to parse reply.");
3671 dbus_message_iter_recurse(&iter, &sub);
3673 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3674 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3675 log_error("Failed to parse reply.");
3679 dbus_message_iter_recurse(&sub, &sub2);
3681 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3684 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3685 log_error("Failed to parse reply.");
3689 dbus_message_iter_get_basic(&sub2, &text);
3692 dbus_message_iter_next(&sub2);
3698 static int switch_root(DBusConnection *bus, char **args) {
3701 _cleanup_free_ char *init = NULL;
3703 l = strv_length(args);
3704 if (l < 2 || l > 3) {
3705 log_error("Wrong number of arguments.");
3712 init = strdup(args[2]);
3714 parse_env_file("/proc/cmdline", WHITESPACE,
3724 log_debug("switching root - root: %s; init: %s", root, init);
3726 return bus_method_call_with_reply(
3728 "org.freedesktop.systemd1",
3729 "/org/freedesktop/systemd1",
3730 "org.freedesktop.systemd1.Manager",
3734 DBUS_TYPE_STRING, &root,
3735 DBUS_TYPE_STRING, &init,
3739 static int set_environment(DBusConnection *bus, char **args) {
3740 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
3743 DBusMessageIter iter;
3749 dbus_error_init(&error);
3751 method = streq(args[0], "set-environment")
3753 : "UnsetEnvironment";
3755 m = dbus_message_new_method_call(
3756 "org.freedesktop.systemd1",
3757 "/org/freedesktop/systemd1",
3758 "org.freedesktop.systemd1.Manager",
3763 dbus_message_iter_init_append(m, &iter);
3765 r = bus_append_strv_iter(&iter, args + 1);
3769 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3771 log_error("Failed to issue method call: %s", bus_error_message(&error));
3772 dbus_error_free(&error);
3779 static int enable_sysv_units(char **args) {
3782 #if defined(HAVE_SYSV_COMPAT) && defined(HAVE_CHKCONFIG)
3783 const char *verb = args[0];
3784 unsigned f = 1, t = 1;
3787 if (arg_scope != UNIT_FILE_SYSTEM)
3790 if (!streq(verb, "enable") &&
3791 !streq(verb, "disable") &&
3792 !streq(verb, "is-enabled"))
3795 /* Processes all SysV units, and reshuffles the array so that
3796 * afterwards only the native units remain */
3799 r = lookup_paths_init(&paths, SYSTEMD_SYSTEM, false, NULL, NULL, NULL);
3804 for (f = 1; args[f]; f++) {
3807 bool found_native = false, found_sysv;
3809 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3810 char **k, *l, *q = NULL;
3817 if (!endswith(name, ".service"))
3820 if (path_is_absolute(name))
3823 STRV_FOREACH(k, paths.unit_path) {
3826 if (!isempty(arg_root))
3827 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3829 asprintf(&p, "%s/%s", *k, name);
3836 found_native = access(p, F_OK) >= 0;
3847 if (!isempty(arg_root))
3848 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3850 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3856 p[strlen(p) - sizeof(".service") + 1] = 0;
3857 found_sysv = access(p, F_OK) >= 0;
3864 /* Mark this entry, so that we don't try enabling it as native unit */
3865 args[f] = (char*) "";
3867 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
3869 if (!isempty(arg_root))
3870 argv[c++] = q = strappend("--root=", arg_root);
3872 argv[c++] = path_get_file_name(p);
3874 streq(verb, "enable") ? "on" :
3875 streq(verb, "disable") ? "off" : "--level=5";
3878 l = strv_join((char**)argv, " ");
3886 log_info("Executing %s", l);
3891 log_error("Failed to fork: %m");
3896 } else if (pid == 0) {
3899 execv(argv[0], (char**) argv);
3900 _exit(EXIT_FAILURE);
3906 j = wait_for_terminate(pid, &status);
3908 log_error("Failed to wait for child: %s", strerror(-r));
3913 if (status.si_code == CLD_EXITED) {
3914 if (streq(verb, "is-enabled")) {
3915 if (status.si_status == 0) {
3924 } else if (status.si_status != 0) {
3935 lookup_paths_free(&paths);
3937 /* Drop all SysV units */
3938 for (f = 1, t = 1; args[f]; f++) {
3940 if (isempty(args[f]))
3943 args[t++] = args[f];
3952 static int mangle_names(char **original_names, char ***mangled_names) {
3953 char **i, **l, **name;
3955 l = new(char*, strv_length(original_names) + 1);
3960 STRV_FOREACH(name, original_names) {
3962 /* When enabling units qualified path names are OK,
3963 * too, hence allow them explicitly. */
3968 *i = unit_name_mangle(*name);
3984 static int enable_unit(DBusConnection *bus, char **args) {
3985 const char *verb = args[0];
3986 UnitFileChange *changes = NULL;
3987 unsigned n_changes = 0, i;
3988 int carries_install_info = -1;
3989 DBusMessage *m = NULL, *reply = NULL;
3992 char **mangled_names = NULL;
3994 r = enable_sysv_units(args);
4001 dbus_error_init(&error);
4003 if (!bus || avoid_bus()) {
4004 if (streq(verb, "enable")) {
4005 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4006 carries_install_info = r;
4007 } else if (streq(verb, "disable"))
4008 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4009 else if (streq(verb, "reenable")) {
4010 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4011 carries_install_info = r;
4012 } else if (streq(verb, "link"))
4013 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4014 else if (streq(verb, "preset")) {
4015 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4016 carries_install_info = r;
4017 } else if (streq(verb, "mask"))
4018 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
4019 else if (streq(verb, "unmask"))
4020 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
4022 assert_not_reached("Unknown verb");
4025 log_error("Operation failed: %s", strerror(-r));
4030 for (i = 0; i < n_changes; i++) {
4031 if (changes[i].type == UNIT_FILE_SYMLINK)
4032 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
4034 log_info("rm '%s'", changes[i].path);
4041 bool send_force = true, expect_carries_install_info = false;
4043 DBusMessageIter iter, sub, sub2;
4045 if (streq(verb, "enable")) {
4046 method = "EnableUnitFiles";
4047 expect_carries_install_info = true;
4048 } else if (streq(verb, "disable")) {
4049 method = "DisableUnitFiles";
4051 } else if (streq(verb, "reenable")) {
4052 method = "ReenableUnitFiles";
4053 expect_carries_install_info = true;
4054 } else if (streq(verb, "link"))
4055 method = "LinkUnitFiles";
4056 else if (streq(verb, "preset")) {
4057 method = "PresetUnitFiles";
4058 expect_carries_install_info = true;
4059 } else if (streq(verb, "mask"))
4060 method = "MaskUnitFiles";
4061 else if (streq(verb, "unmask")) {
4062 method = "UnmaskUnitFiles";
4065 assert_not_reached("Unknown verb");
4067 m = dbus_message_new_method_call(
4068 "org.freedesktop.systemd1",
4069 "/org/freedesktop/systemd1",
4070 "org.freedesktop.systemd1.Manager",
4077 dbus_message_iter_init_append(m, &iter);
4079 r = mangle_names(args+1, &mangled_names);
4083 r = bus_append_strv_iter(&iter, mangled_names);
4085 log_error("Failed to append unit files.");
4090 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
4091 log_error("Failed to append runtime boolean.");
4099 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
4100 log_error("Failed to append force boolean.");
4106 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4108 log_error("Failed to issue method call: %s", bus_error_message(&error));
4113 if (!dbus_message_iter_init(reply, &iter)) {
4114 log_error("Failed to initialize iterator.");
4118 if (expect_carries_install_info) {
4119 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
4121 log_error("Failed to parse reply.");
4125 carries_install_info = b;
4128 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
4129 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
4130 log_error("Failed to parse reply.");
4135 dbus_message_iter_recurse(&iter, &sub);
4136 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
4137 const char *type, *path, *source;
4139 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
4140 log_error("Failed to parse reply.");
4145 dbus_message_iter_recurse(&sub, &sub2);
4147 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
4148 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
4149 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
4150 log_error("Failed to parse reply.");
4156 if (streq(type, "symlink"))
4157 log_info("ln -s '%s' '%s'", source, path);
4159 log_info("rm '%s'", path);
4162 dbus_message_iter_next(&sub);
4165 /* Try to reload if enabeld */
4167 r = daemon_reload(bus, args);
4170 if (carries_install_info == 0)
4172 "The unit files have no [Install] section. They are not meant to be enabled\n"
4173 "using systemctl.\n"
4174 "Possible reasons for having this kind of units are:\n"
4175 "1) A unit may be statically enabled by being symlinked from another unit's\n"
4176 " .wants/ or .requires/ directory.\n"
4177 "2) A unit's purpose may be to act as a helper for some other unit which has\n"
4178 " a requirement dependency on it.\n"
4179 "3) A unit may be started when needed via activation (socket, path, timer,\n"
4180 " D-Bus, udev, scripted systemctl call, ...).\n");
4184 dbus_message_unref(m);
4187 dbus_message_unref(reply);
4189 unit_file_changes_free(changes, n_changes);
4191 dbus_error_free(&error);
4193 strv_free(mangled_names);
4198 static int unit_is_enabled(DBusConnection *bus, char **args) {
4201 DBusMessage *reply = NULL;
4205 dbus_error_init(&error);
4207 r = enable_sysv_units(args);
4213 if (!bus || avoid_bus()) {
4215 STRV_FOREACH(name, args+1) {
4216 UnitFileState state;
4218 state = unit_file_get_state(arg_scope, arg_root, *name);
4224 if (state == UNIT_FILE_ENABLED ||
4225 state == UNIT_FILE_ENABLED_RUNTIME ||
4226 state == UNIT_FILE_STATIC)
4230 puts(unit_file_state_to_string(state));
4234 STRV_FOREACH(name, args+1) {
4237 r = bus_method_call_with_reply (
4239 "org.freedesktop.systemd1",
4240 "/org/freedesktop/systemd1",
4241 "org.freedesktop.systemd1.Manager",
4245 DBUS_TYPE_STRING, name,
4250 if (!dbus_message_get_args(reply, &error,
4251 DBUS_TYPE_STRING, &s,
4252 DBUS_TYPE_INVALID)) {
4253 log_error("Failed to parse reply: %s", bus_error_message(&error));
4258 dbus_message_unref(reply);
4261 if (streq(s, "enabled") ||
4262 streq(s, "enabled-runtime") ||
4271 r = enabled ? 0 : 1;
4275 dbus_message_unref(reply);
4277 dbus_error_free(&error);
4281 static int systemctl_help(void) {
4283 pager_open_if_enabled();
4285 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4286 "Query or send control commands to the systemd manager.\n\n"
4287 " -h --help Show this help\n"
4288 " --version Show package version\n"
4289 " -t --type=TYPE List only units of a particular type\n"
4290 " -p --property=NAME Show only properties by this name\n"
4291 " -a --all Show all units/properties, including dead/empty ones\n"
4292 " --failed Show only failed units\n"
4293 " --full Don't ellipsize unit names on output\n"
4294 " --fail When queueing a new job, fail if conflicting jobs are\n"
4296 " --ignore-dependencies\n"
4297 " When queueing a new job, ignore all its dependencies\n"
4298 " -i --ignore-inhibitors\n"
4299 " When shutting down or sleeping, ignore inhibitors\n"
4300 " --kill-who=WHO Who to send signal to\n"
4301 " -s --signal=SIGNAL Which signal to send\n"
4302 " -H --host=[USER@]HOST\n"
4303 " Show information for remote host\n"
4304 " -P --privileged Acquire privileges before execution\n"
4305 " -q --quiet Suppress output\n"
4306 " --no-block Do not wait until operation finished\n"
4307 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4308 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4310 " --no-legend Do not print a legend (column headers and hints)\n"
4311 " --no-pager Do not pipe output into a pager\n"
4312 " --no-ask-password\n"
4313 " Do not ask for system passwords\n"
4314 " --order When generating graph for dot, show only order\n"
4315 " --require When generating graph for dot, show only requirement\n"
4316 " --system Connect to system manager\n"
4317 " --user Connect to user service manager\n"
4318 " --global Enable/disable unit files globally\n"
4319 " -f --force When enabling unit files, override existing symlinks\n"
4320 " When shutting down, execute action immediately\n"
4321 " --root=PATH Enable unit files in the specified root directory\n"
4322 " --runtime Enable unit files only temporarily until next reboot\n"
4323 " -n --lines=INTEGER Journal entries to show\n"
4324 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
4325 " verbose, export, json, json-pretty, json-sse, cat)\n\n"
4327 " list-units List loaded units\n"
4328 " start [NAME...] Start (activate) one or more units\n"
4329 " stop [NAME...] Stop (deactivate) one or more units\n"
4330 " reload [NAME...] Reload one or more units\n"
4331 " restart [NAME...] Start or restart one or more units\n"
4332 " try-restart [NAME...] Restart one or more units if active\n"
4333 " reload-or-restart [NAME...] Reload one or more units if possible,\n"
4334 " otherwise start or restart\n"
4335 " reload-or-try-restart [NAME...] Reload one or more units if possible,\n"
4336 " otherwise restart if active\n"
4337 " isolate [NAME] Start one unit and stop all others\n"
4338 " kill [NAME...] Send signal to processes of a unit\n"
4339 " is-active [NAME...] Check whether units are active\n"
4340 " is-failed [NAME...] Check whether units are failed\n"
4341 " status [NAME...|PID...] Show runtime status of one or more units\n"
4342 " show [NAME...|JOB...] Show properties of one or more\n"
4343 " units/jobs or the manager\n"
4344 " help [NAME...|PID...] Show manual for one or more units\n"
4345 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4347 " get-cgroup-attr [NAME] [ATTR] ...\n"
4348 " Get control group attrubute\n"
4349 " set-cgroup-attr [NAME] [ATTR] [VALUE] ...\n"
4350 " Set control group attribute\n"
4351 " unset-cgroup-attr [NAME] [ATTR...]\n"
4352 " Unset control group attribute\n"
4353 " set-cgroup [NAME] [CGROUP...] Add unit to a control group\n"
4354 " unset-cgroup [NAME] [CGROUP...] Remove unit from a control group\n"
4355 " load [NAME...] Load one or more units\n"
4356 " list-dependencies [NAME] Recursively show units which are required\n"
4357 " or wanted by this unit\n\n"
4358 "Unit File Commands:\n"
4359 " list-unit-files List installed unit files\n"
4360 " enable [NAME...] Enable one or more unit files\n"
4361 " disable [NAME...] Disable one or more unit files\n"
4362 " reenable [NAME...] Reenable one or more unit files\n"
4363 " preset [NAME...] Enable/disable one or more unit files\n"
4364 " based on preset configuration\n"
4365 " mask [NAME...] Mask one or more units\n"
4366 " unmask [NAME...] Unmask one or more units\n"
4367 " link [PATH...] Link one or more units files into\n"
4368 " the search path\n"
4369 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
4371 " list-jobs List jobs\n"
4372 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
4373 "Status Commands:\n"
4374 " dump Dump server status\n"
4375 " dot Dump dependency graph for dot(1)\n\n"
4376 "Snapshot Commands:\n"
4377 " snapshot [NAME] Create a snapshot\n"
4378 " delete [NAME...] Remove one or more snapshots\n\n"
4379 "Environment Commands:\n"
4380 " show-environment Dump environment\n"
4381 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4382 " unset-environment [NAME...] Unset one or more environment variables\n\n"
4383 "Manager Lifecycle Commands:\n"
4384 " daemon-reload Reload systemd manager configuration\n"
4385 " daemon-reexec Reexecute systemd manager\n\n"
4386 "System Commands:\n"
4387 " default Enter system default mode\n"
4388 " rescue Enter system rescue mode\n"
4389 " emergency Enter system emergency mode\n"
4390 " halt Shut down and halt the system\n"
4391 " poweroff Shut down and power-off the system\n"
4392 " reboot Shut down and reboot the system\n"
4393 " kexec Shut down and reboot the system with kexec\n"
4394 " exit Request user instance exit\n"
4395 " switch-root [ROOT] [INIT] Change to a different root file system\n"
4396 " suspend Suspend the system\n"
4397 " hibernate Hibernate the system\n"
4398 " hybrid-sleep Hibernate and suspend the system\n",
4399 program_invocation_short_name);
4404 static int halt_help(void) {
4406 printf("%s [OPTIONS...]\n\n"
4407 "%s the system.\n\n"
4408 " --help Show this help\n"
4409 " --halt Halt the machine\n"
4410 " -p --poweroff Switch off the machine\n"
4411 " --reboot Reboot the machine\n"
4412 " -f --force Force immediate halt/power-off/reboot\n"
4413 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4414 " -d --no-wtmp Don't write wtmp record\n"
4415 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4416 program_invocation_short_name,
4417 arg_action == ACTION_REBOOT ? "Reboot" :
4418 arg_action == ACTION_POWEROFF ? "Power off" :
4424 static int shutdown_help(void) {
4426 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4427 "Shut down the system.\n\n"
4428 " --help Show this help\n"
4429 " -H --halt Halt the machine\n"
4430 " -P --poweroff Power-off the machine\n"
4431 " -r --reboot Reboot the machine\n"
4432 " -h Equivalent to --poweroff, overridden by --halt\n"
4433 " -k Don't halt/power-off/reboot, just send warnings\n"
4434 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4435 " -c Cancel a pending shutdown\n",
4436 program_invocation_short_name);
4441 static int telinit_help(void) {
4443 printf("%s [OPTIONS...] {COMMAND}\n\n"
4444 "Send control commands to the init daemon.\n\n"
4445 " --help Show this help\n"
4446 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4448 " 0 Power-off the machine\n"
4449 " 6 Reboot the machine\n"
4450 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4451 " 1, s, S Enter rescue mode\n"
4452 " q, Q Reload init daemon configuration\n"
4453 " u, U Reexecute init daemon\n",
4454 program_invocation_short_name);
4459 static int runlevel_help(void) {
4461 printf("%s [OPTIONS...]\n\n"
4462 "Prints the previous and current runlevel of the init system.\n\n"
4463 " --help Show this help\n",
4464 program_invocation_short_name);
4469 static int help_types(void) {
4472 puts("Available unit types:");
4473 for(i = UNIT_SERVICE; i < _UNIT_TYPE_MAX; i++)
4474 if (unit_type_table[i])
4475 puts(unit_type_table[i]);
4477 puts("\nAvailable unit load states: ");
4478 for(i = UNIT_STUB; i < _UNIT_LOAD_STATE_MAX; i++)
4479 if (unit_type_table[i])
4480 puts(unit_load_state_table[i]);
4485 static int systemctl_parse_argv(int argc, char *argv[]) {
4489 ARG_IGNORE_DEPENDENCIES,
4504 ARG_NO_ASK_PASSWORD,
4510 static const struct option options[] = {
4511 { "help", no_argument, NULL, 'h' },
4512 { "version", no_argument, NULL, ARG_VERSION },
4513 { "type", required_argument, NULL, 't' },
4514 { "property", required_argument, NULL, 'p' },
4515 { "all", no_argument, NULL, 'a' },
4516 { "failed", no_argument, NULL, ARG_FAILED },
4517 { "full", no_argument, NULL, ARG_FULL },
4518 { "fail", no_argument, NULL, ARG_FAIL },
4519 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4520 { "ignore-inhibitors", no_argument, NULL, 'i' },
4521 { "user", no_argument, NULL, ARG_USER },
4522 { "system", no_argument, NULL, ARG_SYSTEM },
4523 { "global", no_argument, NULL, ARG_GLOBAL },
4524 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4525 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4526 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4527 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4528 { "quiet", no_argument, NULL, 'q' },
4529 { "order", no_argument, NULL, ARG_ORDER },
4530 { "require", no_argument, NULL, ARG_REQUIRE },
4531 { "root", required_argument, NULL, ARG_ROOT },
4532 { "force", no_argument, NULL, ARG_FORCE },
4533 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4534 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4535 { "signal", required_argument, NULL, 's' },
4536 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4537 { "host", required_argument, NULL, 'H' },
4538 { "privileged",no_argument, NULL, 'P' },
4539 { "runtime", no_argument, NULL, ARG_RUNTIME },
4540 { "lines", required_argument, NULL, 'n' },
4541 { "output", required_argument, NULL, 'o' },
4542 { NULL, 0, NULL, 0 }
4550 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:i", options, NULL)) >= 0) {
4559 puts(PACKAGE_STRING);
4560 puts(SYSTEMD_FEATURES);
4564 if (streq(optarg, "help")) {
4569 if (unit_type_from_string(optarg) >= 0) {
4573 if (unit_load_state_from_string(optarg) >= 0) {
4574 arg_load_state = optarg;
4577 log_error("Unkown unit type or load state '%s'.",
4579 log_info("Use -t help to see a list of allowed values.");
4584 if (!(l = strv_append(arg_property, optarg)))
4587 strv_free(arg_property);
4590 /* If the user asked for a particular
4591 * property, show it to him, even if it is
4602 arg_job_mode = "fail";
4605 case ARG_IGNORE_DEPENDENCIES:
4606 arg_job_mode = "ignore-dependencies";
4610 arg_scope = UNIT_FILE_USER;
4614 arg_scope = UNIT_FILE_SYSTEM;
4618 arg_scope = UNIT_FILE_GLOBAL;
4622 arg_no_block = true;
4626 arg_no_legend = true;
4630 arg_no_pager = true;
4638 arg_dot = DOT_ORDER;
4642 arg_dot = DOT_REQUIRE;
4670 arg_no_reload = true;
4674 arg_kill_who = optarg;
4678 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4679 log_error("Failed to parse signal string %s.", optarg);
4684 case ARG_NO_ASK_PASSWORD:
4685 arg_ask_password = false;
4689 arg_transport = TRANSPORT_POLKIT;
4693 arg_transport = TRANSPORT_SSH;
4702 if (safe_atou(optarg, &arg_lines) < 0) {
4703 log_error("Failed to parse lines '%s'", optarg);
4709 arg_output = output_mode_from_string(optarg);
4710 if (arg_output < 0) {
4711 log_error("Unknown output '%s'.", optarg);
4717 arg_ignore_inhibitors = true;
4724 log_error("Unknown option code '%c'.", c);
4729 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4730 log_error("Cannot access user instance remotely.");
4737 static int halt_parse_argv(int argc, char *argv[]) {
4746 static const struct option options[] = {
4747 { "help", no_argument, NULL, ARG_HELP },
4748 { "halt", no_argument, NULL, ARG_HALT },
4749 { "poweroff", no_argument, NULL, 'p' },
4750 { "reboot", no_argument, NULL, ARG_REBOOT },
4751 { "force", no_argument, NULL, 'f' },
4752 { "wtmp-only", no_argument, NULL, 'w' },
4753 { "no-wtmp", no_argument, NULL, 'd' },
4754 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4755 { NULL, 0, NULL, 0 }
4763 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4764 if (runlevel == '0' || runlevel == '6')
4767 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4775 arg_action = ACTION_HALT;
4779 if (arg_action != ACTION_REBOOT)
4780 arg_action = ACTION_POWEROFF;
4784 arg_action = ACTION_REBOOT;
4806 /* Compatibility nops */
4813 log_error("Unknown option code '%c'.", c);
4818 if (optind < argc) {
4819 log_error("Too many arguments.");
4826 static int parse_time_spec(const char *t, usec_t *_u) {
4830 if (streq(t, "now"))
4832 else if (!strchr(t, ':')) {
4835 if (safe_atou64(t, &u) < 0)
4838 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4847 hour = strtol(t, &e, 10);
4848 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4851 minute = strtol(e+1, &e, 10);
4852 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4855 n = now(CLOCK_REALTIME);
4856 s = (time_t) (n / USEC_PER_SEC);
4859 assert_se(localtime_r(&s, &tm));
4861 tm.tm_hour = (int) hour;
4862 tm.tm_min = (int) minute;
4865 assert_se(s = mktime(&tm));
4867 *_u = (usec_t) s * USEC_PER_SEC;
4870 *_u += USEC_PER_DAY;
4876 static int shutdown_parse_argv(int argc, char *argv[]) {
4883 static const struct option options[] = {
4884 { "help", no_argument, NULL, ARG_HELP },
4885 { "halt", no_argument, NULL, 'H' },
4886 { "poweroff", no_argument, NULL, 'P' },
4887 { "reboot", no_argument, NULL, 'r' },
4888 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4889 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4890 { NULL, 0, NULL, 0 }
4898 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4906 arg_action = ACTION_HALT;
4910 arg_action = ACTION_POWEROFF;
4915 arg_action = ACTION_KEXEC;
4917 arg_action = ACTION_REBOOT;
4921 arg_action = ACTION_KEXEC;
4925 if (arg_action != ACTION_HALT)
4926 arg_action = ACTION_POWEROFF;
4939 /* Compatibility nops */
4943 arg_action = ACTION_CANCEL_SHUTDOWN;
4950 log_error("Unknown option code '%c'.", c);
4955 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
4956 r = parse_time_spec(argv[optind], &arg_when);
4958 log_error("Failed to parse time specification: %s", argv[optind]);
4962 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4964 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
4965 /* No time argument for shutdown cancel */
4966 arg_wall = argv + optind;
4967 else if (argc > optind + 1)
4968 /* We skip the time argument */
4969 arg_wall = argv + optind + 1;
4976 static int telinit_parse_argv(int argc, char *argv[]) {
4983 static const struct option options[] = {
4984 { "help", no_argument, NULL, ARG_HELP },
4985 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4986 { NULL, 0, NULL, 0 }
4989 static const struct {
4993 { '0', ACTION_POWEROFF },
4994 { '6', ACTION_REBOOT },
4995 { '1', ACTION_RESCUE },
4996 { '2', ACTION_RUNLEVEL2 },
4997 { '3', ACTION_RUNLEVEL3 },
4998 { '4', ACTION_RUNLEVEL4 },
4999 { '5', ACTION_RUNLEVEL5 },
5000 { 's', ACTION_RESCUE },
5001 { 'S', ACTION_RESCUE },
5002 { 'q', ACTION_RELOAD },
5003 { 'Q', ACTION_RELOAD },
5004 { 'u', ACTION_REEXEC },
5005 { 'U', ACTION_REEXEC }
5014 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5029 log_error("Unknown option code '%c'.", c);
5034 if (optind >= argc) {
5039 if (optind + 1 < argc) {
5040 log_error("Too many arguments.");
5044 if (strlen(argv[optind]) != 1) {
5045 log_error("Expected single character argument.");
5049 for (i = 0; i < ELEMENTSOF(table); i++)
5050 if (table[i].from == argv[optind][0])
5053 if (i >= ELEMENTSOF(table)) {
5054 log_error("Unknown command '%s'.", argv[optind]);
5058 arg_action = table[i].to;
5065 static int runlevel_parse_argv(int argc, char *argv[]) {
5071 static const struct option options[] = {
5072 { "help", no_argument, NULL, ARG_HELP },
5073 { NULL, 0, NULL, 0 }
5081 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5092 log_error("Unknown option code '%c'.", c);
5097 if (optind < argc) {
5098 log_error("Too many arguments.");
5105 static int parse_argv(int argc, char *argv[]) {
5109 if (program_invocation_short_name) {
5111 if (strstr(program_invocation_short_name, "halt")) {
5112 arg_action = ACTION_HALT;
5113 return halt_parse_argv(argc, argv);
5114 } else if (strstr(program_invocation_short_name, "poweroff")) {
5115 arg_action = ACTION_POWEROFF;
5116 return halt_parse_argv(argc, argv);
5117 } else if (strstr(program_invocation_short_name, "reboot")) {
5119 arg_action = ACTION_KEXEC;
5121 arg_action = ACTION_REBOOT;
5122 return halt_parse_argv(argc, argv);
5123 } else if (strstr(program_invocation_short_name, "shutdown")) {
5124 arg_action = ACTION_POWEROFF;
5125 return shutdown_parse_argv(argc, argv);
5126 } else if (strstr(program_invocation_short_name, "init")) {
5128 if (sd_booted() > 0) {
5129 arg_action = ACTION_INVALID;
5130 return telinit_parse_argv(argc, argv);
5132 /* Hmm, so some other init system is
5133 * running, we need to forward this
5134 * request to it. For now we simply
5135 * guess that it is Upstart. */
5137 execv("/lib/upstart/telinit", argv);
5139 log_error("Couldn't find an alternative telinit implementation to spawn.");
5143 } else if (strstr(program_invocation_short_name, "runlevel")) {
5144 arg_action = ACTION_RUNLEVEL;
5145 return runlevel_parse_argv(argc, argv);
5149 arg_action = ACTION_SYSTEMCTL;
5150 return systemctl_parse_argv(argc, argv);
5153 static int action_to_runlevel(void) {
5155 static const char table[_ACTION_MAX] = {
5156 [ACTION_HALT] = '0',
5157 [ACTION_POWEROFF] = '0',
5158 [ACTION_REBOOT] = '6',
5159 [ACTION_RUNLEVEL2] = '2',
5160 [ACTION_RUNLEVEL3] = '3',
5161 [ACTION_RUNLEVEL4] = '4',
5162 [ACTION_RUNLEVEL5] = '5',
5163 [ACTION_RESCUE] = '1'
5166 assert(arg_action < _ACTION_MAX);
5168 return table[arg_action];
5171 static int talk_upstart(void) {
5172 DBusMessage *m = NULL, *reply = NULL;
5174 int previous, rl, r;
5176 env1_buf[] = "RUNLEVEL=X",
5177 env2_buf[] = "PREVLEVEL=X";
5178 char *env1 = env1_buf, *env2 = env2_buf;
5179 const char *emit = "runlevel";
5180 dbus_bool_t b_false = FALSE;
5181 DBusMessageIter iter, sub;
5182 DBusConnection *bus;
5184 dbus_error_init(&error);
5186 if (!(rl = action_to_runlevel()))
5189 if (utmp_get_runlevel(&previous, NULL) < 0)
5192 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5193 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5198 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5203 if ((r = bus_check_peercred(bus)) < 0) {
5204 log_error("Failed to verify owner of bus.");
5208 if (!(m = dbus_message_new_method_call(
5209 "com.ubuntu.Upstart",
5210 "/com/ubuntu/Upstart",
5211 "com.ubuntu.Upstart0_6",
5214 log_error("Could not allocate message.");
5219 dbus_message_iter_init_append(m, &iter);
5221 env1_buf[sizeof(env1_buf)-2] = rl;
5222 env2_buf[sizeof(env2_buf)-2] = previous;
5224 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5225 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5226 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5227 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5228 !dbus_message_iter_close_container(&iter, &sub) ||
5229 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5230 log_error("Could not append arguments to message.");
5235 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5237 if (bus_error_is_no_service(&error)) {
5242 log_error("Failed to issue method call: %s", bus_error_message(&error));
5251 dbus_message_unref(m);
5254 dbus_message_unref(reply);
5257 dbus_connection_flush(bus);
5258 dbus_connection_close(bus);
5259 dbus_connection_unref(bus);
5262 dbus_error_free(&error);
5267 static int talk_initctl(void) {
5268 struct init_request request;
5272 if (!(rl = action_to_runlevel()))
5276 request.magic = INIT_MAGIC;
5277 request.sleeptime = 0;
5278 request.cmd = INIT_CMD_RUNLVL;
5279 request.runlevel = rl;
5281 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5283 if (errno == ENOENT)
5286 log_error("Failed to open "INIT_FIFO": %m");
5291 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5292 close_nointr_nofail(fd);
5295 log_error("Failed to write to "INIT_FIFO": %m");
5296 return errno ? -errno : -EIO;
5302 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5304 static const struct {
5312 int (* const dispatch)(DBusConnection *bus, char **args);
5314 { "list-units", LESS, 1, list_units },
5315 { "list-unit-files", EQUAL, 1, list_unit_files },
5316 { "list-jobs", EQUAL, 1, list_jobs },
5317 { "clear-jobs", EQUAL, 1, daemon_reload },
5318 { "load", MORE, 2, load_unit },
5319 { "cancel", MORE, 2, cancel_job },
5320 { "start", MORE, 2, start_unit },
5321 { "stop", MORE, 2, start_unit },
5322 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5323 { "reload", MORE, 2, start_unit },
5324 { "restart", MORE, 2, start_unit },
5325 { "try-restart", MORE, 2, start_unit },
5326 { "reload-or-restart", MORE, 2, start_unit },
5327 { "reload-or-try-restart", MORE, 2, start_unit },
5328 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5329 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5330 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5331 { "isolate", EQUAL, 2, start_unit },
5332 { "set-cgroup", MORE, 2, set_cgroup },
5333 { "unset-cgroup", MORE, 2, set_cgroup },
5334 { "get-cgroup-attr", MORE, 2, get_cgroup_attr },
5335 { "set-cgroup-attr", MORE, 2, set_cgroup_attr },
5336 { "unset-cgroup-attr", MORE, 2, set_cgroup },
5337 { "kill", MORE, 2, kill_unit },
5338 { "is-active", MORE, 2, check_unit_active },
5339 { "check", MORE, 2, check_unit_active },
5340 { "is-failed", MORE, 2, check_unit_failed },
5341 { "show", MORE, 1, show },
5342 { "status", MORE, 2, show },
5343 { "help", MORE, 2, show },
5344 { "dump", EQUAL, 1, dump },
5345 { "dot", EQUAL, 1, dot },
5346 { "snapshot", LESS, 2, snapshot },
5347 { "delete", MORE, 2, delete_snapshot },
5348 { "daemon-reload", EQUAL, 1, daemon_reload },
5349 { "daemon-reexec", EQUAL, 1, daemon_reload },
5350 { "show-environment", EQUAL, 1, show_enviroment },
5351 { "set-environment", MORE, 2, set_environment },
5352 { "unset-environment", MORE, 2, set_environment },
5353 { "halt", EQUAL, 1, start_special },
5354 { "poweroff", EQUAL, 1, start_special },
5355 { "reboot", EQUAL, 1, start_special },
5356 { "kexec", EQUAL, 1, start_special },
5357 { "suspend", EQUAL, 1, start_special },
5358 { "hibernate", EQUAL, 1, start_special },
5359 { "hybrid-sleep", EQUAL, 1, start_special },
5360 { "default", EQUAL, 1, start_special },
5361 { "rescue", EQUAL, 1, start_special },
5362 { "emergency", EQUAL, 1, start_special },
5363 { "exit", EQUAL, 1, start_special },
5364 { "reset-failed", MORE, 1, reset_failed },
5365 { "enable", MORE, 2, enable_unit },
5366 { "disable", MORE, 2, enable_unit },
5367 { "is-enabled", MORE, 2, unit_is_enabled },
5368 { "reenable", MORE, 2, enable_unit },
5369 { "preset", MORE, 2, enable_unit },
5370 { "mask", MORE, 2, enable_unit },
5371 { "unmask", MORE, 2, enable_unit },
5372 { "link", MORE, 2, enable_unit },
5373 { "switch-root", MORE, 2, switch_root },
5374 { "list-dependencies", LESS, 2, list_dependencies },
5384 left = argc - optind;
5387 /* Special rule: no arguments means "list-units" */
5390 if (streq(argv[optind], "help") && !argv[optind+1]) {
5391 log_error("This command expects one or more "
5392 "unit names. Did you mean --help?");
5396 for (i = 0; i < ELEMENTSOF(verbs); i++)
5397 if (streq(argv[optind], verbs[i].verb))
5400 if (i >= ELEMENTSOF(verbs)) {
5401 log_error("Unknown operation '%s'.", argv[optind]);
5406 switch (verbs[i].argc_cmp) {
5409 if (left != verbs[i].argc) {
5410 log_error("Invalid number of arguments.");
5417 if (left < verbs[i].argc) {
5418 log_error("Too few arguments.");
5425 if (left > verbs[i].argc) {
5426 log_error("Too many arguments.");
5433 assert_not_reached("Unknown comparison operator.");
5436 /* Require a bus connection for all operations but
5438 if (!streq(verbs[i].verb, "enable") &&
5439 !streq(verbs[i].verb, "disable") &&
5440 !streq(verbs[i].verb, "is-enabled") &&
5441 !streq(verbs[i].verb, "list-unit-files") &&
5442 !streq(verbs[i].verb, "reenable") &&
5443 !streq(verbs[i].verb, "preset") &&
5444 !streq(verbs[i].verb, "mask") &&
5445 !streq(verbs[i].verb, "unmask") &&
5446 !streq(verbs[i].verb, "link")) {
5448 if (running_in_chroot() > 0) {
5449 log_info("Running in chroot, ignoring request.");
5453 if (((!streq(verbs[i].verb, "reboot") &&
5454 !streq(verbs[i].verb, "halt") &&
5455 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5456 log_error("Failed to get D-Bus connection: %s",
5457 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5463 if (!bus && !avoid_bus()) {
5464 log_error("Failed to get D-Bus connection: %s",
5465 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5470 return verbs[i].dispatch(bus, argv + optind);
5473 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5475 struct msghdr msghdr;
5476 struct iovec iovec[2];
5477 union sockaddr_union sockaddr;
5478 struct sd_shutdown_command c;
5480 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5487 c.dry_run = dry_run;
5491 sockaddr.sa.sa_family = AF_UNIX;
5492 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5495 msghdr.msg_name = &sockaddr;
5496 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5499 iovec[0].iov_base = (char*) &c;
5500 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5502 if (isempty(message))
5503 msghdr.msg_iovlen = 1;
5505 iovec[1].iov_base = (char*) message;
5506 iovec[1].iov_len = strlen(message);
5507 msghdr.msg_iovlen = 2;
5509 msghdr.msg_iov = iovec;
5511 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5512 close_nointr_nofail(fd);
5516 close_nointr_nofail(fd);
5520 static int reload_with_fallback(DBusConnection *bus) {
5523 /* First, try systemd via D-Bus. */
5524 if (daemon_reload(bus, NULL) >= 0)
5528 /* Nothing else worked, so let's try signals */
5529 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5531 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5532 log_error("kill() failed: %m");
5539 static int start_with_fallback(DBusConnection *bus) {
5542 /* First, try systemd via D-Bus. */
5543 if (start_unit(bus, NULL) >= 0)
5547 /* Hmm, talking to systemd via D-Bus didn't work. Then
5548 * let's try to talk to Upstart via D-Bus. */
5549 if (talk_upstart() > 0)
5552 /* Nothing else worked, so let's try
5554 if (talk_initctl() > 0)
5557 log_error("Failed to talk to init daemon.");
5561 warn_wall(arg_action);
5565 static _noreturn_ void halt_now(enum action a) {
5567 /* Make sure C-A-D is handled by the kernel from this
5569 reboot(RB_ENABLE_CAD);
5574 log_info("Halting.");
5575 reboot(RB_HALT_SYSTEM);
5578 case ACTION_POWEROFF:
5579 log_info("Powering off.");
5580 reboot(RB_POWER_OFF);
5584 log_info("Rebooting.");
5585 reboot(RB_AUTOBOOT);
5589 assert_not_reached("Unknown halt action.");
5592 assert_not_reached("Uh? This shouldn't happen.");
5595 static int halt_main(DBusConnection *bus) {
5598 r = check_inhibitors(bus, arg_action);
5602 if (geteuid() != 0) {
5603 /* Try logind if we are a normal user and no special
5604 * mode applies. Maybe PolicyKit allows us to shutdown
5607 if (arg_when <= 0 &&
5610 (arg_action == ACTION_POWEROFF ||
5611 arg_action == ACTION_REBOOT)) {
5612 r = reboot_with_logind(bus, arg_action);
5617 log_error("Must be root.");
5624 m = strv_join(arg_wall, " ");
5625 r = send_shutdownd(arg_when,
5626 arg_action == ACTION_HALT ? 'H' :
5627 arg_action == ACTION_POWEROFF ? 'P' :
5628 arg_action == ACTION_KEXEC ? 'K' :
5636 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5638 char date[FORMAT_TIMESTAMP_MAX];
5640 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5641 format_timestamp(date, sizeof(date), arg_when));
5646 if (!arg_dry && !arg_force)
5647 return start_with_fallback(bus);
5650 if (sd_booted() > 0)
5651 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5653 r = utmp_put_shutdown();
5655 log_warning("Failed to write utmp record: %s", strerror(-r));
5662 halt_now(arg_action);
5663 /* We should never reach this. */
5667 static int runlevel_main(void) {
5668 int r, runlevel, previous;
5670 r = utmp_get_runlevel(&runlevel, &previous);
5677 previous <= 0 ? 'N' : previous,
5678 runlevel <= 0 ? 'N' : runlevel);
5683 int main(int argc, char*argv[]) {
5684 int r, retval = EXIT_FAILURE;
5685 DBusConnection *bus = NULL;
5688 dbus_error_init(&error);
5690 setlocale(LC_ALL, "");
5691 log_parse_environment();
5694 r = parse_argv(argc, argv);
5698 retval = EXIT_SUCCESS;
5702 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5703 * let's shortcut this */
5704 if (arg_action == ACTION_RUNLEVEL) {
5705 r = runlevel_main();
5706 retval = r < 0 ? EXIT_FAILURE : r;
5710 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5711 log_info("Running in chroot, ignoring request.");
5717 if (arg_transport == TRANSPORT_NORMAL)
5718 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5719 else if (arg_transport == TRANSPORT_POLKIT) {
5720 bus_connect_system_polkit(&bus, &error);
5721 private_bus = false;
5722 } else if (arg_transport == TRANSPORT_SSH) {
5723 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5724 private_bus = false;
5726 assert_not_reached("Uh, invalid transport...");
5729 switch (arg_action) {
5731 case ACTION_SYSTEMCTL:
5732 r = systemctl_main(bus, argc, argv, &error);
5736 case ACTION_POWEROFF:
5742 case ACTION_RUNLEVEL2:
5743 case ACTION_RUNLEVEL3:
5744 case ACTION_RUNLEVEL4:
5745 case ACTION_RUNLEVEL5:
5747 case ACTION_EMERGENCY:
5748 case ACTION_DEFAULT:
5749 r = start_with_fallback(bus);
5754 r = reload_with_fallback(bus);
5757 case ACTION_CANCEL_SHUTDOWN: {
5761 m = strv_join(arg_wall, " ");
5763 retval = EXIT_FAILURE;
5767 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
5769 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
5774 case ACTION_INVALID:
5775 case ACTION_RUNLEVEL:
5777 assert_not_reached("Unknown action");
5780 retval = r < 0 ? EXIT_FAILURE : r;
5784 dbus_connection_flush(bus);
5785 dbus_connection_close(bus);
5786 dbus_connection_unref(bus);
5789 dbus_error_free(&error);
5793 strv_free(arg_property);
5796 ask_password_agent_close();
5797 polkit_agent_close();