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 * const dependencies[] = {
750 "RequiresOverridable",
752 "RequisiteOverridable",
756 _cleanup_free_ char *path;
757 const char *interface = "org.freedesktop.systemd1.Unit";
759 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
760 DBusMessageIter iter, sub, sub2, sub3;
772 path = unit_dbus_path_from_name(name);
778 r = bus_method_call_with_reply(
780 "org.freedesktop.systemd1",
782 "org.freedesktop.DBus.Properties",
786 DBUS_TYPE_STRING, &interface,
791 if (!dbus_message_iter_init(reply, &iter) ||
792 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
793 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
794 log_error("Failed to parse reply.");
799 dbus_message_iter_recurse(&iter, &sub);
801 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
804 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
805 log_error("Failed to parse reply.");
810 dbus_message_iter_recurse(&sub, &sub2);
812 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
813 log_error("Failed to parse reply.");
818 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
819 log_error("Failed to parse reply.");
824 dbus_message_iter_recurse(&sub2, &sub3);
826 dbus_message_iter_next(&sub);
828 for (i = 0; i < ELEMENTSOF(dependencies); i++)
829 if (streq(dependencies[i], prop)) {
833 if (i == ELEMENTSOF(dependencies))
836 if (dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_ARRAY) {
837 if (dbus_message_iter_get_element_type(&sub3) == DBUS_TYPE_STRING) {
838 DBusMessageIter sub4;
839 dbus_message_iter_recurse(&sub3, &sub4);
841 while (dbus_message_iter_get_arg_type(&sub4) != DBUS_TYPE_INVALID) {
844 assert(dbus_message_iter_get_arg_type(&sub4) == DBUS_TYPE_STRING);
845 dbus_message_iter_get_basic(&sub4, &s);
846 c = strv_append(ret, s);
853 dbus_message_iter_next(&sub4);
865 static int list_dependencies_compare(const void *_a, const void *_b) {
866 const char **a = (const char**) _a, **b = (const char**) _b;
867 if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET)
869 if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET)
871 return strcasecmp(*a, *b);
874 static int list_dependencies_one(DBusConnection *bus, const char *name, int level, char **units, unsigned int branches) {
880 u = strv_append(units, name);
884 r = list_dependencies_get_dependencies(bus, name, &deps);
888 qsort(deps, strv_length(deps), sizeof (char*), list_dependencies_compare);
890 STRV_FOREACH(c, deps) {
891 if (strv_contains(u, *c)) {
892 r = list_dependencies_print("...", level + 1, (branches << 1) | (c[1] == NULL ? 0 : 1), 1);
898 r = list_dependencies_print(*c, level, branches, c[1] == NULL);
902 if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) {
903 r = list_dependencies_one(bus, *c, level + 1, u, (branches << 1) | (c[1] == NULL ? 0 : 1));
916 static int list_dependencies(DBusConnection *bus, char **args) {
918 _cleanup_free_ char *unit = NULL;
923 unit = unit_name_mangle(args[1]);
927 pager_open_if_enabled();
928 printf("%s\n", unit);
929 r = list_dependencies_one(bus, unit, 0, NULL, 0);
933 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
935 static const char * const colors[] = {
936 "Requires", "[color=\"black\"]",
937 "RequiresOverridable", "[color=\"black\"]",
938 "Requisite", "[color=\"darkblue\"]",
939 "RequisiteOverridable", "[color=\"darkblue\"]",
940 "Wants", "[color=\"grey66\"]",
941 "Conflicts", "[color=\"red\"]",
942 "ConflictedBy", "[color=\"red\"]",
943 "After", "[color=\"green\"]"
946 const char *c = NULL;
953 for (i = 0; i < ELEMENTSOF(colors); i += 2)
954 if (streq(colors[i], prop)) {
962 if (arg_dot != DOT_ALL)
963 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
966 switch (dbus_message_iter_get_arg_type(iter)) {
968 case DBUS_TYPE_ARRAY:
970 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
973 dbus_message_iter_recurse(iter, &sub);
975 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
978 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
979 dbus_message_iter_get_basic(&sub, &s);
980 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
982 dbus_message_iter_next(&sub);
992 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
993 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
994 const char *interface = "org.freedesktop.systemd1.Unit";
996 DBusMessageIter iter, sub, sub2, sub3;
1001 r = bus_method_call_with_reply(
1003 "org.freedesktop.systemd1",
1005 "org.freedesktop.DBus.Properties",
1009 DBUS_TYPE_STRING, &interface,
1014 if (!dbus_message_iter_init(reply, &iter) ||
1015 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1016 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
1017 log_error("Failed to parse reply.");
1021 dbus_message_iter_recurse(&iter, &sub);
1023 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1026 assert(dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY);
1027 dbus_message_iter_recurse(&sub, &sub2);
1029 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0 ||
1030 dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
1031 log_error("Failed to parse reply.");
1035 dbus_message_iter_recurse(&sub2, &sub3);
1036 r = dot_one_property(name, prop, &sub3);
1040 dbus_message_iter_next(&sub);
1046 static int dot(DBusConnection *bus, char **args) {
1047 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1048 DBusMessageIter iter, sub, sub2;
1051 r = bus_method_call_with_reply(
1053 "org.freedesktop.systemd1",
1054 "/org/freedesktop/systemd1",
1055 "org.freedesktop.systemd1.Manager",
1063 if (!dbus_message_iter_init(reply, &iter) ||
1064 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1065 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1066 log_error("Failed to parse reply.");
1070 printf("digraph systemd {\n");
1072 dbus_message_iter_recurse(&iter, &sub);
1073 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1074 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
1076 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1077 log_error("Failed to parse reply.");
1081 dbus_message_iter_recurse(&sub, &sub2);
1083 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
1084 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
1085 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
1086 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
1087 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
1088 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
1089 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
1090 log_error("Failed to parse reply.");
1094 r = dot_one(bus, id, unit_path);
1098 /* printf("\t\"%s\";\n", id); */
1099 dbus_message_iter_next(&sub);
1104 log_info(" Color legend: black = Requires\n"
1105 " dark blue = Requisite\n"
1106 " dark grey = Wants\n"
1107 " red = Conflicts\n"
1108 " green = After\n");
1111 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
1112 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
1117 static int list_jobs(DBusConnection *bus, char **args) {
1118 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1119 DBusMessageIter iter, sub, sub2;
1123 pager_open_if_enabled();
1125 r = bus_method_call_with_reply(
1127 "org.freedesktop.systemd1",
1128 "/org/freedesktop/systemd1",
1129 "org.freedesktop.systemd1.Manager",
1137 if (!dbus_message_iter_init(reply, &iter) ||
1138 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1139 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1140 log_error("Failed to parse reply.");
1144 dbus_message_iter_recurse(&iter, &sub);
1147 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
1149 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1150 const char *name, *type, *state, *job_path, *unit_path;
1154 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1155 log_error("Failed to parse reply.");
1159 dbus_message_iter_recurse(&sub, &sub2);
1161 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
1162 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
1163 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
1164 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
1165 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
1166 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
1167 log_error("Failed to parse reply.");
1171 e = arg_full ? NULL : ellipsize(name, 25, 33);
1172 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
1177 dbus_message_iter_next(&sub);
1181 printf("\n%u jobs listed.\n", k);
1186 static int load_unit(DBusConnection *bus, char **args) {
1191 STRV_FOREACH(name, args+1) {
1192 _cleanup_free_ char *n = NULL;
1195 n = unit_name_mangle(*name);
1199 r = bus_method_call_with_reply(
1201 "org.freedesktop.systemd1",
1202 "/org/freedesktop/systemd1",
1203 "org.freedesktop.systemd1.Manager",
1207 DBUS_TYPE_STRING, &n,
1216 static int cancel_job(DBusConnection *bus, char **args) {
1221 if (strv_length(args) <= 1)
1222 return daemon_reload(bus, args);
1224 STRV_FOREACH(name, args+1) {
1228 r = safe_atou32(*name, &id);
1230 log_error("Failed to parse job id: %s", strerror(-r));
1234 r = bus_method_call_with_reply(
1236 "org.freedesktop.systemd1",
1237 "/org/freedesktop/systemd1",
1238 "org.freedesktop.systemd1.Manager",
1242 DBUS_TYPE_UINT32, &id,
1251 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1252 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1253 dbus_bool_t b = FALSE;
1254 DBusMessageIter iter, sub;
1256 *interface = "org.freedesktop.systemd1.Unit",
1257 *property = "NeedDaemonReload",
1259 _cleanup_free_ char *n = NULL;
1262 /* We ignore all errors here, since this is used to show a warning only */
1264 n = unit_name_mangle(unit);
1268 r = bus_method_call_with_reply (
1270 "org.freedesktop.systemd1",
1271 "/org/freedesktop/systemd1",
1272 "org.freedesktop.systemd1.Manager",
1276 DBUS_TYPE_STRING, &n,
1281 if (!dbus_message_get_args(reply, NULL,
1282 DBUS_TYPE_OBJECT_PATH, &path,
1286 dbus_message_unref(reply);
1289 r = bus_method_call_with_reply(
1291 "org.freedesktop.systemd1",
1293 "org.freedesktop.DBus.Properties",
1297 DBUS_TYPE_STRING, &interface,
1298 DBUS_TYPE_STRING, &property,
1303 if (!dbus_message_iter_init(reply, &iter) ||
1304 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1307 dbus_message_iter_recurse(&iter, &sub);
1308 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1311 dbus_message_iter_get_basic(&sub, &b);
1315 typedef struct WaitData {
1322 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1330 dbus_error_init(&error);
1332 log_debug("Got D-Bus request: %s.%s() on %s",
1333 dbus_message_get_interface(message),
1334 dbus_message_get_member(message),
1335 dbus_message_get_path(message));
1337 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1338 log_error("Warning! D-Bus connection terminated.");
1339 dbus_connection_close(connection);
1341 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1343 const char *path, *result, *unit;
1345 if (dbus_message_get_args(message, &error,
1346 DBUS_TYPE_UINT32, &id,
1347 DBUS_TYPE_OBJECT_PATH, &path,
1348 DBUS_TYPE_STRING, &unit,
1349 DBUS_TYPE_STRING, &result,
1350 DBUS_TYPE_INVALID)) {
1352 free(set_remove(d->set, (char*) path));
1354 if (!isempty(result))
1355 d->result = strdup(result);
1358 d->name = strdup(unit);
1363 dbus_error_free(&error);
1364 if (dbus_message_get_args(message, &error,
1365 DBUS_TYPE_UINT32, &id,
1366 DBUS_TYPE_OBJECT_PATH, &path,
1367 DBUS_TYPE_STRING, &result,
1368 DBUS_TYPE_INVALID)) {
1369 /* Compatibility with older systemd versions <
1370 * 183 during upgrades. This should be dropped
1372 free(set_remove(d->set, (char*) path));
1375 d->result = strdup(result);
1381 log_error("Failed to parse message: %s", bus_error_message(&error));
1385 dbus_error_free(&error);
1386 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1389 static int enable_wait_for_jobs(DBusConnection *bus) {
1397 dbus_error_init(&error);
1398 dbus_bus_add_match(bus,
1400 "sender='org.freedesktop.systemd1',"
1401 "interface='org.freedesktop.systemd1.Manager',"
1402 "member='JobRemoved',"
1403 "path='/org/freedesktop/systemd1'",
1406 if (dbus_error_is_set(&error)) {
1407 log_error("Failed to add match: %s", bus_error_message(&error));
1408 dbus_error_free(&error);
1412 /* This is slightly dirty, since we don't undo the match registrations. */
1416 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1426 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL))
1429 while (!set_isempty(s)) {
1431 if (!dbus_connection_read_write_dispatch(bus, -1)) {
1432 log_error("Disconnected from bus.");
1433 return -ECONNREFUSED;
1440 if (streq(d.result, "timeout"))
1441 log_error("Job for %s timed out.", strna(d.name));
1442 else if (streq(d.result, "canceled"))
1443 log_error("Job for %s canceled.", strna(d.name));
1444 else if (streq(d.result, "dependency"))
1445 log_error("A dependency job for %s failed. See 'journalctl -xn' for details.", strna(d.name));
1446 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1447 log_error("Job for %s failed. See 'systemctl status %s' and 'journalctl -xn' for details.", strna(d.name), strna(d.name));
1450 if (streq_ptr(d.result, "timeout"))
1452 else if (streq_ptr(d.result, "canceled"))
1454 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1465 dbus_connection_remove_filter(bus, wait_filter, &d);
1469 static int check_one_unit(DBusConnection *bus, const char *name, char **check_states, bool quiet) {
1470 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1471 _cleanup_free_ char *n = NULL;
1472 DBusMessageIter iter, sub;
1474 *interface = "org.freedesktop.systemd1.Unit",
1475 *property = "ActiveState";
1476 const char *state, *path;
1482 dbus_error_init(&error);
1484 n = unit_name_mangle(name);
1488 r = bus_method_call_with_reply (
1490 "org.freedesktop.systemd1",
1491 "/org/freedesktop/systemd1",
1492 "org.freedesktop.systemd1.Manager",
1496 DBUS_TYPE_STRING, &n,
1499 dbus_error_free(&error);
1506 if (!dbus_message_get_args(reply, NULL,
1507 DBUS_TYPE_OBJECT_PATH, &path,
1508 DBUS_TYPE_INVALID)) {
1509 log_error("Failed to parse reply.");
1513 dbus_message_unref(reply);
1516 r = bus_method_call_with_reply(
1518 "org.freedesktop.systemd1",
1520 "org.freedesktop.DBus.Properties",
1524 DBUS_TYPE_STRING, &interface,
1525 DBUS_TYPE_STRING, &property,
1533 if (!dbus_message_iter_init(reply, &iter) ||
1534 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1535 log_error("Failed to parse reply.");
1539 dbus_message_iter_recurse(&iter, &sub);
1541 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1542 log_error("Failed to parse reply.");
1546 dbus_message_iter_get_basic(&sub, &state);
1551 return strv_find(check_states, state) ? 1 : 0;
1554 static void check_triggering_units(
1555 DBusConnection *bus,
1556 const char *unit_name) {
1558 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1559 DBusMessageIter iter, sub;
1560 const char *interface = "org.freedesktop.systemd1.Unit",
1561 *triggered_by_property = "TriggeredBy";
1562 char _cleanup_free_ *unit_path = NULL, *n = NULL;
1563 bool print_warning_label = true;
1566 n = unit_name_mangle(unit_name);
1572 unit_path = unit_dbus_path_from_name(n);
1578 r = bus_method_call_with_reply(
1580 "org.freedesktop.systemd1",
1582 "org.freedesktop.DBus.Properties",
1586 DBUS_TYPE_STRING, &interface,
1587 DBUS_TYPE_STRING, &triggered_by_property,
1592 if (!dbus_message_iter_init(reply, &iter) ||
1593 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1594 log_error("Failed to parse reply.");
1598 dbus_message_iter_recurse(&iter, &sub);
1599 dbus_message_iter_recurse(&sub, &iter);
1602 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1603 const char * const check_states[] = {
1608 const char *service_trigger;
1610 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1611 log_error("Failed to parse reply.");
1615 dbus_message_iter_get_basic(&sub, &service_trigger);
1617 r = check_one_unit(bus, service_trigger, (char**) check_states, true);
1621 if (print_warning_label) {
1622 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1623 print_warning_label = false;
1626 log_warning(" %s", service_trigger);
1629 dbus_message_iter_next(&sub);
1633 static int start_unit_one(
1634 DBusConnection *bus,
1641 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1642 _cleanup_free_ char *n;
1651 n = unit_name_mangle(name);
1655 r = bus_method_call_with_reply(
1657 "org.freedesktop.systemd1",
1658 "/org/freedesktop/systemd1",
1659 "org.freedesktop.systemd1.Manager",
1663 DBUS_TYPE_STRING, &n,
1664 DBUS_TYPE_STRING, &mode,
1667 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
1668 /* There's always a fallback possible for
1669 * legacy actions. */
1672 log_error("Failed to issue method call: %s", bus_error_message(error));
1677 if (!dbus_message_get_args(reply, error,
1678 DBUS_TYPE_OBJECT_PATH, &path,
1679 DBUS_TYPE_INVALID)) {
1680 log_error("Failed to parse reply: %s", bus_error_message(error));
1684 if (need_daemon_reload(bus, n))
1685 log_warning("Warning: Unit file of %s changed on disk, 'systemctl %s daemon-reload' recommended.",
1686 n, arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1698 log_error("Failed to add path to set.");
1706 static enum action verb_to_action(const char *verb) {
1707 if (streq(verb, "halt"))
1709 else if (streq(verb, "poweroff"))
1710 return ACTION_POWEROFF;
1711 else if (streq(verb, "reboot"))
1712 return ACTION_REBOOT;
1713 else if (streq(verb, "kexec"))
1714 return ACTION_KEXEC;
1715 else if (streq(verb, "rescue"))
1716 return ACTION_RESCUE;
1717 else if (streq(verb, "emergency"))
1718 return ACTION_EMERGENCY;
1719 else if (streq(verb, "default"))
1720 return ACTION_DEFAULT;
1721 else if (streq(verb, "exit"))
1723 else if (streq(verb, "suspend"))
1724 return ACTION_SUSPEND;
1725 else if (streq(verb, "hibernate"))
1726 return ACTION_HIBERNATE;
1727 else if (streq(verb, "hybrid-sleep"))
1728 return ACTION_HYBRID_SLEEP;
1730 return ACTION_INVALID;
1733 static int start_unit(DBusConnection *bus, char **args) {
1735 static const char * const table[_ACTION_MAX] = {
1736 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1737 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1738 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1739 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1740 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1741 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1742 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1743 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1744 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1745 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1746 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1747 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1748 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1749 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET,
1750 [ACTION_HYBRID_SLEEP] = SPECIAL_HYBRID_SLEEP_TARGET
1754 const char *method, *mode, *one_name;
1759 dbus_error_init(&error);
1763 ask_password_agent_open_if_enabled();
1765 if (arg_action == ACTION_SYSTEMCTL) {
1767 streq(args[0], "stop") ||
1768 streq(args[0], "condstop") ? "StopUnit" :
1769 streq(args[0], "reload") ? "ReloadUnit" :
1770 streq(args[0], "restart") ? "RestartUnit" :
1772 streq(args[0], "try-restart") ||
1773 streq(args[0], "condrestart") ? "TryRestartUnit" :
1775 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1777 streq(args[0], "reload-or-try-restart") ||
1778 streq(args[0], "condreload") ||
1780 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1784 (streq(args[0], "isolate") ||
1785 streq(args[0], "rescue") ||
1786 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1788 one_name = table[verb_to_action(args[0])];
1791 assert(arg_action < ELEMENTSOF(table));
1792 assert(table[arg_action]);
1794 method = "StartUnit";
1796 mode = (arg_action == ACTION_EMERGENCY ||
1797 arg_action == ACTION_RESCUE ||
1798 arg_action == ACTION_RUNLEVEL2 ||
1799 arg_action == ACTION_RUNLEVEL3 ||
1800 arg_action == ACTION_RUNLEVEL4 ||
1801 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1803 one_name = table[arg_action];
1806 if (!arg_no_block) {
1807 ret = enable_wait_for_jobs(bus);
1809 log_error("Could not watch jobs: %s", strerror(-ret));
1813 s = set_new(string_hash_func, string_compare_func);
1821 ret = start_unit_one(bus, method, one_name, mode, &error, s);
1823 ret = translate_bus_error_to_exit_status(ret, &error);
1825 STRV_FOREACH(name, args+1) {
1826 r = start_unit_one(bus, method, *name, mode, &error, s);
1828 ret = translate_bus_error_to_exit_status(r, &error);
1829 dbus_error_free(&error);
1834 if (!arg_no_block) {
1835 r = wait_for_jobs(bus, s);
1841 /* When stopping units, warn if they can still be triggered by
1842 * another active unit (socket, path, timer) */
1843 if (!arg_quiet && streq(method, "StopUnit")) {
1845 check_triggering_units(bus, one_name);
1847 STRV_FOREACH(name, args+1)
1848 check_triggering_units(bus, *name);
1854 dbus_error_free(&error);
1859 /* Ask systemd-logind, which might grant access to unprivileged users
1860 * through PolicyKit */
1861 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1864 dbus_bool_t interactive = true;
1869 polkit_agent_open_if_enabled();
1877 case ACTION_POWEROFF:
1878 method = "PowerOff";
1881 case ACTION_SUSPEND:
1885 case ACTION_HIBERNATE:
1886 method = "Hibernate";
1889 case ACTION_HYBRID_SLEEP:
1890 method = "HybridSleep";
1897 return bus_method_call_with_reply(
1899 "org.freedesktop.login1",
1900 "/org/freedesktop/login1",
1901 "org.freedesktop.login1.Manager",
1905 DBUS_TYPE_BOOLEAN, &interactive,
1912 static int check_inhibitors(DBusConnection *bus, enum action a) {
1914 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1915 DBusMessageIter iter, sub, sub2;
1918 _cleanup_strv_free_ char **sessions = NULL;
1924 if (arg_ignore_inhibitors || arg_force > 0)
1936 r = bus_method_call_with_reply(
1938 "org.freedesktop.login1",
1939 "/org/freedesktop/login1",
1940 "org.freedesktop.login1.Manager",
1946 /* If logind is not around, then there are no inhibitors... */
1949 if (!dbus_message_iter_init(reply, &iter) ||
1950 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1951 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
1952 log_error("Failed to parse reply.");
1956 dbus_message_iter_recurse(&iter, &sub);
1957 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1958 const char *what, *who, *why, *mode;
1960 _cleanup_strv_free_ char **sv = NULL;
1961 _cleanup_free_ char *comm = NULL, *user = NULL;
1963 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
1964 log_error("Failed to parse reply.");
1968 dbus_message_iter_recurse(&sub, &sub2);
1970 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &what, true) < 0 ||
1971 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &who, true) < 0 ||
1972 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &why, true) < 0 ||
1973 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &mode, true) < 0 ||
1974 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &uid, true) < 0 ||
1975 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, false) < 0) {
1976 log_error("Failed to parse reply.");
1980 if (!streq(mode, "block"))
1983 sv = strv_split(what, ":");
1987 if (!strv_contains(sv,
1989 a == ACTION_POWEROFF ||
1990 a == ACTION_REBOOT ||
1991 a == ACTION_KEXEC ? "shutdown" : "sleep"))
1994 get_process_comm(pid, &comm);
1995 user = uid_to_name(uid);
1996 log_warning("Operation inhibited by \"%s\" (PID %lu \"%s\", user %s), reason is \"%s\".",
1997 who, (unsigned long) pid, strna(comm), strna(user), why);
2001 dbus_message_iter_next(&sub);
2004 dbus_message_iter_recurse(&iter, &sub);
2006 /* Check for current sessions */
2007 sd_get_sessions(&sessions);
2008 STRV_FOREACH(s, sessions) {
2010 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
2012 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
2015 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
2018 if (sd_session_get_type(*s, &type) < 0 || (!streq(type, "x11") && !streq(type, "tty")))
2021 sd_session_get_tty(*s, &tty);
2022 sd_session_get_seat(*s, &seat);
2023 sd_session_get_service(*s, &service);
2024 user = uid_to_name(uid);
2026 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
2033 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
2034 a == ACTION_HALT ? "halt" :
2035 a == ACTION_POWEROFF ? "poweroff" :
2036 a == ACTION_REBOOT ? "reboot" :
2037 a == ACTION_KEXEC ? "kexec" :
2038 a == ACTION_SUSPEND ? "suspend" :
2039 a == ACTION_HIBERNATE ? "hibernate" : "hybrid-sleep");
2047 static int start_special(DBusConnection *bus, char **args) {
2053 a = verb_to_action(args[0]);
2055 r = check_inhibitors(bus, a);
2059 if (arg_force >= 2 && geteuid() != 0) {
2060 log_error("Must be root.");
2064 if (arg_force >= 2 &&
2065 (a == ACTION_HALT ||
2066 a == ACTION_POWEROFF ||
2067 a == ACTION_REBOOT))
2070 if (arg_force >= 1 &&
2071 (a == ACTION_HALT ||
2072 a == ACTION_POWEROFF ||
2073 a == ACTION_REBOOT ||
2074 a == ACTION_KEXEC ||
2076 return daemon_reload(bus, args);
2078 /* first try logind, to allow authentication with polkit */
2079 if (geteuid() != 0 &&
2080 (a == ACTION_POWEROFF ||
2081 a == ACTION_REBOOT ||
2082 a == ACTION_SUSPEND ||
2083 a == ACTION_HIBERNATE ||
2084 a == ACTION_HYBRID_SLEEP)) {
2085 r = reboot_with_logind(bus, a);
2090 r = start_unit(bus, args);
2097 static int check_unit_active(DBusConnection *bus, char **args) {
2098 const char * const check_states[] = {
2105 int r = 3; /* According to LSB: "program is not running" */
2110 STRV_FOREACH(name, args+1) {
2113 state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
2123 static int check_unit_failed(DBusConnection *bus, char **args) {
2124 const char * const check_states[] = {
2135 STRV_FOREACH(name, args+1) {
2138 state = check_one_unit(bus, *name, (char**) check_states, arg_quiet);
2148 static int kill_unit(DBusConnection *bus, char **args) {
2156 arg_kill_who = "all";
2158 STRV_FOREACH(name, args+1) {
2159 _cleanup_free_ char *n = NULL;
2161 n = unit_name_mangle(*name);
2165 r = bus_method_call_with_reply(
2167 "org.freedesktop.systemd1",
2168 "/org/freedesktop/systemd1",
2169 "org.freedesktop.systemd1.Manager",
2173 DBUS_TYPE_STRING, &n,
2174 DBUS_TYPE_STRING, &arg_kill_who,
2175 DBUS_TYPE_INT32, &arg_signal,
2183 static int set_cgroup(DBusConnection *bus, char **args) {
2184 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
2187 DBusMessageIter iter;
2189 _cleanup_free_ char *n = NULL;
2194 dbus_error_init(&error);
2197 streq(args[0], "set-cgroup") ? "SetUnitControlGroups" :
2198 streq(args[0], "unset-group") ? "UnsetUnitControlGroups"
2199 : "UnsetUnitControlGroupAttributes";
2201 n = unit_name_mangle(args[1]);
2205 m = dbus_message_new_method_call(
2206 "org.freedesktop.systemd1",
2207 "/org/freedesktop/systemd1",
2208 "org.freedesktop.systemd1.Manager",
2213 dbus_message_iter_init_append(m, &iter);
2214 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &n))
2217 r = bus_append_strv_iter(&iter, args + 2);
2221 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2223 log_error("Failed to issue method call: %s", bus_error_message(&error));
2224 dbus_error_free(&error);
2231 static int set_cgroup_attr(DBusConnection *bus, char **args) {
2232 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
2234 DBusMessageIter iter, sub, sub2;
2236 _cleanup_free_ char *n = NULL;
2241 dbus_error_init(&error);
2243 if (strv_length(args) % 2 != 0) {
2244 log_error("Expecting an uneven number of arguments!");
2248 n = unit_name_mangle(args[1]);
2252 m = dbus_message_new_method_call(
2253 "org.freedesktop.systemd1",
2254 "/org/freedesktop/systemd1",
2255 "org.freedesktop.systemd1.Manager",
2256 "SetUnitControlGroupAttributes");
2260 dbus_message_iter_init_append(m, &iter);
2261 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &n) ||
2262 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "(ss)", &sub))
2265 STRV_FOREACH_PAIR(x, y, args + 2) {
2266 if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_STRUCT, NULL, &sub2) ||
2267 !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, x) ||
2268 !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, y) ||
2269 !dbus_message_iter_close_container(&sub, &sub2))
2273 if (!dbus_message_iter_close_container(&iter, &sub))
2276 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
2278 log_error("Failed to issue method call: %s", bus_error_message(&error));
2279 dbus_error_free(&error);
2286 typedef struct ExecStatusInfo {
2294 usec_t start_timestamp;
2295 usec_t exit_timestamp;
2300 LIST_FIELDS(struct ExecStatusInfo, exec);
2303 static void exec_status_info_free(ExecStatusInfo *i) {
2312 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
2313 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
2314 DBusMessageIter sub2, sub3;
2318 int32_t code, status;
2324 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
2327 dbus_message_iter_recurse(sub, &sub2);
2329 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
2332 i->path = strdup(path);
2336 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
2337 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
2341 dbus_message_iter_recurse(&sub2, &sub3);
2342 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2343 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2344 dbus_message_iter_next(&sub3);
2348 i->argv = new0(char*, n+1);
2353 dbus_message_iter_recurse(&sub2, &sub3);
2354 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
2357 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
2358 dbus_message_iter_get_basic(&sub3, &s);
2359 dbus_message_iter_next(&sub3);
2361 i->argv[n] = strdup(s);
2368 if (!dbus_message_iter_next(&sub2) ||
2369 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
2370 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
2371 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
2372 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
2373 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
2374 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
2375 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
2376 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
2380 i->start_timestamp = (usec_t) start_timestamp;
2381 i->exit_timestamp = (usec_t) exit_timestamp;
2382 i->pid = (pid_t) pid;
2389 typedef struct UnitStatusInfo {
2391 const char *load_state;
2392 const char *active_state;
2393 const char *sub_state;
2394 const char *unit_file_state;
2396 const char *description;
2397 const char *following;
2399 char **documentation;
2401 const char *fragment_path;
2402 const char *source_path;
2403 const char *default_control_group;
2405 const char *load_error;
2408 usec_t inactive_exit_timestamp;
2409 usec_t inactive_exit_timestamp_monotonic;
2410 usec_t active_enter_timestamp;
2411 usec_t active_exit_timestamp;
2412 usec_t inactive_enter_timestamp;
2414 bool need_daemon_reload;
2419 const char *status_text;
2422 usec_t start_timestamp;
2423 usec_t exit_timestamp;
2425 int exit_code, exit_status;
2427 usec_t condition_timestamp;
2428 bool condition_result;
2431 unsigned n_accepted;
2432 unsigned n_connections;
2436 const char *sysfs_path;
2438 /* Mount, Automount */
2444 LIST_HEAD(ExecStatusInfo, exec);
2447 static void print_status_info(UnitStatusInfo *i) {
2449 const char *on, *off, *ss;
2451 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
2452 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2455 arg_all * OUTPUT_SHOW_ALL |
2456 (!on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
2457 on_tty() * OUTPUT_COLOR |
2458 !arg_quiet * OUTPUT_WARN_CUTOFF |
2459 arg_full * OUTPUT_FULL_WIDTH;
2463 /* This shows pretty information about a unit. See
2464 * print_property() for a low-level property printer */
2466 printf("%s", strna(i->id));
2468 if (i->description && !streq_ptr(i->id, i->description))
2469 printf(" - %s", i->description);
2474 printf("\t Follow: unit currently follows state of %s\n", i->following);
2476 if (streq_ptr(i->load_state, "error")) {
2477 on = ansi_highlight_red(true);
2478 off = ansi_highlight_red(false);
2482 path = i->source_path ? i->source_path : i->fragment_path;
2485 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2486 else if (path && i->unit_file_state)
2487 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2489 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2491 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2493 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2495 if (streq_ptr(i->active_state, "failed")) {
2496 on = ansi_highlight_red(true);
2497 off = ansi_highlight_red(false);
2498 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2499 on = ansi_highlight_green(true);
2500 off = ansi_highlight_green(false);
2505 printf("\t Active: %s%s (%s)%s",
2507 strna(i->active_state),
2511 printf("\t Active: %s%s%s",
2513 strna(i->active_state),
2516 if (!isempty(i->result) && !streq(i->result, "success"))
2517 printf(" (Result: %s)", i->result);
2519 timestamp = (streq_ptr(i->active_state, "active") ||
2520 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2521 (streq_ptr(i->active_state, "inactive") ||
2522 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2523 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2524 i->active_exit_timestamp;
2526 s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
2527 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2530 printf(" since %s; %s\n", s2, s1);
2532 printf(" since %s\n", s2);
2536 if (!i->condition_result && i->condition_timestamp > 0) {
2537 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
2538 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2541 printf("\t start condition failed at %s; %s\n", s2, s1);
2543 printf("\t start condition failed at %s\n", s2);
2547 printf("\t Device: %s\n", i->sysfs_path);
2549 printf("\t Where: %s\n", i->where);
2551 printf("\t What: %s\n", i->what);
2553 if (!strv_isempty(i->documentation)) {
2557 STRV_FOREACH(t, i->documentation) {
2559 printf("\t Docs: %s\n", *t);
2562 printf("\t %s\n", *t);
2567 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2569 LIST_FOREACH(exec, p, i->exec) {
2570 _cleanup_free_ char *t = NULL;
2573 /* Only show exited processes here */
2577 t = strv_join(p->argv, " ");
2578 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2580 good = is_clean_exit_lsb(p->code, p->status, NULL);
2582 on = ansi_highlight_red(true);
2583 off = ansi_highlight_red(false);
2587 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2589 if (p->code == CLD_EXITED) {
2592 printf("status=%i", p->status);
2594 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2599 printf("signal=%s", signal_to_string(p->status));
2601 printf(")%s\n", off);
2603 if (i->main_pid == p->pid &&
2604 i->start_timestamp == p->start_timestamp &&
2605 i->exit_timestamp == p->start_timestamp)
2606 /* Let's not show this twice */
2609 if (p->pid == i->control_pid)
2613 if (i->main_pid > 0 || i->control_pid > 0) {
2616 if (i->main_pid > 0) {
2617 printf("Main PID: %u", (unsigned) i->main_pid);
2620 _cleanup_free_ char *t = NULL;
2621 get_process_comm(i->main_pid, &t);
2624 } else if (i->exit_code > 0) {
2625 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2627 if (i->exit_code == CLD_EXITED) {
2630 printf("status=%i", i->exit_status);
2632 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2637 printf("signal=%s", signal_to_string(i->exit_status));
2642 if (i->main_pid > 0 && i->control_pid > 0)
2645 if (i->control_pid > 0) {
2646 _cleanup_free_ char *t = NULL;
2648 printf(" Control: %u", (unsigned) i->control_pid);
2650 get_process_comm(i->control_pid, &t);
2659 printf("\t Status: \"%s\"\n", i->status_text);
2661 if (i->default_control_group &&
2662 (i->main_pid > 0 || i->control_pid > 0 || cg_is_empty_by_spec(i->default_control_group, false) == 0)) {
2665 printf("\t CGroup: %s\n", i->default_control_group);
2667 if (arg_transport != TRANSPORT_SSH) {
2677 if (i->main_pid > 0)
2678 extra[k++] = i->main_pid;
2680 if (i->control_pid > 0)
2681 extra[k++] = i->control_pid;
2683 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, extra, k, flags);
2687 if (i->id && arg_transport != TRANSPORT_SSH) {
2689 show_journal_by_unit(stdout,
2693 i->inactive_exit_timestamp_monotonic,
2698 if (i->need_daemon_reload)
2699 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2700 ansi_highlight_red(true),
2701 ansi_highlight_red(false),
2702 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2705 static void show_unit_help(UnitStatusInfo *i) {
2710 if (!i->documentation) {
2711 log_info("Documentation for %s not known.", i->id);
2715 STRV_FOREACH(p, i->documentation) {
2717 if (startswith(*p, "man:")) {
2720 char *page = NULL, *section = NULL;
2721 const char *args[4] = { "man", NULL, NULL, NULL };
2726 if ((*p)[k-1] == ')')
2727 e = strrchr(*p, '(');
2730 page = strndup((*p) + 4, e - *p - 4);
2736 section = strndup(e + 1, *p + k - e - 2);
2750 log_error("Failed to fork: %m");
2758 execvp(args[0], (char**) args);
2759 log_error("Failed to execute man: %m");
2760 _exit(EXIT_FAILURE);
2766 wait_for_terminate(pid, NULL);
2768 log_info("Can't show: %s", *p);
2772 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2778 switch (dbus_message_iter_get_arg_type(iter)) {
2780 case DBUS_TYPE_STRING: {
2783 dbus_message_iter_get_basic(iter, &s);
2786 if (streq(name, "Id"))
2788 else if (streq(name, "LoadState"))
2790 else if (streq(name, "ActiveState"))
2791 i->active_state = s;
2792 else if (streq(name, "SubState"))
2794 else if (streq(name, "Description"))
2796 else if (streq(name, "FragmentPath"))
2797 i->fragment_path = s;
2798 else if (streq(name, "SourcePath"))
2800 else if (streq(name, "DefaultControlGroup"))
2801 i->default_control_group = s;
2802 else if (streq(name, "StatusText"))
2804 else if (streq(name, "SysFSPath"))
2806 else if (streq(name, "Where"))
2808 else if (streq(name, "What"))
2810 else if (streq(name, "Following"))
2812 else if (streq(name, "UnitFileState"))
2813 i->unit_file_state = s;
2814 else if (streq(name, "Result"))
2821 case DBUS_TYPE_BOOLEAN: {
2824 dbus_message_iter_get_basic(iter, &b);
2826 if (streq(name, "Accept"))
2828 else if (streq(name, "NeedDaemonReload"))
2829 i->need_daemon_reload = b;
2830 else if (streq(name, "ConditionResult"))
2831 i->condition_result = b;
2836 case DBUS_TYPE_UINT32: {
2839 dbus_message_iter_get_basic(iter, &u);
2841 if (streq(name, "MainPID")) {
2843 i->main_pid = (pid_t) u;
2846 } else if (streq(name, "ControlPID"))
2847 i->control_pid = (pid_t) u;
2848 else if (streq(name, "ExecMainPID")) {
2850 i->main_pid = (pid_t) u;
2851 } else if (streq(name, "NAccepted"))
2853 else if (streq(name, "NConnections"))
2854 i->n_connections = u;
2859 case DBUS_TYPE_INT32: {
2862 dbus_message_iter_get_basic(iter, &j);
2864 if (streq(name, "ExecMainCode"))
2865 i->exit_code = (int) j;
2866 else if (streq(name, "ExecMainStatus"))
2867 i->exit_status = (int) j;
2872 case DBUS_TYPE_UINT64: {
2875 dbus_message_iter_get_basic(iter, &u);
2877 if (streq(name, "ExecMainStartTimestamp"))
2878 i->start_timestamp = (usec_t) u;
2879 else if (streq(name, "ExecMainExitTimestamp"))
2880 i->exit_timestamp = (usec_t) u;
2881 else if (streq(name, "ActiveEnterTimestamp"))
2882 i->active_enter_timestamp = (usec_t) u;
2883 else if (streq(name, "InactiveEnterTimestamp"))
2884 i->inactive_enter_timestamp = (usec_t) u;
2885 else if (streq(name, "InactiveExitTimestamp"))
2886 i->inactive_exit_timestamp = (usec_t) u;
2887 else if (streq(name, "InactiveExitTimestampMonotonic"))
2888 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2889 else if (streq(name, "ActiveExitTimestamp"))
2890 i->active_exit_timestamp = (usec_t) u;
2891 else if (streq(name, "ConditionTimestamp"))
2892 i->condition_timestamp = (usec_t) u;
2897 case DBUS_TYPE_ARRAY: {
2899 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2900 startswith(name, "Exec")) {
2901 DBusMessageIter sub;
2903 dbus_message_iter_recurse(iter, &sub);
2904 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2905 ExecStatusInfo *info;
2908 if (!(info = new0(ExecStatusInfo, 1)))
2911 if (!(info->name = strdup(name))) {
2916 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2921 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2923 dbus_message_iter_next(&sub);
2925 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2926 streq(name, "Documentation")) {
2928 DBusMessageIter sub;
2930 dbus_message_iter_recurse(iter, &sub);
2931 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2935 dbus_message_iter_get_basic(&sub, &s);
2937 l = strv_append(i->documentation, s);
2941 strv_free(i->documentation);
2942 i->documentation = l;
2944 dbus_message_iter_next(&sub);
2951 case DBUS_TYPE_STRUCT: {
2953 if (streq(name, "LoadError")) {
2954 DBusMessageIter sub;
2955 const char *n, *message;
2958 dbus_message_iter_recurse(iter, &sub);
2960 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2964 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2968 if (!isempty(message))
2969 i->load_error = message;
2979 static int print_property(const char *name, DBusMessageIter *iter) {
2983 /* This is a low-level property printer, see
2984 * print_status_info() for the nicer output */
2986 if (arg_property && !strv_find(arg_property, name))
2989 switch (dbus_message_iter_get_arg_type(iter)) {
2991 case DBUS_TYPE_STRUCT: {
2992 DBusMessageIter sub;
2993 dbus_message_iter_recurse(iter, &sub);
2995 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2998 dbus_message_iter_get_basic(&sub, &u);
3001 printf("%s=%u\n", name, (unsigned) u);
3003 printf("%s=\n", name);
3006 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
3009 dbus_message_iter_get_basic(&sub, &s);
3011 if (arg_all || s[0])
3012 printf("%s=%s\n", name, s);
3015 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
3016 const char *a = NULL, *b = NULL;
3018 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
3019 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
3021 if (arg_all || !isempty(a) || !isempty(b))
3022 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
3030 case DBUS_TYPE_ARRAY:
3032 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
3033 DBusMessageIter sub, sub2;
3035 dbus_message_iter_recurse(iter, &sub);
3036 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3040 dbus_message_iter_recurse(&sub, &sub2);
3042 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
3043 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
3044 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
3046 dbus_message_iter_next(&sub);
3051 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
3052 DBusMessageIter sub, sub2;
3054 dbus_message_iter_recurse(iter, &sub);
3055 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3056 const char *type, *path;
3058 dbus_message_iter_recurse(&sub, &sub2);
3060 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
3061 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
3062 printf("%s=%s\n", type, path);
3064 dbus_message_iter_next(&sub);
3069 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
3070 DBusMessageIter sub, sub2;
3072 dbus_message_iter_recurse(iter, &sub);
3073 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3075 uint64_t value, next_elapse;
3077 dbus_message_iter_recurse(&sub, &sub2);
3079 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
3080 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
3081 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
3082 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
3084 printf("%s={ value=%s ; next_elapse=%s }\n",
3086 format_timespan(timespan1, sizeof(timespan1), value),
3087 format_timespan(timespan2, sizeof(timespan2), next_elapse));
3090 dbus_message_iter_next(&sub);
3095 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
3096 DBusMessageIter sub, sub2;
3098 dbus_message_iter_recurse(iter, &sub);
3099 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3100 const char *controller, *attr, *value;
3102 dbus_message_iter_recurse(&sub, &sub2);
3104 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
3105 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
3106 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
3108 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
3114 dbus_message_iter_next(&sub);
3119 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
3120 DBusMessageIter sub;
3122 dbus_message_iter_recurse(iter, &sub);
3123 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
3124 ExecStatusInfo info;
3127 if (exec_status_info_deserialize(&sub, &info) >= 0) {
3128 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
3131 t = strv_join(info.argv, " ");
3133 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
3137 yes_no(info.ignore),
3138 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
3139 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
3140 (unsigned) info. pid,
3141 sigchld_code_to_string(info.code),
3143 info.code == CLD_EXITED ? "" : "/",
3144 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
3150 strv_free(info.argv);
3152 dbus_message_iter_next(&sub);
3161 if (generic_print_property(name, iter, arg_all) > 0)
3165 printf("%s=[unprintable]\n", name);
3170 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
3171 _cleanup_free_ DBusMessage *reply = NULL;
3172 const char *interface = "";
3174 DBusMessageIter iter, sub, sub2, sub3;
3175 UnitStatusInfo info;
3183 r = bus_method_call_with_reply(
3185 "org.freedesktop.systemd1",
3187 "org.freedesktop.DBus.Properties",
3191 DBUS_TYPE_STRING, &interface,
3196 if (!dbus_message_iter_init(reply, &iter) ||
3197 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3198 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
3199 log_error("Failed to parse reply.");
3203 dbus_message_iter_recurse(&iter, &sub);
3210 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3213 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_DICT_ENTRY);
3214 dbus_message_iter_recurse(&sub, &sub2);
3216 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
3217 dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
3218 log_error("Failed to parse reply.");
3222 dbus_message_iter_recurse(&sub2, &sub3);
3224 if (show_properties)
3225 r = print_property(name, &sub3);
3227 r = status_property(name, &sub3, &info);
3229 log_error("Failed to parse reply.");
3233 dbus_message_iter_next(&sub);
3238 if (!show_properties) {
3239 if (streq(verb, "help"))
3240 show_unit_help(&info);
3242 print_status_info(&info);
3245 strv_free(info.documentation);
3247 if (!streq_ptr(info.active_state, "active") &&
3248 !streq_ptr(info.active_state, "reloading") &&
3249 streq(verb, "status"))
3250 /* According to LSB: "program not running" */
3253 while ((p = info.exec)) {
3254 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
3255 exec_status_info_free(p);
3261 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
3262 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3263 const char *path = NULL;
3267 dbus_error_init(&error);
3269 r = bus_method_call_with_reply(
3271 "org.freedesktop.systemd1",
3272 "/org/freedesktop/systemd1",
3273 "org.freedesktop.systemd1.Manager",
3277 DBUS_TYPE_UINT32, &pid,
3282 if (!dbus_message_get_args(reply, &error,
3283 DBUS_TYPE_OBJECT_PATH, &path,
3284 DBUS_TYPE_INVALID)) {
3285 log_error("Failed to parse reply: %s", bus_error_message(&error));
3290 r = show_one(verb, bus, path, false, new_line);
3293 dbus_error_free(&error);
3298 static int show(DBusConnection *bus, char **args) {
3300 bool show_properties, new_line = false;
3306 show_properties = streq(args[0], "show");
3308 if (show_properties)
3309 pager_open_if_enabled();
3311 /* If no argument is specified inspect the manager itself */
3313 if (show_properties && strv_length(args) <= 1)
3314 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
3316 STRV_FOREACH(name, args+1) {
3319 if (safe_atou32(*name, &id) < 0) {
3320 _cleanup_free_ char *p = NULL, *n = NULL;
3321 /* Interpret as unit name */
3323 n = unit_name_mangle(*name);
3327 p = unit_dbus_path_from_name(n);
3331 r = show_one(args[0], bus, p, show_properties, &new_line);
3335 } else if (show_properties) {
3336 _cleanup_free_ char *p = NULL;
3338 /* Interpret as job id */
3339 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
3342 r = show_one(args[0], bus, p, show_properties, &new_line);
3347 /* Interpret as PID */
3348 r = show_one_by_pid(args[0], bus, id, &new_line);
3357 static int dump(DBusConnection *bus, char **args) {
3358 _cleanup_free_ DBusMessage *reply = NULL;
3363 dbus_error_init(&error);
3365 pager_open_if_enabled();
3367 r = bus_method_call_with_reply(
3369 "org.freedesktop.systemd1",
3370 "/org/freedesktop/systemd1",
3371 "org.freedesktop.systemd1.Manager",
3379 if (!dbus_message_get_args(reply, &error,
3380 DBUS_TYPE_STRING, &text,
3381 DBUS_TYPE_INVALID)) {
3382 log_error("Failed to parse reply: %s", bus_error_message(&error));
3383 dbus_error_free(&error);
3387 fputs(text, stdout);
3391 static int snapshot(DBusConnection *bus, char **args) {
3392 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3395 dbus_bool_t cleanup = FALSE;
3396 DBusMessageIter iter, sub;
3399 *interface = "org.freedesktop.systemd1.Unit",
3401 _cleanup_free_ char *n = NULL;
3403 dbus_error_init(&error);
3405 if (strv_length(args) > 1)
3406 n = snapshot_name_mangle(args[1]);
3412 r = bus_method_call_with_reply (
3414 "org.freedesktop.systemd1",
3415 "/org/freedesktop/systemd1",
3416 "org.freedesktop.systemd1.Manager",
3420 DBUS_TYPE_STRING, &n,
3421 DBUS_TYPE_BOOLEAN, &cleanup,
3426 if (!dbus_message_get_args(reply, &error,
3427 DBUS_TYPE_OBJECT_PATH, &path,
3428 DBUS_TYPE_INVALID)) {
3429 log_error("Failed to parse reply: %s", bus_error_message(&error));
3430 dbus_error_free(&error);
3434 dbus_message_unref(reply);
3437 r = bus_method_call_with_reply (
3439 "org.freedesktop.systemd1",
3441 "org.freedesktop.DBus.Properties",
3445 DBUS_TYPE_STRING, &interface,
3446 DBUS_TYPE_STRING, &property,
3451 if (!dbus_message_iter_init(reply, &iter) ||
3452 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3453 log_error("Failed to parse reply.");
3457 dbus_message_iter_recurse(&iter, &sub);
3459 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3460 log_error("Failed to parse reply.");
3464 dbus_message_iter_get_basic(&sub, &id);
3472 static int delete_snapshot(DBusConnection *bus, char **args) {
3477 STRV_FOREACH(name, args+1) {
3478 _cleanup_free_ char *n = NULL;
3481 n = snapshot_name_mangle(*name);
3485 r = bus_method_call_with_reply(
3487 "org.freedesktop.systemd1",
3488 "/org/freedesktop/systemd1",
3489 "org.freedesktop.systemd1.Manager",
3493 DBUS_TYPE_STRING, &n,
3502 static int daemon_reload(DBusConnection *bus, char **args) {
3507 if (arg_action == ACTION_RELOAD)
3509 else if (arg_action == ACTION_REEXEC)
3510 method = "Reexecute";
3512 assert(arg_action == ACTION_SYSTEMCTL);
3515 streq(args[0], "clear-jobs") ||
3516 streq(args[0], "cancel") ? "ClearJobs" :
3517 streq(args[0], "daemon-reexec") ? "Reexecute" :
3518 streq(args[0], "reset-failed") ? "ResetFailed" :
3519 streq(args[0], "halt") ? "Halt" :
3520 streq(args[0], "poweroff") ? "PowerOff" :
3521 streq(args[0], "reboot") ? "Reboot" :
3522 streq(args[0], "kexec") ? "KExec" :
3523 streq(args[0], "exit") ? "Exit" :
3524 /* "daemon-reload" */ "Reload";
3527 r = bus_method_call_with_reply(
3529 "org.freedesktop.systemd1",
3530 "/org/freedesktop/systemd1",
3531 "org.freedesktop.systemd1.Manager",
3537 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
3538 /* There's always a fallback possible for
3539 * legacy actions. */
3541 else if (r == -ETIMEDOUT && streq(method, "Reexecute"))
3542 /* On reexecution, we expect a disconnect, not
3546 log_error("Failed to issue method call: %s", bus_error_message(&error));
3548 dbus_error_free(&error);
3552 static int reset_failed(DBusConnection *bus, char **args) {
3556 if (strv_length(args) <= 1)
3557 return daemon_reload(bus, args);
3559 STRV_FOREACH(name, args+1) {
3560 _cleanup_free_ char *n;
3562 n = unit_name_mangle(*name);
3566 r = bus_method_call_with_reply(
3568 "org.freedesktop.systemd1",
3569 "/org/freedesktop/systemd1",
3570 "org.freedesktop.systemd1.Manager",
3574 DBUS_TYPE_STRING, &n,
3583 static int show_enviroment(DBusConnection *bus, char **args) {
3584 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
3585 DBusMessageIter iter, sub, sub2;
3588 *interface = "org.freedesktop.systemd1.Manager",
3589 *property = "Environment";
3591 pager_open_if_enabled();
3593 r = bus_method_call_with_reply(
3595 "org.freedesktop.systemd1",
3596 "/org/freedesktop/systemd1",
3597 "org.freedesktop.DBus.Properties",
3601 DBUS_TYPE_STRING, &interface,
3602 DBUS_TYPE_STRING, &property,
3607 if (!dbus_message_iter_init(reply, &iter) ||
3608 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3609 log_error("Failed to parse reply.");
3613 dbus_message_iter_recurse(&iter, &sub);
3615 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3616 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3617 log_error("Failed to parse reply.");
3621 dbus_message_iter_recurse(&sub, &sub2);
3623 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3626 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3627 log_error("Failed to parse reply.");
3631 dbus_message_iter_get_basic(&sub2, &text);
3634 dbus_message_iter_next(&sub2);
3640 static int switch_root(DBusConnection *bus, char **args) {
3643 _cleanup_free_ char *init = NULL;
3645 l = strv_length(args);
3646 if (l < 2 || l > 3) {
3647 log_error("Wrong number of arguments.");
3654 init = strdup(args[2]);
3656 parse_env_file("/proc/cmdline", WHITESPACE,
3666 log_debug("switching root - root: %s; init: %s", root, init);
3668 return bus_method_call_with_reply(
3670 "org.freedesktop.systemd1",
3671 "/org/freedesktop/systemd1",
3672 "org.freedesktop.systemd1.Manager",
3676 DBUS_TYPE_STRING, &root,
3677 DBUS_TYPE_STRING, &init,
3681 static int set_environment(DBusConnection *bus, char **args) {
3682 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
3685 DBusMessageIter iter;
3691 dbus_error_init(&error);
3693 method = streq(args[0], "set-environment")
3695 : "UnsetEnvironment";
3697 m = dbus_message_new_method_call(
3698 "org.freedesktop.systemd1",
3699 "/org/freedesktop/systemd1",
3700 "org.freedesktop.systemd1.Manager",
3705 dbus_message_iter_init_append(m, &iter);
3707 r = bus_append_strv_iter(&iter, args + 1);
3711 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3713 log_error("Failed to issue method call: %s", bus_error_message(&error));
3714 dbus_error_free(&error);
3721 static int enable_sysv_units(char **args) {
3724 #if defined(HAVE_SYSV_COMPAT) && defined(HAVE_CHKCONFIG)
3725 const char *verb = args[0];
3726 unsigned f = 1, t = 1;
3729 if (arg_scope != UNIT_FILE_SYSTEM)
3732 if (!streq(verb, "enable") &&
3733 !streq(verb, "disable") &&
3734 !streq(verb, "is-enabled"))
3737 /* Processes all SysV units, and reshuffles the array so that
3738 * afterwards only the native units remain */
3741 r = lookup_paths_init(&paths, SYSTEMD_SYSTEM, false, NULL, NULL, NULL);
3746 for (f = 1; args[f]; f++) {
3749 bool found_native = false, found_sysv;
3751 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3752 char **k, *l, *q = NULL;
3759 if (!endswith(name, ".service"))
3762 if (path_is_absolute(name))
3765 STRV_FOREACH(k, paths.unit_path) {
3768 if (!isempty(arg_root))
3769 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3771 asprintf(&p, "%s/%s", *k, name);
3778 found_native = access(p, F_OK) >= 0;
3789 if (!isempty(arg_root))
3790 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3792 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3798 p[strlen(p) - sizeof(".service") + 1] = 0;
3799 found_sysv = access(p, F_OK) >= 0;
3806 /* Mark this entry, so that we don't try enabling it as native unit */
3807 args[f] = (char*) "";
3809 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
3811 if (!isempty(arg_root))
3812 argv[c++] = q = strappend("--root=", arg_root);
3814 argv[c++] = path_get_file_name(p);
3816 streq(verb, "enable") ? "on" :
3817 streq(verb, "disable") ? "off" : "--level=5";
3820 l = strv_join((char**)argv, " ");
3828 log_info("Executing %s", l);
3833 log_error("Failed to fork: %m");
3838 } else if (pid == 0) {
3841 execv(argv[0], (char**) argv);
3842 _exit(EXIT_FAILURE);
3848 j = wait_for_terminate(pid, &status);
3850 log_error("Failed to wait for child: %s", strerror(-r));
3855 if (status.si_code == CLD_EXITED) {
3856 if (streq(verb, "is-enabled")) {
3857 if (status.si_status == 0) {
3866 } else if (status.si_status != 0) {
3877 lookup_paths_free(&paths);
3879 /* Drop all SysV units */
3880 for (f = 1, t = 1; args[f]; f++) {
3882 if (isempty(args[f]))
3885 args[t++] = args[f];
3894 static int mangle_names(char **original_names, char ***mangled_names) {
3895 char **i, **l, **name;
3897 l = new(char*, strv_length(original_names) + 1);
3902 STRV_FOREACH(name, original_names) {
3904 /* When enabling units qualified path names are OK,
3905 * too, hence allow them explicitly. */
3910 *i = unit_name_mangle(*name);
3926 static int enable_unit(DBusConnection *bus, char **args) {
3927 const char *verb = args[0];
3928 UnitFileChange *changes = NULL;
3929 unsigned n_changes = 0, i;
3930 int carries_install_info = -1;
3931 DBusMessage *m = NULL, *reply = NULL;
3934 char **mangled_names = NULL;
3936 r = enable_sysv_units(args);
3943 dbus_error_init(&error);
3945 if (!bus || avoid_bus()) {
3946 if (streq(verb, "enable")) {
3947 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3948 carries_install_info = r;
3949 } else if (streq(verb, "disable"))
3950 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3951 else if (streq(verb, "reenable")) {
3952 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3953 carries_install_info = r;
3954 } else if (streq(verb, "link"))
3955 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3956 else if (streq(verb, "preset")) {
3957 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3958 carries_install_info = r;
3959 } else if (streq(verb, "mask"))
3960 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3961 else if (streq(verb, "unmask"))
3962 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3964 assert_not_reached("Unknown verb");
3967 log_error("Operation failed: %s", strerror(-r));
3972 for (i = 0; i < n_changes; i++) {
3973 if (changes[i].type == UNIT_FILE_SYMLINK)
3974 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
3976 log_info("rm '%s'", changes[i].path);
3983 bool send_force = true, expect_carries_install_info = false;
3985 DBusMessageIter iter, sub, sub2;
3987 if (streq(verb, "enable")) {
3988 method = "EnableUnitFiles";
3989 expect_carries_install_info = true;
3990 } else if (streq(verb, "disable")) {
3991 method = "DisableUnitFiles";
3993 } else if (streq(verb, "reenable")) {
3994 method = "ReenableUnitFiles";
3995 expect_carries_install_info = true;
3996 } else if (streq(verb, "link"))
3997 method = "LinkUnitFiles";
3998 else if (streq(verb, "preset")) {
3999 method = "PresetUnitFiles";
4000 expect_carries_install_info = true;
4001 } else if (streq(verb, "mask"))
4002 method = "MaskUnitFiles";
4003 else if (streq(verb, "unmask")) {
4004 method = "UnmaskUnitFiles";
4007 assert_not_reached("Unknown verb");
4009 m = dbus_message_new_method_call(
4010 "org.freedesktop.systemd1",
4011 "/org/freedesktop/systemd1",
4012 "org.freedesktop.systemd1.Manager",
4019 dbus_message_iter_init_append(m, &iter);
4021 r = mangle_names(args+1, &mangled_names);
4025 r = bus_append_strv_iter(&iter, mangled_names);
4027 log_error("Failed to append unit files.");
4032 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
4033 log_error("Failed to append runtime boolean.");
4041 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
4042 log_error("Failed to append force boolean.");
4048 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
4050 log_error("Failed to issue method call: %s", bus_error_message(&error));
4055 if (!dbus_message_iter_init(reply, &iter)) {
4056 log_error("Failed to initialize iterator.");
4060 if (expect_carries_install_info) {
4061 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
4063 log_error("Failed to parse reply.");
4067 carries_install_info = b;
4070 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
4071 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
4072 log_error("Failed to parse reply.");
4077 dbus_message_iter_recurse(&iter, &sub);
4078 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
4079 const char *type, *path, *source;
4081 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
4082 log_error("Failed to parse reply.");
4087 dbus_message_iter_recurse(&sub, &sub2);
4089 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
4090 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
4091 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
4092 log_error("Failed to parse reply.");
4098 if (streq(type, "symlink"))
4099 log_info("ln -s '%s' '%s'", source, path);
4101 log_info("rm '%s'", path);
4104 dbus_message_iter_next(&sub);
4107 /* Try to reload if enabeld */
4109 r = daemon_reload(bus, args);
4112 if (carries_install_info == 0)
4114 "The unit files have no [Install] section. They are not meant to be enabled\n"
4115 "using systemctl.\n"
4116 "Possible reasons for having this kind of units are:\n"
4117 "1) A unit may be statically enabled by being symlinked from another unit's\n"
4118 " .wants/ or .requires/ directory.\n"
4119 "2) A unit's purpose may be to act as a helper for some other unit which has\n"
4120 " a requirement dependency on it.\n"
4121 "3) A unit may be started when needed via activation (socket, path, timer,\n"
4122 " D-Bus, udev, scripted systemctl call, ...).\n");
4126 dbus_message_unref(m);
4129 dbus_message_unref(reply);
4131 unit_file_changes_free(changes, n_changes);
4133 dbus_error_free(&error);
4135 strv_free(mangled_names);
4140 static int unit_is_enabled(DBusConnection *bus, char **args) {
4143 DBusMessage *reply = NULL;
4147 dbus_error_init(&error);
4149 r = enable_sysv_units(args);
4155 if (!bus || avoid_bus()) {
4157 STRV_FOREACH(name, args+1) {
4158 UnitFileState state;
4160 state = unit_file_get_state(arg_scope, arg_root, *name);
4166 if (state == UNIT_FILE_ENABLED ||
4167 state == UNIT_FILE_ENABLED_RUNTIME ||
4168 state == UNIT_FILE_STATIC)
4172 puts(unit_file_state_to_string(state));
4176 STRV_FOREACH(name, args+1) {
4179 r = bus_method_call_with_reply (
4181 "org.freedesktop.systemd1",
4182 "/org/freedesktop/systemd1",
4183 "org.freedesktop.systemd1.Manager",
4187 DBUS_TYPE_STRING, name,
4192 if (!dbus_message_get_args(reply, &error,
4193 DBUS_TYPE_STRING, &s,
4194 DBUS_TYPE_INVALID)) {
4195 log_error("Failed to parse reply: %s", bus_error_message(&error));
4200 dbus_message_unref(reply);
4203 if (streq(s, "enabled") ||
4204 streq(s, "enabled-runtime") ||
4213 r = enabled ? 0 : 1;
4217 dbus_message_unref(reply);
4219 dbus_error_free(&error);
4223 static int systemctl_help(void) {
4225 pager_open_if_enabled();
4227 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4228 "Query or send control commands to the systemd manager.\n\n"
4229 " -h --help Show this help\n"
4230 " --version Show package version\n"
4231 " -t --type=TYPE List only units of a particular type\n"
4232 " -p --property=NAME Show only properties by this name\n"
4233 " -a --all Show all units/properties, including dead/empty ones\n"
4234 " --failed Show only failed units\n"
4235 " --full Don't ellipsize unit names on output\n"
4236 " --fail When queueing a new job, fail if conflicting jobs are\n"
4238 " --ignore-dependencies\n"
4239 " When queueing a new job, ignore all its dependencies\n"
4240 " -i --ignore-inhibitors\n"
4241 " When shutting down or sleeping, ignore inhibitors\n"
4242 " --kill-who=WHO Who to send signal to\n"
4243 " -s --signal=SIGNAL Which signal to send\n"
4244 " -H --host=[USER@]HOST\n"
4245 " Show information for remote host\n"
4246 " -P --privileged Acquire privileges before execution\n"
4247 " -q --quiet Suppress output\n"
4248 " --no-block Do not wait until operation finished\n"
4249 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4250 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4252 " --no-legend Do not print a legend (column headers and hints)\n"
4253 " --no-pager Do not pipe output into a pager\n"
4254 " --no-ask-password\n"
4255 " Do not ask for system passwords\n"
4256 " --order When generating graph for dot, show only order\n"
4257 " --require When generating graph for dot, show only requirement\n"
4258 " --system Connect to system manager\n"
4259 " --user Connect to user service manager\n"
4260 " --global Enable/disable unit files globally\n"
4261 " -f --force When enabling unit files, override existing symlinks\n"
4262 " When shutting down, execute action immediately\n"
4263 " --root=PATH Enable unit files in the specified root directory\n"
4264 " --runtime Enable unit files only temporarily until next reboot\n"
4265 " -n --lines=INTEGER Journal entries to show\n"
4266 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
4267 " verbose, export, json, json-pretty, json-sse, cat)\n\n"
4269 " list-units List loaded units\n"
4270 " start [NAME...] Start (activate) one or more units\n"
4271 " stop [NAME...] Stop (deactivate) one or more units\n"
4272 " reload [NAME...] Reload one or more units\n"
4273 " restart [NAME...] Start or restart one or more units\n"
4274 " try-restart [NAME...] Restart one or more units if active\n"
4275 " reload-or-restart [NAME...] Reload one or more units if possible,\n"
4276 " otherwise start or restart\n"
4277 " reload-or-try-restart [NAME...] Reload one or more units if possible,\n"
4278 " otherwise restart if active\n"
4279 " isolate [NAME] Start one unit and stop all others\n"
4280 " kill [NAME...] Send signal to processes of a unit\n"
4281 " is-active [NAME...] Check whether units are active\n"
4282 " is-failed [NAME...] Check whether units are failed\n"
4283 " status [NAME...|PID...] Show runtime status of one or more units\n"
4284 " show [NAME...|JOB...] Show properties of one or more\n"
4285 " units/jobs or the manager\n"
4286 " help [NAME...|PID...] Show manual for one or more units\n"
4287 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4289 " set-cgroup [NAME] [CGROUP...] Add unit to a control group\n"
4290 " unset-cgroup [NAME] [CGROUP...] Remove unit from a control group\n"
4291 " set-cgroup-attr [NAME] [ATTR] [VALUE] ...\n"
4292 " Set control group attribute\n"
4293 " unset-cgroup-attr [NAME] [ATTR...]\n"
4294 " Unset control group attribute\n"
4295 " load [NAME...] Load one or more units\n"
4296 " list-dependencies [NAME] Recursively show units which are required\n"
4297 " or wanted by this unit\n\n"
4298 "Unit File Commands:\n"
4299 " list-unit-files List installed unit files\n"
4300 " enable [NAME...] Enable one or more unit files\n"
4301 " disable [NAME...] Disable one or more unit files\n"
4302 " reenable [NAME...] Reenable one or more unit files\n"
4303 " preset [NAME...] Enable/disable one or more unit files\n"
4304 " based on preset configuration\n"
4305 " mask [NAME...] Mask one or more units\n"
4306 " unmask [NAME...] Unmask one or more units\n"
4307 " link [PATH...] Link one or more units files into\n"
4308 " the search path\n"
4309 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
4311 " list-jobs List jobs\n"
4312 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
4313 "Status Commands:\n"
4314 " dump Dump server status\n"
4315 " dot Dump dependency graph for dot(1)\n\n"
4316 "Snapshot Commands:\n"
4317 " snapshot [NAME] Create a snapshot\n"
4318 " delete [NAME...] Remove one or more snapshots\n\n"
4319 "Environment Commands:\n"
4320 " show-environment Dump environment\n"
4321 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4322 " unset-environment [NAME...] Unset one or more environment variables\n\n"
4323 "Manager Lifecycle Commands:\n"
4324 " daemon-reload Reload systemd manager configuration\n"
4325 " daemon-reexec Reexecute systemd manager\n\n"
4326 "System Commands:\n"
4327 " default Enter system default mode\n"
4328 " rescue Enter system rescue mode\n"
4329 " emergency Enter system emergency mode\n"
4330 " halt Shut down and halt the system\n"
4331 " poweroff Shut down and power-off the system\n"
4332 " reboot Shut down and reboot the system\n"
4333 " kexec Shut down and reboot the system with kexec\n"
4334 " exit Request user instance exit\n"
4335 " switch-root [ROOT] [INIT] Change to a different root file system\n"
4336 " suspend Suspend the system\n"
4337 " hibernate Hibernate the system\n"
4338 " hybrid-sleep Hibernate and suspend the system\n",
4339 program_invocation_short_name);
4344 static int halt_help(void) {
4346 printf("%s [OPTIONS...]\n\n"
4347 "%s the system.\n\n"
4348 " --help Show this help\n"
4349 " --halt Halt the machine\n"
4350 " -p --poweroff Switch off the machine\n"
4351 " --reboot Reboot the machine\n"
4352 " -f --force Force immediate halt/power-off/reboot\n"
4353 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4354 " -d --no-wtmp Don't write wtmp record\n"
4355 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4356 program_invocation_short_name,
4357 arg_action == ACTION_REBOOT ? "Reboot" :
4358 arg_action == ACTION_POWEROFF ? "Power off" :
4364 static int shutdown_help(void) {
4366 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4367 "Shut down the system.\n\n"
4368 " --help Show this help\n"
4369 " -H --halt Halt the machine\n"
4370 " -P --poweroff Power-off the machine\n"
4371 " -r --reboot Reboot the machine\n"
4372 " -h Equivalent to --poweroff, overridden by --halt\n"
4373 " -k Don't halt/power-off/reboot, just send warnings\n"
4374 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4375 " -c Cancel a pending shutdown\n",
4376 program_invocation_short_name);
4381 static int telinit_help(void) {
4383 printf("%s [OPTIONS...] {COMMAND}\n\n"
4384 "Send control commands to the init daemon.\n\n"
4385 " --help Show this help\n"
4386 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4388 " 0 Power-off the machine\n"
4389 " 6 Reboot the machine\n"
4390 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4391 " 1, s, S Enter rescue mode\n"
4392 " q, Q Reload init daemon configuration\n"
4393 " u, U Reexecute init daemon\n",
4394 program_invocation_short_name);
4399 static int runlevel_help(void) {
4401 printf("%s [OPTIONS...]\n\n"
4402 "Prints the previous and current runlevel of the init system.\n\n"
4403 " --help Show this help\n",
4404 program_invocation_short_name);
4409 static int help_types(void) {
4412 puts("Available unit types:");
4413 for(i = UNIT_SERVICE; i < _UNIT_TYPE_MAX; i++)
4414 if (unit_type_table[i])
4415 puts(unit_type_table[i]);
4417 puts("\nAvailable unit load states: ");
4418 for(i = UNIT_STUB; i < _UNIT_LOAD_STATE_MAX; i++)
4419 if (unit_type_table[i])
4420 puts(unit_load_state_table[i]);
4425 static int systemctl_parse_argv(int argc, char *argv[]) {
4429 ARG_IGNORE_DEPENDENCIES,
4444 ARG_NO_ASK_PASSWORD,
4450 static const struct option options[] = {
4451 { "help", no_argument, NULL, 'h' },
4452 { "version", no_argument, NULL, ARG_VERSION },
4453 { "type", required_argument, NULL, 't' },
4454 { "property", required_argument, NULL, 'p' },
4455 { "all", no_argument, NULL, 'a' },
4456 { "failed", no_argument, NULL, ARG_FAILED },
4457 { "full", no_argument, NULL, ARG_FULL },
4458 { "fail", no_argument, NULL, ARG_FAIL },
4459 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4460 { "ignore-inhibitors", no_argument, NULL, 'i' },
4461 { "user", no_argument, NULL, ARG_USER },
4462 { "system", no_argument, NULL, ARG_SYSTEM },
4463 { "global", no_argument, NULL, ARG_GLOBAL },
4464 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4465 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4466 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4467 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4468 { "quiet", no_argument, NULL, 'q' },
4469 { "order", no_argument, NULL, ARG_ORDER },
4470 { "require", no_argument, NULL, ARG_REQUIRE },
4471 { "root", required_argument, NULL, ARG_ROOT },
4472 { "force", no_argument, NULL, ARG_FORCE },
4473 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4474 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4475 { "signal", required_argument, NULL, 's' },
4476 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4477 { "host", required_argument, NULL, 'H' },
4478 { "privileged",no_argument, NULL, 'P' },
4479 { "runtime", no_argument, NULL, ARG_RUNTIME },
4480 { "lines", required_argument, NULL, 'n' },
4481 { "output", required_argument, NULL, 'o' },
4482 { NULL, 0, NULL, 0 }
4490 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:i", options, NULL)) >= 0) {
4499 puts(PACKAGE_STRING);
4500 puts(SYSTEMD_FEATURES);
4504 if (streq(optarg, "help")) {
4509 if (unit_type_from_string(optarg) >= 0) {
4513 if (unit_load_state_from_string(optarg) >= 0) {
4514 arg_load_state = optarg;
4517 log_error("Unkown unit type or load state '%s'.",
4519 log_info("Use -t help to see a list of allowed values.");
4524 if (!(l = strv_append(arg_property, optarg)))
4527 strv_free(arg_property);
4530 /* If the user asked for a particular
4531 * property, show it to him, even if it is
4542 arg_job_mode = "fail";
4545 case ARG_IGNORE_DEPENDENCIES:
4546 arg_job_mode = "ignore-dependencies";
4550 arg_scope = UNIT_FILE_USER;
4554 arg_scope = UNIT_FILE_SYSTEM;
4558 arg_scope = UNIT_FILE_GLOBAL;
4562 arg_no_block = true;
4566 arg_no_legend = true;
4570 arg_no_pager = true;
4578 arg_dot = DOT_ORDER;
4582 arg_dot = DOT_REQUIRE;
4610 arg_no_reload = true;
4614 arg_kill_who = optarg;
4618 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4619 log_error("Failed to parse signal string %s.", optarg);
4624 case ARG_NO_ASK_PASSWORD:
4625 arg_ask_password = false;
4629 arg_transport = TRANSPORT_POLKIT;
4633 arg_transport = TRANSPORT_SSH;
4642 if (safe_atou(optarg, &arg_lines) < 0) {
4643 log_error("Failed to parse lines '%s'", optarg);
4649 arg_output = output_mode_from_string(optarg);
4650 if (arg_output < 0) {
4651 log_error("Unknown output '%s'.", optarg);
4657 arg_ignore_inhibitors = true;
4664 log_error("Unknown option code '%c'.", c);
4669 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4670 log_error("Cannot access user instance remotely.");
4677 static int halt_parse_argv(int argc, char *argv[]) {
4686 static const struct option options[] = {
4687 { "help", no_argument, NULL, ARG_HELP },
4688 { "halt", no_argument, NULL, ARG_HALT },
4689 { "poweroff", no_argument, NULL, 'p' },
4690 { "reboot", no_argument, NULL, ARG_REBOOT },
4691 { "force", no_argument, NULL, 'f' },
4692 { "wtmp-only", no_argument, NULL, 'w' },
4693 { "no-wtmp", no_argument, NULL, 'd' },
4694 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4695 { NULL, 0, NULL, 0 }
4703 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4704 if (runlevel == '0' || runlevel == '6')
4707 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4715 arg_action = ACTION_HALT;
4719 if (arg_action != ACTION_REBOOT)
4720 arg_action = ACTION_POWEROFF;
4724 arg_action = ACTION_REBOOT;
4746 /* Compatibility nops */
4753 log_error("Unknown option code '%c'.", c);
4758 if (optind < argc) {
4759 log_error("Too many arguments.");
4766 static int parse_time_spec(const char *t, usec_t *_u) {
4770 if (streq(t, "now"))
4772 else if (!strchr(t, ':')) {
4775 if (safe_atou64(t, &u) < 0)
4778 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4787 hour = strtol(t, &e, 10);
4788 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4791 minute = strtol(e+1, &e, 10);
4792 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4795 n = now(CLOCK_REALTIME);
4796 s = (time_t) (n / USEC_PER_SEC);
4799 assert_se(localtime_r(&s, &tm));
4801 tm.tm_hour = (int) hour;
4802 tm.tm_min = (int) minute;
4805 assert_se(s = mktime(&tm));
4807 *_u = (usec_t) s * USEC_PER_SEC;
4810 *_u += USEC_PER_DAY;
4816 static int shutdown_parse_argv(int argc, char *argv[]) {
4823 static const struct option options[] = {
4824 { "help", no_argument, NULL, ARG_HELP },
4825 { "halt", no_argument, NULL, 'H' },
4826 { "poweroff", no_argument, NULL, 'P' },
4827 { "reboot", no_argument, NULL, 'r' },
4828 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4829 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4830 { NULL, 0, NULL, 0 }
4838 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4846 arg_action = ACTION_HALT;
4850 arg_action = ACTION_POWEROFF;
4855 arg_action = ACTION_KEXEC;
4857 arg_action = ACTION_REBOOT;
4861 arg_action = ACTION_KEXEC;
4865 if (arg_action != ACTION_HALT)
4866 arg_action = ACTION_POWEROFF;
4879 /* Compatibility nops */
4883 arg_action = ACTION_CANCEL_SHUTDOWN;
4890 log_error("Unknown option code '%c'.", c);
4895 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
4896 r = parse_time_spec(argv[optind], &arg_when);
4898 log_error("Failed to parse time specification: %s", argv[optind]);
4902 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4904 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
4905 /* No time argument for shutdown cancel */
4906 arg_wall = argv + optind;
4907 else if (argc > optind + 1)
4908 /* We skip the time argument */
4909 arg_wall = argv + optind + 1;
4916 static int telinit_parse_argv(int argc, char *argv[]) {
4923 static const struct option options[] = {
4924 { "help", no_argument, NULL, ARG_HELP },
4925 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4926 { NULL, 0, NULL, 0 }
4929 static const struct {
4933 { '0', ACTION_POWEROFF },
4934 { '6', ACTION_REBOOT },
4935 { '1', ACTION_RESCUE },
4936 { '2', ACTION_RUNLEVEL2 },
4937 { '3', ACTION_RUNLEVEL3 },
4938 { '4', ACTION_RUNLEVEL4 },
4939 { '5', ACTION_RUNLEVEL5 },
4940 { 's', ACTION_RESCUE },
4941 { 'S', ACTION_RESCUE },
4942 { 'q', ACTION_RELOAD },
4943 { 'Q', ACTION_RELOAD },
4944 { 'u', ACTION_REEXEC },
4945 { 'U', ACTION_REEXEC }
4954 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4969 log_error("Unknown option code '%c'.", c);
4974 if (optind >= argc) {
4979 if (optind + 1 < argc) {
4980 log_error("Too many arguments.");
4984 if (strlen(argv[optind]) != 1) {
4985 log_error("Expected single character argument.");
4989 for (i = 0; i < ELEMENTSOF(table); i++)
4990 if (table[i].from == argv[optind][0])
4993 if (i >= ELEMENTSOF(table)) {
4994 log_error("Unknown command '%s'.", argv[optind]);
4998 arg_action = table[i].to;
5005 static int runlevel_parse_argv(int argc, char *argv[]) {
5011 static const struct option options[] = {
5012 { "help", no_argument, NULL, ARG_HELP },
5013 { NULL, 0, NULL, 0 }
5021 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5032 log_error("Unknown option code '%c'.", c);
5037 if (optind < argc) {
5038 log_error("Too many arguments.");
5045 static int parse_argv(int argc, char *argv[]) {
5049 if (program_invocation_short_name) {
5051 if (strstr(program_invocation_short_name, "halt")) {
5052 arg_action = ACTION_HALT;
5053 return halt_parse_argv(argc, argv);
5054 } else if (strstr(program_invocation_short_name, "poweroff")) {
5055 arg_action = ACTION_POWEROFF;
5056 return halt_parse_argv(argc, argv);
5057 } else if (strstr(program_invocation_short_name, "reboot")) {
5059 arg_action = ACTION_KEXEC;
5061 arg_action = ACTION_REBOOT;
5062 return halt_parse_argv(argc, argv);
5063 } else if (strstr(program_invocation_short_name, "shutdown")) {
5064 arg_action = ACTION_POWEROFF;
5065 return shutdown_parse_argv(argc, argv);
5066 } else if (strstr(program_invocation_short_name, "init")) {
5068 if (sd_booted() > 0) {
5069 arg_action = ACTION_INVALID;
5070 return telinit_parse_argv(argc, argv);
5072 /* Hmm, so some other init system is
5073 * running, we need to forward this
5074 * request to it. For now we simply
5075 * guess that it is Upstart. */
5077 execv("/lib/upstart/telinit", argv);
5079 log_error("Couldn't find an alternative telinit implementation to spawn.");
5083 } else if (strstr(program_invocation_short_name, "runlevel")) {
5084 arg_action = ACTION_RUNLEVEL;
5085 return runlevel_parse_argv(argc, argv);
5089 arg_action = ACTION_SYSTEMCTL;
5090 return systemctl_parse_argv(argc, argv);
5093 static int action_to_runlevel(void) {
5095 static const char table[_ACTION_MAX] = {
5096 [ACTION_HALT] = '0',
5097 [ACTION_POWEROFF] = '0',
5098 [ACTION_REBOOT] = '6',
5099 [ACTION_RUNLEVEL2] = '2',
5100 [ACTION_RUNLEVEL3] = '3',
5101 [ACTION_RUNLEVEL4] = '4',
5102 [ACTION_RUNLEVEL5] = '5',
5103 [ACTION_RESCUE] = '1'
5106 assert(arg_action < _ACTION_MAX);
5108 return table[arg_action];
5111 static int talk_upstart(void) {
5112 DBusMessage *m = NULL, *reply = NULL;
5114 int previous, rl, r;
5116 env1_buf[] = "RUNLEVEL=X",
5117 env2_buf[] = "PREVLEVEL=X";
5118 char *env1 = env1_buf, *env2 = env2_buf;
5119 const char *emit = "runlevel";
5120 dbus_bool_t b_false = FALSE;
5121 DBusMessageIter iter, sub;
5122 DBusConnection *bus;
5124 dbus_error_init(&error);
5126 if (!(rl = action_to_runlevel()))
5129 if (utmp_get_runlevel(&previous, NULL) < 0)
5132 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5133 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5138 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5143 if ((r = bus_check_peercred(bus)) < 0) {
5144 log_error("Failed to verify owner of bus.");
5148 if (!(m = dbus_message_new_method_call(
5149 "com.ubuntu.Upstart",
5150 "/com/ubuntu/Upstart",
5151 "com.ubuntu.Upstart0_6",
5154 log_error("Could not allocate message.");
5159 dbus_message_iter_init_append(m, &iter);
5161 env1_buf[sizeof(env1_buf)-2] = rl;
5162 env2_buf[sizeof(env2_buf)-2] = previous;
5164 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5165 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5166 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5167 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5168 !dbus_message_iter_close_container(&iter, &sub) ||
5169 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5170 log_error("Could not append arguments to message.");
5175 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5177 if (bus_error_is_no_service(&error)) {
5182 log_error("Failed to issue method call: %s", bus_error_message(&error));
5191 dbus_message_unref(m);
5194 dbus_message_unref(reply);
5197 dbus_connection_flush(bus);
5198 dbus_connection_close(bus);
5199 dbus_connection_unref(bus);
5202 dbus_error_free(&error);
5207 static int talk_initctl(void) {
5208 struct init_request request;
5212 if (!(rl = action_to_runlevel()))
5216 request.magic = INIT_MAGIC;
5217 request.sleeptime = 0;
5218 request.cmd = INIT_CMD_RUNLVL;
5219 request.runlevel = rl;
5221 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5223 if (errno == ENOENT)
5226 log_error("Failed to open "INIT_FIFO": %m");
5231 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5232 close_nointr_nofail(fd);
5235 log_error("Failed to write to "INIT_FIFO": %m");
5236 return errno ? -errno : -EIO;
5242 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5244 static const struct {
5252 int (* const dispatch)(DBusConnection *bus, char **args);
5254 { "list-units", LESS, 1, list_units },
5255 { "list-unit-files", EQUAL, 1, list_unit_files },
5256 { "list-jobs", EQUAL, 1, list_jobs },
5257 { "clear-jobs", EQUAL, 1, daemon_reload },
5258 { "load", MORE, 2, load_unit },
5259 { "cancel", MORE, 2, cancel_job },
5260 { "start", MORE, 2, start_unit },
5261 { "stop", MORE, 2, start_unit },
5262 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5263 { "reload", MORE, 2, start_unit },
5264 { "restart", MORE, 2, start_unit },
5265 { "try-restart", MORE, 2, start_unit },
5266 { "reload-or-restart", MORE, 2, start_unit },
5267 { "reload-or-try-restart", MORE, 2, start_unit },
5268 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5269 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
5270 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5271 { "isolate", EQUAL, 2, start_unit },
5272 { "set-cgroup", MORE, 2, set_cgroup },
5273 { "unset-cgroup", MORE, 2, set_cgroup },
5274 { "set-cgroup-attr", MORE, 2, set_cgroup_attr },
5275 { "unset-cgroup-attr", MORE, 2, set_cgroup },
5276 { "kill", MORE, 2, kill_unit },
5277 { "is-active", MORE, 2, check_unit_active },
5278 { "check", MORE, 2, check_unit_active },
5279 { "is-failed", MORE, 2, check_unit_failed },
5280 { "show", MORE, 1, show },
5281 { "status", MORE, 2, show },
5282 { "help", MORE, 2, show },
5283 { "dump", EQUAL, 1, dump },
5284 { "dot", EQUAL, 1, dot },
5285 { "snapshot", LESS, 2, snapshot },
5286 { "delete", MORE, 2, delete_snapshot },
5287 { "daemon-reload", EQUAL, 1, daemon_reload },
5288 { "daemon-reexec", EQUAL, 1, daemon_reload },
5289 { "show-environment", EQUAL, 1, show_enviroment },
5290 { "set-environment", MORE, 2, set_environment },
5291 { "unset-environment", MORE, 2, set_environment },
5292 { "halt", EQUAL, 1, start_special },
5293 { "poweroff", EQUAL, 1, start_special },
5294 { "reboot", EQUAL, 1, start_special },
5295 { "kexec", EQUAL, 1, start_special },
5296 { "suspend", EQUAL, 1, start_special },
5297 { "hibernate", EQUAL, 1, start_special },
5298 { "hybrid-sleep", EQUAL, 1, start_special },
5299 { "default", EQUAL, 1, start_special },
5300 { "rescue", EQUAL, 1, start_special },
5301 { "emergency", EQUAL, 1, start_special },
5302 { "exit", EQUAL, 1, start_special },
5303 { "reset-failed", MORE, 1, reset_failed },
5304 { "enable", MORE, 2, enable_unit },
5305 { "disable", MORE, 2, enable_unit },
5306 { "is-enabled", MORE, 2, unit_is_enabled },
5307 { "reenable", MORE, 2, enable_unit },
5308 { "preset", MORE, 2, enable_unit },
5309 { "mask", MORE, 2, enable_unit },
5310 { "unmask", MORE, 2, enable_unit },
5311 { "link", MORE, 2, enable_unit },
5312 { "switch-root", MORE, 2, switch_root },
5313 { "list-dependencies", EQUAL, 2, list_dependencies },
5323 left = argc - optind;
5326 /* Special rule: no arguments means "list-units" */
5329 if (streq(argv[optind], "help") && !argv[optind+1]) {
5330 log_error("This command expects one or more "
5331 "unit names. Did you mean --help?");
5335 for (i = 0; i < ELEMENTSOF(verbs); i++)
5336 if (streq(argv[optind], verbs[i].verb))
5339 if (i >= ELEMENTSOF(verbs)) {
5340 log_error("Unknown operation '%s'.", argv[optind]);
5345 switch (verbs[i].argc_cmp) {
5348 if (left != verbs[i].argc) {
5349 log_error("Invalid number of arguments.");
5356 if (left < verbs[i].argc) {
5357 log_error("Too few arguments.");
5364 if (left > verbs[i].argc) {
5365 log_error("Too many arguments.");
5372 assert_not_reached("Unknown comparison operator.");
5375 /* Require a bus connection for all operations but
5377 if (!streq(verbs[i].verb, "enable") &&
5378 !streq(verbs[i].verb, "disable") &&
5379 !streq(verbs[i].verb, "is-enabled") &&
5380 !streq(verbs[i].verb, "list-unit-files") &&
5381 !streq(verbs[i].verb, "reenable") &&
5382 !streq(verbs[i].verb, "preset") &&
5383 !streq(verbs[i].verb, "mask") &&
5384 !streq(verbs[i].verb, "unmask") &&
5385 !streq(verbs[i].verb, "link")) {
5387 if (running_in_chroot() > 0) {
5388 log_info("Running in chroot, ignoring request.");
5392 if (((!streq(verbs[i].verb, "reboot") &&
5393 !streq(verbs[i].verb, "halt") &&
5394 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5395 log_error("Failed to get D-Bus connection: %s",
5396 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5402 if (!bus && !avoid_bus()) {
5403 log_error("Failed to get D-Bus connection: %s",
5404 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5409 return verbs[i].dispatch(bus, argv + optind);
5412 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5414 struct msghdr msghdr;
5415 struct iovec iovec[2];
5416 union sockaddr_union sockaddr;
5417 struct sd_shutdown_command c;
5419 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5426 c.dry_run = dry_run;
5430 sockaddr.sa.sa_family = AF_UNIX;
5431 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5434 msghdr.msg_name = &sockaddr;
5435 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5438 iovec[0].iov_base = (char*) &c;
5439 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5441 if (isempty(message))
5442 msghdr.msg_iovlen = 1;
5444 iovec[1].iov_base = (char*) message;
5445 iovec[1].iov_len = strlen(message);
5446 msghdr.msg_iovlen = 2;
5448 msghdr.msg_iov = iovec;
5450 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5451 close_nointr_nofail(fd);
5455 close_nointr_nofail(fd);
5459 static int reload_with_fallback(DBusConnection *bus) {
5462 /* First, try systemd via D-Bus. */
5463 if (daemon_reload(bus, NULL) >= 0)
5467 /* Nothing else worked, so let's try signals */
5468 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5470 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5471 log_error("kill() failed: %m");
5478 static int start_with_fallback(DBusConnection *bus) {
5481 /* First, try systemd via D-Bus. */
5482 if (start_unit(bus, NULL) >= 0)
5486 /* Hmm, talking to systemd via D-Bus didn't work. Then
5487 * let's try to talk to Upstart via D-Bus. */
5488 if (talk_upstart() > 0)
5491 /* Nothing else worked, so let's try
5493 if (talk_initctl() > 0)
5496 log_error("Failed to talk to init daemon.");
5500 warn_wall(arg_action);
5504 static _noreturn_ void halt_now(enum action a) {
5506 /* Make sure C-A-D is handled by the kernel from this
5508 reboot(RB_ENABLE_CAD);
5513 log_info("Halting.");
5514 reboot(RB_HALT_SYSTEM);
5517 case ACTION_POWEROFF:
5518 log_info("Powering off.");
5519 reboot(RB_POWER_OFF);
5523 log_info("Rebooting.");
5524 reboot(RB_AUTOBOOT);
5528 assert_not_reached("Unknown halt action.");
5531 assert_not_reached("Uh? This shouldn't happen.");
5534 static int halt_main(DBusConnection *bus) {
5537 r = check_inhibitors(bus, arg_action);
5541 if (geteuid() != 0) {
5542 /* Try logind if we are a normal user and no special
5543 * mode applies. Maybe PolicyKit allows us to shutdown
5546 if (arg_when <= 0 &&
5549 (arg_action == ACTION_POWEROFF ||
5550 arg_action == ACTION_REBOOT)) {
5551 r = reboot_with_logind(bus, arg_action);
5556 log_error("Must be root.");
5563 m = strv_join(arg_wall, " ");
5564 r = send_shutdownd(arg_when,
5565 arg_action == ACTION_HALT ? 'H' :
5566 arg_action == ACTION_POWEROFF ? 'P' :
5567 arg_action == ACTION_KEXEC ? 'K' :
5575 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5577 char date[FORMAT_TIMESTAMP_MAX];
5579 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5580 format_timestamp(date, sizeof(date), arg_when));
5585 if (!arg_dry && !arg_force)
5586 return start_with_fallback(bus);
5589 if (sd_booted() > 0)
5590 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5592 r = utmp_put_shutdown();
5594 log_warning("Failed to write utmp record: %s", strerror(-r));
5601 halt_now(arg_action);
5602 /* We should never reach this. */
5606 static int runlevel_main(void) {
5607 int r, runlevel, previous;
5609 r = utmp_get_runlevel(&runlevel, &previous);
5616 previous <= 0 ? 'N' : previous,
5617 runlevel <= 0 ? 'N' : runlevel);
5622 int main(int argc, char*argv[]) {
5623 int r, retval = EXIT_FAILURE;
5624 DBusConnection *bus = NULL;
5627 dbus_error_init(&error);
5629 setlocale(LC_ALL, "");
5630 log_parse_environment();
5633 r = parse_argv(argc, argv);
5637 retval = EXIT_SUCCESS;
5641 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5642 * let's shortcut this */
5643 if (arg_action == ACTION_RUNLEVEL) {
5644 r = runlevel_main();
5645 retval = r < 0 ? EXIT_FAILURE : r;
5649 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5650 log_info("Running in chroot, ignoring request.");
5656 if (arg_transport == TRANSPORT_NORMAL)
5657 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5658 else if (arg_transport == TRANSPORT_POLKIT) {
5659 bus_connect_system_polkit(&bus, &error);
5660 private_bus = false;
5661 } else if (arg_transport == TRANSPORT_SSH) {
5662 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5663 private_bus = false;
5665 assert_not_reached("Uh, invalid transport...");
5668 switch (arg_action) {
5670 case ACTION_SYSTEMCTL:
5671 r = systemctl_main(bus, argc, argv, &error);
5675 case ACTION_POWEROFF:
5681 case ACTION_RUNLEVEL2:
5682 case ACTION_RUNLEVEL3:
5683 case ACTION_RUNLEVEL4:
5684 case ACTION_RUNLEVEL5:
5686 case ACTION_EMERGENCY:
5687 case ACTION_DEFAULT:
5688 r = start_with_fallback(bus);
5693 r = reload_with_fallback(bus);
5696 case ACTION_CANCEL_SHUTDOWN: {
5700 m = strv_join(arg_wall, " ");
5702 retval = EXIT_FAILURE;
5706 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
5708 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
5713 case ACTION_INVALID:
5714 case ACTION_RUNLEVEL:
5716 assert_not_reached("Unknown action");
5719 retval = r < 0 ? EXIT_FAILURE : r;
5723 dbus_connection_flush(bus);
5724 dbus_connection_close(bus);
5725 dbus_connection_unref(bus);
5728 dbus_error_free(&error);
5732 strv_free(arg_property);
5735 ask_password_agent_close();
5736 polkit_agent_close();