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>
46 #include "utmp-wtmp.h"
49 #include "path-util.h"
51 #include "dbus-common.h"
52 #include "cgroup-show.h"
53 #include "cgroup-util.h"
55 #include "path-lookup.h"
56 #include "conf-parser.h"
57 #include "exit-status.h"
58 #include "bus-errors.h"
60 #include "unit-name.h"
62 #include "spawn-ask-password-agent.h"
63 #include "spawn-polkit-agent.h"
65 #include "logs-show.h"
66 #include "path-util.h"
67 #include "socket-util.h"
69 static const char *arg_type = NULL;
70 static const char *arg_load_state = NULL;
71 static char **arg_property = NULL;
72 static bool arg_all = false;
73 static const char *arg_job_mode = "replace";
74 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
75 static bool arg_no_block = false;
76 static bool arg_no_legend = false;
77 static bool arg_no_pager = false;
78 static bool arg_no_wtmp = false;
79 static bool arg_no_wall = false;
80 static bool arg_no_reload = false;
81 static bool arg_dry = false;
82 static bool arg_quiet = false;
83 static bool arg_full = false;
84 static int arg_force = 0;
85 static bool arg_ask_password = true;
86 static bool arg_failed = false;
87 static bool arg_runtime = false;
88 static char **arg_wall = NULL;
89 static const char *arg_kill_who = NULL;
90 static int arg_signal = SIGTERM;
91 static const char *arg_root = NULL;
92 static usec_t arg_when = 0;
114 ACTION_CANCEL_SHUTDOWN,
116 } arg_action = ACTION_SYSTEMCTL;
122 static enum transport {
126 } arg_transport = TRANSPORT_NORMAL;
127 static const char *arg_host = NULL;
128 static unsigned arg_lines = 10;
129 static OutputMode arg_output = OUTPUT_SHORT;
131 static bool private_bus = false;
133 static int daemon_reload(DBusConnection *bus, char **args);
134 static void halt_now(enum action a);
136 static void pager_open_if_enabled(void) {
144 static void ask_password_agent_open_if_enabled(void) {
146 /* Open the password agent as a child process if necessary */
148 if (!arg_ask_password)
151 if (arg_scope != UNIT_FILE_SYSTEM)
154 ask_password_agent_open();
158 static void polkit_agent_open_if_enabled(void) {
160 /* Open the polkit agent as a child process if necessary */
162 if (!arg_ask_password)
165 if (arg_scope != UNIT_FILE_SYSTEM)
172 static const char *ansi_highlight(bool b) {
177 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
180 static const char *ansi_highlight_red(bool b) {
185 return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
188 static const char *ansi_highlight_green(bool b) {
193 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
196 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
199 if (!dbus_error_is_set(error))
202 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
203 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
204 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
205 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
206 return EXIT_NOPERMISSION;
208 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
209 return EXIT_NOTINSTALLED;
211 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
212 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
213 return EXIT_NOTIMPLEMENTED;
215 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
216 return EXIT_NOTCONFIGURED;
224 static void warn_wall(enum action a) {
225 static const char *table[_ACTION_MAX] = {
226 [ACTION_HALT] = "The system is going down for system halt NOW!",
227 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
228 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
229 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
230 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
231 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!",
232 [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
241 p = strv_join(arg_wall, " ");
243 log_error("Failed to join strings.");
259 utmp_wall(table[a], NULL);
262 static bool avoid_bus(void) {
264 if (running_in_chroot() > 0)
267 if (sd_booted() <= 0)
270 if (!isempty(arg_root))
273 if (arg_scope == UNIT_FILE_GLOBAL)
281 const char *description;
282 const char *load_state;
283 const char *active_state;
284 const char *sub_state;
285 const char *following;
286 const char *unit_path;
288 const char *job_type;
289 const char *job_path;
292 static int compare_unit_info(const void *a, const void *b) {
294 const struct unit_info *u = a, *v = b;
296 d1 = strrchr(u->id, '.');
297 d2 = strrchr(v->id, '.');
302 if ((r = strcasecmp(d1, d2)) != 0)
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");
429 on = ansi_highlight(true);
430 off = ansi_highlight(false);
432 on = ansi_highlight_red(true);
433 off = ansi_highlight_red(false);
437 printf("\n%s%u loaded units listed.%s\n"
438 "To show all installed unit files use 'systemctl list-unit-files'.\n",
441 printf("\n%s%u loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
442 "To show all installed unit files use 'systemctl list-unit-files'.\n",
447 static int list_units(DBusConnection *bus, char **args) {
448 DBusMessage *reply = NULL;
450 DBusMessageIter iter, sub, sub2;
451 unsigned c = 0, n_units = 0;
452 struct unit_info *unit_infos = NULL;
454 pager_open_if_enabled();
456 r = bus_method_call_with_reply (
458 "org.freedesktop.systemd1",
459 "/org/freedesktop/systemd1",
460 "org.freedesktop.systemd1.Manager",
468 if (!dbus_message_iter_init(reply, &iter) ||
469 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
470 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
471 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 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
482 log_error("Failed to parse reply.");
490 n_units = MAX(2*c, 16);
491 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
494 log_error("Failed to allocate unit array.");
504 dbus_message_iter_recurse(&sub, &sub2);
506 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
507 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
508 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
509 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
510 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
511 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
512 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
513 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
514 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
515 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
516 log_error("Failed to parse reply.");
521 dbus_message_iter_next(&sub);
526 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
527 output_units_list(unit_infos, c);
532 dbus_message_unref(reply);
539 static int compare_unit_file_list(const void *a, const void *b) {
541 const UnitFileList *u = a, *v = b;
543 d1 = strrchr(u->path, '.');
544 d2 = strrchr(v->path, '.');
549 r = strcasecmp(d1, d2);
554 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
557 static bool output_show_unit_file(const UnitFileList *u) {
560 return !arg_type || ((dot = strrchr(u->path, '.')) && streq(dot+1, arg_type));
563 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
564 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
565 const UnitFileList *u;
567 max_id_len = sizeof("UNIT FILE")-1;
568 state_cols = sizeof("STATE")-1;
569 for (u = units; u < units + c; u++) {
570 if (!output_show_unit_file(u))
573 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
574 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
579 id_cols = MIN(max_id_len, 25);
580 basic_cols = 1 + id_cols + state_cols;
581 if (basic_cols < (unsigned) columns())
582 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
584 id_cols = max_id_len;
587 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
589 for (u = units; u < units + c; u++) {
591 const char *on, *off;
594 if (!output_show_unit_file(u))
599 if (u->state == UNIT_FILE_MASKED ||
600 u->state == UNIT_FILE_MASKED_RUNTIME ||
601 u->state == UNIT_FILE_DISABLED ||
602 u->state == UNIT_FILE_INVALID) {
603 on = ansi_highlight_red(true);
604 off = ansi_highlight_red(false);
605 } else if (u->state == UNIT_FILE_ENABLED) {
606 on = ansi_highlight_green(true);
607 off = ansi_highlight_green(false);
611 id = path_get_file_name(u->path);
613 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
615 printf("%-*s %s%-*s%s\n",
617 on, state_cols, unit_file_state_to_string(u->state), off);
623 printf("\n%u unit files listed.\n", n_shown);
626 static int list_unit_files(DBusConnection *bus, char **args) {
627 DBusMessage *reply = NULL;
629 DBusMessageIter iter, sub, sub2;
630 unsigned c = 0, n_units = 0;
631 UnitFileList *units = NULL;
633 pager_open_if_enabled();
640 h = hashmap_new(string_hash_func, string_compare_func);
644 r = unit_file_get_list(arg_scope, arg_root, h);
646 unit_file_list_free(h);
647 log_error("Failed to get unit file list: %s", strerror(-r));
651 n_units = hashmap_size(h);
652 units = new(UnitFileList, n_units);
654 unit_file_list_free(h);
658 HASHMAP_FOREACH(u, h, i) {
659 memcpy(units + c++, u, sizeof(UnitFileList));
665 r = bus_method_call_with_reply (
667 "org.freedesktop.systemd1",
668 "/org/freedesktop/systemd1",
669 "org.freedesktop.systemd1.Manager",
677 if (!dbus_message_iter_init(reply, &iter) ||
678 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
679 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
680 log_error("Failed to parse reply.");
685 dbus_message_iter_recurse(&iter, &sub);
687 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
691 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
692 log_error("Failed to parse reply.");
700 n_units = MAX(2*c, 16);
701 w = realloc(units, sizeof(struct UnitFileList) * n_units);
704 log_error("Failed to allocate unit array.");
714 dbus_message_iter_recurse(&sub, &sub2);
716 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
717 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
718 log_error("Failed to parse reply.");
723 u->state = unit_file_state_from_string(state);
725 dbus_message_iter_next(&sub);
731 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
732 output_unit_file_list(units, c);
739 dbus_message_unref(reply);
746 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
747 static const char * const colors[] = {
748 "Requires", "[color=\"black\"]",
749 "RequiresOverridable", "[color=\"black\"]",
750 "Requisite", "[color=\"darkblue\"]",
751 "RequisiteOverridable", "[color=\"darkblue\"]",
752 "Wants", "[color=\"grey66\"]",
753 "Conflicts", "[color=\"red\"]",
754 "ConflictedBy", "[color=\"red\"]",
755 "After", "[color=\"green\"]"
758 const char *c = NULL;
765 for (i = 0; i < ELEMENTSOF(colors); i += 2)
766 if (streq(colors[i], prop)) {
774 if (arg_dot != DOT_ALL)
775 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
778 switch (dbus_message_iter_get_arg_type(iter)) {
780 case DBUS_TYPE_ARRAY:
782 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
785 dbus_message_iter_recurse(iter, &sub);
787 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
790 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
791 dbus_message_iter_get_basic(&sub, &s);
792 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
794 dbus_message_iter_next(&sub);
804 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
805 DBusMessage *reply = NULL;
806 const char *interface = "org.freedesktop.systemd1.Unit";
808 DBusMessageIter iter, sub, sub2, sub3;
812 r = bus_method_call_with_reply (
814 "org.freedesktop.systemd1",
816 "org.freedesktop.DBus.Properties",
820 DBUS_TYPE_STRING, &interface,
825 if (!dbus_message_iter_init(reply, &iter) ||
826 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
827 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
828 log_error("Failed to parse reply.");
833 dbus_message_iter_recurse(&iter, &sub);
835 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
838 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
839 log_error("Failed to parse reply.");
844 dbus_message_iter_recurse(&sub, &sub2);
846 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
847 log_error("Failed to parse reply.");
852 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
853 log_error("Failed to parse reply.");
858 dbus_message_iter_recurse(&sub2, &sub3);
860 if (dot_one_property(name, prop, &sub3)) {
861 log_error("Failed to parse reply.");
866 dbus_message_iter_next(&sub);
871 dbus_message_unref(reply);
876 static int dot(DBusConnection *bus, char **args) {
877 DBusMessage *reply = NULL;
879 DBusMessageIter iter, sub, sub2;
881 r = bus_method_call_with_reply (
883 "org.freedesktop.systemd1",
884 "/org/freedesktop/systemd1",
885 "org.freedesktop.systemd1.Manager",
893 if (!dbus_message_iter_init(reply, &iter) ||
894 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
895 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
896 log_error("Failed to parse reply.");
901 printf("digraph systemd {\n");
903 dbus_message_iter_recurse(&iter, &sub);
904 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
905 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
907 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
908 log_error("Failed to parse reply.");
913 dbus_message_iter_recurse(&sub, &sub2);
915 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
916 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
917 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
918 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
919 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
920 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
921 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
922 log_error("Failed to parse reply.");
927 if ((r = dot_one(bus, id, unit_path)) < 0)
930 /* printf("\t\"%s\";\n", id); */
931 dbus_message_iter_next(&sub);
936 log_info(" Color legend: black = Requires\n"
937 " dark blue = Requisite\n"
938 " dark grey = Wants\n"
943 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
944 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
950 dbus_message_unref(reply);
955 static int list_jobs(DBusConnection *bus, char **args) {
956 DBusMessage *reply = NULL;
958 DBusMessageIter iter, sub, sub2;
961 pager_open_if_enabled();
963 r = bus_method_call_with_reply (
965 "org.freedesktop.systemd1",
966 "/org/freedesktop/systemd1",
967 "org.freedesktop.systemd1.Manager",
975 if (!dbus_message_iter_init(reply, &iter) ||
976 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
977 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
978 log_error("Failed to parse reply.");
983 dbus_message_iter_recurse(&iter, &sub);
986 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
988 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
989 const char *name, *type, *state, *job_path, *unit_path;
993 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
994 log_error("Failed to parse reply.");
999 dbus_message_iter_recurse(&sub, &sub2);
1001 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
1002 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
1003 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
1004 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
1005 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
1006 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
1007 log_error("Failed to parse reply.");
1012 e = arg_full ? NULL : ellipsize(name, 25, 33);
1013 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
1018 dbus_message_iter_next(&sub);
1022 printf("\n%u jobs listed.\n", k);
1028 dbus_message_unref(reply);
1033 static int load_unit(DBusConnection *bus, char **args) {
1039 STRV_FOREACH(name, args+1) {
1040 n = unit_name_mangle(*name);
1041 r = bus_method_call_with_reply (
1043 "org.freedesktop.systemd1",
1044 "/org/freedesktop/systemd1",
1045 "org.freedesktop.systemd1.Manager",
1049 DBUS_TYPE_STRING, n ? &n : name,
1060 static int cancel_job(DBusConnection *bus, char **args) {
1061 DBusMessage *reply = NULL;
1067 if (strv_length(args) <= 1)
1068 return daemon_reload(bus, args);
1070 STRV_FOREACH(name, args+1) {
1074 r = safe_atou(*name, &id);
1076 log_error("Failed to parse job id: %s", strerror(-r));
1079 assert_cc(sizeof(uint32_t) == sizeof(id));
1081 r = bus_method_call_with_reply (
1083 "org.freedesktop.systemd1",
1084 "/org/freedesktop/systemd1",
1085 "org.freedesktop.systemd1.Manager",
1089 DBUS_TYPE_UINT32, &id,
1094 if (!dbus_message_get_args(reply, NULL,
1095 DBUS_TYPE_OBJECT_PATH, &path,
1096 DBUS_TYPE_INVALID)) {
1097 log_error("Failed to parse reply");
1098 dbus_message_unref(reply);
1102 dbus_message_unref(reply);
1104 r = bus_method_call_with_reply (
1106 "org.freedesktop.systemd1",
1108 "org.freedesktop.systemd1.Job",
1121 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1122 DBusMessage *reply = NULL;
1123 dbus_bool_t b = FALSE;
1124 DBusMessageIter iter, sub;
1126 *interface = "org.freedesktop.systemd1.Unit",
1127 *property = "NeedDaemonReload",
1132 /* We ignore all errors here, since this is used to show a warning only */
1134 n = unit_name_mangle(unit);
1135 r = bus_method_call_with_reply (
1137 "org.freedesktop.systemd1",
1138 "/org/freedesktop/systemd1",
1139 "org.freedesktop.systemd1.Manager",
1143 DBUS_TYPE_STRING, n ? (const char**) &n : &unit,
1149 if (!dbus_message_get_args(reply, NULL,
1150 DBUS_TYPE_OBJECT_PATH, &path,
1154 dbus_message_unref(reply);
1155 r = bus_method_call_with_reply (
1157 "org.freedesktop.systemd1",
1159 "org.freedesktop.DBus.Properties",
1163 DBUS_TYPE_STRING, &interface,
1164 DBUS_TYPE_STRING, &property,
1169 if (!dbus_message_iter_init(reply, &iter) ||
1170 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1173 dbus_message_iter_recurse(&iter, &sub);
1175 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1178 dbus_message_iter_get_basic(&sub, &b);
1182 dbus_message_unref(reply);
1187 typedef struct WaitData {
1194 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1202 dbus_error_init(&error);
1204 log_debug("Got D-Bus request: %s.%s() on %s",
1205 dbus_message_get_interface(message),
1206 dbus_message_get_member(message),
1207 dbus_message_get_path(message));
1209 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1210 log_error("Warning! D-Bus connection terminated.");
1211 dbus_connection_close(connection);
1213 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1215 const char *path, *result, *unit;
1216 dbus_bool_t success = true;
1218 if (dbus_message_get_args(message, &error,
1219 DBUS_TYPE_UINT32, &id,
1220 DBUS_TYPE_OBJECT_PATH, &path,
1221 DBUS_TYPE_STRING, &unit,
1222 DBUS_TYPE_STRING, &result,
1223 DBUS_TYPE_INVALID)) {
1226 p = set_remove(d->set, (char*) path);
1229 if (!isempty(result))
1230 d->result = strdup(result);
1233 d->name = strdup(unit);
1238 dbus_error_free(&error);
1239 if (dbus_message_get_args(message, &error,
1240 DBUS_TYPE_UINT32, &id,
1241 DBUS_TYPE_OBJECT_PATH, &path,
1242 DBUS_TYPE_STRING, &result,
1243 DBUS_TYPE_INVALID)) {
1246 /* Compatibility with older systemd versions <
1247 * 183 during upgrades. This should be dropped
1249 p = set_remove(d->set, (char*) path);
1253 d->result = strdup(result);
1258 dbus_error_free(&error);
1259 if (dbus_message_get_args(message, &error,
1260 DBUS_TYPE_UINT32, &id,
1261 DBUS_TYPE_OBJECT_PATH, &path,
1262 DBUS_TYPE_BOOLEAN, &success,
1263 DBUS_TYPE_INVALID)) {
1266 /* Compatibility with older systemd versions <
1267 * 19 during upgrades. This should be dropped
1270 p = set_remove(d->set, (char*) path);
1274 d->result = strdup("failed");
1280 log_error("Failed to parse message: %s", bus_error_message(&error));
1284 dbus_error_free(&error);
1285 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1288 static int enable_wait_for_jobs(DBusConnection *bus) {
1296 dbus_error_init(&error);
1297 dbus_bus_add_match(bus,
1299 "sender='org.freedesktop.systemd1',"
1300 "interface='org.freedesktop.systemd1.Manager',"
1301 "member='JobRemoved',"
1302 "path='/org/freedesktop/systemd1'",
1305 if (dbus_error_is_set(&error)) {
1306 log_error("Failed to add match: %s", bus_error_message(&error));
1307 dbus_error_free(&error);
1311 /* This is slightly dirty, since we don't undo the match registrations. */
1315 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1325 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL))
1328 while (!set_isempty(s)) {
1330 if (!dbus_connection_read_write_dispatch(bus, -1)) {
1331 log_error("Disconnected from bus.");
1332 return -ECONNREFUSED;
1339 if (streq(d.result, "timeout"))
1340 log_error("Job for %s timed out.", strna(d.name));
1341 else if (streq(d.result, "canceled"))
1342 log_error("Job for %s canceled.", strna(d.name));
1343 else if (streq(d.result, "dependency"))
1344 log_error("A dependency job for %s failed. See 'journalctl -n' for details.", strna(d.name));
1345 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1346 log_error("Job for %s failed. See 'systemctl status %s' and 'journalctl -n' for details.", strna(d.name), strna(d.name));
1349 if (streq_ptr(d.result, "timeout"))
1351 else if (streq_ptr(d.result, "canceled"))
1353 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1364 dbus_connection_remove_filter(bus, wait_filter, &d);
1368 static int check_one_unit(DBusConnection *bus, char *name, bool quiet) {
1369 DBusMessage *reply = NULL;
1370 DBusMessageIter iter, sub;
1372 *interface = "org.freedesktop.systemd1.Unit",
1373 *property = "ActiveState";
1374 const char *path = NULL;
1381 n = unit_name_mangle(name);
1382 r = bus_method_call_with_reply (
1384 "org.freedesktop.systemd1",
1385 "/org/freedesktop/systemd1",
1386 "org.freedesktop.systemd1.Manager",
1390 DBUS_TYPE_STRING, n ? &n : &name,
1394 if ((r != -ENOMEM) && (!quiet))
1399 if (!dbus_message_get_args(reply, NULL,
1400 DBUS_TYPE_OBJECT_PATH, &path,
1401 DBUS_TYPE_INVALID)) {
1402 log_error("Failed to parse reply.");
1407 dbus_message_unref(reply);
1408 r = bus_method_call_with_reply (
1410 "org.freedesktop.systemd1",
1412 "org.freedesktop.DBus.Properties",
1416 DBUS_TYPE_STRING, &interface,
1417 DBUS_TYPE_STRING, &property,
1422 if (!dbus_message_iter_init(reply, &iter) ||
1423 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1424 log_error("Failed to parse reply.");
1429 dbus_message_iter_recurse(&iter, &sub);
1431 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1432 log_error("Failed to parse reply.");
1437 dbus_message_iter_get_basic(&sub, &state);
1442 if (streq(state, "active") || streq(state, "reloading"))
1445 r = 3; /* According to LSB: "program is not running" */
1449 dbus_message_unref(reply);
1454 static void check_triggering_units(
1455 DBusConnection *bus,
1456 const char *unit_name) {
1458 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1459 DBusMessageIter iter, sub;
1460 char *service_trigger = NULL;
1461 const char *interface = "org.freedesktop.systemd1.Unit",
1462 *triggered_by_property = "TriggeredBy";
1464 char _cleanup_free_ *unit_path = NULL, *n = NULL;
1465 bool print_warning_label = true;
1468 n = unit_name_mangle(unit_name);
1474 unit_path = unit_dbus_path_from_name(n);
1480 r = bus_method_call_with_reply (
1482 "org.freedesktop.systemd1",
1484 "org.freedesktop.DBus.Properties",
1488 DBUS_TYPE_STRING, &interface,
1489 DBUS_TYPE_STRING, &triggered_by_property,
1494 if (!dbus_message_iter_init(reply, &iter) ||
1495 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1496 log_error("Failed to parse reply.");
1500 dbus_message_iter_recurse(&iter, &sub);
1501 dbus_message_iter_recurse(&sub, &iter);
1504 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1506 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1507 log_error("Failed to parse reply.");
1511 dbus_message_iter_get_basic(&sub, &service_trigger);
1513 r = check_one_unit(bus, service_trigger, true);
1517 if (print_warning_label) {
1518 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1519 print_warning_label = false;
1521 log_warning(" %s", service_trigger);
1524 dbus_message_iter_next(&sub);
1528 static int start_unit_one(
1529 DBusConnection *bus,
1536 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1539 _cleanup_free_ char *n, *p = NULL;
1546 n = unit_name_mangle(name);
1550 r = bus_method_call_with_reply(
1552 "org.freedesktop.systemd1",
1553 "/org/freedesktop/systemd1",
1554 "org.freedesktop.systemd1.Manager",
1558 DBUS_TYPE_STRING, &n,
1559 DBUS_TYPE_STRING, &mode,
1562 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
1563 /* There's always a fallback possible for
1564 * legacy actions. */
1567 log_error("Failed to issue method call: %s", bus_error_message(error));
1572 if (!dbus_message_get_args(reply, error,
1573 DBUS_TYPE_OBJECT_PATH, &path,
1574 DBUS_TYPE_INVALID)) {
1575 log_error("Failed to parse reply: %s", bus_error_message(error));
1579 if (need_daemon_reload(bus, n))
1580 log_warning("Warning: Unit file of %s changed on disk, 'systemctl %s daemon-reload' recommended.",
1581 n, arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1590 log_error("Failed to add path to set.");
1600 static enum action verb_to_action(const char *verb) {
1601 if (streq(verb, "halt"))
1603 else if (streq(verb, "poweroff"))
1604 return ACTION_POWEROFF;
1605 else if (streq(verb, "reboot"))
1606 return ACTION_REBOOT;
1607 else if (streq(verb, "kexec"))
1608 return ACTION_KEXEC;
1609 else if (streq(verb, "rescue"))
1610 return ACTION_RESCUE;
1611 else if (streq(verb, "emergency"))
1612 return ACTION_EMERGENCY;
1613 else if (streq(verb, "default"))
1614 return ACTION_DEFAULT;
1615 else if (streq(verb, "exit"))
1617 else if (streq(verb, "suspend"))
1618 return ACTION_SUSPEND;
1619 else if (streq(verb, "hibernate"))
1620 return ACTION_HIBERNATE;
1621 else if (streq(verb, "hybrid-sleep"))
1622 return ACTION_HYBRID_SLEEP;
1624 return ACTION_INVALID;
1627 static int start_unit(DBusConnection *bus, char **args) {
1629 static const char * const table[_ACTION_MAX] = {
1630 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1631 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1632 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1633 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1634 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1635 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1636 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1637 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1638 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1639 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1640 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1641 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1642 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1643 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET,
1644 [ACTION_HYBRID_SLEEP] = SPECIAL_HYBRID_SLEEP_TARGET
1648 const char *method, *mode, *one_name;
1653 dbus_error_init(&error);
1657 ask_password_agent_open_if_enabled();
1659 if (arg_action == ACTION_SYSTEMCTL) {
1661 streq(args[0], "stop") ||
1662 streq(args[0], "condstop") ? "StopUnit" :
1663 streq(args[0], "reload") ? "ReloadUnit" :
1664 streq(args[0], "restart") ? "RestartUnit" :
1666 streq(args[0], "try-restart") ||
1667 streq(args[0], "condrestart") ? "TryRestartUnit" :
1669 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1671 streq(args[0], "reload-or-try-restart") ||
1672 streq(args[0], "condreload") ||
1674 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1678 (streq(args[0], "isolate") ||
1679 streq(args[0], "rescue") ||
1680 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1682 one_name = table[verb_to_action(args[0])];
1685 assert(arg_action < ELEMENTSOF(table));
1686 assert(table[arg_action]);
1688 method = "StartUnit";
1690 mode = (arg_action == ACTION_EMERGENCY ||
1691 arg_action == ACTION_RESCUE ||
1692 arg_action == ACTION_RUNLEVEL2 ||
1693 arg_action == ACTION_RUNLEVEL3 ||
1694 arg_action == ACTION_RUNLEVEL4 ||
1695 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1697 one_name = table[arg_action];
1700 if (!arg_no_block) {
1701 ret = enable_wait_for_jobs(bus);
1703 log_error("Could not watch jobs: %s", strerror(-ret));
1707 s = set_new(string_hash_func, string_compare_func);
1715 ret = start_unit_one(bus, method, one_name, mode, &error, s);
1717 ret = translate_bus_error_to_exit_status(ret, &error);
1719 STRV_FOREACH(name, args+1) {
1720 r = start_unit_one(bus, method, *name, mode, &error, s);
1722 ret = translate_bus_error_to_exit_status(r, &error);
1723 dbus_error_free(&error);
1728 if (!arg_no_block) {
1729 r = wait_for_jobs(bus, s);
1735 /* When stopping units, warn if they can still be triggered by
1736 * another active unit (socket, path, timer) */
1737 if (!arg_quiet && streq(method, "StopUnit")) {
1739 check_triggering_units(bus, one_name);
1741 STRV_FOREACH(name, args+1)
1742 check_triggering_units(bus, *name);
1748 dbus_error_free(&error);
1753 /* Ask systemd-logind, which might grant access to unprivileged users
1754 * through PolicyKit */
1755 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1758 dbus_bool_t interactive = true;
1760 polkit_agent_open_if_enabled();
1768 case ACTION_POWEROFF:
1769 method = "PowerOff";
1772 case ACTION_SUSPEND:
1776 case ACTION_HIBERNATE:
1777 method = "Hibernate";
1780 case ACTION_HYBRID_SLEEP:
1781 method = "HybridSleep";
1788 return bus_method_call_with_reply (
1790 "org.freedesktop.login1",
1791 "/org/freedesktop/login1",
1792 "org.freedesktop.login1.Manager",
1796 DBUS_TYPE_BOOLEAN, &interactive,
1803 static int start_special(DBusConnection *bus, char **args) {
1809 a = verb_to_action(args[0]);
1811 if (arg_force >= 2 && geteuid() != 0) {
1812 log_error("Must be root.");
1816 if (arg_force >= 2 &&
1817 (a == ACTION_HALT ||
1818 a == ACTION_POWEROFF ||
1819 a == ACTION_REBOOT))
1822 if (arg_force >= 1 &&
1823 (a == ACTION_HALT ||
1824 a == ACTION_POWEROFF ||
1825 a == ACTION_REBOOT ||
1826 a == ACTION_KEXEC ||
1828 return daemon_reload(bus, args);
1830 /* first try logind, to allow authentication with polkit */
1831 if (geteuid() != 0 &&
1832 (a == ACTION_POWEROFF ||
1833 a == ACTION_REBOOT ||
1834 a == ACTION_SUSPEND ||
1835 a == ACTION_HIBERNATE ||
1836 a == ACTION_HYBRID_SLEEP)) {
1837 r = reboot_with_logind(bus, a);
1842 r = start_unit(bus, args);
1849 static int check_unit(DBusConnection *bus, char **args) {
1851 int r = 3; /* According to LSB: "program is not running" */
1856 STRV_FOREACH(name, args+1) {
1857 int state = check_one_unit(bus, *name, arg_quiet);
1867 static int kill_unit(DBusConnection *bus, char **args) {
1874 arg_kill_who = "all";
1876 STRV_FOREACH(name, args+1) {
1877 n = unit_name_mangle(*name);
1878 r = bus_method_call_with_reply (
1880 "org.freedesktop.systemd1",
1881 "/org/freedesktop/systemd1",
1882 "org.freedesktop.systemd1.Manager",
1886 DBUS_TYPE_STRING, n ? &n : name,
1887 DBUS_TYPE_STRING, &arg_kill_who,
1888 DBUS_TYPE_INT32, &arg_signal,
1897 typedef struct ExecStatusInfo {
1905 usec_t start_timestamp;
1906 usec_t exit_timestamp;
1911 LIST_FIELDS(struct ExecStatusInfo, exec);
1914 static void exec_status_info_free(ExecStatusInfo *i) {
1923 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1924 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
1925 DBusMessageIter sub2, sub3;
1929 int32_t code, status;
1935 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1938 dbus_message_iter_recurse(sub, &sub2);
1940 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1943 if (!(i->path = strdup(path)))
1946 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1947 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1951 dbus_message_iter_recurse(&sub2, &sub3);
1952 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1953 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1954 dbus_message_iter_next(&sub3);
1959 if (!(i->argv = new0(char*, n+1)))
1963 dbus_message_iter_recurse(&sub2, &sub3);
1964 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1967 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1968 dbus_message_iter_get_basic(&sub3, &s);
1969 dbus_message_iter_next(&sub3);
1971 if (!(i->argv[n++] = strdup(s)))
1975 if (!dbus_message_iter_next(&sub2) ||
1976 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1977 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1978 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
1979 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1980 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
1981 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1982 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1983 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1987 i->start_timestamp = (usec_t) start_timestamp;
1988 i->exit_timestamp = (usec_t) exit_timestamp;
1989 i->pid = (pid_t) pid;
1996 typedef struct UnitStatusInfo {
1998 const char *load_state;
1999 const char *active_state;
2000 const char *sub_state;
2001 const char *unit_file_state;
2003 const char *description;
2004 const char *following;
2006 char **documentation;
2008 const char *fragment_path;
2009 const char *source_path;
2010 const char *default_control_group;
2012 const char *load_error;
2015 usec_t inactive_exit_timestamp;
2016 usec_t inactive_exit_timestamp_monotonic;
2017 usec_t active_enter_timestamp;
2018 usec_t active_exit_timestamp;
2019 usec_t inactive_enter_timestamp;
2021 bool need_daemon_reload;
2026 const char *status_text;
2029 usec_t start_timestamp;
2030 usec_t exit_timestamp;
2032 int exit_code, exit_status;
2034 usec_t condition_timestamp;
2035 bool condition_result;
2038 unsigned n_accepted;
2039 unsigned n_connections;
2043 const char *sysfs_path;
2045 /* Mount, Automount */
2051 LIST_HEAD(ExecStatusInfo, exec);
2054 static void print_status_info(UnitStatusInfo *i) {
2056 const char *on, *off, *ss;
2058 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2059 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2064 /* This shows pretty information about a unit. See
2065 * print_property() for a low-level property printer */
2067 printf("%s", strna(i->id));
2069 if (i->description && !streq_ptr(i->id, i->description))
2070 printf(" - %s", i->description);
2075 printf("\t Follow: unit currently follows state of %s\n", i->following);
2077 if (streq_ptr(i->load_state, "error")) {
2078 on = ansi_highlight_red(true);
2079 off = ansi_highlight_red(false);
2083 path = i->source_path ? i->source_path : i->fragment_path;
2086 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2087 else if (path && i->unit_file_state)
2088 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2090 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2092 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2094 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2096 if (streq_ptr(i->active_state, "failed")) {
2097 on = ansi_highlight_red(true);
2098 off = ansi_highlight_red(false);
2099 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2100 on = ansi_highlight_green(true);
2101 off = ansi_highlight_green(false);
2106 printf("\t Active: %s%s (%s)%s",
2108 strna(i->active_state),
2112 printf("\t Active: %s%s%s",
2114 strna(i->active_state),
2117 if (!isempty(i->result) && !streq(i->result, "success"))
2118 printf(" (Result: %s)", i->result);
2120 timestamp = (streq_ptr(i->active_state, "active") ||
2121 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2122 (streq_ptr(i->active_state, "inactive") ||
2123 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2124 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2125 i->active_exit_timestamp;
2127 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2128 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2131 printf(" since %s; %s\n", s2, s1);
2133 printf(" since %s\n", s2);
2137 if (!i->condition_result && i->condition_timestamp > 0) {
2138 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2139 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2142 printf("\t start condition failed at %s; %s\n", s2, s1);
2144 printf("\t start condition failed at %s\n", s2);
2148 printf("\t Device: %s\n", i->sysfs_path);
2150 printf("\t Where: %s\n", i->where);
2152 printf("\t What: %s\n", i->what);
2154 if (!strv_isempty(i->documentation)) {
2158 STRV_FOREACH(t, i->documentation) {
2160 printf("\t Docs: %s\n", *t);
2163 printf("\t %s\n", *t);
2168 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2170 LIST_FOREACH(exec, p, i->exec) {
2174 /* Only show exited processes here */
2178 t = strv_join(p->argv, " ");
2179 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2182 good = is_clean_exit_lsb(p->code, p->status, NULL);
2184 on = ansi_highlight_red(true);
2185 off = ansi_highlight_red(false);
2189 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2191 if (p->code == CLD_EXITED) {
2194 printf("status=%i", p->status);
2196 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2201 printf("signal=%s", signal_to_string(p->status));
2203 printf(")%s\n", off);
2205 if (i->main_pid == p->pid &&
2206 i->start_timestamp == p->start_timestamp &&
2207 i->exit_timestamp == p->start_timestamp)
2208 /* Let's not show this twice */
2211 if (p->pid == i->control_pid)
2215 if (i->main_pid > 0 || i->control_pid > 0) {
2218 if (i->main_pid > 0) {
2219 printf("Main PID: %u", (unsigned) i->main_pid);
2223 get_process_comm(i->main_pid, &t);
2228 } else if (i->exit_code > 0) {
2229 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2231 if (i->exit_code == CLD_EXITED) {
2234 printf("status=%i", i->exit_status);
2236 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2241 printf("signal=%s", signal_to_string(i->exit_status));
2246 if (i->main_pid > 0 && i->control_pid > 0)
2249 if (i->control_pid > 0) {
2252 printf(" Control: %u", (unsigned) i->control_pid);
2254 get_process_comm(i->control_pid, &t);
2265 printf("\t Status: \"%s\"\n", i->status_text);
2267 if (i->default_control_group) {
2270 printf("\t CGroup: %s\n", i->default_control_group);
2272 if (arg_transport != TRANSPORT_SSH) {
2282 if (i->main_pid > 0)
2283 extra[k++] = i->main_pid;
2285 if (i->control_pid > 0)
2286 extra[k++] = i->control_pid;
2288 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2292 if (i->id && arg_transport != TRANSPORT_SSH) {
2294 arg_all * OUTPUT_SHOW_ALL |
2295 (!on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
2296 on_tty() * OUTPUT_COLOR |
2297 !arg_quiet * OUTPUT_WARN_CUTOFF;
2300 show_journal_by_unit(stdout,
2304 i->inactive_exit_timestamp_monotonic,
2309 if (i->need_daemon_reload)
2310 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2311 ansi_highlight_red(true),
2312 ansi_highlight_red(false),
2313 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2316 static void show_unit_help(UnitStatusInfo *i) {
2321 if (!i->documentation) {
2322 log_info("Documentation for %s not known.", i->id);
2326 STRV_FOREACH(p, i->documentation) {
2328 if (startswith(*p, "man:")) {
2331 char *page = NULL, *section = NULL;
2332 const char *args[4] = { "man", NULL, NULL, NULL };
2337 if ((*p)[k-1] == ')')
2338 e = strrchr(*p, '(');
2341 page = strndup((*p) + 4, e - *p - 4);
2347 section = strndup(e + 1, *p + k - e - 2);
2361 log_error("Failed to fork: %m");
2369 execvp(args[0], (char**) args);
2370 log_error("Failed to execute man: %m");
2371 _exit(EXIT_FAILURE);
2377 wait_for_terminate(pid, NULL);
2379 log_info("Can't show: %s", *p);
2383 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2389 switch (dbus_message_iter_get_arg_type(iter)) {
2391 case DBUS_TYPE_STRING: {
2394 dbus_message_iter_get_basic(iter, &s);
2397 if (streq(name, "Id"))
2399 else if (streq(name, "LoadState"))
2401 else if (streq(name, "ActiveState"))
2402 i->active_state = s;
2403 else if (streq(name, "SubState"))
2405 else if (streq(name, "Description"))
2407 else if (streq(name, "FragmentPath"))
2408 i->fragment_path = s;
2409 else if (streq(name, "SourcePath"))
2411 else if (streq(name, "DefaultControlGroup"))
2412 i->default_control_group = s;
2413 else if (streq(name, "StatusText"))
2415 else if (streq(name, "SysFSPath"))
2417 else if (streq(name, "Where"))
2419 else if (streq(name, "What"))
2421 else if (streq(name, "Following"))
2423 else if (streq(name, "UnitFileState"))
2424 i->unit_file_state = s;
2425 else if (streq(name, "Result"))
2432 case DBUS_TYPE_BOOLEAN: {
2435 dbus_message_iter_get_basic(iter, &b);
2437 if (streq(name, "Accept"))
2439 else if (streq(name, "NeedDaemonReload"))
2440 i->need_daemon_reload = b;
2441 else if (streq(name, "ConditionResult"))
2442 i->condition_result = b;
2447 case DBUS_TYPE_UINT32: {
2450 dbus_message_iter_get_basic(iter, &u);
2452 if (streq(name, "MainPID")) {
2454 i->main_pid = (pid_t) u;
2457 } else if (streq(name, "ControlPID"))
2458 i->control_pid = (pid_t) u;
2459 else if (streq(name, "ExecMainPID")) {
2461 i->main_pid = (pid_t) u;
2462 } else if (streq(name, "NAccepted"))
2464 else if (streq(name, "NConnections"))
2465 i->n_connections = u;
2470 case DBUS_TYPE_INT32: {
2473 dbus_message_iter_get_basic(iter, &j);
2475 if (streq(name, "ExecMainCode"))
2476 i->exit_code = (int) j;
2477 else if (streq(name, "ExecMainStatus"))
2478 i->exit_status = (int) j;
2483 case DBUS_TYPE_UINT64: {
2486 dbus_message_iter_get_basic(iter, &u);
2488 if (streq(name, "ExecMainStartTimestamp"))
2489 i->start_timestamp = (usec_t) u;
2490 else if (streq(name, "ExecMainExitTimestamp"))
2491 i->exit_timestamp = (usec_t) u;
2492 else if (streq(name, "ActiveEnterTimestamp"))
2493 i->active_enter_timestamp = (usec_t) u;
2494 else if (streq(name, "InactiveEnterTimestamp"))
2495 i->inactive_enter_timestamp = (usec_t) u;
2496 else if (streq(name, "InactiveExitTimestamp"))
2497 i->inactive_exit_timestamp = (usec_t) u;
2498 else if (streq(name, "InactiveExitTimestampMonotonic"))
2499 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2500 else if (streq(name, "ActiveExitTimestamp"))
2501 i->active_exit_timestamp = (usec_t) u;
2502 else if (streq(name, "ConditionTimestamp"))
2503 i->condition_timestamp = (usec_t) u;
2508 case DBUS_TYPE_ARRAY: {
2510 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2511 startswith(name, "Exec")) {
2512 DBusMessageIter sub;
2514 dbus_message_iter_recurse(iter, &sub);
2515 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2516 ExecStatusInfo *info;
2519 if (!(info = new0(ExecStatusInfo, 1)))
2522 if (!(info->name = strdup(name))) {
2527 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2532 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2534 dbus_message_iter_next(&sub);
2536 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2537 streq(name, "Documentation")) {
2539 DBusMessageIter sub;
2541 dbus_message_iter_recurse(iter, &sub);
2542 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2546 dbus_message_iter_get_basic(&sub, &s);
2548 l = strv_append(i->documentation, s);
2552 strv_free(i->documentation);
2553 i->documentation = l;
2555 dbus_message_iter_next(&sub);
2562 case DBUS_TYPE_STRUCT: {
2564 if (streq(name, "LoadError")) {
2565 DBusMessageIter sub;
2566 const char *n, *message;
2569 dbus_message_iter_recurse(iter, &sub);
2571 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2575 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2579 if (!isempty(message))
2580 i->load_error = message;
2590 static int print_property(const char *name, DBusMessageIter *iter) {
2594 /* This is a low-level property printer, see
2595 * print_status_info() for the nicer output */
2597 if (arg_property && !strv_find(arg_property, name))
2600 switch (dbus_message_iter_get_arg_type(iter)) {
2602 case DBUS_TYPE_STRUCT: {
2603 DBusMessageIter sub;
2604 dbus_message_iter_recurse(iter, &sub);
2606 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2609 dbus_message_iter_get_basic(&sub, &u);
2612 printf("%s=%u\n", name, (unsigned) u);
2614 printf("%s=\n", name);
2617 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2620 dbus_message_iter_get_basic(&sub, &s);
2622 if (arg_all || s[0])
2623 printf("%s=%s\n", name, s);
2626 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
2627 const char *a = NULL, *b = NULL;
2629 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
2630 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
2632 if (arg_all || !isempty(a) || !isempty(b))
2633 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
2641 case DBUS_TYPE_ARRAY:
2643 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2644 DBusMessageIter sub, sub2;
2646 dbus_message_iter_recurse(iter, &sub);
2647 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2651 dbus_message_iter_recurse(&sub, &sub2);
2653 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2654 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2655 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2657 dbus_message_iter_next(&sub);
2662 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2663 DBusMessageIter sub, sub2;
2665 dbus_message_iter_recurse(iter, &sub);
2666 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2667 const char *type, *path;
2669 dbus_message_iter_recurse(&sub, &sub2);
2671 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2672 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2673 printf("%s=%s\n", type, path);
2675 dbus_message_iter_next(&sub);
2680 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2681 DBusMessageIter sub, sub2;
2683 dbus_message_iter_recurse(iter, &sub);
2684 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2686 uint64_t value, next_elapse;
2688 dbus_message_iter_recurse(&sub, &sub2);
2690 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2691 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2692 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2693 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2695 printf("%s={ value=%s ; next_elapse=%s }\n",
2697 format_timespan(timespan1, sizeof(timespan1), value),
2698 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2701 dbus_message_iter_next(&sub);
2706 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
2707 DBusMessageIter sub, sub2;
2709 dbus_message_iter_recurse(iter, &sub);
2710 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2711 const char *controller, *attr, *value;
2713 dbus_message_iter_recurse(&sub, &sub2);
2715 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
2716 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
2717 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
2719 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
2725 dbus_message_iter_next(&sub);
2730 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2731 DBusMessageIter sub;
2733 dbus_message_iter_recurse(iter, &sub);
2734 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2735 ExecStatusInfo info;
2738 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2739 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2742 t = strv_join(info.argv, " ");
2744 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2748 yes_no(info.ignore),
2749 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2750 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2751 (unsigned) info. pid,
2752 sigchld_code_to_string(info.code),
2754 info.code == CLD_EXITED ? "" : "/",
2755 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2761 strv_free(info.argv);
2763 dbus_message_iter_next(&sub);
2772 if (generic_print_property(name, iter, arg_all) > 0)
2776 printf("%s=[unprintable]\n", name);
2781 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2782 DBusMessage *reply = NULL;
2783 const char *interface = "";
2785 DBusMessageIter iter, sub, sub2, sub3;
2786 UnitStatusInfo info;
2794 r = bus_method_call_with_reply (
2796 "org.freedesktop.systemd1",
2798 "org.freedesktop.DBus.Properties",
2802 DBUS_TYPE_STRING, &interface,
2807 if (!dbus_message_iter_init(reply, &iter) ||
2808 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2809 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2810 log_error("Failed to parse reply.");
2815 dbus_message_iter_recurse(&iter, &sub);
2822 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2825 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2826 log_error("Failed to parse reply.");
2831 dbus_message_iter_recurse(&sub, &sub2);
2833 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2834 log_error("Failed to parse reply.");
2839 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2840 log_error("Failed to parse reply.");
2845 dbus_message_iter_recurse(&sub2, &sub3);
2847 if (show_properties)
2848 r = print_property(name, &sub3);
2850 r = status_property(name, &sub3, &info);
2853 log_error("Failed to parse reply.");
2858 dbus_message_iter_next(&sub);
2863 if (!show_properties) {
2864 if (streq(verb, "help"))
2865 show_unit_help(&info);
2867 print_status_info(&info);
2870 strv_free(info.documentation);
2872 if (!streq_ptr(info.active_state, "active") &&
2873 !streq_ptr(info.active_state, "reloading") &&
2874 streq(verb, "status"))
2875 /* According to LSB: "program not running" */
2878 while ((p = info.exec)) {
2879 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2880 exec_status_info_free(p);
2885 dbus_message_unref(reply);
2890 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
2891 DBusMessage *reply = NULL;
2892 const char *path = NULL;
2896 dbus_error_init(&error);
2898 r = bus_method_call_with_reply (
2900 "org.freedesktop.systemd1",
2901 "/org/freedesktop/systemd1",
2902 "org.freedesktop.systemd1.Manager",
2906 DBUS_TYPE_UINT32, &pid,
2911 if (!dbus_message_get_args(reply, &error,
2912 DBUS_TYPE_OBJECT_PATH, &path,
2913 DBUS_TYPE_INVALID)) {
2914 log_error("Failed to parse reply: %s", bus_error_message(&error));
2919 r = show_one(verb, bus, path, false, new_line);
2923 dbus_message_unref(reply);
2925 dbus_error_free(&error);
2930 static int show(DBusConnection *bus, char **args) {
2932 bool show_properties, new_line = false;
2938 show_properties = streq(args[0], "show");
2940 if (show_properties)
2941 pager_open_if_enabled();
2943 if (show_properties && strv_length(args) <= 1) {
2944 /* If not argument is specified inspect the manager
2947 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2950 STRV_FOREACH(name, args+1) {
2953 if (safe_atou32(*name, &id) < 0) {
2955 /* Interpret as unit name */
2957 n = unit_name_mangle(*name);
2958 p = unit_dbus_path_from_name(n ? n : *name);
2963 r = show_one(args[0], bus, p, show_properties, &new_line);
2969 } else if (show_properties) {
2971 /* Interpret as job id */
2974 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
2977 r = show_one(args[0], bus, p, show_properties, &new_line);
2985 /* Interpret as PID */
2987 r = show_one_by_pid(args[0], bus, id, &new_line);
2996 static int dump(DBusConnection *bus, char **args) {
2997 DBusMessage *reply = NULL;
3002 dbus_error_init(&error);
3004 pager_open_if_enabled();
3006 r = bus_method_call_with_reply (
3008 "org.freedesktop.systemd1",
3009 "/org/freedesktop/systemd1",
3010 "org.freedesktop.systemd1.Manager",
3018 if (!dbus_message_get_args(reply, &error,
3019 DBUS_TYPE_STRING, &text,
3020 DBUS_TYPE_INVALID)) {
3021 log_error("Failed to parse reply: %s", bus_error_message(&error));
3026 fputs(text, stdout);
3030 dbus_message_unref(reply);
3032 dbus_error_free(&error);
3037 static int snapshot(DBusConnection *bus, char **args) {
3038 DBusMessage *reply = NULL;
3041 dbus_bool_t cleanup = FALSE;
3042 DBusMessageIter iter, sub;
3044 *name = "", *path, *id,
3045 *interface = "org.freedesktop.systemd1.Unit",
3049 dbus_error_init(&error);
3051 if (strv_length(args) > 1)
3054 n = unit_name_mangle(name);
3055 r = bus_method_call_with_reply (
3057 "org.freedesktop.systemd1",
3058 "/org/freedesktop/systemd1",
3059 "org.freedesktop.systemd1.Manager",
3063 DBUS_TYPE_STRING, n ? (const char**) &n : &name,
3064 DBUS_TYPE_BOOLEAN, &cleanup,
3070 if (!dbus_message_get_args(reply, &error,
3071 DBUS_TYPE_OBJECT_PATH, &path,
3072 DBUS_TYPE_INVALID)) {
3073 log_error("Failed to parse reply: %s", bus_error_message(&error));
3078 dbus_message_unref(reply);
3079 r = bus_method_call_with_reply (
3081 "org.freedesktop.systemd1",
3083 "org.freedesktop.DBus.Properties",
3087 DBUS_TYPE_STRING, &interface,
3088 DBUS_TYPE_STRING, &property,
3093 if (!dbus_message_iter_init(reply, &iter) ||
3094 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3095 log_error("Failed to parse reply.");
3100 dbus_message_iter_recurse(&iter, &sub);
3102 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3103 log_error("Failed to parse reply.");
3108 dbus_message_iter_get_basic(&sub, &id);
3115 dbus_message_unref(reply);
3117 dbus_error_free(&error);
3122 static int delete_snapshot(DBusConnection *bus, char **args) {
3123 DBusMessage *reply = NULL;
3130 dbus_error_init(&error);
3132 STRV_FOREACH(name, args+1) {
3133 const char *path = NULL;
3136 n = unit_name_mangle(*name);
3137 r = bus_method_call_with_reply (
3139 "org.freedesktop.systemd1",
3140 "/org/freedesktop/systemd1",
3141 "org.freedesktop.systemd1.Manager",
3145 DBUS_TYPE_STRING, n ? &n : name,
3151 if (!dbus_message_get_args(reply, &error,
3152 DBUS_TYPE_OBJECT_PATH, &path,
3153 DBUS_TYPE_INVALID)) {
3154 log_error("Failed to parse reply: %s", bus_error_message(&error));
3156 dbus_message_unref(reply);
3157 dbus_error_free(&error);
3160 dbus_message_unref(reply);
3162 r = bus_method_call_with_reply (
3164 "org.freedesktop.systemd1",
3166 "org.freedesktop.systemd1.Snapshot",
3179 static int daemon_reload(DBusConnection *bus, char **args) {
3184 if (arg_action == ACTION_RELOAD)
3186 else if (arg_action == ACTION_REEXEC)
3187 method = "Reexecute";
3189 assert(arg_action == ACTION_SYSTEMCTL);
3192 streq(args[0], "clear-jobs") ||
3193 streq(args[0], "cancel") ? "ClearJobs" :
3194 streq(args[0], "daemon-reexec") ? "Reexecute" :
3195 streq(args[0], "reset-failed") ? "ResetFailed" :
3196 streq(args[0], "halt") ? "Halt" :
3197 streq(args[0], "poweroff") ? "PowerOff" :
3198 streq(args[0], "reboot") ? "Reboot" :
3199 streq(args[0], "kexec") ? "KExec" :
3200 streq(args[0], "exit") ? "Exit" :
3201 /* "daemon-reload" */ "Reload";
3204 r = bus_method_call_with_reply (
3206 "org.freedesktop.systemd1",
3207 "/org/freedesktop/systemd1",
3208 "org.freedesktop.systemd1.Manager",
3214 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
3215 /* There's always a fallback possible for
3216 * legacy actions. */
3218 else if (r == -ETIMEDOUT && streq(method, "Reexecute"))
3219 /* On reexecution, we expect a disconnect, not
3223 log_error("Failed to issue method call: %s", bus_error_message(&error));
3224 dbus_error_free(&error);
3229 static int reset_failed(DBusConnection *bus, char **args) {
3233 if (strv_length(args) <= 1)
3234 return daemon_reload(bus, args);
3236 STRV_FOREACH(name, args+1) {
3237 n = unit_name_mangle(*name);
3238 r = bus_method_call_with_reply (
3240 "org.freedesktop.systemd1",
3241 "/org/freedesktop/systemd1",
3242 "org.freedesktop.systemd1.Manager",
3246 DBUS_TYPE_STRING, n ? &n : name,
3257 static int show_enviroment(DBusConnection *bus, char **args) {
3258 DBusMessage *reply = NULL;
3259 DBusMessageIter iter, sub, sub2;
3262 *interface = "org.freedesktop.systemd1.Manager",
3263 *property = "Environment";
3265 pager_open_if_enabled();
3267 r = bus_method_call_with_reply (
3269 "org.freedesktop.systemd1",
3270 "/org/freedesktop/systemd1",
3271 "org.freedesktop.DBus.Properties",
3275 DBUS_TYPE_STRING, &interface,
3276 DBUS_TYPE_STRING, &property,
3281 if (!dbus_message_iter_init(reply, &iter) ||
3282 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3283 log_error("Failed to parse reply.");
3288 dbus_message_iter_recurse(&iter, &sub);
3290 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3291 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3292 log_error("Failed to parse reply.");
3297 dbus_message_iter_recurse(&sub, &sub2);
3299 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3302 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3303 log_error("Failed to parse reply.");
3308 dbus_message_iter_get_basic(&sub2, &text);
3309 printf("%s\n", text);
3311 dbus_message_iter_next(&sub2);
3318 dbus_message_unref(reply);
3323 static int switch_root(DBusConnection *bus, char **args) {
3325 const char *root, *init;
3327 l = strv_length(args);
3328 if (l < 2 || l > 3) {
3329 log_error("Wrong number of arguments.");
3334 init = l >= 3 ? args[2] : "";
3336 return bus_method_call_with_reply (
3338 "org.freedesktop.systemd1",
3339 "/org/freedesktop/systemd1",
3340 "org.freedesktop.systemd1.Manager",
3344 DBUS_TYPE_STRING, &root,
3345 DBUS_TYPE_STRING, &init,
3349 static int set_environment(DBusConnection *bus, char **args) {
3350 _cleanup_dbus_message_unref_ DBusMessage *m = NULL, *reply = NULL;
3353 DBusMessageIter iter;
3358 dbus_error_init(&error);
3360 method = streq(args[0], "set-environment")
3362 : "UnsetEnvironment";
3364 m = dbus_message_new_method_call(
3365 "org.freedesktop.systemd1",
3366 "/org/freedesktop/systemd1",
3367 "org.freedesktop.systemd1.Manager",
3372 dbus_message_iter_init_append(m, &iter);
3374 r = bus_append_strv_iter(&iter, args + 1);
3378 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3380 log_error("Failed to issue method call: %s", bus_error_message(&error));
3388 dbus_error_free(&error);
3392 static int enable_sysv_units(char **args) {
3395 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_ALTLINUX) || defined(TARGET_MAGEIA))
3396 const char *verb = args[0];
3397 unsigned f = 1, t = 1;
3400 if (arg_scope != UNIT_FILE_SYSTEM)
3403 if (!streq(verb, "enable") &&
3404 !streq(verb, "disable") &&
3405 !streq(verb, "is-enabled"))
3408 /* Processes all SysV units, and reshuffles the array so that
3409 * afterwards only the native units remain */
3412 r = lookup_paths_init(&paths, SYSTEMD_SYSTEM, false, NULL, NULL, NULL);
3417 for (f = 1; args[f]; f++) {
3420 bool found_native = false, found_sysv;
3422 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3423 char **k, *l, *q = NULL;
3430 if (!endswith(name, ".service"))
3433 if (path_is_absolute(name))
3436 STRV_FOREACH(k, paths.unit_path) {
3439 if (!isempty(arg_root))
3440 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3442 asprintf(&p, "%s/%s", *k, name);
3449 found_native = access(p, F_OK) >= 0;
3460 if (!isempty(arg_root))
3461 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3463 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3469 p[strlen(p) - sizeof(".service") + 1] = 0;
3470 found_sysv = access(p, F_OK) >= 0;
3477 /* Mark this entry, so that we don't try enabling it as native unit */
3478 args[f] = (char*) "";
3480 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
3482 if (!isempty(arg_root))
3483 argv[c++] = q = strappend("--root=", arg_root);
3485 argv[c++] = path_get_file_name(p);
3487 streq(verb, "enable") ? "on" :
3488 streq(verb, "disable") ? "off" : "--level=5";
3491 l = strv_join((char**)argv, " ");
3499 log_info("Executing %s", l);
3504 log_error("Failed to fork: %m");
3509 } else if (pid == 0) {
3512 execv(argv[0], (char**) argv);
3513 _exit(EXIT_FAILURE);
3519 j = wait_for_terminate(pid, &status);
3521 log_error("Failed to wait for child: %s", strerror(-r));
3526 if (status.si_code == CLD_EXITED) {
3527 if (streq(verb, "is-enabled")) {
3528 if (status.si_status == 0) {
3537 } else if (status.si_status != 0) {
3548 lookup_paths_free(&paths);
3550 /* Drop all SysV units */
3551 for (f = 1, t = 1; args[f]; f++) {
3553 if (isempty(args[f]))
3556 args[t++] = args[f];
3565 static int mangle_names(char **original_names, char ***mangled_names) {
3566 char **i, **l, **name;
3568 l = new(char*, strv_length(original_names) + 1);
3573 STRV_FOREACH(name, original_names) {
3575 /* When enabling units qualified path names are OK,
3576 * too, hence allow them explicitly. */
3581 *i = unit_name_mangle(*name);
3597 static int enable_unit(DBusConnection *bus, char **args) {
3598 const char *verb = args[0];
3599 UnitFileChange *changes = NULL;
3600 unsigned n_changes = 0, i;
3601 int carries_install_info = -1;
3602 DBusMessage *m = NULL, *reply = NULL;
3605 char **mangled_names = NULL;
3607 r = enable_sysv_units(args);
3614 dbus_error_init(&error);
3616 if (!bus || avoid_bus()) {
3617 if (streq(verb, "enable")) {
3618 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3619 carries_install_info = r;
3620 } else if (streq(verb, "disable"))
3621 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3622 else if (streq(verb, "reenable")) {
3623 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3624 carries_install_info = r;
3625 } else if (streq(verb, "link"))
3626 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3627 else if (streq(verb, "preset")) {
3628 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3629 carries_install_info = r;
3630 } else if (streq(verb, "mask"))
3631 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3632 else if (streq(verb, "unmask"))
3633 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3635 assert_not_reached("Unknown verb");
3638 log_error("Operation failed: %s", strerror(-r));
3643 for (i = 0; i < n_changes; i++) {
3644 if (changes[i].type == UNIT_FILE_SYMLINK)
3645 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
3647 log_info("rm '%s'", changes[i].path);
3654 bool send_force = true, expect_carries_install_info = false;
3656 DBusMessageIter iter, sub, sub2;
3658 if (streq(verb, "enable")) {
3659 method = "EnableUnitFiles";
3660 expect_carries_install_info = true;
3661 } else if (streq(verb, "disable")) {
3662 method = "DisableUnitFiles";
3664 } else if (streq(verb, "reenable")) {
3665 method = "ReenableUnitFiles";
3666 expect_carries_install_info = true;
3667 } else if (streq(verb, "link"))
3668 method = "LinkUnitFiles";
3669 else if (streq(verb, "preset")) {
3670 method = "PresetUnitFiles";
3671 expect_carries_install_info = true;
3672 } else if (streq(verb, "mask"))
3673 method = "MaskUnitFiles";
3674 else if (streq(verb, "unmask")) {
3675 method = "UnmaskUnitFiles";
3678 assert_not_reached("Unknown verb");
3680 m = dbus_message_new_method_call(
3681 "org.freedesktop.systemd1",
3682 "/org/freedesktop/systemd1",
3683 "org.freedesktop.systemd1.Manager",
3690 dbus_message_iter_init_append(m, &iter);
3692 r = mangle_names(args+1, &mangled_names);
3696 r = bus_append_strv_iter(&iter, mangled_names);
3698 log_error("Failed to append unit files.");
3703 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
3704 log_error("Failed to append runtime boolean.");
3712 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
3713 log_error("Failed to append force boolean.");
3719 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3721 log_error("Failed to issue method call: %s", bus_error_message(&error));
3726 if (!dbus_message_iter_init(reply, &iter)) {
3727 log_error("Failed to initialize iterator.");
3731 if (expect_carries_install_info) {
3732 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
3734 log_error("Failed to parse reply.");
3738 carries_install_info = b;
3741 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3742 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
3743 log_error("Failed to parse reply.");
3748 dbus_message_iter_recurse(&iter, &sub);
3749 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3750 const char *type, *path, *source;
3752 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
3753 log_error("Failed to parse reply.");
3758 dbus_message_iter_recurse(&sub, &sub2);
3760 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
3761 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
3762 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
3763 log_error("Failed to parse reply.");
3769 if (streq(type, "symlink"))
3770 log_info("ln -s '%s' '%s'", source, path);
3772 log_info("rm '%s'", path);
3775 dbus_message_iter_next(&sub);
3778 /* Try to reload if enabeld */
3780 r = daemon_reload(bus, args);
3783 if (carries_install_info == 0)
3784 log_warning("The unit files have no [Install] section. They are not meant to be enabled using systemctl.");
3788 dbus_message_unref(m);
3791 dbus_message_unref(reply);
3793 unit_file_changes_free(changes, n_changes);
3795 dbus_error_free(&error);
3797 strv_free(mangled_names);
3802 static int unit_is_enabled(DBusConnection *bus, char **args) {
3805 DBusMessage *reply = NULL;
3809 dbus_error_init(&error);
3811 r = enable_sysv_units(args);
3817 if (!bus || avoid_bus()) {
3819 STRV_FOREACH(name, args+1) {
3820 UnitFileState state;
3822 state = unit_file_get_state(arg_scope, arg_root, *name);
3828 if (state == UNIT_FILE_ENABLED ||
3829 state == UNIT_FILE_ENABLED_RUNTIME ||
3830 state == UNIT_FILE_STATIC)
3834 puts(unit_file_state_to_string(state));
3838 STRV_FOREACH(name, args+1) {
3841 r = bus_method_call_with_reply (
3843 "org.freedesktop.systemd1",
3844 "/org/freedesktop/systemd1",
3845 "org.freedesktop.systemd1.Manager",
3849 DBUS_TYPE_STRING, name,
3854 if (!dbus_message_get_args(reply, &error,
3855 DBUS_TYPE_STRING, &s,
3856 DBUS_TYPE_INVALID)) {
3857 log_error("Failed to parse reply: %s", bus_error_message(&error));
3862 dbus_message_unref(reply);
3865 if (streq(s, "enabled") ||
3866 streq(s, "enabled-runtime") ||
3875 r = enabled ? 0 : 1;
3879 dbus_message_unref(reply);
3881 dbus_error_free(&error);
3885 static int systemctl_help(void) {
3887 pager_open_if_enabled();
3889 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3890 "Query or send control commands to the systemd manager.\n\n"
3891 " -h --help Show this help\n"
3892 " --version Show package version\n"
3893 " -t --type=TYPE List only units of a particular type\n"
3894 " -p --property=NAME Show only properties by this name\n"
3895 " -a --all Show all units/properties, including dead/empty ones\n"
3896 " --failed Show only failed units\n"
3897 " --full Don't ellipsize unit names on output\n"
3898 " --fail When queueing a new job, fail if conflicting jobs are\n"
3900 " --ignore-dependencies\n"
3901 " When queueing a new job, ignore all its dependencies\n"
3902 " --kill-who=WHO Who to send signal to\n"
3903 " -s --signal=SIGNAL Which signal to send\n"
3904 " -H --host=[USER@]HOST\n"
3905 " Show information for remote host\n"
3906 " -P --privileged Acquire privileges before execution\n"
3907 " -q --quiet Suppress output\n"
3908 " --no-block Do not wait until operation finished\n"
3909 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3910 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3912 " --no-legend Do not print a legend (column headers and hints)\n"
3913 " --no-pager Do not pipe output into a pager\n"
3914 " --no-ask-password\n"
3915 " Do not ask for system passwords\n"
3916 " --order When generating graph for dot, show only order\n"
3917 " --require When generating graph for dot, show only requirement\n"
3918 " --system Connect to system manager\n"
3919 " --user Connect to user service manager\n"
3920 " --global Enable/disable unit files globally\n"
3921 " -f --force When enabling unit files, override existing symlinks\n"
3922 " When shutting down, execute action immediately\n"
3923 " --root=PATH Enable unit files in the specified root directory\n"
3924 " --runtime Enable unit files only temporarily until next reboot\n"
3925 " -n --lines=INTEGER Journal entries to show\n"
3926 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
3927 " verbose, export, json, json-pretty, json-sse, cat)\n\n"
3929 " list-units List loaded units\n"
3930 " start [NAME...] Start (activate) one or more units\n"
3931 " stop [NAME...] Stop (deactivate) one or more units\n"
3932 " reload [NAME...] Reload one or more units\n"
3933 " restart [NAME...] Start or restart one or more units\n"
3934 " try-restart [NAME...] Restart one or more units if active\n"
3935 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3936 " otherwise start or restart\n"
3937 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3938 " otherwise restart if active\n"
3939 " isolate [NAME] Start one unit and stop all others\n"
3940 " kill [NAME...] Send signal to processes of a unit\n"
3941 " is-active [NAME...] Check whether units are active\n"
3942 " status [NAME...|PID...] Show runtime status of one or more units\n"
3943 " show [NAME...|JOB...] Show properties of one or more\n"
3944 " units/jobs or the manager\n"
3945 " help [NAME...|PID...] Show manual for one or more units\n"
3946 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3948 " load [NAME...] Load one or more units\n\n"
3949 "Unit File Commands:\n"
3950 " list-unit-files List installed unit files\n"
3951 " enable [NAME...] Enable one or more unit files\n"
3952 " disable [NAME...] Disable one or more unit files\n"
3953 " reenable [NAME...] Reenable one or more unit files\n"
3954 " preset [NAME...] Enable/disable one or more unit files\n"
3955 " based on preset configuration\n"
3956 " mask [NAME...] Mask one or more units\n"
3957 " unmask [NAME...] Unmask one or more units\n"
3958 " link [PATH...] Link one or more units files into\n"
3959 " the search path\n"
3960 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
3962 " list-jobs List jobs\n"
3963 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
3964 "Status Commands:\n"
3965 " dump Dump server status\n"
3966 " dot Dump dependency graph for dot(1)\n\n"
3967 "Snapshot Commands:\n"
3968 " snapshot [NAME] Create a snapshot\n"
3969 " delete [NAME...] Remove one or more snapshots\n\n"
3970 "Environment Commands:\n"
3971 " show-environment Dump environment\n"
3972 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3973 " unset-environment [NAME...] Unset one or more environment variables\n\n"
3974 "Manager Lifecycle Commands:\n"
3975 " daemon-reload Reload systemd manager configuration\n"
3976 " daemon-reexec Reexecute systemd manager\n\n"
3977 "System Commands:\n"
3978 " default Enter system default mode\n"
3979 " rescue Enter system rescue mode\n"
3980 " emergency Enter system emergency mode\n"
3981 " halt Shut down and halt the system\n"
3982 " poweroff Shut down and power-off the system\n"
3983 " reboot Shut down and reboot the system\n"
3984 " kexec Shut down and reboot the system with kexec\n"
3985 " exit Request user instance exit\n"
3986 " switch-root [ROOT] [INIT] Change to a different root file system\n"
3987 " suspend Suspend the system\n"
3988 " hibernate Hibernate the system\n"
3989 " hybrid-sleep Hibernate and suspend the system\n",
3990 program_invocation_short_name);
3995 static int halt_help(void) {
3997 printf("%s [OPTIONS...]\n\n"
3998 "%s the system.\n\n"
3999 " --help Show this help\n"
4000 " --halt Halt the machine\n"
4001 " -p --poweroff Switch off the machine\n"
4002 " --reboot Reboot the machine\n"
4003 " -f --force Force immediate halt/power-off/reboot\n"
4004 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4005 " -d --no-wtmp Don't write wtmp record\n"
4006 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4007 program_invocation_short_name,
4008 arg_action == ACTION_REBOOT ? "Reboot" :
4009 arg_action == ACTION_POWEROFF ? "Power off" :
4015 static int shutdown_help(void) {
4017 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4018 "Shut down the system.\n\n"
4019 " --help Show this help\n"
4020 " -H --halt Halt the machine\n"
4021 " -P --poweroff Power-off the machine\n"
4022 " -r --reboot Reboot the machine\n"
4023 " -h Equivalent to --poweroff, overridden by --halt\n"
4024 " -k Don't halt/power-off/reboot, just send warnings\n"
4025 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4026 " -c Cancel a pending shutdown\n",
4027 program_invocation_short_name);
4032 static int telinit_help(void) {
4034 printf("%s [OPTIONS...] {COMMAND}\n\n"
4035 "Send control commands to the init daemon.\n\n"
4036 " --help Show this help\n"
4037 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4039 " 0 Power-off the machine\n"
4040 " 6 Reboot the machine\n"
4041 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4042 " 1, s, S Enter rescue mode\n"
4043 " q, Q Reload init daemon configuration\n"
4044 " u, U Reexecute init daemon\n",
4045 program_invocation_short_name);
4050 static int runlevel_help(void) {
4052 printf("%s [OPTIONS...]\n\n"
4053 "Prints the previous and current runlevel of the init system.\n\n"
4054 " --help Show this help\n",
4055 program_invocation_short_name);
4060 static int systemctl_parse_argv(int argc, char *argv[]) {
4064 ARG_IGNORE_DEPENDENCIES,
4079 ARG_NO_ASK_PASSWORD,
4085 static const struct option options[] = {
4086 { "help", no_argument, NULL, 'h' },
4087 { "version", no_argument, NULL, ARG_VERSION },
4088 { "type", required_argument, NULL, 't' },
4089 { "property", required_argument, NULL, 'p' },
4090 { "all", no_argument, NULL, 'a' },
4091 { "failed", no_argument, NULL, ARG_FAILED },
4092 { "full", no_argument, NULL, ARG_FULL },
4093 { "fail", no_argument, NULL, ARG_FAIL },
4094 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4095 { "user", no_argument, NULL, ARG_USER },
4096 { "system", no_argument, NULL, ARG_SYSTEM },
4097 { "global", no_argument, NULL, ARG_GLOBAL },
4098 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4099 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4100 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4101 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4102 { "quiet", no_argument, NULL, 'q' },
4103 { "order", no_argument, NULL, ARG_ORDER },
4104 { "require", no_argument, NULL, ARG_REQUIRE },
4105 { "root", required_argument, NULL, ARG_ROOT },
4106 { "force", no_argument, NULL, ARG_FORCE },
4107 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4108 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4109 { "signal", required_argument, NULL, 's' },
4110 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4111 { "host", required_argument, NULL, 'H' },
4112 { "privileged",no_argument, NULL, 'P' },
4113 { "runtime", no_argument, NULL, ARG_RUNTIME },
4114 { "lines", required_argument, NULL, 'n' },
4115 { "output", required_argument, NULL, 'o' },
4116 { NULL, 0, NULL, 0 }
4124 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4133 puts(PACKAGE_STRING);
4135 puts(SYSTEMD_FEATURES);
4139 if (unit_type_from_string(optarg) >= 0) {
4143 if (unit_load_state_from_string(optarg) >= 0) {
4144 arg_load_state = optarg;
4147 log_error("Unkown unit type or load state '%s'.",
4153 if (!(l = strv_append(arg_property, optarg)))
4156 strv_free(arg_property);
4159 /* If the user asked for a particular
4160 * property, show it to him, even if it is
4171 arg_job_mode = "fail";
4174 case ARG_IGNORE_DEPENDENCIES:
4175 arg_job_mode = "ignore-dependencies";
4179 arg_scope = UNIT_FILE_USER;
4183 arg_scope = UNIT_FILE_SYSTEM;
4187 arg_scope = UNIT_FILE_GLOBAL;
4191 arg_no_block = true;
4195 arg_no_legend = true;
4199 arg_no_pager = true;
4207 arg_dot = DOT_ORDER;
4211 arg_dot = DOT_REQUIRE;
4239 arg_no_reload = true;
4243 arg_kill_who = optarg;
4247 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4248 log_error("Failed to parse signal string %s.", optarg);
4253 case ARG_NO_ASK_PASSWORD:
4254 arg_ask_password = false;
4258 arg_transport = TRANSPORT_POLKIT;
4262 arg_transport = TRANSPORT_SSH;
4271 if (safe_atou(optarg, &arg_lines) < 0) {
4272 log_error("Failed to parse lines '%s'", optarg);
4278 arg_output = output_mode_from_string(optarg);
4279 if (arg_output < 0) {
4280 log_error("Unknown output '%s'.", optarg);
4289 log_error("Unknown option code '%c'.", c);
4294 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4295 log_error("Cannot access user instance remotely.");
4302 static int halt_parse_argv(int argc, char *argv[]) {
4311 static const struct option options[] = {
4312 { "help", no_argument, NULL, ARG_HELP },
4313 { "halt", no_argument, NULL, ARG_HALT },
4314 { "poweroff", no_argument, NULL, 'p' },
4315 { "reboot", no_argument, NULL, ARG_REBOOT },
4316 { "force", no_argument, NULL, 'f' },
4317 { "wtmp-only", no_argument, NULL, 'w' },
4318 { "no-wtmp", no_argument, NULL, 'd' },
4319 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4320 { NULL, 0, NULL, 0 }
4328 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4329 if (runlevel == '0' || runlevel == '6')
4332 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4340 arg_action = ACTION_HALT;
4344 if (arg_action != ACTION_REBOOT)
4345 arg_action = ACTION_POWEROFF;
4349 arg_action = ACTION_REBOOT;
4371 /* Compatibility nops */
4378 log_error("Unknown option code '%c'.", c);
4383 if (optind < argc) {
4384 log_error("Too many arguments.");
4391 static int parse_time_spec(const char *t, usec_t *_u) {
4395 if (streq(t, "now"))
4397 else if (!strchr(t, ':')) {
4400 if (safe_atou64(t, &u) < 0)
4403 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4412 hour = strtol(t, &e, 10);
4413 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4416 minute = strtol(e+1, &e, 10);
4417 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4420 n = now(CLOCK_REALTIME);
4421 s = (time_t) (n / USEC_PER_SEC);
4424 assert_se(localtime_r(&s, &tm));
4426 tm.tm_hour = (int) hour;
4427 tm.tm_min = (int) minute;
4430 assert_se(s = mktime(&tm));
4432 *_u = (usec_t) s * USEC_PER_SEC;
4435 *_u += USEC_PER_DAY;
4441 static int shutdown_parse_argv(int argc, char *argv[]) {
4448 static const struct option options[] = {
4449 { "help", no_argument, NULL, ARG_HELP },
4450 { "halt", no_argument, NULL, 'H' },
4451 { "poweroff", no_argument, NULL, 'P' },
4452 { "reboot", no_argument, NULL, 'r' },
4453 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4454 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4455 { NULL, 0, NULL, 0 }
4463 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4471 arg_action = ACTION_HALT;
4475 arg_action = ACTION_POWEROFF;
4480 arg_action = ACTION_KEXEC;
4482 arg_action = ACTION_REBOOT;
4486 arg_action = ACTION_KEXEC;
4490 if (arg_action != ACTION_HALT)
4491 arg_action = ACTION_POWEROFF;
4504 /* Compatibility nops */
4508 arg_action = ACTION_CANCEL_SHUTDOWN;
4515 log_error("Unknown option code '%c'.", c);
4520 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
4521 r = parse_time_spec(argv[optind], &arg_when);
4523 log_error("Failed to parse time specification: %s", argv[optind]);
4527 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4529 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
4530 /* No time argument for shutdown cancel */
4531 arg_wall = argv + optind;
4532 else if (argc > optind + 1)
4533 /* We skip the time argument */
4534 arg_wall = argv + optind + 1;
4541 static int telinit_parse_argv(int argc, char *argv[]) {
4548 static const struct option options[] = {
4549 { "help", no_argument, NULL, ARG_HELP },
4550 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4551 { NULL, 0, NULL, 0 }
4554 static const struct {
4558 { '0', ACTION_POWEROFF },
4559 { '6', ACTION_REBOOT },
4560 { '1', ACTION_RESCUE },
4561 { '2', ACTION_RUNLEVEL2 },
4562 { '3', ACTION_RUNLEVEL3 },
4563 { '4', ACTION_RUNLEVEL4 },
4564 { '5', ACTION_RUNLEVEL5 },
4565 { 's', ACTION_RESCUE },
4566 { 'S', ACTION_RESCUE },
4567 { 'q', ACTION_RELOAD },
4568 { 'Q', ACTION_RELOAD },
4569 { 'u', ACTION_REEXEC },
4570 { 'U', ACTION_REEXEC }
4579 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4594 log_error("Unknown option code '%c'.", c);
4599 if (optind >= argc) {
4604 if (optind + 1 < argc) {
4605 log_error("Too many arguments.");
4609 if (strlen(argv[optind]) != 1) {
4610 log_error("Expected single character argument.");
4614 for (i = 0; i < ELEMENTSOF(table); i++)
4615 if (table[i].from == argv[optind][0])
4618 if (i >= ELEMENTSOF(table)) {
4619 log_error("Unknown command '%s'.", argv[optind]);
4623 arg_action = table[i].to;
4630 static int runlevel_parse_argv(int argc, char *argv[]) {
4636 static const struct option options[] = {
4637 { "help", no_argument, NULL, ARG_HELP },
4638 { NULL, 0, NULL, 0 }
4646 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4657 log_error("Unknown option code '%c'.", c);
4662 if (optind < argc) {
4663 log_error("Too many arguments.");
4670 static int parse_argv(int argc, char *argv[]) {
4674 if (program_invocation_short_name) {
4676 if (strstr(program_invocation_short_name, "halt")) {
4677 arg_action = ACTION_HALT;
4678 return halt_parse_argv(argc, argv);
4679 } else if (strstr(program_invocation_short_name, "poweroff")) {
4680 arg_action = ACTION_POWEROFF;
4681 return halt_parse_argv(argc, argv);
4682 } else if (strstr(program_invocation_short_name, "reboot")) {
4684 arg_action = ACTION_KEXEC;
4686 arg_action = ACTION_REBOOT;
4687 return halt_parse_argv(argc, argv);
4688 } else if (strstr(program_invocation_short_name, "shutdown")) {
4689 arg_action = ACTION_POWEROFF;
4690 return shutdown_parse_argv(argc, argv);
4691 } else if (strstr(program_invocation_short_name, "init")) {
4693 if (sd_booted() > 0) {
4694 arg_action = ACTION_INVALID;
4695 return telinit_parse_argv(argc, argv);
4697 /* Hmm, so some other init system is
4698 * running, we need to forward this
4699 * request to it. For now we simply
4700 * guess that it is Upstart. */
4702 execv("/lib/upstart/telinit", argv);
4704 log_error("Couldn't find an alternative telinit implementation to spawn.");
4708 } else if (strstr(program_invocation_short_name, "runlevel")) {
4709 arg_action = ACTION_RUNLEVEL;
4710 return runlevel_parse_argv(argc, argv);
4714 arg_action = ACTION_SYSTEMCTL;
4715 return systemctl_parse_argv(argc, argv);
4718 static int action_to_runlevel(void) {
4720 static const char table[_ACTION_MAX] = {
4721 [ACTION_HALT] = '0',
4722 [ACTION_POWEROFF] = '0',
4723 [ACTION_REBOOT] = '6',
4724 [ACTION_RUNLEVEL2] = '2',
4725 [ACTION_RUNLEVEL3] = '3',
4726 [ACTION_RUNLEVEL4] = '4',
4727 [ACTION_RUNLEVEL5] = '5',
4728 [ACTION_RESCUE] = '1'
4731 assert(arg_action < _ACTION_MAX);
4733 return table[arg_action];
4736 static int talk_upstart(void) {
4737 DBusMessage *m = NULL, *reply = NULL;
4739 int previous, rl, r;
4741 env1_buf[] = "RUNLEVEL=X",
4742 env2_buf[] = "PREVLEVEL=X";
4743 char *env1 = env1_buf, *env2 = env2_buf;
4744 const char *emit = "runlevel";
4745 dbus_bool_t b_false = FALSE;
4746 DBusMessageIter iter, sub;
4747 DBusConnection *bus;
4749 dbus_error_init(&error);
4751 if (!(rl = action_to_runlevel()))
4754 if (utmp_get_runlevel(&previous, NULL) < 0)
4757 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4758 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4763 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4768 if ((r = bus_check_peercred(bus)) < 0) {
4769 log_error("Failed to verify owner of bus.");
4773 if (!(m = dbus_message_new_method_call(
4774 "com.ubuntu.Upstart",
4775 "/com/ubuntu/Upstart",
4776 "com.ubuntu.Upstart0_6",
4779 log_error("Could not allocate message.");
4784 dbus_message_iter_init_append(m, &iter);
4786 env1_buf[sizeof(env1_buf)-2] = rl;
4787 env2_buf[sizeof(env2_buf)-2] = previous;
4789 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4790 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4791 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4792 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4793 !dbus_message_iter_close_container(&iter, &sub) ||
4794 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4795 log_error("Could not append arguments to message.");
4800 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4802 if (bus_error_is_no_service(&error)) {
4807 log_error("Failed to issue method call: %s", bus_error_message(&error));
4816 dbus_message_unref(m);
4819 dbus_message_unref(reply);
4822 dbus_connection_flush(bus);
4823 dbus_connection_close(bus);
4824 dbus_connection_unref(bus);
4827 dbus_error_free(&error);
4832 static int talk_initctl(void) {
4833 struct init_request request;
4837 if (!(rl = action_to_runlevel()))
4841 request.magic = INIT_MAGIC;
4842 request.sleeptime = 0;
4843 request.cmd = INIT_CMD_RUNLVL;
4844 request.runlevel = rl;
4846 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4848 if (errno == ENOENT)
4851 log_error("Failed to open "INIT_FIFO": %m");
4856 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4857 close_nointr_nofail(fd);
4860 log_error("Failed to write to "INIT_FIFO": %m");
4861 return errno ? -errno : -EIO;
4867 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4869 static const struct {
4877 int (* const dispatch)(DBusConnection *bus, char **args);
4879 { "list-units", LESS, 1, list_units },
4880 { "list-unit-files", EQUAL, 1, list_unit_files },
4881 { "list-jobs", EQUAL, 1, list_jobs },
4882 { "clear-jobs", EQUAL, 1, daemon_reload },
4883 { "load", MORE, 2, load_unit },
4884 { "cancel", MORE, 2, cancel_job },
4885 { "start", MORE, 2, start_unit },
4886 { "stop", MORE, 2, start_unit },
4887 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4888 { "reload", MORE, 2, start_unit },
4889 { "restart", MORE, 2, start_unit },
4890 { "try-restart", MORE, 2, start_unit },
4891 { "reload-or-restart", MORE, 2, start_unit },
4892 { "reload-or-try-restart", MORE, 2, start_unit },
4893 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4894 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4895 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4896 { "isolate", EQUAL, 2, start_unit },
4897 { "kill", MORE, 2, kill_unit },
4898 { "is-active", MORE, 2, check_unit },
4899 { "check", MORE, 2, check_unit },
4900 { "show", MORE, 1, show },
4901 { "status", MORE, 2, show },
4902 { "help", MORE, 2, show },
4903 { "dump", EQUAL, 1, dump },
4904 { "dot", EQUAL, 1, dot },
4905 { "snapshot", LESS, 2, snapshot },
4906 { "delete", MORE, 2, delete_snapshot },
4907 { "daemon-reload", EQUAL, 1, daemon_reload },
4908 { "daemon-reexec", EQUAL, 1, daemon_reload },
4909 { "show-environment", EQUAL, 1, show_enviroment },
4910 { "set-environment", MORE, 2, set_environment },
4911 { "unset-environment", MORE, 2, set_environment },
4912 { "halt", EQUAL, 1, start_special },
4913 { "poweroff", EQUAL, 1, start_special },
4914 { "reboot", EQUAL, 1, start_special },
4915 { "kexec", EQUAL, 1, start_special },
4916 { "suspend", EQUAL, 1, start_special },
4917 { "hibernate", EQUAL, 1, start_special },
4918 { "hybrid-sleep", EQUAL, 1, start_special },
4919 { "default", EQUAL, 1, start_special },
4920 { "rescue", EQUAL, 1, start_special },
4921 { "emergency", EQUAL, 1, start_special },
4922 { "exit", EQUAL, 1, start_special },
4923 { "reset-failed", MORE, 1, reset_failed },
4924 { "enable", MORE, 2, enable_unit },
4925 { "disable", MORE, 2, enable_unit },
4926 { "is-enabled", MORE, 2, unit_is_enabled },
4927 { "reenable", MORE, 2, enable_unit },
4928 { "preset", MORE, 2, enable_unit },
4929 { "mask", MORE, 2, enable_unit },
4930 { "unmask", MORE, 2, enable_unit },
4931 { "link", MORE, 2, enable_unit },
4932 { "switch-root", MORE, 2, switch_root },
4942 left = argc - optind;
4945 /* Special rule: no arguments means "list-units" */
4948 if (streq(argv[optind], "help") && !argv[optind+1]) {
4949 log_error("This command expects one or more "
4950 "unit names. Did you mean --help?");
4954 for (i = 0; i < ELEMENTSOF(verbs); i++)
4955 if (streq(argv[optind], verbs[i].verb))
4958 if (i >= ELEMENTSOF(verbs)) {
4959 log_error("Unknown operation '%s'.", argv[optind]);
4964 switch (verbs[i].argc_cmp) {
4967 if (left != verbs[i].argc) {
4968 log_error("Invalid number of arguments.");
4975 if (left < verbs[i].argc) {
4976 log_error("Too few arguments.");
4983 if (left > verbs[i].argc) {
4984 log_error("Too many arguments.");
4991 assert_not_reached("Unknown comparison operator.");
4994 /* Require a bus connection for all operations but
4996 if (!streq(verbs[i].verb, "enable") &&
4997 !streq(verbs[i].verb, "disable") &&
4998 !streq(verbs[i].verb, "is-enabled") &&
4999 !streq(verbs[i].verb, "list-unit-files") &&
5000 !streq(verbs[i].verb, "reenable") &&
5001 !streq(verbs[i].verb, "preset") &&
5002 !streq(verbs[i].verb, "mask") &&
5003 !streq(verbs[i].verb, "unmask") &&
5004 !streq(verbs[i].verb, "link")) {
5006 if (running_in_chroot() > 0) {
5007 log_info("Running in chroot, ignoring request.");
5011 if (((!streq(verbs[i].verb, "reboot") &&
5012 !streq(verbs[i].verb, "halt") &&
5013 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5014 log_error("Failed to get D-Bus connection: %s",
5015 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5021 if (!bus && !avoid_bus()) {
5022 log_error("Failed to get D-Bus connection: %s",
5023 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5028 return verbs[i].dispatch(bus, argv + optind);
5031 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5033 struct msghdr msghdr;
5034 struct iovec iovec[2];
5035 union sockaddr_union sockaddr;
5036 struct sd_shutdown_command c;
5038 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5045 c.dry_run = dry_run;
5049 sockaddr.sa.sa_family = AF_UNIX;
5050 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5053 msghdr.msg_name = &sockaddr;
5054 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5057 iovec[0].iov_base = (char*) &c;
5058 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5060 if (isempty(message))
5061 msghdr.msg_iovlen = 1;
5063 iovec[1].iov_base = (char*) message;
5064 iovec[1].iov_len = strlen(message);
5065 msghdr.msg_iovlen = 2;
5067 msghdr.msg_iov = iovec;
5069 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5070 close_nointr_nofail(fd);
5074 close_nointr_nofail(fd);
5078 static int reload_with_fallback(DBusConnection *bus) {
5081 /* First, try systemd via D-Bus. */
5082 if (daemon_reload(bus, NULL) >= 0)
5086 /* Nothing else worked, so let's try signals */
5087 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5089 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5090 log_error("kill() failed: %m");
5097 static int start_with_fallback(DBusConnection *bus) {
5100 /* First, try systemd via D-Bus. */
5101 if (start_unit(bus, NULL) >= 0)
5105 /* Hmm, talking to systemd via D-Bus didn't work. Then
5106 * let's try to talk to Upstart via D-Bus. */
5107 if (talk_upstart() > 0)
5110 /* Nothing else worked, so let's try
5112 if (talk_initctl() > 0)
5115 log_error("Failed to talk to init daemon.");
5119 warn_wall(arg_action);
5123 static _noreturn_ void halt_now(enum action a) {
5125 /* Make sure C-A-D is handled by the kernel from this
5127 reboot(RB_ENABLE_CAD);
5132 log_info("Halting.");
5133 reboot(RB_HALT_SYSTEM);
5136 case ACTION_POWEROFF:
5137 log_info("Powering off.");
5138 reboot(RB_POWER_OFF);
5142 log_info("Rebooting.");
5143 reboot(RB_AUTOBOOT);
5147 assert_not_reached("Unknown halt action.");
5150 assert_not_reached("Uh? This shouldn't happen.");
5153 static int halt_main(DBusConnection *bus) {
5156 if (geteuid() != 0) {
5157 /* Try logind if we are a normal user and no special
5158 * mode applies. Maybe PolicyKit allows us to shutdown
5161 if (arg_when <= 0 &&
5164 (arg_action == ACTION_POWEROFF ||
5165 arg_action == ACTION_REBOOT)) {
5166 r = reboot_with_logind(bus, arg_action);
5171 log_error("Must be root.");
5178 m = strv_join(arg_wall, " ");
5179 r = send_shutdownd(arg_when,
5180 arg_action == ACTION_HALT ? 'H' :
5181 arg_action == ACTION_POWEROFF ? 'P' :
5182 arg_action == ACTION_KEXEC ? 'K' :
5190 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5192 char date[FORMAT_TIMESTAMP_MAX];
5194 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5195 format_timestamp(date, sizeof(date), arg_when));
5200 if (!arg_dry && !arg_force)
5201 return start_with_fallback(bus);
5204 if (sd_booted() > 0)
5205 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5207 r = utmp_put_shutdown();
5209 log_warning("Failed to write utmp record: %s", strerror(-r));
5216 halt_now(arg_action);
5217 /* We should never reach this. */
5221 static int runlevel_main(void) {
5222 int r, runlevel, previous;
5224 r = utmp_get_runlevel(&runlevel, &previous);
5231 previous <= 0 ? 'N' : previous,
5232 runlevel <= 0 ? 'N' : runlevel);
5237 int main(int argc, char*argv[]) {
5238 int r, retval = EXIT_FAILURE;
5239 DBusConnection *bus = NULL;
5242 dbus_error_init(&error);
5244 setlocale(LC_ALL, "");
5245 log_parse_environment();
5248 r = parse_argv(argc, argv);
5252 retval = EXIT_SUCCESS;
5256 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5257 * let's shortcut this */
5258 if (arg_action == ACTION_RUNLEVEL) {
5259 r = runlevel_main();
5260 retval = r < 0 ? EXIT_FAILURE : r;
5264 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5265 log_info("Running in chroot, ignoring request.");
5271 if (arg_transport == TRANSPORT_NORMAL)
5272 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5273 else if (arg_transport == TRANSPORT_POLKIT) {
5274 bus_connect_system_polkit(&bus, &error);
5275 private_bus = false;
5276 } else if (arg_transport == TRANSPORT_SSH) {
5277 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5278 private_bus = false;
5280 assert_not_reached("Uh, invalid transport...");
5283 switch (arg_action) {
5285 case ACTION_SYSTEMCTL:
5286 r = systemctl_main(bus, argc, argv, &error);
5290 case ACTION_POWEROFF:
5296 case ACTION_RUNLEVEL2:
5297 case ACTION_RUNLEVEL3:
5298 case ACTION_RUNLEVEL4:
5299 case ACTION_RUNLEVEL5:
5301 case ACTION_EMERGENCY:
5302 case ACTION_DEFAULT:
5303 r = start_with_fallback(bus);
5308 r = reload_with_fallback(bus);
5311 case ACTION_CANCEL_SHUTDOWN: {
5315 m = strv_join(arg_wall, " ");
5317 retval = EXIT_FAILURE;
5321 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
5323 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
5328 case ACTION_INVALID:
5329 case ACTION_RUNLEVEL:
5331 assert_not_reached("Unknown action");
5334 retval = r < 0 ? EXIT_FAILURE : r;
5338 dbus_connection_flush(bus);
5339 dbus_connection_close(bus);
5340 dbus_connection_unref(bus);
5343 dbus_error_free(&error);
5347 strv_free(arg_property);
5350 ask_password_agent_close();
5351 polkit_agent_close();