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>
28 #include <sys/ioctl.h>
32 #include <sys/socket.h>
35 #include <sys/prctl.h>
36 #include <dbus/dbus.h>
38 #include <systemd/sd-daemon.h>
39 #include <systemd/sd-shutdown.h>
45 #include "utmp-wtmp.h"
48 #include "path-util.h"
50 #include "dbus-common.h"
51 #include "cgroup-show.h"
52 #include "cgroup-util.h"
54 #include "path-lookup.h"
55 #include "conf-parser.h"
56 #include "exit-status.h"
57 #include "bus-errors.h"
59 #include "unit-name.h"
61 #include "spawn-ask-password-agent.h"
62 #include "spawn-polkit-agent.h"
64 #include "logs-show.h"
65 #include "path-util.h"
66 #include "socket-util.h"
68 static const char *arg_type = NULL;
69 static const char *arg_load_state = NULL;
70 static char **arg_property = NULL;
71 static bool arg_all = false;
72 static const char *arg_job_mode = "replace";
73 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
74 static bool arg_no_block = false;
75 static bool arg_no_legend = false;
76 static bool arg_no_pager = false;
77 static bool arg_no_wtmp = false;
78 static bool arg_no_wall = false;
79 static bool arg_no_reload = false;
80 static bool arg_dry = false;
81 static bool arg_quiet = false;
82 static bool arg_full = false;
83 static int arg_force = 0;
84 static bool arg_ask_password = true;
85 static bool arg_failed = false;
86 static bool arg_runtime = false;
87 static char **arg_wall = NULL;
88 static const char *arg_kill_who = NULL;
89 static int arg_signal = SIGTERM;
90 static const char *arg_root = NULL;
91 static usec_t arg_when = 0;
112 ACTION_CANCEL_SHUTDOWN,
114 } arg_action = ACTION_SYSTEMCTL;
120 static enum transport {
124 } arg_transport = TRANSPORT_NORMAL;
125 static const char *arg_host = NULL;
126 static unsigned arg_lines = 10;
127 static OutputMode arg_output = OUTPUT_SHORT;
129 static bool private_bus = false;
131 static int daemon_reload(DBusConnection *bus, char **args);
132 static void halt_now(enum action a);
134 static void pager_open_if_enabled(void) {
142 static void ask_password_agent_open_if_enabled(void) {
144 /* Open the password agent as a child process if necessary */
146 if (!arg_ask_password)
149 if (arg_scope != UNIT_FILE_SYSTEM)
152 ask_password_agent_open();
156 static void polkit_agent_open_if_enabled(void) {
158 /* Open the polkit agent as a child process if necessary */
160 if (!arg_ask_password)
163 if (arg_scope != UNIT_FILE_SYSTEM)
170 static const char *ansi_highlight(bool b) {
175 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
178 static const char *ansi_highlight_red(bool b) {
183 return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
186 static const char *ansi_highlight_green(bool b) {
191 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
194 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
197 if (!dbus_error_is_set(error))
200 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
201 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
202 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
203 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
204 return EXIT_NOPERMISSION;
206 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
207 return EXIT_NOTINSTALLED;
209 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
210 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
211 return EXIT_NOTIMPLEMENTED;
213 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
214 return EXIT_NOTCONFIGURED;
222 static void warn_wall(enum action a) {
223 static const char *table[_ACTION_MAX] = {
224 [ACTION_HALT] = "The system is going down for system halt NOW!",
225 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
226 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
227 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
228 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
229 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!",
230 [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
239 p = strv_join(arg_wall, " ");
241 log_error("Failed to join strings.");
257 utmp_wall(table[a], NULL);
260 static bool avoid_bus(void) {
262 if (running_in_chroot() > 0)
265 if (sd_booted() <= 0)
268 if (!isempty(arg_root))
271 if (arg_scope == UNIT_FILE_GLOBAL)
279 const char *description;
280 const char *load_state;
281 const char *active_state;
282 const char *sub_state;
283 const char *following;
284 const char *unit_path;
286 const char *job_type;
287 const char *job_path;
290 static int compare_unit_info(const void *a, const void *b) {
292 const struct unit_info *u = a, *v = b;
294 d1 = strrchr(u->id, '.');
295 d2 = strrchr(v->id, '.');
300 if ((r = strcasecmp(d1, d2)) != 0)
304 return strcasecmp(u->id, v->id);
307 static bool output_show_unit(const struct unit_info *u) {
311 return streq(u->active_state, "failed");
313 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
314 streq(dot+1, arg_type))) &&
315 (!arg_load_state || streq(u->load_state, arg_load_state)) &&
316 (arg_all || !(streq(u->active_state, "inactive")
317 || u->following[0]) || u->job_id > 0);
320 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
321 unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
322 const struct unit_info *u;
324 max_id_len = sizeof("UNIT")-1;
325 active_len = sizeof("ACTIVE")-1;
326 sub_len = sizeof("SUB")-1;
327 job_len = sizeof("JOB")-1;
330 for (u = unit_infos; u < unit_infos + c; u++) {
331 if (!output_show_unit(u))
334 max_id_len = MAX(max_id_len, strlen(u->id));
335 active_len = MAX(active_len, strlen(u->active_state));
336 sub_len = MAX(sub_len, strlen(u->sub_state));
338 job_len = MAX(job_len, strlen(u->job_type));
343 id_len = MIN(max_id_len, 25);
344 basic_len = 5 + id_len + 6 + active_len + sub_len + job_len;
345 if (basic_len < (unsigned) columns()) {
346 unsigned extra_len, incr;
347 extra_len = columns() - basic_len;
348 /* Either UNIT already got 25, or is fully satisfied.
349 * Grant up to 25 to DESC now. */
350 incr = MIN(extra_len, 25);
353 /* split the remaining space between UNIT and DESC,
354 * but do not give UNIT more than it needs. */
356 incr = MIN(extra_len / 2, max_id_len - id_len);
358 desc_len += extra_len - incr;
364 for (u = unit_infos; u < unit_infos + c; u++) {
366 const char *on_loaded, *off_loaded;
367 const char *on_active, *off_active;
369 if (!output_show_unit(u))
372 if (!n_shown && !arg_no_legend) {
373 printf("%-*s %-6s %-*s %-*s %-*s ", id_len, "UNIT", "LOAD",
374 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
375 if (!arg_full && arg_no_pager)
376 printf("%.*s\n", desc_len, "DESCRIPTION");
378 printf("%s\n", "DESCRIPTION");
383 if (streq(u->load_state, "error")) {
384 on_loaded = ansi_highlight_red(true);
385 off_loaded = ansi_highlight_red(false);
387 on_loaded = off_loaded = "";
389 if (streq(u->active_state, "failed")) {
390 on_active = ansi_highlight_red(true);
391 off_active = ansi_highlight_red(false);
393 on_active = off_active = "";
395 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
397 printf("%-*s %s%-6s%s %s%-*s %-*s%s %-*s ",
398 id_len, e ? e : u->id,
399 on_loaded, u->load_state, off_loaded,
400 on_active, active_len, u->active_state,
401 sub_len, u->sub_state, off_active,
402 job_len, u->job_id ? u->job_type : "");
403 if (!arg_full && arg_no_pager)
404 printf("%.*s\n", desc_len, u->description);
406 printf("%s\n", u->description);
411 if (!arg_no_legend) {
412 const char *on, *off;
415 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
416 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
417 "SUB = The low-level unit activation state, values depend on unit type.\n"
418 "JOB = Pending job for the unit.\n\n");
419 on = ansi_highlight(true);
420 off = ansi_highlight(false);
422 on = ansi_highlight_red(true);
423 off = ansi_highlight_red(false);
427 printf("%s%u loaded units listed.%s\n"
428 "To show all installed unit files use 'systemctl list-unit-files'.\n",
431 printf("%s%u loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
432 "To show all installed unit files use 'systemctl list-unit-files'.\n",
437 static int list_units(DBusConnection *bus, char **args) {
438 DBusMessage *reply = NULL;
440 DBusMessageIter iter, sub, sub2;
441 unsigned c = 0, n_units = 0;
442 struct unit_info *unit_infos = NULL;
444 pager_open_if_enabled();
446 r = bus_method_call_with_reply (
448 "org.freedesktop.systemd1",
449 "/org/freedesktop/systemd1",
450 "org.freedesktop.systemd1.Manager",
458 if (!dbus_message_iter_init(reply, &iter) ||
459 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
460 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
461 log_error("Failed to parse reply.");
466 dbus_message_iter_recurse(&iter, &sub);
468 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
471 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
472 log_error("Failed to parse reply.");
480 n_units = MAX(2*c, 16);
481 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
484 log_error("Failed to allocate unit array.");
494 dbus_message_iter_recurse(&sub, &sub2);
496 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
497 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
498 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
499 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
500 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
501 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
502 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
503 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
504 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
505 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
506 log_error("Failed to parse reply.");
511 dbus_message_iter_next(&sub);
516 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
517 output_units_list(unit_infos, c);
522 dbus_message_unref(reply);
529 static int compare_unit_file_list(const void *a, const void *b) {
531 const UnitFileList *u = a, *v = b;
533 d1 = strrchr(u->path, '.');
534 d2 = strrchr(v->path, '.');
539 r = strcasecmp(d1, d2);
544 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
547 static bool output_show_unit_file(const UnitFileList *u) {
550 return !arg_type || ((dot = strrchr(u->path, '.')) && streq(dot+1, arg_type));
553 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
554 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
555 const UnitFileList *u;
557 max_id_len = sizeof("UNIT FILE")-1;
558 state_cols = sizeof("STATE")-1;
559 for (u = units; u < units + c; u++) {
560 if (!output_show_unit_file(u))
563 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
564 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
569 id_cols = MIN(max_id_len, 25);
570 basic_cols = 1 + id_cols + state_cols;
571 if (basic_cols < (unsigned) columns())
572 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
574 id_cols = max_id_len;
577 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
579 for (u = units; u < units + c; u++) {
581 const char *on, *off;
584 if (!output_show_unit_file(u))
589 if (u->state == UNIT_FILE_MASKED ||
590 u->state == UNIT_FILE_MASKED_RUNTIME ||
591 u->state == UNIT_FILE_DISABLED ||
592 u->state == UNIT_FILE_INVALID) {
593 on = ansi_highlight_red(true);
594 off = ansi_highlight_red(false);
595 } else if (u->state == UNIT_FILE_ENABLED) {
596 on = ansi_highlight_green(true);
597 off = ansi_highlight_green(false);
601 id = path_get_file_name(u->path);
603 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
605 printf("%-*s %s%-*s%s\n",
607 on, state_cols, unit_file_state_to_string(u->state), off);
613 printf("\n%u unit files listed.\n", n_shown);
616 static int list_unit_files(DBusConnection *bus, char **args) {
617 DBusMessage *reply = NULL;
619 DBusMessageIter iter, sub, sub2;
620 unsigned c = 0, n_units = 0;
621 UnitFileList *units = NULL;
623 pager_open_if_enabled();
630 h = hashmap_new(string_hash_func, string_compare_func);
634 r = unit_file_get_list(arg_scope, arg_root, h);
636 unit_file_list_free(h);
637 log_error("Failed to get unit file list: %s", strerror(-r));
641 n_units = hashmap_size(h);
642 units = new(UnitFileList, n_units);
644 unit_file_list_free(h);
648 HASHMAP_FOREACH(u, h, i) {
649 memcpy(units + c++, u, sizeof(UnitFileList));
655 r = bus_method_call_with_reply (
657 "org.freedesktop.systemd1",
658 "/org/freedesktop/systemd1",
659 "org.freedesktop.systemd1.Manager",
667 if (!dbus_message_iter_init(reply, &iter) ||
668 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
669 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
670 log_error("Failed to parse reply.");
675 dbus_message_iter_recurse(&iter, &sub);
677 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
681 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
682 log_error("Failed to parse reply.");
690 n_units = MAX(2*c, 16);
691 w = realloc(units, sizeof(struct UnitFileList) * n_units);
694 log_error("Failed to allocate unit array.");
704 dbus_message_iter_recurse(&sub, &sub2);
706 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
707 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
708 log_error("Failed to parse reply.");
713 u->state = unit_file_state_from_string(state);
715 dbus_message_iter_next(&sub);
721 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
722 output_unit_file_list(units, c);
729 dbus_message_unref(reply);
736 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
737 static const char * const colors[] = {
738 "Requires", "[color=\"black\"]",
739 "RequiresOverridable", "[color=\"black\"]",
740 "Requisite", "[color=\"darkblue\"]",
741 "RequisiteOverridable", "[color=\"darkblue\"]",
742 "Wants", "[color=\"grey66\"]",
743 "Conflicts", "[color=\"red\"]",
744 "ConflictedBy", "[color=\"red\"]",
745 "After", "[color=\"green\"]"
748 const char *c = NULL;
755 for (i = 0; i < ELEMENTSOF(colors); i += 2)
756 if (streq(colors[i], prop)) {
764 if (arg_dot != DOT_ALL)
765 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
768 switch (dbus_message_iter_get_arg_type(iter)) {
770 case DBUS_TYPE_ARRAY:
772 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
775 dbus_message_iter_recurse(iter, &sub);
777 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
780 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
781 dbus_message_iter_get_basic(&sub, &s);
782 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
784 dbus_message_iter_next(&sub);
794 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
795 DBusMessage *reply = NULL;
796 const char *interface = "org.freedesktop.systemd1.Unit";
798 DBusMessageIter iter, sub, sub2, sub3;
802 r = bus_method_call_with_reply (
804 "org.freedesktop.systemd1",
806 "org.freedesktop.DBus.Properties",
810 DBUS_TYPE_STRING, &interface,
815 if (!dbus_message_iter_init(reply, &iter) ||
816 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
817 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
818 log_error("Failed to parse reply.");
823 dbus_message_iter_recurse(&iter, &sub);
825 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
828 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
829 log_error("Failed to parse reply.");
834 dbus_message_iter_recurse(&sub, &sub2);
836 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
837 log_error("Failed to parse reply.");
842 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
843 log_error("Failed to parse reply.");
848 dbus_message_iter_recurse(&sub2, &sub3);
850 if (dot_one_property(name, prop, &sub3)) {
851 log_error("Failed to parse reply.");
856 dbus_message_iter_next(&sub);
861 dbus_message_unref(reply);
866 static int dot(DBusConnection *bus, char **args) {
867 DBusMessage *reply = NULL;
869 DBusMessageIter iter, sub, sub2;
871 r = bus_method_call_with_reply (
873 "org.freedesktop.systemd1",
874 "/org/freedesktop/systemd1",
875 "org.freedesktop.systemd1.Manager",
883 if (!dbus_message_iter_init(reply, &iter) ||
884 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
885 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
886 log_error("Failed to parse reply.");
891 printf("digraph systemd {\n");
893 dbus_message_iter_recurse(&iter, &sub);
894 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
895 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
897 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
898 log_error("Failed to parse reply.");
903 dbus_message_iter_recurse(&sub, &sub2);
905 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
906 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
907 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
908 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
909 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
910 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
911 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
912 log_error("Failed to parse reply.");
917 if ((r = dot_one(bus, id, unit_path)) < 0)
920 /* printf("\t\"%s\";\n", id); */
921 dbus_message_iter_next(&sub);
926 log_info(" Color legend: black = Requires\n"
927 " dark blue = Requisite\n"
928 " dark grey = Wants\n"
933 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
934 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
940 dbus_message_unref(reply);
945 static int list_jobs(DBusConnection *bus, char **args) {
946 DBusMessage *reply = NULL;
948 DBusMessageIter iter, sub, sub2;
951 pager_open_if_enabled();
953 r = bus_method_call_with_reply (
955 "org.freedesktop.systemd1",
956 "/org/freedesktop/systemd1",
957 "org.freedesktop.systemd1.Manager",
965 if (!dbus_message_iter_init(reply, &iter) ||
966 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
967 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
968 log_error("Failed to parse reply.");
973 dbus_message_iter_recurse(&iter, &sub);
976 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
978 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
979 const char *name, *type, *state, *job_path, *unit_path;
983 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
984 log_error("Failed to parse reply.");
989 dbus_message_iter_recurse(&sub, &sub2);
991 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
992 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
993 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
994 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
995 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
996 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
997 log_error("Failed to parse reply.");
1002 e = arg_full ? NULL : ellipsize(name, 25, 33);
1003 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
1008 dbus_message_iter_next(&sub);
1012 printf("\n%u jobs listed.\n", k);
1018 dbus_message_unref(reply);
1023 static int load_unit(DBusConnection *bus, char **args) {
1029 STRV_FOREACH(name, args+1) {
1030 n = unit_name_mangle(*name);
1031 r = bus_method_call_with_reply (
1033 "org.freedesktop.systemd1",
1034 "/org/freedesktop/systemd1",
1035 "org.freedesktop.systemd1.Manager",
1039 DBUS_TYPE_STRING, n ? &n : name,
1050 static int cancel_job(DBusConnection *bus, char **args) {
1051 DBusMessage *reply = NULL;
1057 if (strv_length(args) <= 1)
1058 return daemon_reload(bus, args);
1060 STRV_FOREACH(name, args+1) {
1064 r = safe_atou(*name, &id);
1066 log_error("Failed to parse job id: %s", strerror(-r));
1069 assert_cc(sizeof(uint32_t) == sizeof(id));
1071 r = bus_method_call_with_reply (
1073 "org.freedesktop.systemd1",
1074 "/org/freedesktop/systemd1",
1075 "org.freedesktop.systemd1.Manager",
1079 DBUS_TYPE_UINT32, &id,
1084 if (!dbus_message_get_args(reply, NULL,
1085 DBUS_TYPE_OBJECT_PATH, &path,
1086 DBUS_TYPE_INVALID)) {
1087 log_error("Failed to parse reply");
1088 dbus_message_unref(reply);
1092 dbus_message_unref(reply);
1094 r = bus_method_call_with_reply (
1096 "org.freedesktop.systemd1",
1098 "org.freedesktop.systemd1.Job",
1111 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1112 DBusMessage *reply = NULL;
1113 dbus_bool_t b = FALSE;
1114 DBusMessageIter iter, sub;
1116 *interface = "org.freedesktop.systemd1.Unit",
1117 *property = "NeedDaemonReload",
1122 /* We ignore all errors here, since this is used to show a warning only */
1124 n = unit_name_mangle(unit);
1125 r = bus_method_call_with_reply (
1127 "org.freedesktop.systemd1",
1128 "/org/freedesktop/systemd1",
1129 "org.freedesktop.systemd1.Manager",
1133 DBUS_TYPE_STRING, n ? (const char**) &n : &unit,
1139 if (!dbus_message_get_args(reply, NULL,
1140 DBUS_TYPE_OBJECT_PATH, &path,
1144 dbus_message_unref(reply);
1145 r = bus_method_call_with_reply (
1147 "org.freedesktop.systemd1",
1149 "org.freedesktop.DBus.Properties",
1153 DBUS_TYPE_STRING, &interface,
1154 DBUS_TYPE_STRING, &property,
1159 if (!dbus_message_iter_init(reply, &iter) ||
1160 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1163 dbus_message_iter_recurse(&iter, &sub);
1165 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1168 dbus_message_iter_get_basic(&sub, &b);
1172 dbus_message_unref(reply);
1177 typedef struct WaitData {
1184 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1192 dbus_error_init(&error);
1194 log_debug("Got D-Bus request: %s.%s() on %s",
1195 dbus_message_get_interface(message),
1196 dbus_message_get_member(message),
1197 dbus_message_get_path(message));
1199 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1200 log_error("Warning! D-Bus connection terminated.");
1201 dbus_connection_close(connection);
1203 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1205 const char *path, *result, *unit;
1206 dbus_bool_t success = true;
1208 if (dbus_message_get_args(message, &error,
1209 DBUS_TYPE_UINT32, &id,
1210 DBUS_TYPE_OBJECT_PATH, &path,
1211 DBUS_TYPE_STRING, &unit,
1212 DBUS_TYPE_STRING, &result,
1213 DBUS_TYPE_INVALID)) {
1216 p = set_remove(d->set, (char*) path);
1219 if (!isempty(result))
1220 d->result = strdup(result);
1223 d->name = strdup(unit);
1228 dbus_error_free(&error);
1229 if (dbus_message_get_args(message, &error,
1230 DBUS_TYPE_UINT32, &id,
1231 DBUS_TYPE_OBJECT_PATH, &path,
1232 DBUS_TYPE_STRING, &result,
1233 DBUS_TYPE_INVALID)) {
1236 /* Compatibility with older systemd versions <
1237 * 183 during upgrades. This should be dropped
1239 p = set_remove(d->set, (char*) path);
1243 d->result = strdup(result);
1248 dbus_error_free(&error);
1249 if (dbus_message_get_args(message, &error,
1250 DBUS_TYPE_UINT32, &id,
1251 DBUS_TYPE_OBJECT_PATH, &path,
1252 DBUS_TYPE_BOOLEAN, &success,
1253 DBUS_TYPE_INVALID)) {
1256 /* Compatibility with older systemd versions <
1257 * 19 during upgrades. This should be dropped
1260 p = set_remove(d->set, (char*) path);
1264 d->result = strdup("failed");
1270 log_error("Failed to parse message: %s", bus_error_message(&error));
1274 dbus_error_free(&error);
1275 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1278 static int enable_wait_for_jobs(DBusConnection *bus) {
1286 dbus_error_init(&error);
1287 dbus_bus_add_match(bus,
1289 "sender='org.freedesktop.systemd1',"
1290 "interface='org.freedesktop.systemd1.Manager',"
1291 "member='JobRemoved',"
1292 "path='/org/freedesktop/systemd1'",
1295 if (dbus_error_is_set(&error)) {
1296 log_error("Failed to add match: %s", bus_error_message(&error));
1297 dbus_error_free(&error);
1301 /* This is slightly dirty, since we don't undo the match registrations. */
1305 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1315 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL))
1318 while (!set_isempty(s)) {
1320 if (!dbus_connection_read_write_dispatch(bus, -1)) {
1321 log_error("Disconnected from bus.");
1322 return -ECONNREFUSED;
1329 if (streq(d.result, "timeout"))
1330 log_error("Job for %s timed out.", strna(d.name));
1331 else if (streq(d.result, "canceled"))
1332 log_error("Job for %s canceled.", strna(d.name));
1333 else if (streq(d.result, "dependency"))
1334 log_error("A dependency job for %s failed. See 'journalctl' for details.", strna(d.name));
1335 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1336 log_error("Job for %s failed. See 'systemctl status %s' and 'journalctl' for details.", strna(d.name), strna(d.name));
1339 if (streq_ptr(d.result, "timeout"))
1341 else if (streq_ptr(d.result, "canceled"))
1343 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1354 dbus_connection_remove_filter(bus, wait_filter, &d);
1358 static int check_one_unit(DBusConnection *bus, char *name, bool quiet) {
1359 DBusMessage *reply = NULL;
1360 DBusMessageIter iter, sub;
1362 *interface = "org.freedesktop.systemd1.Unit",
1363 *property = "ActiveState";
1364 const char *path = NULL;
1371 n = unit_name_mangle(name);
1372 r = bus_method_call_with_reply (
1374 "org.freedesktop.systemd1",
1375 "/org/freedesktop/systemd1",
1376 "org.freedesktop.systemd1.Manager",
1380 DBUS_TYPE_STRING, n ? &n : &name,
1384 if ((r != -ENOMEM) && (!quiet))
1389 if (!dbus_message_get_args(reply, NULL,
1390 DBUS_TYPE_OBJECT_PATH, &path,
1391 DBUS_TYPE_INVALID)) {
1392 log_error("Failed to parse reply.");
1397 dbus_message_unref(reply);
1398 r = bus_method_call_with_reply (
1400 "org.freedesktop.systemd1",
1402 "org.freedesktop.DBus.Properties",
1406 DBUS_TYPE_STRING, &interface,
1407 DBUS_TYPE_STRING, &property,
1412 if (!dbus_message_iter_init(reply, &iter) ||
1413 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1414 log_error("Failed to parse reply.");
1419 dbus_message_iter_recurse(&iter, &sub);
1421 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1422 log_error("Failed to parse reply.");
1427 dbus_message_iter_get_basic(&sub, &state);
1432 if (streq(state, "active") || streq(state, "reloading"))
1435 r = 3; /* According to LSB: "program is not running" */
1439 dbus_message_unref(reply);
1444 static void check_triggering_units(
1445 DBusConnection *bus,
1446 const char *unit_name) {
1448 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1449 DBusMessageIter iter, sub;
1450 char *service_trigger = NULL;
1451 const char *interface = "org.freedesktop.systemd1.Unit",
1452 *triggered_by_property = "TriggeredBy";
1454 char _cleanup_free_ *unit_path = NULL, *n = NULL;
1455 bool print_warning_label = true;
1458 n = unit_name_mangle(unit_name);
1464 unit_path = unit_dbus_path_from_name(n);
1470 r = bus_method_call_with_reply (
1472 "org.freedesktop.systemd1",
1474 "org.freedesktop.DBus.Properties",
1478 DBUS_TYPE_STRING, &interface,
1479 DBUS_TYPE_STRING, &triggered_by_property,
1484 if (!dbus_message_iter_init(reply, &iter) ||
1485 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1486 log_error("Failed to parse reply.");
1490 dbus_message_iter_recurse(&iter, &sub);
1491 dbus_message_iter_recurse(&sub, &iter);
1494 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1496 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1497 log_error("Failed to parse reply.");
1501 dbus_message_iter_get_basic(&sub, &service_trigger);
1503 r = check_one_unit(bus, service_trigger, true);
1507 if (print_warning_label) {
1508 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1509 print_warning_label = false;
1511 log_warning(" %s", service_trigger);
1514 dbus_message_iter_next(&sub);
1518 static int start_unit_one(
1519 DBusConnection *bus,
1526 _cleanup_dbus_message_unref_ DBusMessage *reply = NULL;
1529 _cleanup_free_ char *n, *p = NULL;
1536 n = unit_name_mangle(name);
1540 r = bus_method_call_with_reply(
1542 "org.freedesktop.systemd1",
1543 "/org/freedesktop/systemd1",
1544 "org.freedesktop.systemd1.Manager",
1548 DBUS_TYPE_STRING, &n,
1549 DBUS_TYPE_STRING, &mode,
1552 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
1553 /* There's always a fallback possible for
1554 * legacy actions. */
1557 log_error("Failed to issue method call: %s", bus_error_message(error));
1562 if (!dbus_message_get_args(reply, error,
1563 DBUS_TYPE_OBJECT_PATH, &path,
1564 DBUS_TYPE_INVALID)) {
1565 log_error("Failed to parse reply: %s", bus_error_message(error));
1569 if (need_daemon_reload(bus, n))
1570 log_warning("Warning: Unit file of %s changed on disk, 'systemctl %s daemon-reload' recommended.",
1571 n, arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1580 log_error("Failed to add path to set.");
1590 static enum action verb_to_action(const char *verb) {
1591 if (streq(verb, "halt"))
1593 else if (streq(verb, "poweroff"))
1594 return ACTION_POWEROFF;
1595 else if (streq(verb, "reboot"))
1596 return ACTION_REBOOT;
1597 else if (streq(verb, "kexec"))
1598 return ACTION_KEXEC;
1599 else if (streq(verb, "rescue"))
1600 return ACTION_RESCUE;
1601 else if (streq(verb, "emergency"))
1602 return ACTION_EMERGENCY;
1603 else if (streq(verb, "default"))
1604 return ACTION_DEFAULT;
1605 else if (streq(verb, "exit"))
1607 else if (streq(verb, "suspend"))
1608 return ACTION_SUSPEND;
1609 else if (streq(verb, "hibernate"))
1610 return ACTION_HIBERNATE;
1612 return ACTION_INVALID;
1615 static int start_unit(DBusConnection *bus, char **args) {
1617 static const char * const table[_ACTION_MAX] = {
1618 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1619 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1620 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1621 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1622 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1623 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1624 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1625 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1626 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1627 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1628 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1629 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1630 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1631 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET
1635 const char *method, *mode, *one_name;
1640 dbus_error_init(&error);
1644 ask_password_agent_open_if_enabled();
1646 if (arg_action == ACTION_SYSTEMCTL) {
1648 streq(args[0], "stop") ||
1649 streq(args[0], "condstop") ? "StopUnit" :
1650 streq(args[0], "reload") ? "ReloadUnit" :
1651 streq(args[0], "restart") ? "RestartUnit" :
1653 streq(args[0], "try-restart") ||
1654 streq(args[0], "condrestart") ? "TryRestartUnit" :
1656 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1658 streq(args[0], "reload-or-try-restart") ||
1659 streq(args[0], "condreload") ||
1661 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1665 (streq(args[0], "isolate") ||
1666 streq(args[0], "rescue") ||
1667 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1669 one_name = table[verb_to_action(args[0])];
1672 assert(arg_action < ELEMENTSOF(table));
1673 assert(table[arg_action]);
1675 method = "StartUnit";
1677 mode = (arg_action == ACTION_EMERGENCY ||
1678 arg_action == ACTION_RESCUE ||
1679 arg_action == ACTION_RUNLEVEL2 ||
1680 arg_action == ACTION_RUNLEVEL3 ||
1681 arg_action == ACTION_RUNLEVEL4 ||
1682 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1684 one_name = table[arg_action];
1687 if (!arg_no_block) {
1688 ret = enable_wait_for_jobs(bus);
1690 log_error("Could not watch jobs: %s", strerror(-ret));
1694 s = set_new(string_hash_func, string_compare_func);
1702 ret = start_unit_one(bus, method, one_name, mode, &error, s);
1704 ret = translate_bus_error_to_exit_status(ret, &error);
1706 STRV_FOREACH(name, args+1) {
1707 r = start_unit_one(bus, method, *name, mode, &error, s);
1709 ret = translate_bus_error_to_exit_status(r, &error);
1710 dbus_error_free(&error);
1715 if (!arg_no_block) {
1716 r = wait_for_jobs(bus, s);
1722 /* When stopping units, warn if they can still be triggered by
1723 * another active unit (socket, path, timer) */
1724 if (!arg_quiet && streq(method, "StopUnit")) {
1726 check_triggering_units(bus, one_name);
1728 STRV_FOREACH(name, args+1)
1729 check_triggering_units(bus, *name);
1735 dbus_error_free(&error);
1740 /* Ask systemd-logind, which might grant access to unprivileged users
1741 * through PolicyKit */
1742 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1745 dbus_bool_t interactive = true;
1747 polkit_agent_open_if_enabled();
1755 case ACTION_POWEROFF:
1756 method = "PowerOff";
1759 case ACTION_SUSPEND:
1763 case ACTION_HIBERNATE:
1764 method = "Hibernate";
1771 return bus_method_call_with_reply (
1773 "org.freedesktop.login1",
1774 "/org/freedesktop/login1",
1775 "org.freedesktop.login1.Manager",
1779 DBUS_TYPE_BOOLEAN, &interactive,
1786 static int start_special(DBusConnection *bus, char **args) {
1792 a = verb_to_action(args[0]);
1794 if (arg_force >= 2 && geteuid() != 0) {
1795 log_error("Must be root.");
1799 if (arg_force >= 2 &&
1800 (a == ACTION_HALT ||
1801 a == ACTION_POWEROFF ||
1802 a == ACTION_REBOOT))
1805 if (arg_force >= 1 &&
1806 (a == ACTION_HALT ||
1807 a == ACTION_POWEROFF ||
1808 a == ACTION_REBOOT ||
1809 a == ACTION_KEXEC ||
1811 return daemon_reload(bus, args);
1813 /* first try logind, to allow authentication with polkit */
1814 if (geteuid() != 0 &&
1815 (a == ACTION_POWEROFF ||
1816 a == ACTION_REBOOT ||
1817 a == ACTION_SUSPEND ||
1818 a == ACTION_HIBERNATE)) {
1819 r = reboot_with_logind(bus, a);
1824 r = start_unit(bus, args);
1831 static int check_unit(DBusConnection *bus, char **args) {
1833 int r = 3; /* According to LSB: "program is not running" */
1838 STRV_FOREACH(name, args+1) {
1839 int state = check_one_unit(bus, *name, arg_quiet);
1849 static int kill_unit(DBusConnection *bus, char **args) {
1856 arg_kill_who = "all";
1858 STRV_FOREACH(name, args+1) {
1859 n = unit_name_mangle(*name);
1860 r = bus_method_call_with_reply (
1862 "org.freedesktop.systemd1",
1863 "/org/freedesktop/systemd1",
1864 "org.freedesktop.systemd1.Manager",
1868 DBUS_TYPE_STRING, n ? &n : name,
1869 DBUS_TYPE_STRING, &arg_kill_who,
1870 DBUS_TYPE_INT32, &arg_signal,
1879 typedef struct ExecStatusInfo {
1887 usec_t start_timestamp;
1888 usec_t exit_timestamp;
1893 LIST_FIELDS(struct ExecStatusInfo, exec);
1896 static void exec_status_info_free(ExecStatusInfo *i) {
1905 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1906 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
1907 DBusMessageIter sub2, sub3;
1911 int32_t code, status;
1917 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1920 dbus_message_iter_recurse(sub, &sub2);
1922 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1925 if (!(i->path = strdup(path)))
1928 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1929 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1933 dbus_message_iter_recurse(&sub2, &sub3);
1934 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1935 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1936 dbus_message_iter_next(&sub3);
1941 if (!(i->argv = new0(char*, n+1)))
1945 dbus_message_iter_recurse(&sub2, &sub3);
1946 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1949 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1950 dbus_message_iter_get_basic(&sub3, &s);
1951 dbus_message_iter_next(&sub3);
1953 if (!(i->argv[n++] = strdup(s)))
1957 if (!dbus_message_iter_next(&sub2) ||
1958 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1959 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1960 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
1961 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1962 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
1963 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1964 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1965 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1969 i->start_timestamp = (usec_t) start_timestamp;
1970 i->exit_timestamp = (usec_t) exit_timestamp;
1971 i->pid = (pid_t) pid;
1978 typedef struct UnitStatusInfo {
1980 const char *load_state;
1981 const char *active_state;
1982 const char *sub_state;
1983 const char *unit_file_state;
1985 const char *description;
1986 const char *following;
1988 char **documentation;
1990 const char *fragment_path;
1991 const char *source_path;
1992 const char *default_control_group;
1994 const char *load_error;
1997 usec_t inactive_exit_timestamp;
1998 usec_t inactive_exit_timestamp_monotonic;
1999 usec_t active_enter_timestamp;
2000 usec_t active_exit_timestamp;
2001 usec_t inactive_enter_timestamp;
2003 bool need_daemon_reload;
2008 const char *status_text;
2011 usec_t start_timestamp;
2012 usec_t exit_timestamp;
2014 int exit_code, exit_status;
2016 usec_t condition_timestamp;
2017 bool condition_result;
2020 unsigned n_accepted;
2021 unsigned n_connections;
2025 const char *sysfs_path;
2027 /* Mount, Automount */
2033 LIST_HEAD(ExecStatusInfo, exec);
2036 static void print_status_info(UnitStatusInfo *i) {
2038 const char *on, *off, *ss;
2040 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2041 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2046 /* This shows pretty information about a unit. See
2047 * print_property() for a low-level property printer */
2049 printf("%s", strna(i->id));
2051 if (i->description && !streq_ptr(i->id, i->description))
2052 printf(" - %s", i->description);
2057 printf("\t Follow: unit currently follows state of %s\n", i->following);
2059 if (streq_ptr(i->load_state, "error")) {
2060 on = ansi_highlight_red(true);
2061 off = ansi_highlight_red(false);
2065 path = i->source_path ? i->source_path : i->fragment_path;
2068 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2069 else if (path && i->unit_file_state)
2070 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2072 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2074 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2076 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2078 if (streq_ptr(i->active_state, "failed")) {
2079 on = ansi_highlight_red(true);
2080 off = ansi_highlight_red(false);
2081 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2082 on = ansi_highlight_green(true);
2083 off = ansi_highlight_green(false);
2088 printf("\t Active: %s%s (%s)%s",
2090 strna(i->active_state),
2094 printf("\t Active: %s%s%s",
2096 strna(i->active_state),
2099 if (!isempty(i->result) && !streq(i->result, "success"))
2100 printf(" (Result: %s)", i->result);
2102 timestamp = (streq_ptr(i->active_state, "active") ||
2103 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2104 (streq_ptr(i->active_state, "inactive") ||
2105 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2106 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2107 i->active_exit_timestamp;
2109 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2110 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2113 printf(" since %s; %s\n", s2, s1);
2115 printf(" since %s\n", s2);
2119 if (!i->condition_result && i->condition_timestamp > 0) {
2120 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2121 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2124 printf("\t start condition failed at %s; %s\n", s2, s1);
2126 printf("\t start condition failed at %s\n", s2);
2130 printf("\t Device: %s\n", i->sysfs_path);
2132 printf("\t Where: %s\n", i->where);
2134 printf("\t What: %s\n", i->what);
2136 if (!strv_isempty(i->documentation)) {
2140 STRV_FOREACH(t, i->documentation) {
2142 printf("\t Docs: %s\n", *t);
2145 printf("\t %s\n", *t);
2150 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2152 LIST_FOREACH(exec, p, i->exec) {
2156 /* Only show exited processes here */
2160 t = strv_join(p->argv, " ");
2161 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2164 good = is_clean_exit_lsb(p->code, p->status, NULL);
2166 on = ansi_highlight_red(true);
2167 off = ansi_highlight_red(false);
2171 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2173 if (p->code == CLD_EXITED) {
2176 printf("status=%i", p->status);
2178 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2183 printf("signal=%s", signal_to_string(p->status));
2185 printf(")%s\n", off);
2187 if (i->main_pid == p->pid &&
2188 i->start_timestamp == p->start_timestamp &&
2189 i->exit_timestamp == p->start_timestamp)
2190 /* Let's not show this twice */
2193 if (p->pid == i->control_pid)
2197 if (i->main_pid > 0 || i->control_pid > 0) {
2200 if (i->main_pid > 0) {
2201 printf("Main PID: %u", (unsigned) i->main_pid);
2205 get_process_comm(i->main_pid, &t);
2210 } else if (i->exit_code > 0) {
2211 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2213 if (i->exit_code == CLD_EXITED) {
2216 printf("status=%i", i->exit_status);
2218 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2223 printf("signal=%s", signal_to_string(i->exit_status));
2228 if (i->main_pid > 0 && i->control_pid > 0)
2231 if (i->control_pid > 0) {
2234 printf(" Control: %u", (unsigned) i->control_pid);
2236 get_process_comm(i->control_pid, &t);
2247 printf("\t Status: \"%s\"\n", i->status_text);
2249 if (i->default_control_group) {
2252 printf("\t CGroup: %s\n", i->default_control_group);
2254 if (arg_transport != TRANSPORT_SSH) {
2264 if (i->main_pid > 0)
2265 extra[k++] = i->main_pid;
2267 if (i->control_pid > 0)
2268 extra[k++] = i->control_pid;
2270 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2274 if (i->id && arg_transport != TRANSPORT_SSH) {
2276 arg_all * OUTPUT_SHOW_ALL |
2277 (!on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
2278 on_tty() * OUTPUT_COLOR |
2279 !arg_quiet * OUTPUT_WARN_CUTOFF;
2282 show_journal_by_unit(stdout,
2286 i->inactive_exit_timestamp_monotonic,
2291 if (i->need_daemon_reload)
2292 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2293 ansi_highlight_red(true),
2294 ansi_highlight_red(false),
2295 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2298 static void show_unit_help(UnitStatusInfo *i) {
2303 if (!i->documentation) {
2304 log_info("Documentation for %s not known.", i->id);
2308 STRV_FOREACH(p, i->documentation) {
2310 if (startswith(*p, "man:")) {
2313 char *page = NULL, *section = NULL;
2314 const char *args[4] = { "man", NULL, NULL, NULL };
2319 if ((*p)[k-1] == ')')
2320 e = strrchr(*p, '(');
2323 page = strndup((*p) + 4, e - *p - 4);
2329 section = strndup(e + 1, *p + k - e - 2);
2343 log_error("Failed to fork: %m");
2351 execvp(args[0], (char**) args);
2352 log_error("Failed to execute man: %m");
2353 _exit(EXIT_FAILURE);
2359 wait_for_terminate(pid, NULL);
2361 log_info("Can't show: %s", *p);
2365 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2371 switch (dbus_message_iter_get_arg_type(iter)) {
2373 case DBUS_TYPE_STRING: {
2376 dbus_message_iter_get_basic(iter, &s);
2379 if (streq(name, "Id"))
2381 else if (streq(name, "LoadState"))
2383 else if (streq(name, "ActiveState"))
2384 i->active_state = s;
2385 else if (streq(name, "SubState"))
2387 else if (streq(name, "Description"))
2389 else if (streq(name, "FragmentPath"))
2390 i->fragment_path = s;
2391 else if (streq(name, "SourcePath"))
2393 else if (streq(name, "DefaultControlGroup"))
2394 i->default_control_group = s;
2395 else if (streq(name, "StatusText"))
2397 else if (streq(name, "SysFSPath"))
2399 else if (streq(name, "Where"))
2401 else if (streq(name, "What"))
2403 else if (streq(name, "Following"))
2405 else if (streq(name, "UnitFileState"))
2406 i->unit_file_state = s;
2407 else if (streq(name, "Result"))
2414 case DBUS_TYPE_BOOLEAN: {
2417 dbus_message_iter_get_basic(iter, &b);
2419 if (streq(name, "Accept"))
2421 else if (streq(name, "NeedDaemonReload"))
2422 i->need_daemon_reload = b;
2423 else if (streq(name, "ConditionResult"))
2424 i->condition_result = b;
2429 case DBUS_TYPE_UINT32: {
2432 dbus_message_iter_get_basic(iter, &u);
2434 if (streq(name, "MainPID")) {
2436 i->main_pid = (pid_t) u;
2439 } else if (streq(name, "ControlPID"))
2440 i->control_pid = (pid_t) u;
2441 else if (streq(name, "ExecMainPID")) {
2443 i->main_pid = (pid_t) u;
2444 } else if (streq(name, "NAccepted"))
2446 else if (streq(name, "NConnections"))
2447 i->n_connections = u;
2452 case DBUS_TYPE_INT32: {
2455 dbus_message_iter_get_basic(iter, &j);
2457 if (streq(name, "ExecMainCode"))
2458 i->exit_code = (int) j;
2459 else if (streq(name, "ExecMainStatus"))
2460 i->exit_status = (int) j;
2465 case DBUS_TYPE_UINT64: {
2468 dbus_message_iter_get_basic(iter, &u);
2470 if (streq(name, "ExecMainStartTimestamp"))
2471 i->start_timestamp = (usec_t) u;
2472 else if (streq(name, "ExecMainExitTimestamp"))
2473 i->exit_timestamp = (usec_t) u;
2474 else if (streq(name, "ActiveEnterTimestamp"))
2475 i->active_enter_timestamp = (usec_t) u;
2476 else if (streq(name, "InactiveEnterTimestamp"))
2477 i->inactive_enter_timestamp = (usec_t) u;
2478 else if (streq(name, "InactiveExitTimestamp"))
2479 i->inactive_exit_timestamp = (usec_t) u;
2480 else if (streq(name, "InactiveExitTimestampMonotonic"))
2481 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2482 else if (streq(name, "ActiveExitTimestamp"))
2483 i->active_exit_timestamp = (usec_t) u;
2484 else if (streq(name, "ConditionTimestamp"))
2485 i->condition_timestamp = (usec_t) u;
2490 case DBUS_TYPE_ARRAY: {
2492 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2493 startswith(name, "Exec")) {
2494 DBusMessageIter sub;
2496 dbus_message_iter_recurse(iter, &sub);
2497 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2498 ExecStatusInfo *info;
2501 if (!(info = new0(ExecStatusInfo, 1)))
2504 if (!(info->name = strdup(name))) {
2509 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2514 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2516 dbus_message_iter_next(&sub);
2518 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2519 streq(name, "Documentation")) {
2521 DBusMessageIter sub;
2523 dbus_message_iter_recurse(iter, &sub);
2524 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2528 dbus_message_iter_get_basic(&sub, &s);
2530 l = strv_append(i->documentation, s);
2534 strv_free(i->documentation);
2535 i->documentation = l;
2537 dbus_message_iter_next(&sub);
2544 case DBUS_TYPE_STRUCT: {
2546 if (streq(name, "LoadError")) {
2547 DBusMessageIter sub;
2548 const char *n, *message;
2551 dbus_message_iter_recurse(iter, &sub);
2553 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2557 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2561 if (!isempty(message))
2562 i->load_error = message;
2572 static int print_property(const char *name, DBusMessageIter *iter) {
2576 /* This is a low-level property printer, see
2577 * print_status_info() for the nicer output */
2579 if (arg_property && !strv_find(arg_property, name))
2582 switch (dbus_message_iter_get_arg_type(iter)) {
2584 case DBUS_TYPE_STRUCT: {
2585 DBusMessageIter sub;
2586 dbus_message_iter_recurse(iter, &sub);
2588 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2591 dbus_message_iter_get_basic(&sub, &u);
2594 printf("%s=%u\n", name, (unsigned) u);
2596 printf("%s=\n", name);
2599 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2602 dbus_message_iter_get_basic(&sub, &s);
2604 if (arg_all || s[0])
2605 printf("%s=%s\n", name, s);
2608 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
2609 const char *a = NULL, *b = NULL;
2611 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
2612 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
2614 if (arg_all || !isempty(a) || !isempty(b))
2615 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
2623 case DBUS_TYPE_ARRAY:
2625 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2626 DBusMessageIter sub, sub2;
2628 dbus_message_iter_recurse(iter, &sub);
2629 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2633 dbus_message_iter_recurse(&sub, &sub2);
2635 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2636 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2637 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2639 dbus_message_iter_next(&sub);
2644 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2645 DBusMessageIter sub, sub2;
2647 dbus_message_iter_recurse(iter, &sub);
2648 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2649 const char *type, *path;
2651 dbus_message_iter_recurse(&sub, &sub2);
2653 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2654 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2655 printf("%s=%s\n", type, path);
2657 dbus_message_iter_next(&sub);
2662 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2663 DBusMessageIter sub, sub2;
2665 dbus_message_iter_recurse(iter, &sub);
2666 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2668 uint64_t value, next_elapse;
2670 dbus_message_iter_recurse(&sub, &sub2);
2672 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2673 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2674 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2675 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2677 printf("%s={ value=%s ; next_elapse=%s }\n",
2679 format_timespan(timespan1, sizeof(timespan1), value),
2680 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2683 dbus_message_iter_next(&sub);
2688 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
2689 DBusMessageIter sub, sub2;
2691 dbus_message_iter_recurse(iter, &sub);
2692 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2693 const char *controller, *attr, *value;
2695 dbus_message_iter_recurse(&sub, &sub2);
2697 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
2698 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
2699 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
2701 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
2707 dbus_message_iter_next(&sub);
2712 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2713 DBusMessageIter sub;
2715 dbus_message_iter_recurse(iter, &sub);
2716 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2717 ExecStatusInfo info;
2720 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2721 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2724 t = strv_join(info.argv, " ");
2726 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2730 yes_no(info.ignore),
2731 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2732 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2733 (unsigned) info. pid,
2734 sigchld_code_to_string(info.code),
2736 info.code == CLD_EXITED ? "" : "/",
2737 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2743 strv_free(info.argv);
2745 dbus_message_iter_next(&sub);
2754 if (generic_print_property(name, iter, arg_all) > 0)
2758 printf("%s=[unprintable]\n", name);
2763 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2764 DBusMessage *reply = NULL;
2765 const char *interface = "";
2767 DBusMessageIter iter, sub, sub2, sub3;
2768 UnitStatusInfo info;
2776 r = bus_method_call_with_reply (
2778 "org.freedesktop.systemd1",
2780 "org.freedesktop.DBus.Properties",
2784 DBUS_TYPE_STRING, &interface,
2789 if (!dbus_message_iter_init(reply, &iter) ||
2790 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2791 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2792 log_error("Failed to parse reply.");
2797 dbus_message_iter_recurse(&iter, &sub);
2804 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2807 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2808 log_error("Failed to parse reply.");
2813 dbus_message_iter_recurse(&sub, &sub2);
2815 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2816 log_error("Failed to parse reply.");
2821 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2822 log_error("Failed to parse reply.");
2827 dbus_message_iter_recurse(&sub2, &sub3);
2829 if (show_properties)
2830 r = print_property(name, &sub3);
2832 r = status_property(name, &sub3, &info);
2835 log_error("Failed to parse reply.");
2840 dbus_message_iter_next(&sub);
2845 if (!show_properties) {
2846 if (streq(verb, "help"))
2847 show_unit_help(&info);
2849 print_status_info(&info);
2852 strv_free(info.documentation);
2854 if (!streq_ptr(info.active_state, "active") &&
2855 !streq_ptr(info.active_state, "reloading") &&
2856 streq(verb, "status"))
2857 /* According to LSB: "program not running" */
2860 while ((p = info.exec)) {
2861 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2862 exec_status_info_free(p);
2867 dbus_message_unref(reply);
2872 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
2873 DBusMessage *reply = NULL;
2874 const char *path = NULL;
2878 dbus_error_init(&error);
2880 r = bus_method_call_with_reply (
2882 "org.freedesktop.systemd1",
2883 "/org/freedesktop/systemd1",
2884 "org.freedesktop.systemd1.Manager",
2888 DBUS_TYPE_UINT32, &pid,
2893 if (!dbus_message_get_args(reply, &error,
2894 DBUS_TYPE_OBJECT_PATH, &path,
2895 DBUS_TYPE_INVALID)) {
2896 log_error("Failed to parse reply: %s", bus_error_message(&error));
2901 r = show_one(verb, bus, path, false, new_line);
2905 dbus_message_unref(reply);
2907 dbus_error_free(&error);
2912 static int show(DBusConnection *bus, char **args) {
2914 bool show_properties, new_line = false;
2920 show_properties = streq(args[0], "show");
2922 if (show_properties)
2923 pager_open_if_enabled();
2925 if (show_properties && strv_length(args) <= 1) {
2926 /* If not argument is specified inspect the manager
2929 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2932 STRV_FOREACH(name, args+1) {
2935 if (safe_atou32(*name, &id) < 0) {
2937 /* Interpret as unit name */
2939 n = unit_name_mangle(*name);
2940 p = unit_dbus_path_from_name(n ? n : *name);
2945 r = show_one(args[0], bus, p, show_properties, &new_line);
2951 } else if (show_properties) {
2953 /* Interpret as job id */
2956 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
2959 r = show_one(args[0], bus, p, show_properties, &new_line);
2967 /* Interpret as PID */
2969 r = show_one_by_pid(args[0], bus, id, &new_line);
2978 static int dump(DBusConnection *bus, char **args) {
2979 DBusMessage *reply = NULL;
2984 dbus_error_init(&error);
2986 pager_open_if_enabled();
2988 r = bus_method_call_with_reply (
2990 "org.freedesktop.systemd1",
2991 "/org/freedesktop/systemd1",
2992 "org.freedesktop.systemd1.Manager",
3000 if (!dbus_message_get_args(reply, &error,
3001 DBUS_TYPE_STRING, &text,
3002 DBUS_TYPE_INVALID)) {
3003 log_error("Failed to parse reply: %s", bus_error_message(&error));
3008 fputs(text, stdout);
3012 dbus_message_unref(reply);
3014 dbus_error_free(&error);
3019 static int snapshot(DBusConnection *bus, char **args) {
3020 DBusMessage *reply = NULL;
3023 dbus_bool_t cleanup = FALSE;
3024 DBusMessageIter iter, sub;
3026 *name = "", *path, *id,
3027 *interface = "org.freedesktop.systemd1.Unit",
3031 dbus_error_init(&error);
3033 if (strv_length(args) > 1)
3036 n = unit_name_mangle(name);
3037 r = bus_method_call_with_reply (
3039 "org.freedesktop.systemd1",
3040 "/org/freedesktop/systemd1",
3041 "org.freedesktop.systemd1.Manager",
3045 DBUS_TYPE_STRING, n ? (const char**) &n : &name,
3046 DBUS_TYPE_BOOLEAN, &cleanup,
3052 if (!dbus_message_get_args(reply, &error,
3053 DBUS_TYPE_OBJECT_PATH, &path,
3054 DBUS_TYPE_INVALID)) {
3055 log_error("Failed to parse reply: %s", bus_error_message(&error));
3060 dbus_message_unref(reply);
3061 r = bus_method_call_with_reply (
3063 "org.freedesktop.systemd1",
3065 "org.freedesktop.DBus.Properties",
3069 DBUS_TYPE_STRING, &interface,
3070 DBUS_TYPE_STRING, &property,
3075 if (!dbus_message_iter_init(reply, &iter) ||
3076 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3077 log_error("Failed to parse reply.");
3082 dbus_message_iter_recurse(&iter, &sub);
3084 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3085 log_error("Failed to parse reply.");
3090 dbus_message_iter_get_basic(&sub, &id);
3097 dbus_message_unref(reply);
3099 dbus_error_free(&error);
3104 static int delete_snapshot(DBusConnection *bus, char **args) {
3105 DBusMessage *reply = NULL;
3112 dbus_error_init(&error);
3114 STRV_FOREACH(name, args+1) {
3115 const char *path = NULL;
3118 n = unit_name_mangle(*name);
3119 r = bus_method_call_with_reply (
3121 "org.freedesktop.systemd1",
3122 "/org/freedesktop/systemd1",
3123 "org.freedesktop.systemd1.Manager",
3127 DBUS_TYPE_STRING, n ? &n : name,
3133 if (!dbus_message_get_args(reply, &error,
3134 DBUS_TYPE_OBJECT_PATH, &path,
3135 DBUS_TYPE_INVALID)) {
3136 log_error("Failed to parse reply: %s", bus_error_message(&error));
3138 dbus_message_unref(reply);
3139 dbus_error_free(&error);
3142 dbus_message_unref(reply);
3144 r = bus_method_call_with_reply (
3146 "org.freedesktop.systemd1",
3148 "org.freedesktop.systemd1.Snapshot",
3161 static int daemon_reload(DBusConnection *bus, char **args) {
3166 if (arg_action == ACTION_RELOAD)
3168 else if (arg_action == ACTION_REEXEC)
3169 method = "Reexecute";
3171 assert(arg_action == ACTION_SYSTEMCTL);
3174 streq(args[0], "clear-jobs") ||
3175 streq(args[0], "cancel") ? "ClearJobs" :
3176 streq(args[0], "daemon-reexec") ? "Reexecute" :
3177 streq(args[0], "reset-failed") ? "ResetFailed" :
3178 streq(args[0], "halt") ? "Halt" :
3179 streq(args[0], "poweroff") ? "PowerOff" :
3180 streq(args[0], "reboot") ? "Reboot" :
3181 streq(args[0], "kexec") ? "KExec" :
3182 streq(args[0], "exit") ? "Exit" :
3183 /* "daemon-reload" */ "Reload";
3186 r = bus_method_call_with_reply (
3188 "org.freedesktop.systemd1",
3189 "/org/freedesktop/systemd1",
3190 "org.freedesktop.systemd1.Manager",
3196 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
3197 /* There's always a fallback possible for
3198 * legacy actions. */
3200 else if (r == -ETIMEDOUT && streq(method, "Reexecute"))
3201 /* On reexecution, we expect a disconnect, not
3205 log_error("Failed to issue method call: %s", bus_error_message(&error));
3206 dbus_error_free(&error);
3211 static int reset_failed(DBusConnection *bus, char **args) {
3215 if (strv_length(args) <= 1)
3216 return daemon_reload(bus, args);
3218 STRV_FOREACH(name, args+1) {
3219 n = unit_name_mangle(*name);
3220 r = bus_method_call_with_reply (
3222 "org.freedesktop.systemd1",
3223 "/org/freedesktop/systemd1",
3224 "org.freedesktop.systemd1.Manager",
3228 DBUS_TYPE_STRING, n ? &n : name,
3239 static int show_enviroment(DBusConnection *bus, char **args) {
3240 DBusMessage *reply = NULL;
3241 DBusMessageIter iter, sub, sub2;
3244 *interface = "org.freedesktop.systemd1.Manager",
3245 *property = "Environment";
3247 pager_open_if_enabled();
3249 r = bus_method_call_with_reply (
3251 "org.freedesktop.systemd1",
3252 "/org/freedesktop/systemd1",
3253 "org.freedesktop.DBus.Properties",
3257 DBUS_TYPE_STRING, &interface,
3258 DBUS_TYPE_STRING, &property,
3263 if (!dbus_message_iter_init(reply, &iter) ||
3264 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3265 log_error("Failed to parse reply.");
3270 dbus_message_iter_recurse(&iter, &sub);
3272 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3273 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3274 log_error("Failed to parse reply.");
3279 dbus_message_iter_recurse(&sub, &sub2);
3281 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3284 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3285 log_error("Failed to parse reply.");
3290 dbus_message_iter_get_basic(&sub2, &text);
3291 printf("%s\n", text);
3293 dbus_message_iter_next(&sub2);
3300 dbus_message_unref(reply);
3305 static int switch_root(DBusConnection *bus, char **args) {
3307 const char *root, *init;
3309 l = strv_length(args);
3310 if (l < 2 || l > 3) {
3311 log_error("Wrong number of arguments.");
3316 init = l >= 3 ? args[2] : "";
3318 return bus_method_call_with_reply (
3320 "org.freedesktop.systemd1",
3321 "/org/freedesktop/systemd1",
3322 "org.freedesktop.systemd1.Manager",
3326 DBUS_TYPE_STRING, &root,
3327 DBUS_TYPE_STRING, &init,
3331 static int set_environment(DBusConnection *bus, char **args) {
3332 DBusMessage *m = NULL, *reply = NULL;
3336 DBusMessageIter iter, sub;
3339 dbus_error_init(&error);
3341 method = streq(args[0], "set-environment")
3343 : "UnsetEnvironment";
3345 if (!(m = dbus_message_new_method_call(
3346 "org.freedesktop.systemd1",
3347 "/org/freedesktop/systemd1",
3348 "org.freedesktop.systemd1.Manager",
3351 log_error("Could not allocate message.");
3355 dbus_message_iter_init_append(m, &iter);
3357 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3358 log_error("Could not append arguments to message.");
3363 STRV_FOREACH(name, args+1)
3364 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, name)) {
3365 log_error("Could not append arguments to message.");
3370 if (!dbus_message_iter_close_container(&iter, &sub)) {
3371 log_error("Could not append arguments to message.");
3376 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3377 log_error("Failed to issue method call: %s", bus_error_message(&error));
3386 dbus_message_unref(m);
3389 dbus_message_unref(reply);
3391 dbus_error_free(&error);
3396 static int enable_sysv_units(char **args) {
3399 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_ALTLINUX) || defined(TARGET_MAGEIA))
3400 const char *verb = args[0];
3401 unsigned f = 1, t = 1;
3404 if (arg_scope != UNIT_FILE_SYSTEM)
3407 if (!streq(verb, "enable") &&
3408 !streq(verb, "disable") &&
3409 !streq(verb, "is-enabled"))
3412 /* Processes all SysV units, and reshuffles the array so that
3413 * afterwards only the native units remain */
3416 r = lookup_paths_init(&paths, SYSTEMD_SYSTEM, false, NULL, NULL, NULL);
3421 for (f = 1; args[f]; f++) {
3424 bool found_native = false, found_sysv;
3426 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3427 char **k, *l, *q = NULL;
3434 if (!endswith(name, ".service"))
3437 if (path_is_absolute(name))
3440 STRV_FOREACH(k, paths.unit_path) {
3443 if (!isempty(arg_root))
3444 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3446 asprintf(&p, "%s/%s", *k, name);
3453 found_native = access(p, F_OK) >= 0;
3464 if (!isempty(arg_root))
3465 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3467 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3473 p[strlen(p) - sizeof(".service") + 1] = 0;
3474 found_sysv = access(p, F_OK) >= 0;
3481 /* Mark this entry, so that we don't try enabling it as native unit */
3482 args[f] = (char*) "";
3484 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
3486 if (!isempty(arg_root))
3487 argv[c++] = q = strappend("--root=", arg_root);
3489 argv[c++] = path_get_file_name(p);
3491 streq(verb, "enable") ? "on" :
3492 streq(verb, "disable") ? "off" : "--level=5";
3495 l = strv_join((char**)argv, " ");
3503 log_info("Executing %s", l);
3508 log_error("Failed to fork: %m");
3513 } else if (pid == 0) {
3516 execv(argv[0], (char**) argv);
3517 _exit(EXIT_FAILURE);
3523 j = wait_for_terminate(pid, &status);
3525 log_error("Failed to wait for child: %s", strerror(-r));
3530 if (status.si_code == CLD_EXITED) {
3531 if (streq(verb, "is-enabled")) {
3532 if (status.si_status == 0) {
3541 } else if (status.si_status != 0) {
3552 lookup_paths_free(&paths);
3554 /* Drop all SysV units */
3555 for (f = 1, t = 1; args[f]; f++) {
3557 if (isempty(args[f]))
3560 args[t++] = args[f];
3569 static int mangle_names(char **original_names, char ***mangled_names) {
3570 char **i, **l, **name;
3572 l = new(char*, strv_length(original_names) + 1);
3577 STRV_FOREACH(name, original_names) {
3579 /* When enabling units qualified path names are OK,
3580 * too, hence allow them explicitly. */
3585 *i = unit_name_mangle(*name);
3601 static int enable_unit(DBusConnection *bus, char **args) {
3602 const char *verb = args[0];
3603 UnitFileChange *changes = NULL;
3604 unsigned n_changes = 0, i;
3605 int carries_install_info = -1;
3606 DBusMessage *m = NULL, *reply = NULL;
3609 char **mangled_names = NULL;
3611 r = enable_sysv_units(args);
3618 dbus_error_init(&error);
3620 if (!bus || avoid_bus()) {
3621 if (streq(verb, "enable")) {
3622 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3623 carries_install_info = r;
3624 } else if (streq(verb, "disable"))
3625 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3626 else if (streq(verb, "reenable")) {
3627 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3628 carries_install_info = r;
3629 } else if (streq(verb, "link"))
3630 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3631 else if (streq(verb, "preset")) {
3632 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3633 carries_install_info = r;
3634 } else if (streq(verb, "mask"))
3635 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3636 else if (streq(verb, "unmask"))
3637 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3639 assert_not_reached("Unknown verb");
3642 log_error("Operation failed: %s", strerror(-r));
3647 for (i = 0; i < n_changes; i++) {
3648 if (changes[i].type == UNIT_FILE_SYMLINK)
3649 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
3651 log_info("rm '%s'", changes[i].path);
3657 bool send_force = true, expect_carries_install_info = false;
3659 DBusMessageIter iter, sub, sub2;
3661 if (streq(verb, "enable")) {
3662 method = "EnableUnitFiles";
3663 expect_carries_install_info = true;
3664 } else if (streq(verb, "disable")) {
3665 method = "DisableUnitFiles";
3667 } else if (streq(verb, "reenable")) {
3668 method = "ReenableUnitFiles";
3669 expect_carries_install_info = true;
3670 } else if (streq(verb, "link"))
3671 method = "LinkUnitFiles";
3672 else if (streq(verb, "preset")) {
3673 method = "PresetUnitFiles";
3674 expect_carries_install_info = true;
3675 } else if (streq(verb, "mask"))
3676 method = "MaskUnitFiles";
3677 else if (streq(verb, "unmask")) {
3678 method = "UnmaskUnitFiles";
3681 assert_not_reached("Unknown verb");
3683 m = dbus_message_new_method_call(
3684 "org.freedesktop.systemd1",
3685 "/org/freedesktop/systemd1",
3686 "org.freedesktop.systemd1.Manager",
3693 dbus_message_iter_init_append(m, &iter);
3695 r = mangle_names(args+1, &mangled_names);
3699 r = bus_append_strv_iter(&iter, mangled_names);
3701 log_error("Failed to append unit files.");
3706 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
3707 log_error("Failed to append runtime boolean.");
3715 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
3716 log_error("Failed to append force boolean.");
3722 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3724 log_error("Failed to issue method call: %s", bus_error_message(&error));
3729 if (!dbus_message_iter_init(reply, &iter)) {
3730 log_error("Failed to initialize iterator.");
3734 if (expect_carries_install_info) {
3735 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
3737 log_error("Failed to parse reply.");
3741 carries_install_info = b;
3744 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3745 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
3746 log_error("Failed to parse reply.");
3751 dbus_message_iter_recurse(&iter, &sub);
3752 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3753 const char *type, *path, *source;
3755 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
3756 log_error("Failed to parse reply.");
3761 dbus_message_iter_recurse(&sub, &sub2);
3763 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
3764 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
3765 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
3766 log_error("Failed to parse reply.");
3772 if (streq(type, "symlink"))
3773 log_info("ln -s '%s' '%s'", source, path);
3775 log_info("rm '%s'", path);
3778 dbus_message_iter_next(&sub);
3781 /* Try to reload if enabeld */
3783 r = daemon_reload(bus, args);
3786 if (carries_install_info == 0)
3787 log_warning("The unit files have no [Install] section. They are not meant to be enabled using systemctl.");
3791 dbus_message_unref(m);
3794 dbus_message_unref(reply);
3796 unit_file_changes_free(changes, n_changes);
3798 dbus_error_free(&error);
3800 strv_free(mangled_names);
3805 static int unit_is_enabled(DBusConnection *bus, char **args) {
3808 DBusMessage *reply = NULL;
3812 dbus_error_init(&error);
3814 r = enable_sysv_units(args);
3820 if (!bus || avoid_bus()) {
3822 STRV_FOREACH(name, args+1) {
3823 UnitFileState state;
3825 state = unit_file_get_state(arg_scope, arg_root, *name);
3831 if (state == UNIT_FILE_ENABLED ||
3832 state == UNIT_FILE_ENABLED_RUNTIME ||
3833 state == UNIT_FILE_STATIC)
3837 puts(unit_file_state_to_string(state));
3841 STRV_FOREACH(name, args+1) {
3844 r = bus_method_call_with_reply (
3846 "org.freedesktop.systemd1",
3847 "/org/freedesktop/systemd1",
3848 "org.freedesktop.systemd1.Manager",
3852 DBUS_TYPE_STRING, name,
3857 if (!dbus_message_get_args(reply, &error,
3858 DBUS_TYPE_STRING, &s,
3859 DBUS_TYPE_INVALID)) {
3860 log_error("Failed to parse reply: %s", bus_error_message(&error));
3865 dbus_message_unref(reply);
3868 if (streq(s, "enabled") ||
3869 streq(s, "enabled-runtime") ||
3878 r = enabled ? 0 : 1;
3882 dbus_message_unref(reply);
3884 dbus_error_free(&error);
3888 static int systemctl_help(void) {
3890 pager_open_if_enabled();
3892 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3893 "Query or send control commands to the systemd manager.\n\n"
3894 " -h --help Show this help\n"
3895 " --version Show package version\n"
3896 " -t --type=TYPE List only units of a particular type\n"
3897 " -p --property=NAME Show only properties by this name\n"
3898 " -a --all Show all units/properties, including dead/empty ones\n"
3899 " --failed Show only failed units\n"
3900 " --full Don't ellipsize unit names on output\n"
3901 " --fail When queueing a new job, fail if conflicting jobs are\n"
3903 " --ignore-dependencies\n"
3904 " When queueing a new job, ignore all its dependencies\n"
3905 " --kill-who=WHO Who to send signal to\n"
3906 " -s --signal=SIGNAL Which signal to send\n"
3907 " -H --host=[USER@]HOST\n"
3908 " Show information for remote host\n"
3909 " -P --privileged Acquire privileges before execution\n"
3910 " -q --quiet Suppress output\n"
3911 " --no-block Do not wait until operation finished\n"
3912 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3913 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3915 " --no-legend Do not print a legend (column headers and hints)\n"
3916 " --no-pager Do not pipe output into a pager\n"
3917 " --no-ask-password\n"
3918 " Do not ask for system passwords\n"
3919 " --order When generating graph for dot, show only order\n"
3920 " --require When generating graph for dot, show only requirement\n"
3921 " --system Connect to system manager\n"
3922 " --user Connect to user service manager\n"
3923 " --global Enable/disable unit files globally\n"
3924 " -f --force When enabling unit files, override existing symlinks\n"
3925 " When shutting down, execute action immediately\n"
3926 " --root=PATH Enable unit files in the specified root directory\n"
3927 " --runtime Enable unit files only temporarily until next reboot\n"
3928 " -n --lines=INTEGER Journal entries to show\n"
3929 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
3930 " verbose, export, json, json-pretty, json-sse, cat)\n\n"
3932 " list-units List loaded units\n"
3933 " start [NAME...] Start (activate) one or more units\n"
3934 " stop [NAME...] Stop (deactivate) one or more units\n"
3935 " reload [NAME...] Reload one or more units\n"
3936 " restart [NAME...] Start or restart one or more units\n"
3937 " try-restart [NAME...] Restart one or more units if active\n"
3938 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3939 " otherwise start or restart\n"
3940 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3941 " otherwise restart if active\n"
3942 " isolate [NAME] Start one unit and stop all others\n"
3943 " kill [NAME...] Send signal to processes of a unit\n"
3944 " is-active [NAME...] Check whether units are active\n"
3945 " status [NAME...|PID...] Show runtime status of one or more units\n"
3946 " show [NAME...|JOB...] Show properties of one or more\n"
3947 " units/jobs or the manager\n"
3948 " help [NAME...|PID...] Show manual for one or more units\n"
3949 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3951 " load [NAME...] Load one or more units\n\n"
3952 "Unit File Commands:\n"
3953 " list-unit-files List installed unit files\n"
3954 " enable [NAME...] Enable one or more unit files\n"
3955 " disable [NAME...] Disable one or more unit files\n"
3956 " reenable [NAME...] Reenable one or more unit files\n"
3957 " preset [NAME...] Enable/disable one or more unit files\n"
3958 " based on preset configuration\n"
3959 " mask [NAME...] Mask one or more units\n"
3960 " unmask [NAME...] Unmask one or more units\n"
3961 " link [PATH...] Link one or more units files into\n"
3962 " the search path\n"
3963 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
3965 " list-jobs List jobs\n"
3966 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
3967 "Status Commands:\n"
3968 " dump Dump server status\n"
3969 " dot Dump dependency graph for dot(1)\n\n"
3970 "Snapshot Commands:\n"
3971 " snapshot [NAME] Create a snapshot\n"
3972 " delete [NAME...] Remove one or more snapshots\n\n"
3973 "Environment Commands:\n"
3974 " show-environment Dump environment\n"
3975 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3976 " unset-environment [NAME...] Unset one or more environment variables\n\n"
3977 "Manager Lifecycle Commands:\n"
3978 " daemon-reload Reload systemd manager configuration\n"
3979 " daemon-reexec Reexecute systemd manager\n\n"
3980 "System Commands:\n"
3981 " default Enter system default mode\n"
3982 " rescue Enter system rescue mode\n"
3983 " emergency Enter system emergency mode\n"
3984 " halt Shut down and halt the system\n"
3985 " poweroff Shut down and power-off the system\n"
3986 " reboot Shut down and reboot the system\n"
3987 " kexec Shut down and reboot the system with kexec\n"
3988 " exit Request user instance exit\n"
3989 " switch-root [ROOT] [INIT] Change to a different root file system\n"
3990 " suspend Suspend the system\n"
3991 " hibernate Hibernate the system\n",
3992 program_invocation_short_name);
3997 static int halt_help(void) {
3999 printf("%s [OPTIONS...]\n\n"
4000 "%s the system.\n\n"
4001 " --help Show this help\n"
4002 " --halt Halt the machine\n"
4003 " -p --poweroff Switch off the machine\n"
4004 " --reboot Reboot the machine\n"
4005 " -f --force Force immediate halt/power-off/reboot\n"
4006 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4007 " -d --no-wtmp Don't write wtmp record\n"
4008 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4009 program_invocation_short_name,
4010 arg_action == ACTION_REBOOT ? "Reboot" :
4011 arg_action == ACTION_POWEROFF ? "Power off" :
4017 static int shutdown_help(void) {
4019 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4020 "Shut down the system.\n\n"
4021 " --help Show this help\n"
4022 " -H --halt Halt the machine\n"
4023 " -P --poweroff Power-off the machine\n"
4024 " -r --reboot Reboot the machine\n"
4025 " -h Equivalent to --poweroff, overridden by --halt\n"
4026 " -k Don't halt/power-off/reboot, just send warnings\n"
4027 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4028 " -c Cancel a pending shutdown\n",
4029 program_invocation_short_name);
4034 static int telinit_help(void) {
4036 printf("%s [OPTIONS...] {COMMAND}\n\n"
4037 "Send control commands to the init daemon.\n\n"
4038 " --help Show this help\n"
4039 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4041 " 0 Power-off the machine\n"
4042 " 6 Reboot the machine\n"
4043 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4044 " 1, s, S Enter rescue mode\n"
4045 " q, Q Reload init daemon configuration\n"
4046 " u, U Reexecute init daemon\n",
4047 program_invocation_short_name);
4052 static int runlevel_help(void) {
4054 printf("%s [OPTIONS...]\n\n"
4055 "Prints the previous and current runlevel of the init system.\n\n"
4056 " --help Show this help\n",
4057 program_invocation_short_name);
4062 static int systemctl_parse_argv(int argc, char *argv[]) {
4066 ARG_IGNORE_DEPENDENCIES,
4081 ARG_NO_ASK_PASSWORD,
4087 static const struct option options[] = {
4088 { "help", no_argument, NULL, 'h' },
4089 { "version", no_argument, NULL, ARG_VERSION },
4090 { "type", required_argument, NULL, 't' },
4091 { "property", required_argument, NULL, 'p' },
4092 { "all", no_argument, NULL, 'a' },
4093 { "failed", no_argument, NULL, ARG_FAILED },
4094 { "full", no_argument, NULL, ARG_FULL },
4095 { "fail", no_argument, NULL, ARG_FAIL },
4096 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4097 { "user", no_argument, NULL, ARG_USER },
4098 { "system", no_argument, NULL, ARG_SYSTEM },
4099 { "global", no_argument, NULL, ARG_GLOBAL },
4100 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4101 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4102 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4103 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4104 { "quiet", no_argument, NULL, 'q' },
4105 { "order", no_argument, NULL, ARG_ORDER },
4106 { "require", no_argument, NULL, ARG_REQUIRE },
4107 { "root", required_argument, NULL, ARG_ROOT },
4108 { "force", no_argument, NULL, ARG_FORCE },
4109 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4110 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4111 { "signal", required_argument, NULL, 's' },
4112 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4113 { "host", required_argument, NULL, 'H' },
4114 { "privileged",no_argument, NULL, 'P' },
4115 { "runtime", no_argument, NULL, ARG_RUNTIME },
4116 { "lines", required_argument, NULL, 'n' },
4117 { "output", required_argument, NULL, 'o' },
4118 { NULL, 0, NULL, 0 }
4126 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4135 puts(PACKAGE_STRING);
4137 puts(SYSTEMD_FEATURES);
4141 if (unit_type_from_string(optarg) >= 0) {
4145 if (unit_load_state_from_string(optarg) >= 0) {
4146 arg_load_state = optarg;
4149 log_error("Unkown unit type or load state '%s'.",
4155 if (!(l = strv_append(arg_property, optarg)))
4158 strv_free(arg_property);
4161 /* If the user asked for a particular
4162 * property, show it to him, even if it is
4173 arg_job_mode = "fail";
4176 case ARG_IGNORE_DEPENDENCIES:
4177 arg_job_mode = "ignore-dependencies";
4181 arg_scope = UNIT_FILE_USER;
4185 arg_scope = UNIT_FILE_SYSTEM;
4189 arg_scope = UNIT_FILE_GLOBAL;
4193 arg_no_block = true;
4197 arg_no_legend = true;
4201 arg_no_pager = true;
4209 arg_dot = DOT_ORDER;
4213 arg_dot = DOT_REQUIRE;
4241 arg_no_reload = true;
4245 arg_kill_who = optarg;
4249 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4250 log_error("Failed to parse signal string %s.", optarg);
4255 case ARG_NO_ASK_PASSWORD:
4256 arg_ask_password = false;
4260 arg_transport = TRANSPORT_POLKIT;
4264 arg_transport = TRANSPORT_SSH;
4273 if (safe_atou(optarg, &arg_lines) < 0) {
4274 log_error("Failed to parse lines '%s'", optarg);
4280 arg_output = output_mode_from_string(optarg);
4281 if (arg_output < 0) {
4282 log_error("Unknown output '%s'.", optarg);
4291 log_error("Unknown option code '%c'.", c);
4296 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4297 log_error("Cannot access user instance remotely.");
4304 static int halt_parse_argv(int argc, char *argv[]) {
4313 static const struct option options[] = {
4314 { "help", no_argument, NULL, ARG_HELP },
4315 { "halt", no_argument, NULL, ARG_HALT },
4316 { "poweroff", no_argument, NULL, 'p' },
4317 { "reboot", no_argument, NULL, ARG_REBOOT },
4318 { "force", no_argument, NULL, 'f' },
4319 { "wtmp-only", no_argument, NULL, 'w' },
4320 { "no-wtmp", no_argument, NULL, 'd' },
4321 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4322 { NULL, 0, NULL, 0 }
4330 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4331 if (runlevel == '0' || runlevel == '6')
4334 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4342 arg_action = ACTION_HALT;
4346 if (arg_action != ACTION_REBOOT)
4347 arg_action = ACTION_POWEROFF;
4351 arg_action = ACTION_REBOOT;
4373 /* Compatibility nops */
4380 log_error("Unknown option code '%c'.", c);
4385 if (optind < argc) {
4386 log_error("Too many arguments.");
4393 static int parse_time_spec(const char *t, usec_t *_u) {
4397 if (streq(t, "now"))
4399 else if (!strchr(t, ':')) {
4402 if (safe_atou64(t, &u) < 0)
4405 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4414 hour = strtol(t, &e, 10);
4415 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4418 minute = strtol(e+1, &e, 10);
4419 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4422 n = now(CLOCK_REALTIME);
4423 s = (time_t) (n / USEC_PER_SEC);
4426 assert_se(localtime_r(&s, &tm));
4428 tm.tm_hour = (int) hour;
4429 tm.tm_min = (int) minute;
4432 assert_se(s = mktime(&tm));
4434 *_u = (usec_t) s * USEC_PER_SEC;
4437 *_u += USEC_PER_DAY;
4443 static int shutdown_parse_argv(int argc, char *argv[]) {
4450 static const struct option options[] = {
4451 { "help", no_argument, NULL, ARG_HELP },
4452 { "halt", no_argument, NULL, 'H' },
4453 { "poweroff", no_argument, NULL, 'P' },
4454 { "reboot", no_argument, NULL, 'r' },
4455 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4456 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4457 { NULL, 0, NULL, 0 }
4465 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4473 arg_action = ACTION_HALT;
4477 arg_action = ACTION_POWEROFF;
4482 arg_action = ACTION_KEXEC;
4484 arg_action = ACTION_REBOOT;
4488 arg_action = ACTION_KEXEC;
4492 if (arg_action != ACTION_HALT)
4493 arg_action = ACTION_POWEROFF;
4506 /* Compatibility nops */
4510 arg_action = ACTION_CANCEL_SHUTDOWN;
4517 log_error("Unknown option code '%c'.", c);
4522 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
4523 r = parse_time_spec(argv[optind], &arg_when);
4525 log_error("Failed to parse time specification: %s", argv[optind]);
4529 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4531 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
4532 /* No time argument for shutdown cancel */
4533 arg_wall = argv + optind;
4534 else if (argc > optind + 1)
4535 /* We skip the time argument */
4536 arg_wall = argv + optind + 1;
4543 static int telinit_parse_argv(int argc, char *argv[]) {
4550 static const struct option options[] = {
4551 { "help", no_argument, NULL, ARG_HELP },
4552 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4553 { NULL, 0, NULL, 0 }
4556 static const struct {
4560 { '0', ACTION_POWEROFF },
4561 { '6', ACTION_REBOOT },
4562 { '1', ACTION_RESCUE },
4563 { '2', ACTION_RUNLEVEL2 },
4564 { '3', ACTION_RUNLEVEL3 },
4565 { '4', ACTION_RUNLEVEL4 },
4566 { '5', ACTION_RUNLEVEL5 },
4567 { 's', ACTION_RESCUE },
4568 { 'S', ACTION_RESCUE },
4569 { 'q', ACTION_RELOAD },
4570 { 'Q', ACTION_RELOAD },
4571 { 'u', ACTION_REEXEC },
4572 { 'U', ACTION_REEXEC }
4581 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4596 log_error("Unknown option code '%c'.", c);
4601 if (optind >= argc) {
4606 if (optind + 1 < argc) {
4607 log_error("Too many arguments.");
4611 if (strlen(argv[optind]) != 1) {
4612 log_error("Expected single character argument.");
4616 for (i = 0; i < ELEMENTSOF(table); i++)
4617 if (table[i].from == argv[optind][0])
4620 if (i >= ELEMENTSOF(table)) {
4621 log_error("Unknown command '%s'.", argv[optind]);
4625 arg_action = table[i].to;
4632 static int runlevel_parse_argv(int argc, char *argv[]) {
4638 static const struct option options[] = {
4639 { "help", no_argument, NULL, ARG_HELP },
4640 { NULL, 0, NULL, 0 }
4648 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4659 log_error("Unknown option code '%c'.", c);
4664 if (optind < argc) {
4665 log_error("Too many arguments.");
4672 static int parse_argv(int argc, char *argv[]) {
4676 if (program_invocation_short_name) {
4678 if (strstr(program_invocation_short_name, "halt")) {
4679 arg_action = ACTION_HALT;
4680 return halt_parse_argv(argc, argv);
4681 } else if (strstr(program_invocation_short_name, "poweroff")) {
4682 arg_action = ACTION_POWEROFF;
4683 return halt_parse_argv(argc, argv);
4684 } else if (strstr(program_invocation_short_name, "reboot")) {
4686 arg_action = ACTION_KEXEC;
4688 arg_action = ACTION_REBOOT;
4689 return halt_parse_argv(argc, argv);
4690 } else if (strstr(program_invocation_short_name, "shutdown")) {
4691 arg_action = ACTION_POWEROFF;
4692 return shutdown_parse_argv(argc, argv);
4693 } else if (strstr(program_invocation_short_name, "init")) {
4695 if (sd_booted() > 0) {
4696 arg_action = ACTION_INVALID;
4697 return telinit_parse_argv(argc, argv);
4699 /* Hmm, so some other init system is
4700 * running, we need to forward this
4701 * request to it. For now we simply
4702 * guess that it is Upstart. */
4704 execv("/lib/upstart/telinit", argv);
4706 log_error("Couldn't find an alternative telinit implementation to spawn.");
4710 } else if (strstr(program_invocation_short_name, "runlevel")) {
4711 arg_action = ACTION_RUNLEVEL;
4712 return runlevel_parse_argv(argc, argv);
4716 arg_action = ACTION_SYSTEMCTL;
4717 return systemctl_parse_argv(argc, argv);
4720 static int action_to_runlevel(void) {
4722 static const char table[_ACTION_MAX] = {
4723 [ACTION_HALT] = '0',
4724 [ACTION_POWEROFF] = '0',
4725 [ACTION_REBOOT] = '6',
4726 [ACTION_RUNLEVEL2] = '2',
4727 [ACTION_RUNLEVEL3] = '3',
4728 [ACTION_RUNLEVEL4] = '4',
4729 [ACTION_RUNLEVEL5] = '5',
4730 [ACTION_RESCUE] = '1'
4733 assert(arg_action < _ACTION_MAX);
4735 return table[arg_action];
4738 static int talk_upstart(void) {
4739 DBusMessage *m = NULL, *reply = NULL;
4741 int previous, rl, r;
4743 env1_buf[] = "RUNLEVEL=X",
4744 env2_buf[] = "PREVLEVEL=X";
4745 char *env1 = env1_buf, *env2 = env2_buf;
4746 const char *emit = "runlevel";
4747 dbus_bool_t b_false = FALSE;
4748 DBusMessageIter iter, sub;
4749 DBusConnection *bus;
4751 dbus_error_init(&error);
4753 if (!(rl = action_to_runlevel()))
4756 if (utmp_get_runlevel(&previous, NULL) < 0)
4759 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4760 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4765 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4770 if ((r = bus_check_peercred(bus)) < 0) {
4771 log_error("Failed to verify owner of bus.");
4775 if (!(m = dbus_message_new_method_call(
4776 "com.ubuntu.Upstart",
4777 "/com/ubuntu/Upstart",
4778 "com.ubuntu.Upstart0_6",
4781 log_error("Could not allocate message.");
4786 dbus_message_iter_init_append(m, &iter);
4788 env1_buf[sizeof(env1_buf)-2] = rl;
4789 env2_buf[sizeof(env2_buf)-2] = previous;
4791 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4792 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4793 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4794 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4795 !dbus_message_iter_close_container(&iter, &sub) ||
4796 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4797 log_error("Could not append arguments to message.");
4802 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4804 if (bus_error_is_no_service(&error)) {
4809 log_error("Failed to issue method call: %s", bus_error_message(&error));
4818 dbus_message_unref(m);
4821 dbus_message_unref(reply);
4824 dbus_connection_flush(bus);
4825 dbus_connection_close(bus);
4826 dbus_connection_unref(bus);
4829 dbus_error_free(&error);
4834 static int talk_initctl(void) {
4835 struct init_request request;
4839 if (!(rl = action_to_runlevel()))
4843 request.magic = INIT_MAGIC;
4844 request.sleeptime = 0;
4845 request.cmd = INIT_CMD_RUNLVL;
4846 request.runlevel = rl;
4848 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4850 if (errno == ENOENT)
4853 log_error("Failed to open "INIT_FIFO": %m");
4858 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4859 close_nointr_nofail(fd);
4862 log_error("Failed to write to "INIT_FIFO": %m");
4863 return errno ? -errno : -EIO;
4869 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4871 static const struct {
4879 int (* const dispatch)(DBusConnection *bus, char **args);
4881 { "list-units", LESS, 1, list_units },
4882 { "list-unit-files", EQUAL, 1, list_unit_files },
4883 { "list-jobs", EQUAL, 1, list_jobs },
4884 { "clear-jobs", EQUAL, 1, daemon_reload },
4885 { "load", MORE, 2, load_unit },
4886 { "cancel", MORE, 2, cancel_job },
4887 { "start", MORE, 2, start_unit },
4888 { "stop", MORE, 2, start_unit },
4889 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4890 { "reload", MORE, 2, start_unit },
4891 { "restart", MORE, 2, start_unit },
4892 { "try-restart", MORE, 2, start_unit },
4893 { "reload-or-restart", MORE, 2, start_unit },
4894 { "reload-or-try-restart", MORE, 2, start_unit },
4895 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4896 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4897 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4898 { "isolate", EQUAL, 2, start_unit },
4899 { "kill", MORE, 2, kill_unit },
4900 { "is-active", MORE, 2, check_unit },
4901 { "check", MORE, 2, check_unit },
4902 { "show", MORE, 1, show },
4903 { "status", MORE, 2, show },
4904 { "help", MORE, 2, show },
4905 { "dump", EQUAL, 1, dump },
4906 { "dot", EQUAL, 1, dot },
4907 { "snapshot", LESS, 2, snapshot },
4908 { "delete", MORE, 2, delete_snapshot },
4909 { "daemon-reload", EQUAL, 1, daemon_reload },
4910 { "daemon-reexec", EQUAL, 1, daemon_reload },
4911 { "show-environment", EQUAL, 1, show_enviroment },
4912 { "set-environment", MORE, 2, set_environment },
4913 { "unset-environment", MORE, 2, set_environment },
4914 { "halt", EQUAL, 1, start_special },
4915 { "poweroff", EQUAL, 1, start_special },
4916 { "reboot", EQUAL, 1, start_special },
4917 { "kexec", EQUAL, 1, start_special },
4918 { "suspend", EQUAL, 1, start_special },
4919 { "hibernate", EQUAL, 1, start_special },
4920 { "default", EQUAL, 1, start_special },
4921 { "rescue", EQUAL, 1, start_special },
4922 { "emergency", EQUAL, 1, start_special },
4923 { "exit", EQUAL, 1, start_special },
4924 { "reset-failed", MORE, 1, reset_failed },
4925 { "enable", MORE, 2, enable_unit },
4926 { "disable", MORE, 2, enable_unit },
4927 { "is-enabled", MORE, 2, unit_is_enabled },
4928 { "reenable", MORE, 2, enable_unit },
4929 { "preset", MORE, 2, enable_unit },
4930 { "mask", MORE, 2, enable_unit },
4931 { "unmask", MORE, 2, enable_unit },
4932 { "link", MORE, 2, enable_unit },
4933 { "switch-root", MORE, 2, switch_root },
4943 left = argc - optind;
4946 /* Special rule: no arguments means "list-units" */
4949 if (streq(argv[optind], "help") && !argv[optind+1]) {
4950 log_error("This command expects one or more "
4951 "unit names. Did you mean --help?");
4955 for (i = 0; i < ELEMENTSOF(verbs); i++)
4956 if (streq(argv[optind], verbs[i].verb))
4959 if (i >= ELEMENTSOF(verbs)) {
4960 log_error("Unknown operation '%s'.", argv[optind]);
4965 switch (verbs[i].argc_cmp) {
4968 if (left != verbs[i].argc) {
4969 log_error("Invalid number of arguments.");
4976 if (left < verbs[i].argc) {
4977 log_error("Too few arguments.");
4984 if (left > verbs[i].argc) {
4985 log_error("Too many arguments.");
4992 assert_not_reached("Unknown comparison operator.");
4995 /* Require a bus connection for all operations but
4997 if (!streq(verbs[i].verb, "enable") &&
4998 !streq(verbs[i].verb, "disable") &&
4999 !streq(verbs[i].verb, "is-enabled") &&
5000 !streq(verbs[i].verb, "list-unit-files") &&
5001 !streq(verbs[i].verb, "reenable") &&
5002 !streq(verbs[i].verb, "preset") &&
5003 !streq(verbs[i].verb, "mask") &&
5004 !streq(verbs[i].verb, "unmask") &&
5005 !streq(verbs[i].verb, "link")) {
5007 if (running_in_chroot() > 0) {
5008 log_info("Running in chroot, ignoring request.");
5012 if (((!streq(verbs[i].verb, "reboot") &&
5013 !streq(verbs[i].verb, "halt") &&
5014 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5015 log_error("Failed to get D-Bus connection: %s",
5016 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5022 if (!bus && !avoid_bus()) {
5023 log_error("Failed to get D-Bus connection: %s",
5024 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5029 return verbs[i].dispatch(bus, argv + optind);
5032 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5034 struct msghdr msghdr;
5035 struct iovec iovec[2];
5036 union sockaddr_union sockaddr;
5037 struct sd_shutdown_command c;
5039 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5046 c.dry_run = dry_run;
5050 sockaddr.sa.sa_family = AF_UNIX;
5051 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5054 msghdr.msg_name = &sockaddr;
5055 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5058 iovec[0].iov_base = (char*) &c;
5059 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5061 if (isempty(message))
5062 msghdr.msg_iovlen = 1;
5064 iovec[1].iov_base = (char*) message;
5065 iovec[1].iov_len = strlen(message);
5066 msghdr.msg_iovlen = 2;
5068 msghdr.msg_iov = iovec;
5070 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5071 close_nointr_nofail(fd);
5075 close_nointr_nofail(fd);
5079 static int reload_with_fallback(DBusConnection *bus) {
5082 /* First, try systemd via D-Bus. */
5083 if (daemon_reload(bus, NULL) >= 0)
5087 /* Nothing else worked, so let's try signals */
5088 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5090 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5091 log_error("kill() failed: %m");
5098 static int start_with_fallback(DBusConnection *bus) {
5101 /* First, try systemd via D-Bus. */
5102 if (start_unit(bus, NULL) >= 0)
5106 /* Hmm, talking to systemd via D-Bus didn't work. Then
5107 * let's try to talk to Upstart via D-Bus. */
5108 if (talk_upstart() > 0)
5111 /* Nothing else worked, so let's try
5113 if (talk_initctl() > 0)
5116 log_error("Failed to talk to init daemon.");
5120 warn_wall(arg_action);
5124 static _noreturn_ void halt_now(enum action a) {
5126 /* Make sure C-A-D is handled by the kernel from this
5128 reboot(RB_ENABLE_CAD);
5133 log_info("Halting.");
5134 reboot(RB_HALT_SYSTEM);
5137 case ACTION_POWEROFF:
5138 log_info("Powering off.");
5139 reboot(RB_POWER_OFF);
5143 log_info("Rebooting.");
5144 reboot(RB_AUTOBOOT);
5148 assert_not_reached("Unknown halt action.");
5151 assert_not_reached("Uh? This shouldn't happen.");
5154 static int halt_main(DBusConnection *bus) {
5157 if (geteuid() != 0) {
5158 /* Try logind if we are a normal user and no special
5159 * mode applies. Maybe PolicyKit allows us to shutdown
5162 if (arg_when <= 0 &&
5165 (arg_action == ACTION_POWEROFF ||
5166 arg_action == ACTION_REBOOT)) {
5167 r = reboot_with_logind(bus, arg_action);
5172 log_error("Must be root.");
5179 m = strv_join(arg_wall, " ");
5180 r = send_shutdownd(arg_when,
5181 arg_action == ACTION_HALT ? 'H' :
5182 arg_action == ACTION_POWEROFF ? 'P' :
5183 arg_action == ACTION_KEXEC ? 'K' :
5191 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5193 char date[FORMAT_TIMESTAMP_MAX];
5195 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5196 format_timestamp(date, sizeof(date), arg_when));
5201 if (!arg_dry && !arg_force)
5202 return start_with_fallback(bus);
5205 if (sd_booted() > 0)
5206 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5208 r = utmp_put_shutdown();
5210 log_warning("Failed to write utmp record: %s", strerror(-r));
5217 halt_now(arg_action);
5218 /* We should never reach this. */
5222 static int runlevel_main(void) {
5223 int r, runlevel, previous;
5225 r = utmp_get_runlevel(&runlevel, &previous);
5232 previous <= 0 ? 'N' : previous,
5233 runlevel <= 0 ? 'N' : runlevel);
5238 int main(int argc, char*argv[]) {
5239 int r, retval = EXIT_FAILURE;
5240 DBusConnection *bus = NULL;
5243 dbus_error_init(&error);
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();