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"
67 static const char *arg_type = NULL;
68 static const char *arg_load_state = NULL;
69 static char **arg_property = NULL;
70 static bool arg_all = false;
71 static const char *arg_job_mode = "replace";
72 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
73 static bool arg_no_block = false;
74 static bool arg_no_legend = false;
75 static bool arg_no_pager = false;
76 static bool arg_no_wtmp = false;
77 static bool arg_no_wall = false;
78 static bool arg_no_reload = false;
79 static bool arg_dry = false;
80 static bool arg_quiet = false;
81 static bool arg_full = false;
82 static int arg_force = 0;
83 static bool arg_ask_password = true;
84 static bool arg_failed = false;
85 static bool arg_runtime = false;
86 static char **arg_wall = NULL;
87 static const char *arg_kill_who = NULL;
88 static int arg_signal = SIGTERM;
89 static const char *arg_root = NULL;
90 static usec_t arg_when = 0;
111 ACTION_CANCEL_SHUTDOWN,
113 } arg_action = ACTION_SYSTEMCTL;
119 static enum transport {
123 } arg_transport = TRANSPORT_NORMAL;
124 static const char *arg_host = NULL;
125 static bool arg_follow = false;
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 bool on_tty(void) {
137 /* Note that this is invoked relatively early, before we start
138 * the pager. That means the value we return reflects whether
139 * we originally were started on a tty, not if we currently
140 * are. But this is intended, since we want colour and so on
141 * when run in our own pager. */
143 if (_unlikely_(t < 0))
144 t = isatty(STDOUT_FILENO) > 0;
149 static void pager_open_if_enabled(void) {
151 /* Cache result before we open the pager */
160 static void ask_password_agent_open_if_enabled(void) {
162 /* Open the password agent as a child process if necessary */
164 if (!arg_ask_password)
167 if (arg_scope != UNIT_FILE_SYSTEM)
170 ask_password_agent_open();
174 static void polkit_agent_open_if_enabled(void) {
176 /* Open the polkit agent as a child process if necessary */
178 if (!arg_ask_password)
181 if (arg_scope != UNIT_FILE_SYSTEM)
188 static const char *ansi_highlight_red(bool b) {
193 return b ? ANSI_HIGHLIGHT_RED_ON : ANSI_HIGHLIGHT_OFF;
196 static const char *ansi_highlight_green(bool b) {
201 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
204 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
207 if (!dbus_error_is_set(error))
210 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
211 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
212 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
213 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
214 return EXIT_NOPERMISSION;
216 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
217 return EXIT_NOTINSTALLED;
219 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
220 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
221 return EXIT_NOTIMPLEMENTED;
223 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
224 return EXIT_NOTCONFIGURED;
232 static void warn_wall(enum action a) {
233 static const char *table[_ACTION_MAX] = {
234 [ACTION_HALT] = "The system is going down for system halt NOW!",
235 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
236 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
237 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
238 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
239 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!",
240 [ACTION_CANCEL_SHUTDOWN] = "The system shutdown has been cancelled NOW!"
249 p = strv_join(arg_wall, " ");
251 log_error("Failed to join strings.");
267 utmp_wall(table[a], NULL);
270 static bool avoid_bus(void) {
272 if (running_in_chroot() > 0)
275 if (sd_booted() <= 0)
278 if (!isempty(arg_root))
281 if (arg_scope == UNIT_FILE_GLOBAL)
289 const char *description;
290 const char *load_state;
291 const char *active_state;
292 const char *sub_state;
293 const char *following;
294 const char *unit_path;
296 const char *job_type;
297 const char *job_path;
300 static int compare_unit_info(const void *a, const void *b) {
302 const struct unit_info *u = a, *v = b;
304 d1 = strrchr(u->id, '.');
305 d2 = strrchr(v->id, '.');
310 if ((r = strcasecmp(d1, d2)) != 0)
314 return strcasecmp(u->id, v->id);
317 static bool output_show_unit(const struct unit_info *u) {
321 return streq(u->active_state, "failed");
323 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
324 streq(dot+1, arg_type))) &&
325 (!arg_load_state || streq(u->load_state, arg_load_state)) &&
326 (arg_all || !(streq(u->active_state, "inactive")
327 || u->following[0]) || u->job_id > 0);
330 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
331 unsigned id_len, max_id_len, active_len, sub_len, job_len, desc_len, n_shown = 0;
332 const struct unit_info *u;
334 max_id_len = sizeof("UNIT")-1;
335 active_len = sizeof("ACTIVE")-1;
336 sub_len = sizeof("SUB")-1;
337 job_len = sizeof("JOB")-1;
340 for (u = unit_infos; u < unit_infos + c; u++) {
341 if (!output_show_unit(u))
344 max_id_len = MAX(max_id_len, strlen(u->id));
345 active_len = MAX(active_len, strlen(u->active_state));
346 sub_len = MAX(sub_len, strlen(u->sub_state));
348 job_len = MAX(job_len, strlen(u->job_type));
353 id_len = MIN(max_id_len, 25);
354 basic_len = 5 + id_len + 6 + active_len + sub_len + job_len;
355 if (basic_len < (unsigned) columns()) {
356 unsigned extra_len, incr;
357 extra_len = columns() - basic_len;
358 /* Either UNIT already got 25, or is fully satisfied.
359 * Grant up to 25 to DESC now. */
360 incr = MIN(extra_len, 25);
363 /* split the remaining space between UNIT and DESC,
364 * but do not give UNIT more than it needs. */
366 incr = MIN(extra_len / 2, max_id_len - id_len);
368 desc_len += extra_len - incr;
374 if (!arg_no_legend) {
375 printf("%-*s %-6s %-*s %-*s %-*s ", id_len, "UNIT", "LOAD",
376 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
377 if (!arg_full && arg_no_pager)
378 printf("%.*s\n", desc_len, "DESCRIPTION");
380 printf("%s\n", "DESCRIPTION");
383 for (u = unit_infos; u < unit_infos + c; u++) {
385 const char *on_loaded, *off_loaded;
386 const char *on_active, *off_active;
388 if (!output_show_unit(u))
393 if (streq(u->load_state, "error")) {
394 on_loaded = ansi_highlight_red(true);
395 off_loaded = ansi_highlight_red(false);
397 on_loaded = off_loaded = "";
399 if (streq(u->active_state, "failed")) {
400 on_active = ansi_highlight_red(true);
401 off_active = ansi_highlight_red(false);
403 on_active = off_active = "";
405 e = arg_full ? NULL : ellipsize(u->id, id_len, 33);
407 printf("%-*s %s%-6s%s %s%-*s %-*s%s %-*s ",
408 id_len, e ? e : u->id,
409 on_loaded, u->load_state, off_loaded,
410 on_active, active_len, u->active_state,
411 sub_len, u->sub_state, off_active,
412 job_len, u->job_id ? u->job_type : "");
413 if (!arg_full && arg_no_pager)
414 printf("%.*s\n", desc_len, u->description);
416 printf("%s\n", u->description);
421 if (!arg_no_legend) {
422 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
423 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
424 "SUB = The low-level unit activation state, values depend on unit type.\n"
425 "JOB = Pending job for the unit.\n");
428 printf("\n%u units listed.\n", n_shown);
430 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
434 static int list_units(DBusConnection *bus, char **args) {
435 DBusMessage *reply = NULL;
437 DBusMessageIter iter, sub, sub2;
438 unsigned c = 0, n_units = 0;
439 struct unit_info *unit_infos = NULL;
441 pager_open_if_enabled();
443 r = bus_method_call_with_reply (
445 "org.freedesktop.systemd1",
446 "/org/freedesktop/systemd1",
447 "org.freedesktop.systemd1.Manager",
455 if (!dbus_message_iter_init(reply, &iter) ||
456 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
457 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
458 log_error("Failed to parse reply.");
463 dbus_message_iter_recurse(&iter, &sub);
465 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
468 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
469 log_error("Failed to parse reply.");
477 n_units = MAX(2*c, 16);
478 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
481 log_error("Failed to allocate unit array.");
491 dbus_message_iter_recurse(&sub, &sub2);
493 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
494 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
495 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
496 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
497 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
498 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
499 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
500 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
501 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
502 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
503 log_error("Failed to parse reply.");
508 dbus_message_iter_next(&sub);
513 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
514 output_units_list(unit_infos, c);
519 dbus_message_unref(reply);
526 static int compare_unit_file_list(const void *a, const void *b) {
528 const UnitFileList *u = a, *v = b;
530 d1 = strrchr(u->path, '.');
531 d2 = strrchr(v->path, '.');
536 r = strcasecmp(d1, d2);
541 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
544 static bool output_show_unit_file(const UnitFileList *u) {
547 return !arg_type || ((dot = strrchr(u->path, '.')) && streq(dot+1, arg_type));
550 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
551 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
552 const UnitFileList *u;
554 max_id_len = sizeof("UNIT FILE")-1;
555 state_cols = sizeof("STATE")-1;
556 for (u = units; u < units + c; u++) {
557 if (!output_show_unit_file(u))
560 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
561 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
566 id_cols = MIN(max_id_len, 25);
567 basic_cols = 1 + id_cols + state_cols;
568 if (basic_cols < (unsigned) columns())
569 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
571 id_cols = max_id_len;
574 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
576 for (u = units; u < units + c; u++) {
578 const char *on, *off;
581 if (!output_show_unit_file(u))
586 if (u->state == UNIT_FILE_MASKED ||
587 u->state == UNIT_FILE_MASKED_RUNTIME ||
588 u->state == UNIT_FILE_DISABLED) {
589 on = ansi_highlight_red(true);
590 off = ansi_highlight_red(false);
591 } else if (u->state == UNIT_FILE_ENABLED) {
592 on = ansi_highlight_green(true);
593 off = ansi_highlight_green(false);
597 id = path_get_file_name(u->path);
599 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
601 printf("%-*s %s%-*s%s\n",
603 on, state_cols, unit_file_state_to_string(u->state), off);
609 printf("\n%u unit files listed.\n", n_shown);
612 static int list_unit_files(DBusConnection *bus, char **args) {
613 DBusMessage *reply = NULL;
615 DBusMessageIter iter, sub, sub2;
616 unsigned c = 0, n_units = 0;
617 UnitFileList *units = NULL;
619 pager_open_if_enabled();
626 h = hashmap_new(string_hash_func, string_compare_func);
630 r = unit_file_get_list(arg_scope, arg_root, h);
632 unit_file_list_free(h);
633 log_error("Failed to get unit file list: %s", strerror(-r));
637 n_units = hashmap_size(h);
638 units = new(UnitFileList, n_units);
640 unit_file_list_free(h);
644 HASHMAP_FOREACH(u, h, i) {
645 memcpy(units + c++, u, sizeof(UnitFileList));
651 r = bus_method_call_with_reply (
653 "org.freedesktop.systemd1",
654 "/org/freedesktop/systemd1",
655 "org.freedesktop.systemd1.Manager",
663 if (!dbus_message_iter_init(reply, &iter) ||
664 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
665 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
666 log_error("Failed to parse reply.");
671 dbus_message_iter_recurse(&iter, &sub);
673 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
677 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
678 log_error("Failed to parse reply.");
686 n_units = MAX(2*c, 16);
687 w = realloc(units, sizeof(struct UnitFileList) * n_units);
690 log_error("Failed to allocate unit array.");
700 dbus_message_iter_recurse(&sub, &sub2);
702 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
703 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
704 log_error("Failed to parse reply.");
709 u->state = unit_file_state_from_string(state);
711 dbus_message_iter_next(&sub);
717 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
718 output_unit_file_list(units, c);
725 dbus_message_unref(reply);
732 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
733 static const char * const colors[] = {
734 "Requires", "[color=\"black\"]",
735 "RequiresOverridable", "[color=\"black\"]",
736 "Requisite", "[color=\"darkblue\"]",
737 "RequisiteOverridable", "[color=\"darkblue\"]",
738 "Wants", "[color=\"grey66\"]",
739 "Conflicts", "[color=\"red\"]",
740 "ConflictedBy", "[color=\"red\"]",
741 "After", "[color=\"green\"]"
744 const char *c = NULL;
751 for (i = 0; i < ELEMENTSOF(colors); i += 2)
752 if (streq(colors[i], prop)) {
760 if (arg_dot != DOT_ALL)
761 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
764 switch (dbus_message_iter_get_arg_type(iter)) {
766 case DBUS_TYPE_ARRAY:
768 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
771 dbus_message_iter_recurse(iter, &sub);
773 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
776 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
777 dbus_message_iter_get_basic(&sub, &s);
778 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
780 dbus_message_iter_next(&sub);
790 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
791 DBusMessage *reply = NULL;
792 const char *interface = "org.freedesktop.systemd1.Unit";
794 DBusMessageIter iter, sub, sub2, sub3;
798 r = bus_method_call_with_reply (
800 "org.freedesktop.systemd1",
802 "org.freedesktop.DBus.Properties",
806 DBUS_TYPE_STRING, &interface,
811 if (!dbus_message_iter_init(reply, &iter) ||
812 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
813 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
814 log_error("Failed to parse reply.");
819 dbus_message_iter_recurse(&iter, &sub);
821 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
824 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
825 log_error("Failed to parse reply.");
830 dbus_message_iter_recurse(&sub, &sub2);
832 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
833 log_error("Failed to parse reply.");
838 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
839 log_error("Failed to parse reply.");
844 dbus_message_iter_recurse(&sub2, &sub3);
846 if (dot_one_property(name, prop, &sub3)) {
847 log_error("Failed to parse reply.");
852 dbus_message_iter_next(&sub);
857 dbus_message_unref(reply);
862 static int dot(DBusConnection *bus, char **args) {
863 DBusMessage *reply = NULL;
865 DBusMessageIter iter, sub, sub2;
867 r = bus_method_call_with_reply (
869 "org.freedesktop.systemd1",
870 "/org/freedesktop/systemd1",
871 "org.freedesktop.systemd1.Manager",
879 if (!dbus_message_iter_init(reply, &iter) ||
880 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
881 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
882 log_error("Failed to parse reply.");
887 printf("digraph systemd {\n");
889 dbus_message_iter_recurse(&iter, &sub);
890 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
891 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
893 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
894 log_error("Failed to parse reply.");
899 dbus_message_iter_recurse(&sub, &sub2);
901 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
902 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
903 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
904 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
905 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
906 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
907 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
908 log_error("Failed to parse reply.");
913 if ((r = dot_one(bus, id, unit_path)) < 0)
916 /* printf("\t\"%s\";\n", id); */
917 dbus_message_iter_next(&sub);
922 log_info(" Color legend: black = Requires\n"
923 " dark blue = Requisite\n"
924 " dark grey = Wants\n"
929 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
930 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
936 dbus_message_unref(reply);
941 static int list_jobs(DBusConnection *bus, char **args) {
942 DBusMessage *reply = NULL;
944 DBusMessageIter iter, sub, sub2;
947 pager_open_if_enabled();
949 r = bus_method_call_with_reply (
951 "org.freedesktop.systemd1",
952 "/org/freedesktop/systemd1",
953 "org.freedesktop.systemd1.Manager",
961 if (!dbus_message_iter_init(reply, &iter) ||
962 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
963 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
964 log_error("Failed to parse reply.");
969 dbus_message_iter_recurse(&iter, &sub);
972 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
974 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
975 const char *name, *type, *state, *job_path, *unit_path;
979 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
980 log_error("Failed to parse reply.");
985 dbus_message_iter_recurse(&sub, &sub2);
987 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
988 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
989 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
990 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
991 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
992 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
993 log_error("Failed to parse reply.");
998 e = arg_full ? NULL : ellipsize(name, 25, 33);
999 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
1004 dbus_message_iter_next(&sub);
1008 printf("\n%u jobs listed.\n", k);
1014 dbus_message_unref(reply);
1019 static int load_unit(DBusConnection *bus, char **args) {
1025 STRV_FOREACH(name, args+1) {
1026 n = unit_name_mangle(*name);
1027 r = bus_method_call_with_reply (
1029 "org.freedesktop.systemd1",
1030 "/org/freedesktop/systemd1",
1031 "org.freedesktop.systemd1.Manager",
1035 DBUS_TYPE_STRING, n ? &n : name,
1046 static int cancel_job(DBusConnection *bus, char **args) {
1047 DBusMessage *reply = NULL;
1053 if (strv_length(args) <= 1)
1054 return daemon_reload(bus, args);
1056 STRV_FOREACH(name, args+1) {
1060 r = safe_atou(*name, &id);
1062 log_error("Failed to parse job id: %s", strerror(-r));
1065 assert_cc(sizeof(uint32_t) == sizeof(id));
1067 r = bus_method_call_with_reply (
1069 "org.freedesktop.systemd1",
1070 "/org/freedesktop/systemd1",
1071 "org.freedesktop.systemd1.Manager",
1075 DBUS_TYPE_UINT32, &id,
1080 if (!dbus_message_get_args(reply, NULL,
1081 DBUS_TYPE_OBJECT_PATH, &path,
1082 DBUS_TYPE_INVALID)) {
1083 log_error("Failed to parse reply");
1084 dbus_message_unref(reply);
1088 dbus_message_unref(reply);
1090 r = bus_method_call_with_reply (
1092 "org.freedesktop.systemd1",
1094 "org.freedesktop.systemd1.Job",
1107 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1108 DBusMessage *reply = NULL;
1109 dbus_bool_t b = FALSE;
1110 DBusMessageIter iter, sub;
1112 *interface = "org.freedesktop.systemd1.Unit",
1113 *property = "NeedDaemonReload",
1118 /* We ignore all errors here, since this is used to show a warning only */
1120 n = unit_name_mangle(unit);
1121 r = bus_method_call_with_reply (
1123 "org.freedesktop.systemd1",
1124 "/org/freedesktop/systemd1",
1125 "org.freedesktop.systemd1.Manager",
1129 DBUS_TYPE_STRING, n ? (const char**) &n : &unit,
1135 if (!dbus_message_get_args(reply, NULL,
1136 DBUS_TYPE_OBJECT_PATH, &path,
1140 dbus_message_unref(reply);
1141 r = bus_method_call_with_reply (
1143 "org.freedesktop.systemd1",
1145 "org.freedesktop.DBus.Properties",
1149 DBUS_TYPE_STRING, &interface,
1150 DBUS_TYPE_STRING, &property,
1155 if (!dbus_message_iter_init(reply, &iter) ||
1156 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1159 dbus_message_iter_recurse(&iter, &sub);
1161 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1164 dbus_message_iter_get_basic(&sub, &b);
1168 dbus_message_unref(reply);
1173 typedef struct WaitData {
1178 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1186 dbus_error_init(&error);
1188 log_debug("Got D-Bus request: %s.%s() on %s",
1189 dbus_message_get_interface(message),
1190 dbus_message_get_member(message),
1191 dbus_message_get_path(message));
1193 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1194 log_error("Warning! D-Bus connection terminated.");
1195 dbus_connection_close(connection);
1197 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1199 const char *path, *result, *unit;
1200 dbus_bool_t success = true;
1202 if (dbus_message_get_args(message, &error,
1203 DBUS_TYPE_UINT32, &id,
1204 DBUS_TYPE_OBJECT_PATH, &path,
1205 DBUS_TYPE_STRING, &unit,
1206 DBUS_TYPE_STRING, &result,
1207 DBUS_TYPE_INVALID)) {
1210 p = set_remove(d->set, (char*) path);
1214 d->result = strdup(result);
1219 dbus_error_free(&error);
1220 if (dbus_message_get_args(message, &error,
1221 DBUS_TYPE_UINT32, &id,
1222 DBUS_TYPE_OBJECT_PATH, &path,
1223 DBUS_TYPE_STRING, &result,
1224 DBUS_TYPE_INVALID)) {
1227 /* Compatibility with older systemd versions <
1228 * 183 during upgrades. This should be dropped
1230 p = set_remove(d->set, (char*) path);
1234 d->result = strdup(result);
1239 dbus_error_free(&error);
1240 if (dbus_message_get_args(message, &error,
1241 DBUS_TYPE_UINT32, &id,
1242 DBUS_TYPE_OBJECT_PATH, &path,
1243 DBUS_TYPE_BOOLEAN, &success,
1244 DBUS_TYPE_INVALID)) {
1247 /* Compatibility with older systemd versions <
1248 * 19 during upgrades. This should be dropped
1251 p = set_remove(d->set, (char*) path);
1255 d->result = strdup("failed");
1261 log_error("Failed to parse message: %s", bus_error_message(&error));
1265 dbus_error_free(&error);
1266 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1269 static int enable_wait_for_jobs(DBusConnection *bus) {
1277 dbus_error_init(&error);
1278 dbus_bus_add_match(bus,
1280 "sender='org.freedesktop.systemd1',"
1281 "interface='org.freedesktop.systemd1.Manager',"
1282 "member='JobRemoved',"
1283 "path='/org/freedesktop/systemd1'",
1286 if (dbus_error_is_set(&error)) {
1287 log_error("Failed to add match: %s", bus_error_message(&error));
1288 dbus_error_free(&error);
1292 /* This is slightly dirty, since we don't undo the match registrations. */
1296 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1306 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1307 log_error("Failed to add filter.");
1312 while (!set_isempty(s) &&
1313 dbus_connection_read_write_dispatch(bus, -1))
1316 if (!arg_quiet && d.result) {
1317 if (streq(d.result, "timeout"))
1318 log_error("Job timed out.");
1319 else if (streq(d.result, "canceled"))
1320 log_error("Job canceled.");
1321 else if (streq(d.result, "dependency"))
1322 log_error("A dependency job failed. See system journal for details.");
1323 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1324 log_error("Job failed. See system journal and 'systemctl status' for details.");
1327 if (streq_ptr(d.result, "timeout"))
1329 else if (streq_ptr(d.result, "canceled"))
1331 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1339 /* This is slightly dirty, since we don't undo the filter registration. */
1344 static int check_one_unit(DBusConnection *bus, char *name, bool quiet) {
1345 DBusMessage *reply = NULL;
1346 DBusMessageIter iter, sub;
1348 *interface = "org.freedesktop.systemd1.Unit",
1349 *property = "ActiveState";
1350 const char *path = NULL;
1357 n = unit_name_mangle(name);
1358 r = bus_method_call_with_reply (
1360 "org.freedesktop.systemd1",
1361 "/org/freedesktop/systemd1",
1362 "org.freedesktop.systemd1.Manager",
1366 DBUS_TYPE_STRING, n ? &n : &name,
1370 if ((r != -ENOMEM) && (!quiet))
1375 if (!dbus_message_get_args(reply, NULL,
1376 DBUS_TYPE_OBJECT_PATH, &path,
1377 DBUS_TYPE_INVALID)) {
1378 log_error("Failed to parse reply.");
1383 dbus_message_unref(reply);
1384 r = bus_method_call_with_reply (
1386 "org.freedesktop.systemd1",
1388 "org.freedesktop.DBus.Properties",
1392 DBUS_TYPE_STRING, &interface,
1393 DBUS_TYPE_STRING, &property,
1398 if (!dbus_message_iter_init(reply, &iter) ||
1399 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1400 log_error("Failed to parse reply.");
1405 dbus_message_iter_recurse(&iter, &sub);
1407 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1408 log_error("Failed to parse reply.");
1413 dbus_message_iter_get_basic(&sub, &state);
1418 if (streq(state, "active") || streq(state, "reloading"))
1421 r = 3; /* According to LSB: "program is not running" */
1425 dbus_message_unref(reply);
1430 static void check_triggering_units(
1431 DBusConnection *bus,
1432 const char *unit_name) {
1434 DBusMessage *reply = NULL;
1435 DBusMessageIter iter, sub;
1436 char *service_trigger = NULL;
1437 const char *interface = "org.freedesktop.systemd1.Unit",
1438 *triggered_by_property = "TriggeredBy";
1440 char *unit_path = NULL, *n = NULL;
1441 bool print_warning_label = true;
1444 n = unit_name_mangle(unit_name);
1445 unit_path = unit_dbus_path_from_name(n ? n : unit_name);
1448 log_error("Could not allocate dbus path.");
1452 r = bus_method_call_with_reply (
1454 "org.freedesktop.systemd1",
1456 "org.freedesktop.DBus.Properties",
1460 DBUS_TYPE_STRING, &interface,
1461 DBUS_TYPE_STRING, &triggered_by_property,
1466 if (!dbus_message_iter_init(reply, &iter) ||
1467 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1468 log_error("Failed to parse reply.");
1473 dbus_message_iter_recurse(&iter, &sub);
1474 dbus_message_iter_recurse(&sub, &iter);
1477 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1479 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1480 log_error("Failed to parse reply.");
1484 dbus_message_iter_get_basic(&sub, &service_trigger);
1486 r = check_one_unit(bus, service_trigger, true);
1490 if (print_warning_label) {
1491 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1492 print_warning_label = false;
1494 log_warning(" %s", service_trigger);
1497 dbus_message_iter_next(&sub);
1501 dbus_message_unref(reply);
1506 static int start_unit_one(
1507 DBusConnection *bus,
1514 DBusMessage *reply = NULL;
1523 assert(arg_no_block || s);
1525 n = unit_name_mangle(name);
1526 r = bus_method_call_with_reply (
1528 "org.freedesktop.systemd1",
1529 "/org/freedesktop/systemd1",
1530 "org.freedesktop.systemd1.Manager",
1534 DBUS_TYPE_STRING, n ? (const char **) &n : &name,
1535 DBUS_TYPE_STRING, &mode,
1539 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL )
1540 /* There's always a fallback possible for
1541 * legacy actions. */
1544 log_error("Failed to issue method call: %s", bus_error_message(error));
1548 if (!dbus_message_get_args(reply, error,
1549 DBUS_TYPE_OBJECT_PATH, &path,
1550 DBUS_TYPE_INVALID)) {
1551 log_error("Failed to parse reply: %s", bus_error_message(error));
1556 if (need_daemon_reload(bus, name))
1557 log_warning("Warning: Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1558 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1560 if (!arg_no_block) {
1563 if (!(p = strdup(path))) {
1564 log_error("Failed to duplicate path.");
1569 if ((r = set_put(s, p)) < 0) {
1571 log_error("Failed to add path to set.");
1576 /* When stopping a unit warn if it can still be triggered by
1577 * another active unit (socket, path, timer) */
1578 if (!arg_quiet && streq(method, "StopUnit"))
1579 check_triggering_units(bus, name);
1585 dbus_message_unref(reply);
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 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1689 log_error("Could not watch jobs: %s", strerror(-ret));
1693 if (!(s = set_new(string_hash_func, string_compare_func))) {
1694 log_error("Failed to allocate set.");
1701 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1704 STRV_FOREACH(name, args+1)
1705 if ((r = start_unit_one(bus, method, *name, mode, &error, s)) != 0) {
1706 ret = translate_bus_error_to_exit_status(r, &error);
1707 dbus_error_free(&error);
1712 if ((r = wait_for_jobs(bus, s)) < 0) {
1721 dbus_error_free(&error);
1726 /* Ask systemd-logind, which might grant access to unprivileged users
1727 * through PolicyKit */
1728 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1731 dbus_bool_t interactive = true;
1733 polkit_agent_open_if_enabled();
1741 case ACTION_POWEROFF:
1742 method = "PowerOff";
1745 case ACTION_SUSPEND:
1749 case ACTION_HIBERNATE:
1750 method = "Hibernate";
1757 return bus_method_call_with_reply (
1759 "org.freedesktop.login1",
1760 "/org/freedesktop/login1",
1761 "org.freedesktop.login1.Manager",
1765 DBUS_TYPE_BOOLEAN, &interactive,
1772 static int start_special(DBusConnection *bus, char **args) {
1778 a = verb_to_action(args[0]);
1780 if (arg_force >= 2 && geteuid() != 0) {
1781 log_error("Must be root.");
1785 if (arg_force >= 2 &&
1786 (a == ACTION_HALT ||
1787 a == ACTION_POWEROFF ||
1788 a == ACTION_REBOOT))
1791 if (arg_force >= 1 &&
1792 (a == ACTION_HALT ||
1793 a == ACTION_POWEROFF ||
1794 a == ACTION_REBOOT ||
1795 a == ACTION_KEXEC ||
1797 return daemon_reload(bus, args);
1799 /* first try logind, to allow authentication with polkit */
1800 if (geteuid() != 0 &&
1801 (a == ACTION_POWEROFF ||
1802 a == ACTION_REBOOT ||
1803 a == ACTION_SUSPEND ||
1804 a == ACTION_HIBERNATE)) {
1805 r = reboot_with_logind(bus, a);
1810 r = start_unit(bus, args);
1817 static int check_unit(DBusConnection *bus, char **args) {
1819 int r = 3; /* According to LSB: "program is not running" */
1824 STRV_FOREACH(name, args+1) {
1825 int state = check_one_unit(bus, *name, arg_quiet);
1835 static int kill_unit(DBusConnection *bus, char **args) {
1842 arg_kill_who = "all";
1844 STRV_FOREACH(name, args+1) {
1845 n = unit_name_mangle(*name);
1846 r = bus_method_call_with_reply (
1848 "org.freedesktop.systemd1",
1849 "/org/freedesktop/systemd1",
1850 "org.freedesktop.systemd1.Manager",
1854 DBUS_TYPE_STRING, n ? &n : name,
1855 DBUS_TYPE_STRING, &arg_kill_who,
1856 DBUS_TYPE_INT32, &arg_signal,
1865 typedef struct ExecStatusInfo {
1873 usec_t start_timestamp;
1874 usec_t exit_timestamp;
1879 LIST_FIELDS(struct ExecStatusInfo, exec);
1882 static void exec_status_info_free(ExecStatusInfo *i) {
1891 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1892 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
1893 DBusMessageIter sub2, sub3;
1897 int32_t code, status;
1903 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1906 dbus_message_iter_recurse(sub, &sub2);
1908 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1911 if (!(i->path = strdup(path)))
1914 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1915 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1919 dbus_message_iter_recurse(&sub2, &sub3);
1920 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1921 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1922 dbus_message_iter_next(&sub3);
1927 if (!(i->argv = new0(char*, n+1)))
1931 dbus_message_iter_recurse(&sub2, &sub3);
1932 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_get_basic(&sub3, &s);
1937 dbus_message_iter_next(&sub3);
1939 if (!(i->argv[n++] = strdup(s)))
1943 if (!dbus_message_iter_next(&sub2) ||
1944 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1945 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1946 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
1947 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1948 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
1949 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1950 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1951 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1955 i->start_timestamp = (usec_t) start_timestamp;
1956 i->exit_timestamp = (usec_t) exit_timestamp;
1957 i->pid = (pid_t) pid;
1964 typedef struct UnitStatusInfo {
1966 const char *load_state;
1967 const char *active_state;
1968 const char *sub_state;
1969 const char *unit_file_state;
1971 const char *description;
1972 const char *following;
1974 char **documentation;
1976 const char *fragment_path;
1977 const char *source_path;
1978 const char *default_control_group;
1980 const char *load_error;
1983 usec_t inactive_exit_timestamp;
1984 usec_t inactive_exit_timestamp_monotonic;
1985 usec_t active_enter_timestamp;
1986 usec_t active_exit_timestamp;
1987 usec_t inactive_enter_timestamp;
1989 bool need_daemon_reload;
1994 const char *status_text;
1997 usec_t start_timestamp;
1998 usec_t exit_timestamp;
2000 int exit_code, exit_status;
2002 usec_t condition_timestamp;
2003 bool condition_result;
2006 unsigned n_accepted;
2007 unsigned n_connections;
2011 const char *sysfs_path;
2013 /* Mount, Automount */
2019 LIST_HEAD(ExecStatusInfo, exec);
2022 static void print_status_info(UnitStatusInfo *i) {
2024 const char *on, *off, *ss;
2026 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2027 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2032 /* This shows pretty information about a unit. See
2033 * print_property() for a low-level property printer */
2035 printf("%s", strna(i->id));
2037 if (i->description && !streq_ptr(i->id, i->description))
2038 printf(" - %s", i->description);
2043 printf("\t Follow: unit currently follows state of %s\n", i->following);
2045 if (streq_ptr(i->load_state, "error")) {
2046 on = ansi_highlight_red(true);
2047 off = ansi_highlight_red(false);
2051 path = i->source_path ? i->source_path : i->fragment_path;
2054 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2055 else if (path && i->unit_file_state)
2056 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2058 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2060 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2062 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2064 if (streq_ptr(i->active_state, "failed")) {
2065 on = ansi_highlight_red(true);
2066 off = ansi_highlight_red(false);
2067 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2068 on = ansi_highlight_green(true);
2069 off = ansi_highlight_green(false);
2074 printf("\t Active: %s%s (%s)%s",
2076 strna(i->active_state),
2080 printf("\t Active: %s%s%s",
2082 strna(i->active_state),
2085 if (!isempty(i->result) && !streq(i->result, "success"))
2086 printf(" (Result: %s)", i->result);
2088 timestamp = (streq_ptr(i->active_state, "active") ||
2089 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2090 (streq_ptr(i->active_state, "inactive") ||
2091 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2092 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2093 i->active_exit_timestamp;
2095 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2096 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2099 printf(" since %s; %s\n", s2, s1);
2101 printf(" since %s\n", s2);
2105 if (!i->condition_result && i->condition_timestamp > 0) {
2106 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2107 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2110 printf("\t start condition failed at %s; %s\n", s2, s1);
2112 printf("\t start condition failed at %s\n", s2);
2116 printf("\t Device: %s\n", i->sysfs_path);
2118 printf("\t Where: %s\n", i->where);
2120 printf("\t What: %s\n", i->what);
2122 if (!strv_isempty(i->documentation)) {
2126 STRV_FOREACH(t, i->documentation) {
2128 printf("\t Docs: %s\n", *t);
2131 printf("\t %s\n", *t);
2136 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2138 LIST_FOREACH(exec, p, i->exec) {
2142 /* Only show exited processes here */
2146 t = strv_join(p->argv, " ");
2147 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2150 good = is_clean_exit_lsb(p->code, p->status, NULL);
2152 on = ansi_highlight_red(true);
2153 off = ansi_highlight_red(false);
2157 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2159 if (p->code == CLD_EXITED) {
2162 printf("status=%i", p->status);
2164 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2169 printf("signal=%s", signal_to_string(p->status));
2171 printf(")%s\n", off);
2173 if (i->main_pid == p->pid &&
2174 i->start_timestamp == p->start_timestamp &&
2175 i->exit_timestamp == p->start_timestamp)
2176 /* Let's not show this twice */
2179 if (p->pid == i->control_pid)
2183 if (i->main_pid > 0 || i->control_pid > 0) {
2186 if (i->main_pid > 0) {
2187 printf("Main PID: %u", (unsigned) i->main_pid);
2191 get_process_comm(i->main_pid, &t);
2196 } else if (i->exit_code > 0) {
2197 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2199 if (i->exit_code == CLD_EXITED) {
2202 printf("status=%i", i->exit_status);
2204 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2209 printf("signal=%s", signal_to_string(i->exit_status));
2214 if (i->main_pid > 0 && i->control_pid > 0)
2217 if (i->control_pid > 0) {
2220 printf(" Control: %u", (unsigned) i->control_pid);
2222 get_process_comm(i->control_pid, &t);
2233 printf("\t Status: \"%s\"\n", i->status_text);
2235 if (i->default_control_group) {
2238 printf("\t CGroup: %s\n", i->default_control_group);
2240 if (arg_transport != TRANSPORT_SSH) {
2250 if (i->main_pid > 0)
2251 extra[k++] = i->main_pid;
2253 if (i->control_pid > 0)
2254 extra[k++] = i->control_pid;
2256 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2260 if (i->id && arg_transport != TRANSPORT_SSH) {
2262 arg_lines * OUTPUT_SHOW_ALL |
2263 arg_follow * OUTPUT_FOLLOW |
2264 !arg_quiet * OUTPUT_WARN_CUTOFF |
2265 on_tty() * OUTPUT_COLOR;
2268 show_journal_by_unit(i->id, arg_output, 0,
2269 i->inactive_exit_timestamp_monotonic,
2273 if (i->need_daemon_reload)
2274 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2275 ansi_highlight_red(true),
2276 ansi_highlight_red(false),
2277 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2280 static void show_unit_help(UnitStatusInfo *i) {
2285 if (!i->documentation) {
2286 log_info("Documentation for %s not known.", i->id);
2290 STRV_FOREACH(p, i->documentation) {
2292 if (startswith(*p, "man:")) {
2295 char *page = NULL, *section = NULL;
2296 const char *args[4] = { "man", NULL, NULL, NULL };
2301 if ((*p)[k-1] == ')')
2302 e = strrchr(*p, '(');
2305 page = strndup((*p) + 4, e - *p - 4);
2311 section = strndup(e + 1, *p + k - e - 2);
2325 log_error("Failed to fork: %m");
2333 execvp(args[0], (char**) args);
2334 log_error("Failed to execute man: %m");
2335 _exit(EXIT_FAILURE);
2341 wait_for_terminate(pid, NULL);
2343 log_info("Can't show: %s", *p);
2347 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2353 switch (dbus_message_iter_get_arg_type(iter)) {
2355 case DBUS_TYPE_STRING: {
2358 dbus_message_iter_get_basic(iter, &s);
2361 if (streq(name, "Id"))
2363 else if (streq(name, "LoadState"))
2365 else if (streq(name, "ActiveState"))
2366 i->active_state = s;
2367 else if (streq(name, "SubState"))
2369 else if (streq(name, "Description"))
2371 else if (streq(name, "FragmentPath"))
2372 i->fragment_path = s;
2373 else if (streq(name, "SourcePath"))
2375 else if (streq(name, "DefaultControlGroup"))
2376 i->default_control_group = s;
2377 else if (streq(name, "StatusText"))
2379 else if (streq(name, "SysFSPath"))
2381 else if (streq(name, "Where"))
2383 else if (streq(name, "What"))
2385 else if (streq(name, "Following"))
2387 else if (streq(name, "UnitFileState"))
2388 i->unit_file_state = s;
2389 else if (streq(name, "Result"))
2396 case DBUS_TYPE_BOOLEAN: {
2399 dbus_message_iter_get_basic(iter, &b);
2401 if (streq(name, "Accept"))
2403 else if (streq(name, "NeedDaemonReload"))
2404 i->need_daemon_reload = b;
2405 else if (streq(name, "ConditionResult"))
2406 i->condition_result = b;
2411 case DBUS_TYPE_UINT32: {
2414 dbus_message_iter_get_basic(iter, &u);
2416 if (streq(name, "MainPID")) {
2418 i->main_pid = (pid_t) u;
2421 } else if (streq(name, "ControlPID"))
2422 i->control_pid = (pid_t) u;
2423 else if (streq(name, "ExecMainPID")) {
2425 i->main_pid = (pid_t) u;
2426 } else if (streq(name, "NAccepted"))
2428 else if (streq(name, "NConnections"))
2429 i->n_connections = u;
2434 case DBUS_TYPE_INT32: {
2437 dbus_message_iter_get_basic(iter, &j);
2439 if (streq(name, "ExecMainCode"))
2440 i->exit_code = (int) j;
2441 else if (streq(name, "ExecMainStatus"))
2442 i->exit_status = (int) j;
2447 case DBUS_TYPE_UINT64: {
2450 dbus_message_iter_get_basic(iter, &u);
2452 if (streq(name, "ExecMainStartTimestamp"))
2453 i->start_timestamp = (usec_t) u;
2454 else if (streq(name, "ExecMainExitTimestamp"))
2455 i->exit_timestamp = (usec_t) u;
2456 else if (streq(name, "ActiveEnterTimestamp"))
2457 i->active_enter_timestamp = (usec_t) u;
2458 else if (streq(name, "InactiveEnterTimestamp"))
2459 i->inactive_enter_timestamp = (usec_t) u;
2460 else if (streq(name, "InactiveExitTimestamp"))
2461 i->inactive_exit_timestamp = (usec_t) u;
2462 else if (streq(name, "InactiveExitTimestampMonotonic"))
2463 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2464 else if (streq(name, "ActiveExitTimestamp"))
2465 i->active_exit_timestamp = (usec_t) u;
2466 else if (streq(name, "ConditionTimestamp"))
2467 i->condition_timestamp = (usec_t) u;
2472 case DBUS_TYPE_ARRAY: {
2474 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2475 startswith(name, "Exec")) {
2476 DBusMessageIter sub;
2478 dbus_message_iter_recurse(iter, &sub);
2479 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2480 ExecStatusInfo *info;
2483 if (!(info = new0(ExecStatusInfo, 1)))
2486 if (!(info->name = strdup(name))) {
2491 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2496 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2498 dbus_message_iter_next(&sub);
2500 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2501 streq(name, "Documentation")) {
2503 DBusMessageIter sub;
2505 dbus_message_iter_recurse(iter, &sub);
2506 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2510 dbus_message_iter_get_basic(&sub, &s);
2512 l = strv_append(i->documentation, s);
2516 strv_free(i->documentation);
2517 i->documentation = l;
2519 dbus_message_iter_next(&sub);
2526 case DBUS_TYPE_STRUCT: {
2528 if (streq(name, "LoadError")) {
2529 DBusMessageIter sub;
2530 const char *n, *message;
2533 dbus_message_iter_recurse(iter, &sub);
2535 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2539 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2543 if (!isempty(message))
2544 i->load_error = message;
2554 static int print_property(const char *name, DBusMessageIter *iter) {
2558 /* This is a low-level property printer, see
2559 * print_status_info() for the nicer output */
2561 if (arg_property && !strv_find(arg_property, name))
2564 switch (dbus_message_iter_get_arg_type(iter)) {
2566 case DBUS_TYPE_STRUCT: {
2567 DBusMessageIter sub;
2568 dbus_message_iter_recurse(iter, &sub);
2570 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2573 dbus_message_iter_get_basic(&sub, &u);
2576 printf("%s=%u\n", name, (unsigned) u);
2578 printf("%s=\n", name);
2581 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2584 dbus_message_iter_get_basic(&sub, &s);
2586 if (arg_all || s[0])
2587 printf("%s=%s\n", name, s);
2590 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
2591 const char *a = NULL, *b = NULL;
2593 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
2594 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
2596 if (arg_all || !isempty(a) || !isempty(b))
2597 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
2605 case DBUS_TYPE_ARRAY:
2607 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2608 DBusMessageIter sub, sub2;
2610 dbus_message_iter_recurse(iter, &sub);
2611 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2615 dbus_message_iter_recurse(&sub, &sub2);
2617 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2618 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2619 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2621 dbus_message_iter_next(&sub);
2626 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2627 DBusMessageIter sub, sub2;
2629 dbus_message_iter_recurse(iter, &sub);
2630 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2631 const char *type, *path;
2633 dbus_message_iter_recurse(&sub, &sub2);
2635 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2636 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2637 printf("%s=%s\n", type, path);
2639 dbus_message_iter_next(&sub);
2644 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2645 DBusMessageIter sub, sub2;
2647 dbus_message_iter_recurse(iter, &sub);
2648 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2650 uint64_t value, next_elapse;
2652 dbus_message_iter_recurse(&sub, &sub2);
2654 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2655 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2656 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2657 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2659 printf("%s={ value=%s ; next_elapse=%s }\n",
2661 format_timespan(timespan1, sizeof(timespan1), value),
2662 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2665 dbus_message_iter_next(&sub);
2670 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
2671 DBusMessageIter sub, sub2;
2673 dbus_message_iter_recurse(iter, &sub);
2674 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2675 const char *controller, *attr, *value;
2677 dbus_message_iter_recurse(&sub, &sub2);
2679 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
2680 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
2681 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
2683 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
2689 dbus_message_iter_next(&sub);
2694 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2695 DBusMessageIter sub;
2697 dbus_message_iter_recurse(iter, &sub);
2698 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2699 ExecStatusInfo info;
2702 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2703 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2706 t = strv_join(info.argv, " ");
2708 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2712 yes_no(info.ignore),
2713 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2714 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2715 (unsigned) info. pid,
2716 sigchld_code_to_string(info.code),
2718 info.code == CLD_EXITED ? "" : "/",
2719 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2725 strv_free(info.argv);
2727 dbus_message_iter_next(&sub);
2736 if (generic_print_property(name, iter, arg_all) > 0)
2740 printf("%s=[unprintable]\n", name);
2745 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2746 DBusMessage *reply = NULL;
2747 const char *interface = "";
2749 DBusMessageIter iter, sub, sub2, sub3;
2750 UnitStatusInfo info;
2758 r = bus_method_call_with_reply (
2760 "org.freedesktop.systemd1",
2762 "org.freedesktop.DBus.Properties",
2766 DBUS_TYPE_STRING, &interface,
2771 if (!dbus_message_iter_init(reply, &iter) ||
2772 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2773 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2774 log_error("Failed to parse reply.");
2779 dbus_message_iter_recurse(&iter, &sub);
2786 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2789 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2790 log_error("Failed to parse reply.");
2795 dbus_message_iter_recurse(&sub, &sub2);
2797 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2798 log_error("Failed to parse reply.");
2803 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2804 log_error("Failed to parse reply.");
2809 dbus_message_iter_recurse(&sub2, &sub3);
2811 if (show_properties)
2812 r = print_property(name, &sub3);
2814 r = status_property(name, &sub3, &info);
2817 log_error("Failed to parse reply.");
2822 dbus_message_iter_next(&sub);
2827 if (!show_properties) {
2828 if (streq(verb, "help"))
2829 show_unit_help(&info);
2831 print_status_info(&info);
2834 strv_free(info.documentation);
2836 if (!streq_ptr(info.active_state, "active") &&
2837 !streq_ptr(info.active_state, "reloading") &&
2838 streq(verb, "status"))
2839 /* According to LSB: "program not running" */
2842 while ((p = info.exec)) {
2843 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2844 exec_status_info_free(p);
2849 dbus_message_unref(reply);
2854 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
2855 DBusMessage *reply = NULL;
2856 const char *path = NULL;
2860 dbus_error_init(&error);
2862 r = bus_method_call_with_reply (
2864 "org.freedesktop.systemd1",
2865 "/org/freedesktop/systemd1",
2866 "org.freedesktop.systemd1.Manager",
2870 DBUS_TYPE_UINT32, &pid,
2875 if (!dbus_message_get_args(reply, &error,
2876 DBUS_TYPE_OBJECT_PATH, &path,
2877 DBUS_TYPE_INVALID)) {
2878 log_error("Failed to parse reply: %s", bus_error_message(&error));
2883 r = show_one(verb, bus, path, false, new_line);
2887 dbus_message_unref(reply);
2889 dbus_error_free(&error);
2894 static int show(DBusConnection *bus, char **args) {
2896 bool show_properties, new_line = false;
2902 show_properties = streq(args[0], "show");
2904 if (show_properties)
2905 pager_open_if_enabled();
2907 if (show_properties && strv_length(args) <= 1) {
2908 /* If not argument is specified inspect the manager
2911 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2914 STRV_FOREACH(name, args+1) {
2917 if (safe_atou32(*name, &id) < 0) {
2919 /* Interpret as unit name */
2921 n = unit_name_mangle(*name);
2922 p = unit_dbus_path_from_name(n ? n : *name);
2927 r = show_one(args[0], bus, p, show_properties, &new_line);
2933 } else if (show_properties) {
2935 /* Interpret as job id */
2938 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
2941 r = show_one(args[0], bus, p, show_properties, &new_line);
2949 /* Interpret as PID */
2951 r = show_one_by_pid(args[0], bus, id, &new_line);
2960 static int dump(DBusConnection *bus, char **args) {
2961 DBusMessage *reply = NULL;
2966 dbus_error_init(&error);
2968 pager_open_if_enabled();
2970 r = bus_method_call_with_reply (
2972 "org.freedesktop.systemd1",
2973 "/org/freedesktop/systemd1",
2974 "org.freedesktop.systemd1.Manager",
2982 if (!dbus_message_get_args(reply, &error,
2983 DBUS_TYPE_STRING, &text,
2984 DBUS_TYPE_INVALID)) {
2985 log_error("Failed to parse reply: %s", bus_error_message(&error));
2990 fputs(text, stdout);
2994 dbus_message_unref(reply);
2996 dbus_error_free(&error);
3001 static int snapshot(DBusConnection *bus, char **args) {
3002 DBusMessage *reply = NULL;
3005 dbus_bool_t cleanup = FALSE;
3006 DBusMessageIter iter, sub;
3008 *name = "", *path, *id,
3009 *interface = "org.freedesktop.systemd1.Unit",
3013 dbus_error_init(&error);
3015 if (strv_length(args) > 1)
3018 n = unit_name_mangle(name);
3019 r = bus_method_call_with_reply (
3021 "org.freedesktop.systemd1",
3022 "/org/freedesktop/systemd1",
3023 "org.freedesktop.systemd1.Manager",
3027 DBUS_TYPE_STRING, n ? (const char**) &n : &name,
3028 DBUS_TYPE_BOOLEAN, &cleanup,
3034 if (!dbus_message_get_args(reply, &error,
3035 DBUS_TYPE_OBJECT_PATH, &path,
3036 DBUS_TYPE_INVALID)) {
3037 log_error("Failed to parse reply: %s", bus_error_message(&error));
3042 dbus_message_unref(reply);
3043 r = bus_method_call_with_reply (
3045 "org.freedesktop.systemd1",
3047 "org.freedesktop.DBus.Properties",
3051 DBUS_TYPE_STRING, &interface,
3052 DBUS_TYPE_STRING, &property,
3057 if (!dbus_message_iter_init(reply, &iter) ||
3058 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3059 log_error("Failed to parse reply.");
3064 dbus_message_iter_recurse(&iter, &sub);
3066 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3067 log_error("Failed to parse reply.");
3072 dbus_message_iter_get_basic(&sub, &id);
3079 dbus_message_unref(reply);
3081 dbus_error_free(&error);
3086 static int delete_snapshot(DBusConnection *bus, char **args) {
3087 DBusMessage *reply = NULL;
3094 dbus_error_init(&error);
3096 STRV_FOREACH(name, args+1) {
3097 const char *path = NULL;
3100 n = unit_name_mangle(*name);
3101 r = bus_method_call_with_reply (
3103 "org.freedesktop.systemd1",
3104 "/org/freedesktop/systemd1",
3105 "org.freedesktop.systemd1.Manager",
3109 DBUS_TYPE_STRING, n ? &n : name,
3115 if (!dbus_message_get_args(reply, &error,
3116 DBUS_TYPE_OBJECT_PATH, &path,
3117 DBUS_TYPE_INVALID)) {
3118 log_error("Failed to parse reply: %s", bus_error_message(&error));
3120 dbus_message_unref(reply);
3121 dbus_error_free(&error);
3124 dbus_message_unref(reply);
3126 r = bus_method_call_with_reply (
3128 "org.freedesktop.systemd1",
3130 "org.freedesktop.systemd1.Snapshot",
3143 static int daemon_reload(DBusConnection *bus, char **args) {
3148 if (arg_action == ACTION_RELOAD)
3150 else if (arg_action == ACTION_REEXEC)
3151 method = "Reexecute";
3153 assert(arg_action == ACTION_SYSTEMCTL);
3156 streq(args[0], "clear-jobs") ||
3157 streq(args[0], "cancel") ? "ClearJobs" :
3158 streq(args[0], "daemon-reexec") ? "Reexecute" :
3159 streq(args[0], "reset-failed") ? "ResetFailed" :
3160 streq(args[0], "halt") ? "Halt" :
3161 streq(args[0], "poweroff") ? "PowerOff" :
3162 streq(args[0], "reboot") ? "Reboot" :
3163 streq(args[0], "kexec") ? "KExec" :
3164 streq(args[0], "exit") ? "Exit" :
3165 /* "daemon-reload" */ "Reload";
3168 r = bus_method_call_with_reply (
3170 "org.freedesktop.systemd1",
3171 "/org/freedesktop/systemd1",
3172 "org.freedesktop.systemd1.Manager",
3178 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
3179 /* There's always a fallback possible for
3180 * legacy actions. */
3182 else if (r == -ETIMEDOUT && streq(method, "Reexecute"))
3183 /* On reexecution, we expect a disconnect, not
3187 log_error("Failed to issue method call: %s", bus_error_message(&error));
3188 dbus_error_free(&error);
3193 static int reset_failed(DBusConnection *bus, char **args) {
3197 if (strv_length(args) <= 1)
3198 return daemon_reload(bus, args);
3200 STRV_FOREACH(name, args+1) {
3201 n = unit_name_mangle(*name);
3202 r = bus_method_call_with_reply (
3204 "org.freedesktop.systemd1",
3205 "/org/freedesktop/systemd1",
3206 "org.freedesktop.systemd1.Manager",
3210 DBUS_TYPE_STRING, n ? &n : name,
3221 static int show_enviroment(DBusConnection *bus, char **args) {
3222 DBusMessage *reply = NULL;
3223 DBusMessageIter iter, sub, sub2;
3226 *interface = "org.freedesktop.systemd1.Manager",
3227 *property = "Environment";
3229 pager_open_if_enabled();
3231 r = bus_method_call_with_reply (
3233 "org.freedesktop.systemd1",
3234 "/org/freedesktop/systemd1",
3235 "org.freedesktop.DBus.Properties",
3239 DBUS_TYPE_STRING, &interface,
3240 DBUS_TYPE_STRING, &property,
3245 if (!dbus_message_iter_init(reply, &iter) ||
3246 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3247 log_error("Failed to parse reply.");
3252 dbus_message_iter_recurse(&iter, &sub);
3254 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3255 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3256 log_error("Failed to parse reply.");
3261 dbus_message_iter_recurse(&sub, &sub2);
3263 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3266 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3267 log_error("Failed to parse reply.");
3272 dbus_message_iter_get_basic(&sub2, &text);
3273 printf("%s\n", text);
3275 dbus_message_iter_next(&sub2);
3282 dbus_message_unref(reply);
3287 static int switch_root(DBusConnection *bus, char **args) {
3289 const char *root, *init;
3291 l = strv_length(args);
3292 if (l < 2 || l > 3) {
3293 log_error("Wrong number of arguments.");
3298 init = l >= 3 ? args[2] : "";
3300 return bus_method_call_with_reply (
3302 "org.freedesktop.systemd1",
3303 "/org/freedesktop/systemd1",
3304 "org.freedesktop.systemd1.Manager",
3308 DBUS_TYPE_STRING, &root,
3309 DBUS_TYPE_STRING, &init,
3313 static int set_environment(DBusConnection *bus, char **args) {
3314 DBusMessage *m = NULL, *reply = NULL;
3318 DBusMessageIter iter, sub;
3321 dbus_error_init(&error);
3323 method = streq(args[0], "set-environment")
3325 : "UnsetEnvironment";
3327 if (!(m = dbus_message_new_method_call(
3328 "org.freedesktop.systemd1",
3329 "/org/freedesktop/systemd1",
3330 "org.freedesktop.systemd1.Manager",
3333 log_error("Could not allocate message.");
3337 dbus_message_iter_init_append(m, &iter);
3339 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3340 log_error("Could not append arguments to message.");
3345 STRV_FOREACH(name, args+1)
3346 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, name)) {
3347 log_error("Could not append arguments to message.");
3352 if (!dbus_message_iter_close_container(&iter, &sub)) {
3353 log_error("Could not append arguments to message.");
3358 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3359 log_error("Failed to issue method call: %s", bus_error_message(&error));
3368 dbus_message_unref(m);
3371 dbus_message_unref(reply);
3373 dbus_error_free(&error);
3378 static int enable_sysv_units(char **args) {
3381 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_ALTLINUX) || defined(TARGET_MAGEIA))
3382 const char *verb = args[0];
3383 unsigned f = 1, t = 1;
3386 if (arg_scope != UNIT_FILE_SYSTEM)
3389 if (!streq(verb, "enable") &&
3390 !streq(verb, "disable") &&
3391 !streq(verb, "is-enabled"))
3394 /* Processes all SysV units, and reshuffles the array so that
3395 * afterwards only the native units remain */
3398 r = lookup_paths_init(&paths, MANAGER_SYSTEM, false, NULL, NULL, NULL);
3403 for (f = 1; args[f]; f++) {
3406 bool found_native = false, found_sysv;
3408 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3409 char **k, *l, *q = NULL;
3416 if (!endswith(name, ".service"))
3419 if (path_is_absolute(name))
3422 STRV_FOREACH(k, paths.unit_path) {
3425 if (!isempty(arg_root))
3426 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3428 asprintf(&p, "%s/%s", *k, name);
3435 found_native = access(p, F_OK) >= 0;
3446 if (!isempty(arg_root))
3447 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3449 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3455 p[strlen(p) - sizeof(".service") + 1] = 0;
3456 found_sysv = access(p, F_OK) >= 0;
3463 /* Mark this entry, so that we don't try enabling it as native unit */
3464 args[f] = (char*) "";
3466 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
3468 if (!isempty(arg_root))
3469 argv[c++] = q = strappend("--root=", arg_root);
3471 argv[c++] = path_get_file_name(p);
3473 streq(verb, "enable") ? "on" :
3474 streq(verb, "disable") ? "off" : "--level=5";
3477 l = strv_join((char**)argv, " ");
3485 log_info("Executing %s", l);
3490 log_error("Failed to fork: %m");
3495 } else if (pid == 0) {
3498 execv(argv[0], (char**) argv);
3499 _exit(EXIT_FAILURE);
3505 j = wait_for_terminate(pid, &status);
3507 log_error("Failed to wait for child: %s", strerror(-r));
3512 if (status.si_code == CLD_EXITED) {
3513 if (streq(verb, "is-enabled")) {
3514 if (status.si_status == 0) {
3523 } else if (status.si_status != 0) {
3534 lookup_paths_free(&paths);
3536 /* Drop all SysV units */
3537 for (f = 1, t = 1; args[f]; f++) {
3539 if (isempty(args[f]))
3542 args[t++] = args[f];
3551 static int enable_unit(DBusConnection *bus, char **args) {
3552 const char *verb = args[0];
3553 UnitFileChange *changes = NULL;
3554 unsigned n_changes = 0, i;
3555 int carries_install_info = -1;
3556 DBusMessage *m = NULL, *reply = NULL;
3560 r = enable_sysv_units(args);
3567 dbus_error_init(&error);
3569 if (!bus || avoid_bus()) {
3570 if (streq(verb, "enable")) {
3571 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3572 carries_install_info = r;
3573 } else if (streq(verb, "disable"))
3574 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3575 else if (streq(verb, "reenable")) {
3576 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3577 carries_install_info = r;
3578 } else if (streq(verb, "link"))
3579 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3580 else if (streq(verb, "preset")) {
3581 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3582 carries_install_info = r;
3583 } else if (streq(verb, "mask"))
3584 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3585 else if (streq(verb, "unmask"))
3586 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3588 assert_not_reached("Unknown verb");
3591 log_error("Operation failed: %s", strerror(-r));
3596 for (i = 0; i < n_changes; i++) {
3597 if (changes[i].type == UNIT_FILE_SYMLINK)
3598 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
3600 log_info("rm '%s'", changes[i].path);
3606 bool send_force = true, expect_carries_install_info = false;
3608 DBusMessageIter iter, sub, sub2;
3610 if (streq(verb, "enable")) {
3611 method = "EnableUnitFiles";
3612 expect_carries_install_info = true;
3613 } else if (streq(verb, "disable")) {
3614 method = "DisableUnitFiles";
3616 } else if (streq(verb, "reenable")) {
3617 method = "ReenableUnitFiles";
3618 expect_carries_install_info = true;
3619 } else if (streq(verb, "link"))
3620 method = "LinkUnitFiles";
3621 else if (streq(verb, "preset")) {
3622 method = "PresetUnitFiles";
3623 expect_carries_install_info = true;
3624 } else if (streq(verb, "mask"))
3625 method = "MaskUnitFiles";
3626 else if (streq(verb, "unmask")) {
3627 method = "UnmaskUnitFiles";
3630 assert_not_reached("Unknown verb");
3632 m = dbus_message_new_method_call(
3633 "org.freedesktop.systemd1",
3634 "/org/freedesktop/systemd1",
3635 "org.freedesktop.systemd1.Manager",
3642 dbus_message_iter_init_append(m, &iter);
3644 r = bus_append_strv_iter(&iter, args+1);
3646 log_error("Failed to append unit files.");
3651 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
3652 log_error("Failed to append runtime boolean.");
3660 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
3661 log_error("Failed to append force boolean.");
3667 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3669 log_error("Failed to issue method call: %s", bus_error_message(&error));
3674 if (!dbus_message_iter_init(reply, &iter)) {
3675 log_error("Failed to initialize iterator.");
3679 if (expect_carries_install_info) {
3680 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
3682 log_error("Failed to parse reply.");
3686 carries_install_info = b;
3689 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3690 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
3691 log_error("Failed to parse reply.");
3696 dbus_message_iter_recurse(&iter, &sub);
3697 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3698 const char *type, *path, *source;
3700 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
3701 log_error("Failed to parse reply.");
3706 dbus_message_iter_recurse(&sub, &sub2);
3708 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
3709 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
3710 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
3711 log_error("Failed to parse reply.");
3717 if (streq(type, "symlink"))
3718 log_info("ln -s '%s' '%s'", source, path);
3720 log_info("rm '%s'", path);
3723 dbus_message_iter_next(&sub);
3726 /* Try to reload if enabeld */
3728 r = daemon_reload(bus, args);
3731 if (carries_install_info == 0)
3732 log_warning("The unit files have no [Install] section. They are not meant to be enabled using systemctl.");
3736 dbus_message_unref(m);
3739 dbus_message_unref(reply);
3741 unit_file_changes_free(changes, n_changes);
3743 dbus_error_free(&error);
3747 static int unit_is_enabled(DBusConnection *bus, char **args) {
3750 DBusMessage *reply = NULL;
3754 dbus_error_init(&error);
3756 r = enable_sysv_units(args);
3762 if (!bus || avoid_bus()) {
3764 STRV_FOREACH(name, args+1) {
3765 UnitFileState state;
3767 state = unit_file_get_state(arg_scope, arg_root, *name);
3773 if (state == UNIT_FILE_ENABLED ||
3774 state == UNIT_FILE_ENABLED_RUNTIME ||
3775 state == UNIT_FILE_STATIC)
3779 puts(unit_file_state_to_string(state));
3783 STRV_FOREACH(name, args+1) {
3786 r = bus_method_call_with_reply (
3788 "org.freedesktop.systemd1",
3789 "/org/freedesktop/systemd1",
3790 "org.freedesktop.systemd1.Manager",
3794 DBUS_TYPE_STRING, name,
3799 if (!dbus_message_get_args(reply, &error,
3800 DBUS_TYPE_STRING, &s,
3801 DBUS_TYPE_INVALID)) {
3802 log_error("Failed to parse reply: %s", bus_error_message(&error));
3807 dbus_message_unref(reply);
3810 if (streq(s, "enabled") ||
3811 streq(s, "enabled-runtime") ||
3820 r = enabled ? 0 : 1;
3824 dbus_message_unref(reply);
3826 dbus_error_free(&error);
3830 static int systemctl_help(void) {
3832 pager_open_if_enabled();
3834 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3835 "Query or send control commands to the systemd manager.\n\n"
3836 " -h --help Show this help\n"
3837 " --version Show package version\n"
3838 " -t --type=TYPE List only units of a particular type\n"
3839 " -p --property=NAME Show only properties by this name\n"
3840 " -a --all Show all units/properties, including dead/empty ones\n"
3841 " --failed Show only failed units\n"
3842 " --full Don't ellipsize unit names on output\n"
3843 " --fail When queueing a new job, fail if conflicting jobs are\n"
3845 " --ignore-dependencies\n"
3846 " When queueing a new job, ignore all its dependencies\n"
3847 " --kill-who=WHO Who to send signal to\n"
3848 " -s --signal=SIGNAL Which signal to send\n"
3849 " -H --host=[USER@]HOST\n"
3850 " Show information for remote host\n"
3851 " -P --privileged Acquire privileges before execution\n"
3852 " -q --quiet Suppress output\n"
3853 " --no-block Do not wait until operation finished\n"
3854 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3855 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3857 " --no-legend Do not print a legend (column headers and hints)\n"
3858 " --no-pager Do not pipe output into a pager\n"
3859 " --no-ask-password\n"
3860 " Do not ask for system passwords\n"
3861 " --order When generating graph for dot, show only order\n"
3862 " --require When generating graph for dot, show only requirement\n"
3863 " --system Connect to system manager\n"
3864 " --user Connect to user service manager\n"
3865 " --global Enable/disable unit files globally\n"
3866 " -f --force When enabling unit files, override existing symlinks\n"
3867 " When shutting down, execute action immediately\n"
3868 " --root=PATH Enable unit files in the specified root directory\n"
3869 " --runtime Enable unit files only temporarily until next reboot\n"
3870 " -n --lines=INTEGER Journal entries to show\n"
3871 " --follow Follow journal\n"
3872 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
3873 " verbose, export, json, json-pretty, cat)\n\n"
3875 " list-units List loaded units\n"
3876 " start [NAME...] Start (activate) one or more units\n"
3877 " stop [NAME...] Stop (deactivate) one or more units\n"
3878 " reload [NAME...] Reload one or more units\n"
3879 " restart [NAME...] Start or restart one or more units\n"
3880 " try-restart [NAME...] Restart one or more units if active\n"
3881 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3882 " otherwise start or restart\n"
3883 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3884 " otherwise restart if active\n"
3885 " isolate [NAME] Start one unit and stop all others\n"
3886 " kill [NAME...] Send signal to processes of a unit\n"
3887 " is-active [NAME...] Check whether units are active\n"
3888 " status [NAME...|PID...] Show runtime status of one or more units\n"
3889 " show [NAME...|JOB...] Show properties of one or more\n"
3890 " units/jobs or the manager\n"
3891 " help [NAME...|PID...] Show manual for one or more units\n"
3892 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3894 " load [NAME...] Load one or more units\n\n"
3895 "Unit File Commands:\n"
3896 " list-unit-files List installed unit files\n"
3897 " enable [NAME...] Enable one or more unit files\n"
3898 " disable [NAME...] Disable one or more unit files\n"
3899 " reenable [NAME...] Reenable one or more unit files\n"
3900 " preset [NAME...] Enable/disable one or more unit files\n"
3901 " based on preset configuration\n"
3902 " mask [NAME...] Mask one or more units\n"
3903 " unmask [NAME...] Unmask one or more units\n"
3904 " link [PATH...] Link one or more units files into\n"
3905 " the search path\n"
3906 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
3908 " list-jobs List jobs\n"
3909 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
3910 "Status Commands:\n"
3911 " dump Dump server status\n"
3912 " dot Dump dependency graph for dot(1)\n\n"
3913 "Snapshot Commands:\n"
3914 " snapshot [NAME] Create a snapshot\n"
3915 " delete [NAME...] Remove one or more snapshots\n\n"
3916 "Environment Commands:\n"
3917 " show-environment Dump environment\n"
3918 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3919 " unset-environment [NAME...] Unset one or more environment variables\n\n"
3920 "Manager Lifecycle Commands:\n"
3921 " daemon-reload Reload systemd manager configuration\n"
3922 " daemon-reexec Reexecute systemd manager\n\n"
3923 "System Commands:\n"
3924 " default Enter system default mode\n"
3925 " rescue Enter system rescue mode\n"
3926 " emergency Enter system emergency mode\n"
3927 " halt Shut down and halt the system\n"
3928 " poweroff Shut down and power-off the system\n"
3929 " reboot Shut down and reboot the system\n"
3930 " kexec Shut down and reboot the system with kexec\n"
3931 " exit Request user instance exit\n"
3932 " switch-root [ROOT] [INIT] Change to a different root file system\n"
3933 " suspend Suspend the system\n"
3934 " hibernate Hibernate the system\n",
3935 program_invocation_short_name);
3940 static int halt_help(void) {
3942 printf("%s [OPTIONS...]\n\n"
3943 "%s the system.\n\n"
3944 " --help Show this help\n"
3945 " --halt Halt the machine\n"
3946 " -p --poweroff Switch off the machine\n"
3947 " --reboot Reboot the machine\n"
3948 " -f --force Force immediate halt/power-off/reboot\n"
3949 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3950 " -d --no-wtmp Don't write wtmp record\n"
3951 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3952 program_invocation_short_name,
3953 arg_action == ACTION_REBOOT ? "Reboot" :
3954 arg_action == ACTION_POWEROFF ? "Power off" :
3960 static int shutdown_help(void) {
3962 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3963 "Shut down the system.\n\n"
3964 " --help Show this help\n"
3965 " -H --halt Halt the machine\n"
3966 " -P --poweroff Power-off the machine\n"
3967 " -r --reboot Reboot the machine\n"
3968 " -h Equivalent to --poweroff, overridden by --halt\n"
3969 " -k Don't halt/power-off/reboot, just send warnings\n"
3970 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3971 " -c Cancel a pending shutdown\n",
3972 program_invocation_short_name);
3977 static int telinit_help(void) {
3979 printf("%s [OPTIONS...] {COMMAND}\n\n"
3980 "Send control commands to the init daemon.\n\n"
3981 " --help Show this help\n"
3982 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3984 " 0 Power-off the machine\n"
3985 " 6 Reboot the machine\n"
3986 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3987 " 1, s, S Enter rescue mode\n"
3988 " q, Q Reload init daemon configuration\n"
3989 " u, U Reexecute init daemon\n",
3990 program_invocation_short_name);
3995 static int runlevel_help(void) {
3997 printf("%s [OPTIONS...]\n\n"
3998 "Prints the previous and current runlevel of the init system.\n\n"
3999 " --help Show this help\n",
4000 program_invocation_short_name);
4005 static int systemctl_parse_argv(int argc, char *argv[]) {
4009 ARG_IGNORE_DEPENDENCIES,
4024 ARG_NO_ASK_PASSWORD,
4031 static const struct option options[] = {
4032 { "help", no_argument, NULL, 'h' },
4033 { "version", no_argument, NULL, ARG_VERSION },
4034 { "type", required_argument, NULL, 't' },
4035 { "property", required_argument, NULL, 'p' },
4036 { "all", no_argument, NULL, 'a' },
4037 { "failed", no_argument, NULL, ARG_FAILED },
4038 { "full", no_argument, NULL, ARG_FULL },
4039 { "fail", no_argument, NULL, ARG_FAIL },
4040 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4041 { "user", no_argument, NULL, ARG_USER },
4042 { "system", no_argument, NULL, ARG_SYSTEM },
4043 { "global", no_argument, NULL, ARG_GLOBAL },
4044 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4045 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4046 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4047 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4048 { "quiet", no_argument, NULL, 'q' },
4049 { "order", no_argument, NULL, ARG_ORDER },
4050 { "require", no_argument, NULL, ARG_REQUIRE },
4051 { "root", required_argument, NULL, ARG_ROOT },
4052 { "force", no_argument, NULL, ARG_FORCE },
4053 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4054 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4055 { "signal", required_argument, NULL, 's' },
4056 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4057 { "host", required_argument, NULL, 'H' },
4058 { "privileged",no_argument, NULL, 'P' },
4059 { "runtime", no_argument, NULL, ARG_RUNTIME },
4060 { "lines", required_argument, NULL, 'n' },
4061 { "follow", no_argument, NULL, ARG_FOLLOW },
4062 { "output", required_argument, NULL, 'o' },
4063 { NULL, 0, NULL, 0 }
4071 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4080 puts(PACKAGE_STRING);
4082 puts(SYSTEMD_FEATURES);
4086 if (unit_type_from_string(optarg) >= 0) {
4090 if (unit_load_state_from_string(optarg) >= 0) {
4091 arg_load_state = optarg;
4094 log_error("Unkown unit type or load state '%s'.",
4100 if (!(l = strv_append(arg_property, optarg)))
4103 strv_free(arg_property);
4106 /* If the user asked for a particular
4107 * property, show it to him, even if it is
4118 arg_job_mode = "fail";
4121 case ARG_IGNORE_DEPENDENCIES:
4122 arg_job_mode = "ignore-dependencies";
4126 arg_scope = UNIT_FILE_USER;
4130 arg_scope = UNIT_FILE_SYSTEM;
4134 arg_scope = UNIT_FILE_GLOBAL;
4138 arg_no_block = true;
4142 arg_no_legend = true;
4146 arg_no_pager = true;
4154 arg_dot = DOT_ORDER;
4158 arg_dot = DOT_REQUIRE;
4186 /* -f is short for both --follow and --force! */
4192 arg_no_reload = true;
4196 arg_kill_who = optarg;
4200 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4201 log_error("Failed to parse signal string %s.", optarg);
4206 case ARG_NO_ASK_PASSWORD:
4207 arg_ask_password = false;
4211 arg_transport = TRANSPORT_POLKIT;
4215 arg_transport = TRANSPORT_SSH;
4224 if (safe_atou(optarg, &arg_lines) < 0) {
4225 log_error("Failed to parse lines '%s'", optarg);
4231 arg_output = output_mode_from_string(optarg);
4232 if (arg_output < 0) {
4233 log_error("Unknown output '%s'.", optarg);
4242 log_error("Unknown option code '%c'.", c);
4247 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4248 log_error("Cannot access user instance remotely.");
4255 static int halt_parse_argv(int argc, char *argv[]) {
4264 static const struct option options[] = {
4265 { "help", no_argument, NULL, ARG_HELP },
4266 { "halt", no_argument, NULL, ARG_HALT },
4267 { "poweroff", no_argument, NULL, 'p' },
4268 { "reboot", no_argument, NULL, ARG_REBOOT },
4269 { "force", no_argument, NULL, 'f' },
4270 { "wtmp-only", no_argument, NULL, 'w' },
4271 { "no-wtmp", no_argument, NULL, 'd' },
4272 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4273 { NULL, 0, NULL, 0 }
4281 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4282 if (runlevel == '0' || runlevel == '6')
4285 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4293 arg_action = ACTION_HALT;
4297 if (arg_action != ACTION_REBOOT)
4298 arg_action = ACTION_POWEROFF;
4302 arg_action = ACTION_REBOOT;
4324 /* Compatibility nops */
4331 log_error("Unknown option code '%c'.", c);
4336 if (optind < argc) {
4337 log_error("Too many arguments.");
4344 static int parse_time_spec(const char *t, usec_t *_u) {
4348 if (streq(t, "now"))
4350 else if (!strchr(t, ':')) {
4353 if (safe_atou64(t, &u) < 0)
4356 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4365 hour = strtol(t, &e, 10);
4366 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4369 minute = strtol(e+1, &e, 10);
4370 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4373 n = now(CLOCK_REALTIME);
4374 s = (time_t) (n / USEC_PER_SEC);
4377 assert_se(localtime_r(&s, &tm));
4379 tm.tm_hour = (int) hour;
4380 tm.tm_min = (int) minute;
4383 assert_se(s = mktime(&tm));
4385 *_u = (usec_t) s * USEC_PER_SEC;
4388 *_u += USEC_PER_DAY;
4394 static int shutdown_parse_argv(int argc, char *argv[]) {
4401 static const struct option options[] = {
4402 { "help", no_argument, NULL, ARG_HELP },
4403 { "halt", no_argument, NULL, 'H' },
4404 { "poweroff", no_argument, NULL, 'P' },
4405 { "reboot", no_argument, NULL, 'r' },
4406 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4407 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4408 { NULL, 0, NULL, 0 }
4416 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4424 arg_action = ACTION_HALT;
4428 arg_action = ACTION_POWEROFF;
4433 arg_action = ACTION_KEXEC;
4435 arg_action = ACTION_REBOOT;
4439 arg_action = ACTION_KEXEC;
4443 if (arg_action != ACTION_HALT)
4444 arg_action = ACTION_POWEROFF;
4457 /* Compatibility nops */
4461 arg_action = ACTION_CANCEL_SHUTDOWN;
4468 log_error("Unknown option code '%c'.", c);
4473 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
4474 r = parse_time_spec(argv[optind], &arg_when);
4476 log_error("Failed to parse time specification: %s", argv[optind]);
4480 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4482 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
4483 /* No time argument for shutdown cancel */
4484 arg_wall = argv + optind;
4485 else if (argc > optind + 1)
4486 /* We skip the time argument */
4487 arg_wall = argv + optind + 1;
4494 static int telinit_parse_argv(int argc, char *argv[]) {
4501 static const struct option options[] = {
4502 { "help", no_argument, NULL, ARG_HELP },
4503 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4504 { NULL, 0, NULL, 0 }
4507 static const struct {
4511 { '0', ACTION_POWEROFF },
4512 { '6', ACTION_REBOOT },
4513 { '1', ACTION_RESCUE },
4514 { '2', ACTION_RUNLEVEL2 },
4515 { '3', ACTION_RUNLEVEL3 },
4516 { '4', ACTION_RUNLEVEL4 },
4517 { '5', ACTION_RUNLEVEL5 },
4518 { 's', ACTION_RESCUE },
4519 { 'S', ACTION_RESCUE },
4520 { 'q', ACTION_RELOAD },
4521 { 'Q', ACTION_RELOAD },
4522 { 'u', ACTION_REEXEC },
4523 { 'U', ACTION_REEXEC }
4532 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4547 log_error("Unknown option code '%c'.", c);
4552 if (optind >= argc) {
4557 if (optind + 1 < argc) {
4558 log_error("Too many arguments.");
4562 if (strlen(argv[optind]) != 1) {
4563 log_error("Expected single character argument.");
4567 for (i = 0; i < ELEMENTSOF(table); i++)
4568 if (table[i].from == argv[optind][0])
4571 if (i >= ELEMENTSOF(table)) {
4572 log_error("Unknown command '%s'.", argv[optind]);
4576 arg_action = table[i].to;
4583 static int runlevel_parse_argv(int argc, char *argv[]) {
4589 static const struct option options[] = {
4590 { "help", no_argument, NULL, ARG_HELP },
4591 { NULL, 0, NULL, 0 }
4599 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4610 log_error("Unknown option code '%c'.", c);
4615 if (optind < argc) {
4616 log_error("Too many arguments.");
4623 static int parse_argv(int argc, char *argv[]) {
4627 if (program_invocation_short_name) {
4629 if (strstr(program_invocation_short_name, "halt")) {
4630 arg_action = ACTION_HALT;
4631 return halt_parse_argv(argc, argv);
4632 } else if (strstr(program_invocation_short_name, "poweroff")) {
4633 arg_action = ACTION_POWEROFF;
4634 return halt_parse_argv(argc, argv);
4635 } else if (strstr(program_invocation_short_name, "reboot")) {
4637 arg_action = ACTION_KEXEC;
4639 arg_action = ACTION_REBOOT;
4640 return halt_parse_argv(argc, argv);
4641 } else if (strstr(program_invocation_short_name, "shutdown")) {
4642 arg_action = ACTION_POWEROFF;
4643 return shutdown_parse_argv(argc, argv);
4644 } else if (strstr(program_invocation_short_name, "init")) {
4646 if (sd_booted() > 0) {
4647 arg_action = ACTION_INVALID;
4648 return telinit_parse_argv(argc, argv);
4650 /* Hmm, so some other init system is
4651 * running, we need to forward this
4652 * request to it. For now we simply
4653 * guess that it is Upstart. */
4655 execv("/lib/upstart/telinit", argv);
4657 log_error("Couldn't find an alternative telinit implementation to spawn.");
4661 } else if (strstr(program_invocation_short_name, "runlevel")) {
4662 arg_action = ACTION_RUNLEVEL;
4663 return runlevel_parse_argv(argc, argv);
4667 arg_action = ACTION_SYSTEMCTL;
4668 return systemctl_parse_argv(argc, argv);
4671 static int action_to_runlevel(void) {
4673 static const char table[_ACTION_MAX] = {
4674 [ACTION_HALT] = '0',
4675 [ACTION_POWEROFF] = '0',
4676 [ACTION_REBOOT] = '6',
4677 [ACTION_RUNLEVEL2] = '2',
4678 [ACTION_RUNLEVEL3] = '3',
4679 [ACTION_RUNLEVEL4] = '4',
4680 [ACTION_RUNLEVEL5] = '5',
4681 [ACTION_RESCUE] = '1'
4684 assert(arg_action < _ACTION_MAX);
4686 return table[arg_action];
4689 static int talk_upstart(void) {
4690 DBusMessage *m = NULL, *reply = NULL;
4692 int previous, rl, r;
4694 env1_buf[] = "RUNLEVEL=X",
4695 env2_buf[] = "PREVLEVEL=X";
4696 char *env1 = env1_buf, *env2 = env2_buf;
4697 const char *emit = "runlevel";
4698 dbus_bool_t b_false = FALSE;
4699 DBusMessageIter iter, sub;
4700 DBusConnection *bus;
4702 dbus_error_init(&error);
4704 if (!(rl = action_to_runlevel()))
4707 if (utmp_get_runlevel(&previous, NULL) < 0)
4710 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4711 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4716 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4721 if ((r = bus_check_peercred(bus)) < 0) {
4722 log_error("Failed to verify owner of bus.");
4726 if (!(m = dbus_message_new_method_call(
4727 "com.ubuntu.Upstart",
4728 "/com/ubuntu/Upstart",
4729 "com.ubuntu.Upstart0_6",
4732 log_error("Could not allocate message.");
4737 dbus_message_iter_init_append(m, &iter);
4739 env1_buf[sizeof(env1_buf)-2] = rl;
4740 env2_buf[sizeof(env2_buf)-2] = previous;
4742 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4743 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4744 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4745 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4746 !dbus_message_iter_close_container(&iter, &sub) ||
4747 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4748 log_error("Could not append arguments to message.");
4753 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4755 if (bus_error_is_no_service(&error)) {
4760 log_error("Failed to issue method call: %s", bus_error_message(&error));
4769 dbus_message_unref(m);
4772 dbus_message_unref(reply);
4775 dbus_connection_flush(bus);
4776 dbus_connection_close(bus);
4777 dbus_connection_unref(bus);
4780 dbus_error_free(&error);
4785 static int talk_initctl(void) {
4786 struct init_request request;
4790 if (!(rl = action_to_runlevel()))
4794 request.magic = INIT_MAGIC;
4795 request.sleeptime = 0;
4796 request.cmd = INIT_CMD_RUNLVL;
4797 request.runlevel = rl;
4799 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4801 if (errno == ENOENT)
4804 log_error("Failed to open "INIT_FIFO": %m");
4809 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4810 close_nointr_nofail(fd);
4813 log_error("Failed to write to "INIT_FIFO": %m");
4814 return errno ? -errno : -EIO;
4820 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4822 static const struct {
4830 int (* const dispatch)(DBusConnection *bus, char **args);
4832 { "list-units", LESS, 1, list_units },
4833 { "list-unit-files", EQUAL, 1, list_unit_files },
4834 { "list-jobs", EQUAL, 1, list_jobs },
4835 { "clear-jobs", EQUAL, 1, daemon_reload },
4836 { "load", MORE, 2, load_unit },
4837 { "cancel", MORE, 2, cancel_job },
4838 { "start", MORE, 2, start_unit },
4839 { "stop", MORE, 2, start_unit },
4840 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4841 { "reload", MORE, 2, start_unit },
4842 { "restart", MORE, 2, start_unit },
4843 { "try-restart", MORE, 2, start_unit },
4844 { "reload-or-restart", MORE, 2, start_unit },
4845 { "reload-or-try-restart", MORE, 2, start_unit },
4846 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4847 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4848 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4849 { "isolate", EQUAL, 2, start_unit },
4850 { "kill", MORE, 2, kill_unit },
4851 { "is-active", MORE, 2, check_unit },
4852 { "check", MORE, 2, check_unit },
4853 { "show", MORE, 1, show },
4854 { "status", MORE, 2, show },
4855 { "help", MORE, 2, show },
4856 { "dump", EQUAL, 1, dump },
4857 { "dot", EQUAL, 1, dot },
4858 { "snapshot", LESS, 2, snapshot },
4859 { "delete", MORE, 2, delete_snapshot },
4860 { "daemon-reload", EQUAL, 1, daemon_reload },
4861 { "daemon-reexec", EQUAL, 1, daemon_reload },
4862 { "show-environment", EQUAL, 1, show_enviroment },
4863 { "set-environment", MORE, 2, set_environment },
4864 { "unset-environment", MORE, 2, set_environment },
4865 { "halt", EQUAL, 1, start_special },
4866 { "poweroff", EQUAL, 1, start_special },
4867 { "reboot", EQUAL, 1, start_special },
4868 { "kexec", EQUAL, 1, start_special },
4869 { "suspend", EQUAL, 1, start_special },
4870 { "hibernate", EQUAL, 1, start_special },
4871 { "default", EQUAL, 1, start_special },
4872 { "rescue", EQUAL, 1, start_special },
4873 { "emergency", EQUAL, 1, start_special },
4874 { "exit", EQUAL, 1, start_special },
4875 { "reset-failed", MORE, 1, reset_failed },
4876 { "enable", MORE, 2, enable_unit },
4877 { "disable", MORE, 2, enable_unit },
4878 { "is-enabled", MORE, 2, unit_is_enabled },
4879 { "reenable", MORE, 2, enable_unit },
4880 { "preset", MORE, 2, enable_unit },
4881 { "mask", MORE, 2, enable_unit },
4882 { "unmask", MORE, 2, enable_unit },
4883 { "link", MORE, 2, enable_unit },
4884 { "switch-root", MORE, 2, switch_root },
4894 left = argc - optind;
4897 /* Special rule: no arguments means "list-units" */
4900 if (streq(argv[optind], "help") && !argv[optind+1]) {
4901 log_error("This command expects one or more "
4902 "unit names. Did you mean --help?");
4906 for (i = 0; i < ELEMENTSOF(verbs); i++)
4907 if (streq(argv[optind], verbs[i].verb))
4910 if (i >= ELEMENTSOF(verbs)) {
4911 log_error("Unknown operation '%s'.", argv[optind]);
4916 switch (verbs[i].argc_cmp) {
4919 if (left != verbs[i].argc) {
4920 log_error("Invalid number of arguments.");
4927 if (left < verbs[i].argc) {
4928 log_error("Too few arguments.");
4935 if (left > verbs[i].argc) {
4936 log_error("Too many arguments.");
4943 assert_not_reached("Unknown comparison operator.");
4946 /* Require a bus connection for all operations but
4948 if (!streq(verbs[i].verb, "enable") &&
4949 !streq(verbs[i].verb, "disable") &&
4950 !streq(verbs[i].verb, "is-enabled") &&
4951 !streq(verbs[i].verb, "list-unit-files") &&
4952 !streq(verbs[i].verb, "reenable") &&
4953 !streq(verbs[i].verb, "preset") &&
4954 !streq(verbs[i].verb, "mask") &&
4955 !streq(verbs[i].verb, "unmask") &&
4956 !streq(verbs[i].verb, "link")) {
4958 if (running_in_chroot() > 0) {
4959 log_info("Running in chroot, ignoring request.");
4963 if (((!streq(verbs[i].verb, "reboot") &&
4964 !streq(verbs[i].verb, "halt") &&
4965 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
4966 log_error("Failed to get D-Bus connection: %s",
4967 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
4973 if (!bus && !avoid_bus()) {
4974 log_error("Failed to get D-Bus connection: %s",
4975 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
4980 return verbs[i].dispatch(bus, argv + optind);
4983 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
4985 struct msghdr msghdr;
4986 struct iovec iovec[2];
4987 union sockaddr_union sockaddr;
4988 struct sd_shutdown_command c;
4990 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
4997 c.dry_run = dry_run;
5001 sockaddr.sa.sa_family = AF_UNIX;
5002 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5005 msghdr.msg_name = &sockaddr;
5006 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5009 iovec[0].iov_base = (char*) &c;
5010 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5012 if (isempty(message))
5013 msghdr.msg_iovlen = 1;
5015 iovec[1].iov_base = (char*) message;
5016 iovec[1].iov_len = strlen(message);
5017 msghdr.msg_iovlen = 2;
5019 msghdr.msg_iov = iovec;
5021 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5022 close_nointr_nofail(fd);
5026 close_nointr_nofail(fd);
5030 static int reload_with_fallback(DBusConnection *bus) {
5033 /* First, try systemd via D-Bus. */
5034 if (daemon_reload(bus, NULL) >= 0)
5038 /* Nothing else worked, so let's try signals */
5039 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5041 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5042 log_error("kill() failed: %m");
5049 static int start_with_fallback(DBusConnection *bus) {
5052 /* First, try systemd via D-Bus. */
5053 if (start_unit(bus, NULL) >= 0)
5057 /* Hmm, talking to systemd via D-Bus didn't work. Then
5058 * let's try to talk to Upstart via D-Bus. */
5059 if (talk_upstart() > 0)
5062 /* Nothing else worked, so let's try
5064 if (talk_initctl() > 0)
5067 log_error("Failed to talk to init daemon.");
5071 warn_wall(arg_action);
5075 static _noreturn_ void halt_now(enum action a) {
5077 /* Make sure C-A-D is handled by the kernel from this
5079 reboot(RB_ENABLE_CAD);
5084 log_info("Halting.");
5085 reboot(RB_HALT_SYSTEM);
5088 case ACTION_POWEROFF:
5089 log_info("Powering off.");
5090 reboot(RB_POWER_OFF);
5094 log_info("Rebooting.");
5095 reboot(RB_AUTOBOOT);
5099 assert_not_reached("Unknown halt action.");
5102 assert_not_reached("Uh? This shouldn't happen.");
5105 static int halt_main(DBusConnection *bus) {
5108 if (geteuid() != 0) {
5109 /* Try logind if we are a normal user and no special
5110 * mode applies. Maybe PolicyKit allows us to shutdown
5113 if (arg_when <= 0 &&
5116 (arg_action == ACTION_POWEROFF ||
5117 arg_action == ACTION_REBOOT)) {
5118 r = reboot_with_logind(bus, arg_action);
5123 log_error("Must be root.");
5130 m = strv_join(arg_wall, " ");
5131 r = send_shutdownd(arg_when,
5132 arg_action == ACTION_HALT ? 'H' :
5133 arg_action == ACTION_POWEROFF ? 'P' :
5134 arg_action == ACTION_KEXEC ? 'K' :
5142 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5144 char date[FORMAT_TIMESTAMP_MAX];
5146 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5147 format_timestamp(date, sizeof(date), arg_when));
5152 if (!arg_dry && !arg_force)
5153 return start_with_fallback(bus);
5156 if (sd_booted() > 0)
5157 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5159 r = utmp_put_shutdown();
5161 log_warning("Failed to write utmp record: %s", strerror(-r));
5168 halt_now(arg_action);
5169 /* We should never reach this. */
5173 static int runlevel_main(void) {
5174 int r, runlevel, previous;
5176 r = utmp_get_runlevel(&runlevel, &previous);
5183 previous <= 0 ? 'N' : previous,
5184 runlevel <= 0 ? 'N' : runlevel);
5189 int main(int argc, char*argv[]) {
5190 int r, retval = EXIT_FAILURE;
5191 DBusConnection *bus = NULL;
5194 dbus_error_init(&error);
5196 log_parse_environment();
5199 r = parse_argv(argc, argv);
5203 retval = EXIT_SUCCESS;
5207 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5208 * let's shortcut this */
5209 if (arg_action == ACTION_RUNLEVEL) {
5210 r = runlevel_main();
5211 retval = r < 0 ? EXIT_FAILURE : r;
5215 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5216 log_info("Running in chroot, ignoring request.");
5222 if (arg_transport == TRANSPORT_NORMAL)
5223 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5224 else if (arg_transport == TRANSPORT_POLKIT) {
5225 bus_connect_system_polkit(&bus, &error);
5226 private_bus = false;
5227 } else if (arg_transport == TRANSPORT_SSH) {
5228 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5229 private_bus = false;
5231 assert_not_reached("Uh, invalid transport...");
5234 switch (arg_action) {
5236 case ACTION_SYSTEMCTL:
5237 r = systemctl_main(bus, argc, argv, &error);
5241 case ACTION_POWEROFF:
5247 case ACTION_RUNLEVEL2:
5248 case ACTION_RUNLEVEL3:
5249 case ACTION_RUNLEVEL4:
5250 case ACTION_RUNLEVEL5:
5252 case ACTION_EMERGENCY:
5253 case ACTION_DEFAULT:
5254 r = start_with_fallback(bus);
5259 r = reload_with_fallback(bus);
5262 case ACTION_CANCEL_SHUTDOWN: {
5266 m = strv_join(arg_wall, " ");
5268 retval = EXIT_FAILURE;
5272 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
5274 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
5279 case ACTION_INVALID:
5280 case ACTION_RUNLEVEL:
5282 assert_not_reached("Unknown action");
5285 retval = r < 0 ? EXIT_FAILURE : r;
5289 dbus_connection_flush(bus);
5290 dbus_connection_close(bus);
5291 dbus_connection_unref(bus);
5294 dbus_error_free(&error);
5298 strv_free(arg_property);
5301 ask_password_agent_close();
5302 polkit_agent_close();