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 loaded units listed.\n"
429 "To show all installed unit files use 'systemctl list-unit-files'.\n", n_shown);
431 printf("\n%u loaded units listed. Pass --all to see loaded but inactive units, too.\n"
432 "To show all installed unit files use 'systemctl list-unit-files'.\n", n_shown);
436 static int list_units(DBusConnection *bus, char **args) {
437 DBusMessage *reply = NULL;
439 DBusMessageIter iter, sub, sub2;
440 unsigned c = 0, n_units = 0;
441 struct unit_info *unit_infos = NULL;
443 pager_open_if_enabled();
445 r = bus_method_call_with_reply (
447 "org.freedesktop.systemd1",
448 "/org/freedesktop/systemd1",
449 "org.freedesktop.systemd1.Manager",
457 if (!dbus_message_iter_init(reply, &iter) ||
458 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
459 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
460 log_error("Failed to parse reply.");
465 dbus_message_iter_recurse(&iter, &sub);
467 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
470 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
471 log_error("Failed to parse reply.");
479 n_units = MAX(2*c, 16);
480 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
483 log_error("Failed to allocate unit array.");
493 dbus_message_iter_recurse(&sub, &sub2);
495 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
496 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
497 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
498 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
499 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
500 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
501 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
502 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
503 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
504 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
505 log_error("Failed to parse reply.");
510 dbus_message_iter_next(&sub);
515 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
516 output_units_list(unit_infos, c);
521 dbus_message_unref(reply);
528 static int compare_unit_file_list(const void *a, const void *b) {
530 const UnitFileList *u = a, *v = b;
532 d1 = strrchr(u->path, '.');
533 d2 = strrchr(v->path, '.');
538 r = strcasecmp(d1, d2);
543 return strcasecmp(path_get_file_name(u->path), path_get_file_name(v->path));
546 static bool output_show_unit_file(const UnitFileList *u) {
549 return !arg_type || ((dot = strrchr(u->path, '.')) && streq(dot+1, arg_type));
552 static void output_unit_file_list(const UnitFileList *units, unsigned c) {
553 unsigned max_id_len, id_cols, state_cols, n_shown = 0;
554 const UnitFileList *u;
556 max_id_len = sizeof("UNIT FILE")-1;
557 state_cols = sizeof("STATE")-1;
558 for (u = units; u < units + c; u++) {
559 if (!output_show_unit_file(u))
562 max_id_len = MAX(max_id_len, strlen(path_get_file_name(u->path)));
563 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
568 id_cols = MIN(max_id_len, 25);
569 basic_cols = 1 + id_cols + state_cols;
570 if (basic_cols < (unsigned) columns())
571 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
573 id_cols = max_id_len;
576 printf("%-*s %-*s\n", id_cols, "UNIT FILE", state_cols, "STATE");
578 for (u = units; u < units + c; u++) {
580 const char *on, *off;
583 if (!output_show_unit_file(u))
588 if (u->state == UNIT_FILE_MASKED ||
589 u->state == UNIT_FILE_MASKED_RUNTIME ||
590 u->state == UNIT_FILE_DISABLED ||
591 u->state == UNIT_FILE_INVALID) {
592 on = ansi_highlight_red(true);
593 off = ansi_highlight_red(false);
594 } else if (u->state == UNIT_FILE_ENABLED) {
595 on = ansi_highlight_green(true);
596 off = ansi_highlight_green(false);
600 id = path_get_file_name(u->path);
602 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
604 printf("%-*s %s%-*s%s\n",
606 on, state_cols, unit_file_state_to_string(u->state), off);
612 printf("\n%u unit files listed.\n", n_shown);
615 static int list_unit_files(DBusConnection *bus, char **args) {
616 DBusMessage *reply = NULL;
618 DBusMessageIter iter, sub, sub2;
619 unsigned c = 0, n_units = 0;
620 UnitFileList *units = NULL;
622 pager_open_if_enabled();
629 h = hashmap_new(string_hash_func, string_compare_func);
633 r = unit_file_get_list(arg_scope, arg_root, h);
635 unit_file_list_free(h);
636 log_error("Failed to get unit file list: %s", strerror(-r));
640 n_units = hashmap_size(h);
641 units = new(UnitFileList, n_units);
643 unit_file_list_free(h);
647 HASHMAP_FOREACH(u, h, i) {
648 memcpy(units + c++, u, sizeof(UnitFileList));
654 r = bus_method_call_with_reply (
656 "org.freedesktop.systemd1",
657 "/org/freedesktop/systemd1",
658 "org.freedesktop.systemd1.Manager",
666 if (!dbus_message_iter_init(reply, &iter) ||
667 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
668 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
669 log_error("Failed to parse reply.");
674 dbus_message_iter_recurse(&iter, &sub);
676 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
680 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
681 log_error("Failed to parse reply.");
689 n_units = MAX(2*c, 16);
690 w = realloc(units, sizeof(struct UnitFileList) * n_units);
693 log_error("Failed to allocate unit array.");
703 dbus_message_iter_recurse(&sub, &sub2);
705 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->path, true) < 0 ||
706 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, false) < 0) {
707 log_error("Failed to parse reply.");
712 u->state = unit_file_state_from_string(state);
714 dbus_message_iter_next(&sub);
720 qsort(units, c, sizeof(UnitFileList), compare_unit_file_list);
721 output_unit_file_list(units, c);
728 dbus_message_unref(reply);
735 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
736 static const char * const colors[] = {
737 "Requires", "[color=\"black\"]",
738 "RequiresOverridable", "[color=\"black\"]",
739 "Requisite", "[color=\"darkblue\"]",
740 "RequisiteOverridable", "[color=\"darkblue\"]",
741 "Wants", "[color=\"grey66\"]",
742 "Conflicts", "[color=\"red\"]",
743 "ConflictedBy", "[color=\"red\"]",
744 "After", "[color=\"green\"]"
747 const char *c = NULL;
754 for (i = 0; i < ELEMENTSOF(colors); i += 2)
755 if (streq(colors[i], prop)) {
763 if (arg_dot != DOT_ALL)
764 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
767 switch (dbus_message_iter_get_arg_type(iter)) {
769 case DBUS_TYPE_ARRAY:
771 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
774 dbus_message_iter_recurse(iter, &sub);
776 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
779 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
780 dbus_message_iter_get_basic(&sub, &s);
781 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
783 dbus_message_iter_next(&sub);
793 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
794 DBusMessage *reply = NULL;
795 const char *interface = "org.freedesktop.systemd1.Unit";
797 DBusMessageIter iter, sub, sub2, sub3;
801 r = bus_method_call_with_reply (
803 "org.freedesktop.systemd1",
805 "org.freedesktop.DBus.Properties",
809 DBUS_TYPE_STRING, &interface,
814 if (!dbus_message_iter_init(reply, &iter) ||
815 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
816 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
817 log_error("Failed to parse reply.");
822 dbus_message_iter_recurse(&iter, &sub);
824 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
827 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
828 log_error("Failed to parse reply.");
833 dbus_message_iter_recurse(&sub, &sub2);
835 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
836 log_error("Failed to parse reply.");
841 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
842 log_error("Failed to parse reply.");
847 dbus_message_iter_recurse(&sub2, &sub3);
849 if (dot_one_property(name, prop, &sub3)) {
850 log_error("Failed to parse reply.");
855 dbus_message_iter_next(&sub);
860 dbus_message_unref(reply);
865 static int dot(DBusConnection *bus, char **args) {
866 DBusMessage *reply = NULL;
868 DBusMessageIter iter, sub, sub2;
870 r = bus_method_call_with_reply (
872 "org.freedesktop.systemd1",
873 "/org/freedesktop/systemd1",
874 "org.freedesktop.systemd1.Manager",
882 if (!dbus_message_iter_init(reply, &iter) ||
883 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
884 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
885 log_error("Failed to parse reply.");
890 printf("digraph systemd {\n");
892 dbus_message_iter_recurse(&iter, &sub);
893 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
894 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
896 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
897 log_error("Failed to parse reply.");
902 dbus_message_iter_recurse(&sub, &sub2);
904 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
905 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
906 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
907 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
908 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
909 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
910 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
911 log_error("Failed to parse reply.");
916 if ((r = dot_one(bus, id, unit_path)) < 0)
919 /* printf("\t\"%s\";\n", id); */
920 dbus_message_iter_next(&sub);
925 log_info(" Color legend: black = Requires\n"
926 " dark blue = Requisite\n"
927 " dark grey = Wants\n"
932 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
933 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
939 dbus_message_unref(reply);
944 static int list_jobs(DBusConnection *bus, char **args) {
945 DBusMessage *reply = NULL;
947 DBusMessageIter iter, sub, sub2;
950 pager_open_if_enabled();
952 r = bus_method_call_with_reply (
954 "org.freedesktop.systemd1",
955 "/org/freedesktop/systemd1",
956 "org.freedesktop.systemd1.Manager",
964 if (!dbus_message_iter_init(reply, &iter) ||
965 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
966 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
967 log_error("Failed to parse reply.");
972 dbus_message_iter_recurse(&iter, &sub);
975 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
977 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
978 const char *name, *type, *state, *job_path, *unit_path;
982 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
983 log_error("Failed to parse reply.");
988 dbus_message_iter_recurse(&sub, &sub2);
990 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
991 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
992 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
993 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
994 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
995 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
996 log_error("Failed to parse reply.");
1001 e = arg_full ? NULL : ellipsize(name, 25, 33);
1002 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
1007 dbus_message_iter_next(&sub);
1011 printf("\n%u jobs listed.\n", k);
1017 dbus_message_unref(reply);
1022 static int load_unit(DBusConnection *bus, char **args) {
1028 STRV_FOREACH(name, args+1) {
1029 n = unit_name_mangle(*name);
1030 r = bus_method_call_with_reply (
1032 "org.freedesktop.systemd1",
1033 "/org/freedesktop/systemd1",
1034 "org.freedesktop.systemd1.Manager",
1038 DBUS_TYPE_STRING, n ? &n : name,
1049 static int cancel_job(DBusConnection *bus, char **args) {
1050 DBusMessage *reply = NULL;
1056 if (strv_length(args) <= 1)
1057 return daemon_reload(bus, args);
1059 STRV_FOREACH(name, args+1) {
1063 r = safe_atou(*name, &id);
1065 log_error("Failed to parse job id: %s", strerror(-r));
1068 assert_cc(sizeof(uint32_t) == sizeof(id));
1070 r = bus_method_call_with_reply (
1072 "org.freedesktop.systemd1",
1073 "/org/freedesktop/systemd1",
1074 "org.freedesktop.systemd1.Manager",
1078 DBUS_TYPE_UINT32, &id,
1083 if (!dbus_message_get_args(reply, NULL,
1084 DBUS_TYPE_OBJECT_PATH, &path,
1085 DBUS_TYPE_INVALID)) {
1086 log_error("Failed to parse reply");
1087 dbus_message_unref(reply);
1091 dbus_message_unref(reply);
1093 r = bus_method_call_with_reply (
1095 "org.freedesktop.systemd1",
1097 "org.freedesktop.systemd1.Job",
1110 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1111 DBusMessage *reply = NULL;
1112 dbus_bool_t b = FALSE;
1113 DBusMessageIter iter, sub;
1115 *interface = "org.freedesktop.systemd1.Unit",
1116 *property = "NeedDaemonReload",
1121 /* We ignore all errors here, since this is used to show a warning only */
1123 n = unit_name_mangle(unit);
1124 r = bus_method_call_with_reply (
1126 "org.freedesktop.systemd1",
1127 "/org/freedesktop/systemd1",
1128 "org.freedesktop.systemd1.Manager",
1132 DBUS_TYPE_STRING, n ? (const char**) &n : &unit,
1138 if (!dbus_message_get_args(reply, NULL,
1139 DBUS_TYPE_OBJECT_PATH, &path,
1143 dbus_message_unref(reply);
1144 r = bus_method_call_with_reply (
1146 "org.freedesktop.systemd1",
1148 "org.freedesktop.DBus.Properties",
1152 DBUS_TYPE_STRING, &interface,
1153 DBUS_TYPE_STRING, &property,
1158 if (!dbus_message_iter_init(reply, &iter) ||
1159 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1162 dbus_message_iter_recurse(&iter, &sub);
1164 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1167 dbus_message_iter_get_basic(&sub, &b);
1171 dbus_message_unref(reply);
1176 typedef struct WaitData {
1183 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1191 dbus_error_init(&error);
1193 log_debug("Got D-Bus request: %s.%s() on %s",
1194 dbus_message_get_interface(message),
1195 dbus_message_get_member(message),
1196 dbus_message_get_path(message));
1198 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1199 log_error("Warning! D-Bus connection terminated.");
1200 dbus_connection_close(connection);
1202 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1204 const char *path, *result, *unit;
1205 dbus_bool_t success = true;
1207 if (dbus_message_get_args(message, &error,
1208 DBUS_TYPE_UINT32, &id,
1209 DBUS_TYPE_OBJECT_PATH, &path,
1210 DBUS_TYPE_STRING, &unit,
1211 DBUS_TYPE_STRING, &result,
1212 DBUS_TYPE_INVALID)) {
1215 p = set_remove(d->set, (char*) path);
1218 if (!isempty(result))
1219 d->result = strdup(result);
1222 d->name = strdup(unit);
1227 dbus_error_free(&error);
1228 if (dbus_message_get_args(message, &error,
1229 DBUS_TYPE_UINT32, &id,
1230 DBUS_TYPE_OBJECT_PATH, &path,
1231 DBUS_TYPE_STRING, &result,
1232 DBUS_TYPE_INVALID)) {
1235 /* Compatibility with older systemd versions <
1236 * 183 during upgrades. This should be dropped
1238 p = set_remove(d->set, (char*) path);
1242 d->result = strdup(result);
1247 dbus_error_free(&error);
1248 if (dbus_message_get_args(message, &error,
1249 DBUS_TYPE_UINT32, &id,
1250 DBUS_TYPE_OBJECT_PATH, &path,
1251 DBUS_TYPE_BOOLEAN, &success,
1252 DBUS_TYPE_INVALID)) {
1255 /* Compatibility with older systemd versions <
1256 * 19 during upgrades. This should be dropped
1259 p = set_remove(d->set, (char*) path);
1263 d->result = strdup("failed");
1269 log_error("Failed to parse message: %s", bus_error_message(&error));
1273 dbus_error_free(&error);
1274 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1277 static int enable_wait_for_jobs(DBusConnection *bus) {
1285 dbus_error_init(&error);
1286 dbus_bus_add_match(bus,
1288 "sender='org.freedesktop.systemd1',"
1289 "interface='org.freedesktop.systemd1.Manager',"
1290 "member='JobRemoved',"
1291 "path='/org/freedesktop/systemd1'",
1294 if (dbus_error_is_set(&error)) {
1295 log_error("Failed to add match: %s", bus_error_message(&error));
1296 dbus_error_free(&error);
1300 /* This is slightly dirty, since we don't undo the match registrations. */
1304 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1314 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL))
1317 while (!set_isempty(s)) {
1319 if (!dbus_connection_read_write_dispatch(bus, -1)) {
1320 log_error("Disconnected from bus.");
1321 return -ECONNREFUSED;
1324 if (!arg_quiet && d.result) {
1325 if (streq(d.result, "timeout"))
1326 log_error("Job for %s timed out.", strna(d.name));
1327 else if (streq(d.result, "canceled"))
1328 log_error("Job for %s canceled.", strna(d.name));
1329 else if (streq(d.result, "dependency"))
1330 log_error("A dependency job for %s failed. See 'journalctl' for details.", strna(d.name));
1331 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1332 log_error("Job for %s failed. See 'systemctl status %s' and 'journalctl' for details.", strna(d.name), strna(d.name));
1335 if (streq_ptr(d.result, "timeout"))
1337 else if (streq_ptr(d.result, "canceled"))
1339 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1349 /* This is slightly dirty, since we don't undo the filter registration. */
1353 static int check_one_unit(DBusConnection *bus, char *name, bool quiet) {
1354 DBusMessage *reply = NULL;
1355 DBusMessageIter iter, sub;
1357 *interface = "org.freedesktop.systemd1.Unit",
1358 *property = "ActiveState";
1359 const char *path = NULL;
1366 n = unit_name_mangle(name);
1367 r = bus_method_call_with_reply (
1369 "org.freedesktop.systemd1",
1370 "/org/freedesktop/systemd1",
1371 "org.freedesktop.systemd1.Manager",
1375 DBUS_TYPE_STRING, n ? &n : &name,
1379 if ((r != -ENOMEM) && (!quiet))
1384 if (!dbus_message_get_args(reply, NULL,
1385 DBUS_TYPE_OBJECT_PATH, &path,
1386 DBUS_TYPE_INVALID)) {
1387 log_error("Failed to parse reply.");
1392 dbus_message_unref(reply);
1393 r = bus_method_call_with_reply (
1395 "org.freedesktop.systemd1",
1397 "org.freedesktop.DBus.Properties",
1401 DBUS_TYPE_STRING, &interface,
1402 DBUS_TYPE_STRING, &property,
1407 if (!dbus_message_iter_init(reply, &iter) ||
1408 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1409 log_error("Failed to parse reply.");
1414 dbus_message_iter_recurse(&iter, &sub);
1416 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1417 log_error("Failed to parse reply.");
1422 dbus_message_iter_get_basic(&sub, &state);
1427 if (streq(state, "active") || streq(state, "reloading"))
1430 r = 3; /* According to LSB: "program is not running" */
1434 dbus_message_unref(reply);
1439 static void check_triggering_units(
1440 DBusConnection *bus,
1441 const char *unit_name) {
1443 DBusMessage *reply = NULL;
1444 DBusMessageIter iter, sub;
1445 char *service_trigger = NULL;
1446 const char *interface = "org.freedesktop.systemd1.Unit",
1447 *triggered_by_property = "TriggeredBy";
1449 char *unit_path = NULL, *n = NULL;
1450 bool print_warning_label = true;
1453 n = unit_name_mangle(unit_name);
1454 unit_path = unit_dbus_path_from_name(n ? n : unit_name);
1457 log_error("Could not allocate dbus path.");
1461 r = bus_method_call_with_reply (
1463 "org.freedesktop.systemd1",
1465 "org.freedesktop.DBus.Properties",
1469 DBUS_TYPE_STRING, &interface,
1470 DBUS_TYPE_STRING, &triggered_by_property,
1475 if (!dbus_message_iter_init(reply, &iter) ||
1476 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1477 log_error("Failed to parse reply.");
1482 dbus_message_iter_recurse(&iter, &sub);
1483 dbus_message_iter_recurse(&sub, &iter);
1486 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1488 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1489 log_error("Failed to parse reply.");
1493 dbus_message_iter_get_basic(&sub, &service_trigger);
1495 r = check_one_unit(bus, service_trigger, true);
1499 if (print_warning_label) {
1500 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1501 print_warning_label = false;
1503 log_warning(" %s", service_trigger);
1506 dbus_message_iter_next(&sub);
1510 dbus_message_unref(reply);
1515 static int start_unit_one(
1516 DBusConnection *bus,
1523 DBusMessage *reply = NULL;
1526 _cleanup_free_ char *n, *p = NULL;
1533 n = unit_name_mangle(name);
1537 r = bus_method_call_with_reply(
1539 "org.freedesktop.systemd1",
1540 "/org/freedesktop/systemd1",
1541 "org.freedesktop.systemd1.Manager",
1545 DBUS_TYPE_STRING, &n,
1546 DBUS_TYPE_STRING, &mode,
1549 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
1550 /* There's always a fallback possible for
1551 * legacy actions. */
1554 log_error("Failed to issue method call: %s", bus_error_message(error));
1559 if (!dbus_message_get_args(reply, error,
1560 DBUS_TYPE_OBJECT_PATH, &path,
1561 DBUS_TYPE_INVALID)) {
1562 log_error("Failed to parse reply: %s", bus_error_message(error));
1567 if (need_daemon_reload(bus, n))
1568 log_warning("Warning: Unit file of %s changed on disk, 'systemctl %s daemon-reload' recommended.",
1569 n, arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1580 log_error("Failed to add path to set.");
1587 /* When stopping a unit warn if it can still be triggered by
1588 * another active unit (socket, path, timer) */
1589 if (!arg_quiet && streq(method, "StopUnit"))
1590 check_triggering_units(bus, name);
1596 dbus_message_unref(reply);
1601 static enum action verb_to_action(const char *verb) {
1602 if (streq(verb, "halt"))
1604 else if (streq(verb, "poweroff"))
1605 return ACTION_POWEROFF;
1606 else if (streq(verb, "reboot"))
1607 return ACTION_REBOOT;
1608 else if (streq(verb, "kexec"))
1609 return ACTION_KEXEC;
1610 else if (streq(verb, "rescue"))
1611 return ACTION_RESCUE;
1612 else if (streq(verb, "emergency"))
1613 return ACTION_EMERGENCY;
1614 else if (streq(verb, "default"))
1615 return ACTION_DEFAULT;
1616 else if (streq(verb, "exit"))
1618 else if (streq(verb, "suspend"))
1619 return ACTION_SUSPEND;
1620 else if (streq(verb, "hibernate"))
1621 return ACTION_HIBERNATE;
1623 return ACTION_INVALID;
1626 static int start_unit(DBusConnection *bus, char **args) {
1628 static const char * const table[_ACTION_MAX] = {
1629 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1630 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1631 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1632 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1633 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1634 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1635 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1636 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1637 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1638 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1639 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1640 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1641 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1642 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET
1646 const char *method, *mode, *one_name;
1651 dbus_error_init(&error);
1655 ask_password_agent_open_if_enabled();
1657 if (arg_action == ACTION_SYSTEMCTL) {
1659 streq(args[0], "stop") ||
1660 streq(args[0], "condstop") ? "StopUnit" :
1661 streq(args[0], "reload") ? "ReloadUnit" :
1662 streq(args[0], "restart") ? "RestartUnit" :
1664 streq(args[0], "try-restart") ||
1665 streq(args[0], "condrestart") ? "TryRestartUnit" :
1667 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1669 streq(args[0], "reload-or-try-restart") ||
1670 streq(args[0], "condreload") ||
1672 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1676 (streq(args[0], "isolate") ||
1677 streq(args[0], "rescue") ||
1678 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1680 one_name = table[verb_to_action(args[0])];
1683 assert(arg_action < ELEMENTSOF(table));
1684 assert(table[arg_action]);
1686 method = "StartUnit";
1688 mode = (arg_action == ACTION_EMERGENCY ||
1689 arg_action == ACTION_RESCUE ||
1690 arg_action == ACTION_RUNLEVEL2 ||
1691 arg_action == ACTION_RUNLEVEL3 ||
1692 arg_action == ACTION_RUNLEVEL4 ||
1693 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1695 one_name = table[arg_action];
1698 if (!arg_no_block) {
1699 ret = enable_wait_for_jobs(bus);
1701 log_error("Could not watch jobs: %s", strerror(-ret));
1705 s = set_new(string_hash_func, string_compare_func);
1713 ret = start_unit_one(bus, method, one_name, mode, &error, s);
1715 ret = translate_bus_error_to_exit_status(ret, &error);
1717 STRV_FOREACH(name, args+1) {
1718 r = start_unit_one(bus, method, *name, mode, &error, s);
1720 ret = translate_bus_error_to_exit_status(r, &error);
1721 dbus_error_free(&error);
1726 if (!arg_no_block) {
1727 r = wait_for_jobs(bus, s);
1736 dbus_error_free(&error);
1741 /* Ask systemd-logind, which might grant access to unprivileged users
1742 * through PolicyKit */
1743 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1746 dbus_bool_t interactive = true;
1748 polkit_agent_open_if_enabled();
1756 case ACTION_POWEROFF:
1757 method = "PowerOff";
1760 case ACTION_SUSPEND:
1764 case ACTION_HIBERNATE:
1765 method = "Hibernate";
1772 return bus_method_call_with_reply (
1774 "org.freedesktop.login1",
1775 "/org/freedesktop/login1",
1776 "org.freedesktop.login1.Manager",
1780 DBUS_TYPE_BOOLEAN, &interactive,
1787 static int start_special(DBusConnection *bus, char **args) {
1793 a = verb_to_action(args[0]);
1795 if (arg_force >= 2 && geteuid() != 0) {
1796 log_error("Must be root.");
1800 if (arg_force >= 2 &&
1801 (a == ACTION_HALT ||
1802 a == ACTION_POWEROFF ||
1803 a == ACTION_REBOOT))
1806 if (arg_force >= 1 &&
1807 (a == ACTION_HALT ||
1808 a == ACTION_POWEROFF ||
1809 a == ACTION_REBOOT ||
1810 a == ACTION_KEXEC ||
1812 return daemon_reload(bus, args);
1814 /* first try logind, to allow authentication with polkit */
1815 if (geteuid() != 0 &&
1816 (a == ACTION_POWEROFF ||
1817 a == ACTION_REBOOT ||
1818 a == ACTION_SUSPEND ||
1819 a == ACTION_HIBERNATE)) {
1820 r = reboot_with_logind(bus, a);
1825 r = start_unit(bus, args);
1832 static int check_unit(DBusConnection *bus, char **args) {
1834 int r = 3; /* According to LSB: "program is not running" */
1839 STRV_FOREACH(name, args+1) {
1840 int state = check_one_unit(bus, *name, arg_quiet);
1850 static int kill_unit(DBusConnection *bus, char **args) {
1857 arg_kill_who = "all";
1859 STRV_FOREACH(name, args+1) {
1860 n = unit_name_mangle(*name);
1861 r = bus_method_call_with_reply (
1863 "org.freedesktop.systemd1",
1864 "/org/freedesktop/systemd1",
1865 "org.freedesktop.systemd1.Manager",
1869 DBUS_TYPE_STRING, n ? &n : name,
1870 DBUS_TYPE_STRING, &arg_kill_who,
1871 DBUS_TYPE_INT32, &arg_signal,
1880 typedef struct ExecStatusInfo {
1888 usec_t start_timestamp;
1889 usec_t exit_timestamp;
1894 LIST_FIELDS(struct ExecStatusInfo, exec);
1897 static void exec_status_info_free(ExecStatusInfo *i) {
1906 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1907 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
1908 DBusMessageIter sub2, sub3;
1912 int32_t code, status;
1918 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1921 dbus_message_iter_recurse(sub, &sub2);
1923 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1926 if (!(i->path = strdup(path)))
1929 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1930 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1934 dbus_message_iter_recurse(&sub2, &sub3);
1935 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1936 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1937 dbus_message_iter_next(&sub3);
1942 if (!(i->argv = new0(char*, n+1)))
1946 dbus_message_iter_recurse(&sub2, &sub3);
1947 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1950 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1951 dbus_message_iter_get_basic(&sub3, &s);
1952 dbus_message_iter_next(&sub3);
1954 if (!(i->argv[n++] = strdup(s)))
1958 if (!dbus_message_iter_next(&sub2) ||
1959 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1960 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1961 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
1962 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1963 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
1964 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1965 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1966 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1970 i->start_timestamp = (usec_t) start_timestamp;
1971 i->exit_timestamp = (usec_t) exit_timestamp;
1972 i->pid = (pid_t) pid;
1979 typedef struct UnitStatusInfo {
1981 const char *load_state;
1982 const char *active_state;
1983 const char *sub_state;
1984 const char *unit_file_state;
1986 const char *description;
1987 const char *following;
1989 char **documentation;
1991 const char *fragment_path;
1992 const char *source_path;
1993 const char *default_control_group;
1995 const char *load_error;
1998 usec_t inactive_exit_timestamp;
1999 usec_t inactive_exit_timestamp_monotonic;
2000 usec_t active_enter_timestamp;
2001 usec_t active_exit_timestamp;
2002 usec_t inactive_enter_timestamp;
2004 bool need_daemon_reload;
2009 const char *status_text;
2012 usec_t start_timestamp;
2013 usec_t exit_timestamp;
2015 int exit_code, exit_status;
2017 usec_t condition_timestamp;
2018 bool condition_result;
2021 unsigned n_accepted;
2022 unsigned n_connections;
2026 const char *sysfs_path;
2028 /* Mount, Automount */
2034 LIST_HEAD(ExecStatusInfo, exec);
2037 static void print_status_info(UnitStatusInfo *i) {
2039 const char *on, *off, *ss;
2041 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2042 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2047 /* This shows pretty information about a unit. See
2048 * print_property() for a low-level property printer */
2050 printf("%s", strna(i->id));
2052 if (i->description && !streq_ptr(i->id, i->description))
2053 printf(" - %s", i->description);
2058 printf("\t Follow: unit currently follows state of %s\n", i->following);
2060 if (streq_ptr(i->load_state, "error")) {
2061 on = ansi_highlight_red(true);
2062 off = ansi_highlight_red(false);
2066 path = i->source_path ? i->source_path : i->fragment_path;
2069 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2070 else if (path && i->unit_file_state)
2071 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2073 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2075 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2077 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2079 if (streq_ptr(i->active_state, "failed")) {
2080 on = ansi_highlight_red(true);
2081 off = ansi_highlight_red(false);
2082 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2083 on = ansi_highlight_green(true);
2084 off = ansi_highlight_green(false);
2089 printf("\t Active: %s%s (%s)%s",
2091 strna(i->active_state),
2095 printf("\t Active: %s%s%s",
2097 strna(i->active_state),
2100 if (!isempty(i->result) && !streq(i->result, "success"))
2101 printf(" (Result: %s)", i->result);
2103 timestamp = (streq_ptr(i->active_state, "active") ||
2104 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2105 (streq_ptr(i->active_state, "inactive") ||
2106 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2107 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2108 i->active_exit_timestamp;
2110 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2111 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2114 printf(" since %s; %s\n", s2, s1);
2116 printf(" since %s\n", s2);
2120 if (!i->condition_result && i->condition_timestamp > 0) {
2121 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2122 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2125 printf("\t start condition failed at %s; %s\n", s2, s1);
2127 printf("\t start condition failed at %s\n", s2);
2131 printf("\t Device: %s\n", i->sysfs_path);
2133 printf("\t Where: %s\n", i->where);
2135 printf("\t What: %s\n", i->what);
2137 if (!strv_isempty(i->documentation)) {
2141 STRV_FOREACH(t, i->documentation) {
2143 printf("\t Docs: %s\n", *t);
2146 printf("\t %s\n", *t);
2151 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2153 LIST_FOREACH(exec, p, i->exec) {
2157 /* Only show exited processes here */
2161 t = strv_join(p->argv, " ");
2162 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2165 good = is_clean_exit_lsb(p->code, p->status, NULL);
2167 on = ansi_highlight_red(true);
2168 off = ansi_highlight_red(false);
2172 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2174 if (p->code == CLD_EXITED) {
2177 printf("status=%i", p->status);
2179 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2184 printf("signal=%s", signal_to_string(p->status));
2186 printf(")%s\n", off);
2188 if (i->main_pid == p->pid &&
2189 i->start_timestamp == p->start_timestamp &&
2190 i->exit_timestamp == p->start_timestamp)
2191 /* Let's not show this twice */
2194 if (p->pid == i->control_pid)
2198 if (i->main_pid > 0 || i->control_pid > 0) {
2201 if (i->main_pid > 0) {
2202 printf("Main PID: %u", (unsigned) i->main_pid);
2206 get_process_comm(i->main_pid, &t);
2211 } else if (i->exit_code > 0) {
2212 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2214 if (i->exit_code == CLD_EXITED) {
2217 printf("status=%i", i->exit_status);
2219 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2224 printf("signal=%s", signal_to_string(i->exit_status));
2229 if (i->main_pid > 0 && i->control_pid > 0)
2232 if (i->control_pid > 0) {
2235 printf(" Control: %u", (unsigned) i->control_pid);
2237 get_process_comm(i->control_pid, &t);
2248 printf("\t Status: \"%s\"\n", i->status_text);
2250 if (i->default_control_group) {
2253 printf("\t CGroup: %s\n", i->default_control_group);
2255 if (arg_transport != TRANSPORT_SSH) {
2265 if (i->main_pid > 0)
2266 extra[k++] = i->main_pid;
2268 if (i->control_pid > 0)
2269 extra[k++] = i->control_pid;
2271 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2275 if (i->id && arg_transport != TRANSPORT_SSH) {
2277 arg_all * OUTPUT_SHOW_ALL |
2278 arg_follow * OUTPUT_FOLLOW |
2279 !arg_quiet * OUTPUT_WARN_CUTOFF |
2280 on_tty() * OUTPUT_COLOR;
2283 show_journal_by_unit(i->id, arg_output, 0,
2284 i->inactive_exit_timestamp_monotonic,
2288 if (i->need_daemon_reload)
2289 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2290 ansi_highlight_red(true),
2291 ansi_highlight_red(false),
2292 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2295 static void show_unit_help(UnitStatusInfo *i) {
2300 if (!i->documentation) {
2301 log_info("Documentation for %s not known.", i->id);
2305 STRV_FOREACH(p, i->documentation) {
2307 if (startswith(*p, "man:")) {
2310 char *page = NULL, *section = NULL;
2311 const char *args[4] = { "man", NULL, NULL, NULL };
2316 if ((*p)[k-1] == ')')
2317 e = strrchr(*p, '(');
2320 page = strndup((*p) + 4, e - *p - 4);
2326 section = strndup(e + 1, *p + k - e - 2);
2340 log_error("Failed to fork: %m");
2348 execvp(args[0], (char**) args);
2349 log_error("Failed to execute man: %m");
2350 _exit(EXIT_FAILURE);
2356 wait_for_terminate(pid, NULL);
2358 log_info("Can't show: %s", *p);
2362 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2368 switch (dbus_message_iter_get_arg_type(iter)) {
2370 case DBUS_TYPE_STRING: {
2373 dbus_message_iter_get_basic(iter, &s);
2376 if (streq(name, "Id"))
2378 else if (streq(name, "LoadState"))
2380 else if (streq(name, "ActiveState"))
2381 i->active_state = s;
2382 else if (streq(name, "SubState"))
2384 else if (streq(name, "Description"))
2386 else if (streq(name, "FragmentPath"))
2387 i->fragment_path = s;
2388 else if (streq(name, "SourcePath"))
2390 else if (streq(name, "DefaultControlGroup"))
2391 i->default_control_group = s;
2392 else if (streq(name, "StatusText"))
2394 else if (streq(name, "SysFSPath"))
2396 else if (streq(name, "Where"))
2398 else if (streq(name, "What"))
2400 else if (streq(name, "Following"))
2402 else if (streq(name, "UnitFileState"))
2403 i->unit_file_state = s;
2404 else if (streq(name, "Result"))
2411 case DBUS_TYPE_BOOLEAN: {
2414 dbus_message_iter_get_basic(iter, &b);
2416 if (streq(name, "Accept"))
2418 else if (streq(name, "NeedDaemonReload"))
2419 i->need_daemon_reload = b;
2420 else if (streq(name, "ConditionResult"))
2421 i->condition_result = b;
2426 case DBUS_TYPE_UINT32: {
2429 dbus_message_iter_get_basic(iter, &u);
2431 if (streq(name, "MainPID")) {
2433 i->main_pid = (pid_t) u;
2436 } else if (streq(name, "ControlPID"))
2437 i->control_pid = (pid_t) u;
2438 else if (streq(name, "ExecMainPID")) {
2440 i->main_pid = (pid_t) u;
2441 } else if (streq(name, "NAccepted"))
2443 else if (streq(name, "NConnections"))
2444 i->n_connections = u;
2449 case DBUS_TYPE_INT32: {
2452 dbus_message_iter_get_basic(iter, &j);
2454 if (streq(name, "ExecMainCode"))
2455 i->exit_code = (int) j;
2456 else if (streq(name, "ExecMainStatus"))
2457 i->exit_status = (int) j;
2462 case DBUS_TYPE_UINT64: {
2465 dbus_message_iter_get_basic(iter, &u);
2467 if (streq(name, "ExecMainStartTimestamp"))
2468 i->start_timestamp = (usec_t) u;
2469 else if (streq(name, "ExecMainExitTimestamp"))
2470 i->exit_timestamp = (usec_t) u;
2471 else if (streq(name, "ActiveEnterTimestamp"))
2472 i->active_enter_timestamp = (usec_t) u;
2473 else if (streq(name, "InactiveEnterTimestamp"))
2474 i->inactive_enter_timestamp = (usec_t) u;
2475 else if (streq(name, "InactiveExitTimestamp"))
2476 i->inactive_exit_timestamp = (usec_t) u;
2477 else if (streq(name, "InactiveExitTimestampMonotonic"))
2478 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2479 else if (streq(name, "ActiveExitTimestamp"))
2480 i->active_exit_timestamp = (usec_t) u;
2481 else if (streq(name, "ConditionTimestamp"))
2482 i->condition_timestamp = (usec_t) u;
2487 case DBUS_TYPE_ARRAY: {
2489 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2490 startswith(name, "Exec")) {
2491 DBusMessageIter sub;
2493 dbus_message_iter_recurse(iter, &sub);
2494 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2495 ExecStatusInfo *info;
2498 if (!(info = new0(ExecStatusInfo, 1)))
2501 if (!(info->name = strdup(name))) {
2506 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2511 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2513 dbus_message_iter_next(&sub);
2515 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2516 streq(name, "Documentation")) {
2518 DBusMessageIter sub;
2520 dbus_message_iter_recurse(iter, &sub);
2521 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2525 dbus_message_iter_get_basic(&sub, &s);
2527 l = strv_append(i->documentation, s);
2531 strv_free(i->documentation);
2532 i->documentation = l;
2534 dbus_message_iter_next(&sub);
2541 case DBUS_TYPE_STRUCT: {
2543 if (streq(name, "LoadError")) {
2544 DBusMessageIter sub;
2545 const char *n, *message;
2548 dbus_message_iter_recurse(iter, &sub);
2550 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2554 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2558 if (!isempty(message))
2559 i->load_error = message;
2569 static int print_property(const char *name, DBusMessageIter *iter) {
2573 /* This is a low-level property printer, see
2574 * print_status_info() for the nicer output */
2576 if (arg_property && !strv_find(arg_property, name))
2579 switch (dbus_message_iter_get_arg_type(iter)) {
2581 case DBUS_TYPE_STRUCT: {
2582 DBusMessageIter sub;
2583 dbus_message_iter_recurse(iter, &sub);
2585 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2588 dbus_message_iter_get_basic(&sub, &u);
2591 printf("%s=%u\n", name, (unsigned) u);
2593 printf("%s=\n", name);
2596 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2599 dbus_message_iter_get_basic(&sub, &s);
2601 if (arg_all || s[0])
2602 printf("%s=%s\n", name, s);
2605 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
2606 const char *a = NULL, *b = NULL;
2608 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
2609 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
2611 if (arg_all || !isempty(a) || !isempty(b))
2612 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
2620 case DBUS_TYPE_ARRAY:
2622 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2623 DBusMessageIter sub, sub2;
2625 dbus_message_iter_recurse(iter, &sub);
2626 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2630 dbus_message_iter_recurse(&sub, &sub2);
2632 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2633 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2634 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2636 dbus_message_iter_next(&sub);
2641 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2642 DBusMessageIter sub, sub2;
2644 dbus_message_iter_recurse(iter, &sub);
2645 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2646 const char *type, *path;
2648 dbus_message_iter_recurse(&sub, &sub2);
2650 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2651 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2652 printf("%s=%s\n", type, path);
2654 dbus_message_iter_next(&sub);
2659 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2660 DBusMessageIter sub, sub2;
2662 dbus_message_iter_recurse(iter, &sub);
2663 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2665 uint64_t value, next_elapse;
2667 dbus_message_iter_recurse(&sub, &sub2);
2669 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2670 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2671 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2672 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2674 printf("%s={ value=%s ; next_elapse=%s }\n",
2676 format_timespan(timespan1, sizeof(timespan1), value),
2677 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2680 dbus_message_iter_next(&sub);
2685 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
2686 DBusMessageIter sub, sub2;
2688 dbus_message_iter_recurse(iter, &sub);
2689 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2690 const char *controller, *attr, *value;
2692 dbus_message_iter_recurse(&sub, &sub2);
2694 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
2695 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
2696 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
2698 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
2704 dbus_message_iter_next(&sub);
2709 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2710 DBusMessageIter sub;
2712 dbus_message_iter_recurse(iter, &sub);
2713 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2714 ExecStatusInfo info;
2717 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2718 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2721 t = strv_join(info.argv, " ");
2723 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2727 yes_no(info.ignore),
2728 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2729 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2730 (unsigned) info. pid,
2731 sigchld_code_to_string(info.code),
2733 info.code == CLD_EXITED ? "" : "/",
2734 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2740 strv_free(info.argv);
2742 dbus_message_iter_next(&sub);
2751 if (generic_print_property(name, iter, arg_all) > 0)
2755 printf("%s=[unprintable]\n", name);
2760 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2761 DBusMessage *reply = NULL;
2762 const char *interface = "";
2764 DBusMessageIter iter, sub, sub2, sub3;
2765 UnitStatusInfo info;
2773 r = bus_method_call_with_reply (
2775 "org.freedesktop.systemd1",
2777 "org.freedesktop.DBus.Properties",
2781 DBUS_TYPE_STRING, &interface,
2786 if (!dbus_message_iter_init(reply, &iter) ||
2787 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2788 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2789 log_error("Failed to parse reply.");
2794 dbus_message_iter_recurse(&iter, &sub);
2801 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2804 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2805 log_error("Failed to parse reply.");
2810 dbus_message_iter_recurse(&sub, &sub2);
2812 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2813 log_error("Failed to parse reply.");
2818 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2819 log_error("Failed to parse reply.");
2824 dbus_message_iter_recurse(&sub2, &sub3);
2826 if (show_properties)
2827 r = print_property(name, &sub3);
2829 r = status_property(name, &sub3, &info);
2832 log_error("Failed to parse reply.");
2837 dbus_message_iter_next(&sub);
2842 if (!show_properties) {
2843 if (streq(verb, "help"))
2844 show_unit_help(&info);
2846 print_status_info(&info);
2849 strv_free(info.documentation);
2851 if (!streq_ptr(info.active_state, "active") &&
2852 !streq_ptr(info.active_state, "reloading") &&
2853 streq(verb, "status"))
2854 /* According to LSB: "program not running" */
2857 while ((p = info.exec)) {
2858 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2859 exec_status_info_free(p);
2864 dbus_message_unref(reply);
2869 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
2870 DBusMessage *reply = NULL;
2871 const char *path = NULL;
2875 dbus_error_init(&error);
2877 r = bus_method_call_with_reply (
2879 "org.freedesktop.systemd1",
2880 "/org/freedesktop/systemd1",
2881 "org.freedesktop.systemd1.Manager",
2885 DBUS_TYPE_UINT32, &pid,
2890 if (!dbus_message_get_args(reply, &error,
2891 DBUS_TYPE_OBJECT_PATH, &path,
2892 DBUS_TYPE_INVALID)) {
2893 log_error("Failed to parse reply: %s", bus_error_message(&error));
2898 r = show_one(verb, bus, path, false, new_line);
2902 dbus_message_unref(reply);
2904 dbus_error_free(&error);
2909 static int show(DBusConnection *bus, char **args) {
2911 bool show_properties, new_line = false;
2917 show_properties = streq(args[0], "show");
2919 if (show_properties)
2920 pager_open_if_enabled();
2922 if (show_properties && strv_length(args) <= 1) {
2923 /* If not argument is specified inspect the manager
2926 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2929 STRV_FOREACH(name, args+1) {
2932 if (safe_atou32(*name, &id) < 0) {
2934 /* Interpret as unit name */
2936 n = unit_name_mangle(*name);
2937 p = unit_dbus_path_from_name(n ? n : *name);
2942 r = show_one(args[0], bus, p, show_properties, &new_line);
2948 } else if (show_properties) {
2950 /* Interpret as job id */
2953 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
2956 r = show_one(args[0], bus, p, show_properties, &new_line);
2964 /* Interpret as PID */
2966 r = show_one_by_pid(args[0], bus, id, &new_line);
2975 static int dump(DBusConnection *bus, char **args) {
2976 DBusMessage *reply = NULL;
2981 dbus_error_init(&error);
2983 pager_open_if_enabled();
2985 r = bus_method_call_with_reply (
2987 "org.freedesktop.systemd1",
2988 "/org/freedesktop/systemd1",
2989 "org.freedesktop.systemd1.Manager",
2997 if (!dbus_message_get_args(reply, &error,
2998 DBUS_TYPE_STRING, &text,
2999 DBUS_TYPE_INVALID)) {
3000 log_error("Failed to parse reply: %s", bus_error_message(&error));
3005 fputs(text, stdout);
3009 dbus_message_unref(reply);
3011 dbus_error_free(&error);
3016 static int snapshot(DBusConnection *bus, char **args) {
3017 DBusMessage *reply = NULL;
3020 dbus_bool_t cleanup = FALSE;
3021 DBusMessageIter iter, sub;
3023 *name = "", *path, *id,
3024 *interface = "org.freedesktop.systemd1.Unit",
3028 dbus_error_init(&error);
3030 if (strv_length(args) > 1)
3033 n = unit_name_mangle(name);
3034 r = bus_method_call_with_reply (
3036 "org.freedesktop.systemd1",
3037 "/org/freedesktop/systemd1",
3038 "org.freedesktop.systemd1.Manager",
3042 DBUS_TYPE_STRING, n ? (const char**) &n : &name,
3043 DBUS_TYPE_BOOLEAN, &cleanup,
3049 if (!dbus_message_get_args(reply, &error,
3050 DBUS_TYPE_OBJECT_PATH, &path,
3051 DBUS_TYPE_INVALID)) {
3052 log_error("Failed to parse reply: %s", bus_error_message(&error));
3057 dbus_message_unref(reply);
3058 r = bus_method_call_with_reply (
3060 "org.freedesktop.systemd1",
3062 "org.freedesktop.DBus.Properties",
3066 DBUS_TYPE_STRING, &interface,
3067 DBUS_TYPE_STRING, &property,
3072 if (!dbus_message_iter_init(reply, &iter) ||
3073 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3074 log_error("Failed to parse reply.");
3079 dbus_message_iter_recurse(&iter, &sub);
3081 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3082 log_error("Failed to parse reply.");
3087 dbus_message_iter_get_basic(&sub, &id);
3094 dbus_message_unref(reply);
3096 dbus_error_free(&error);
3101 static int delete_snapshot(DBusConnection *bus, char **args) {
3102 DBusMessage *reply = NULL;
3109 dbus_error_init(&error);
3111 STRV_FOREACH(name, args+1) {
3112 const char *path = NULL;
3115 n = unit_name_mangle(*name);
3116 r = bus_method_call_with_reply (
3118 "org.freedesktop.systemd1",
3119 "/org/freedesktop/systemd1",
3120 "org.freedesktop.systemd1.Manager",
3124 DBUS_TYPE_STRING, n ? &n : name,
3130 if (!dbus_message_get_args(reply, &error,
3131 DBUS_TYPE_OBJECT_PATH, &path,
3132 DBUS_TYPE_INVALID)) {
3133 log_error("Failed to parse reply: %s", bus_error_message(&error));
3135 dbus_message_unref(reply);
3136 dbus_error_free(&error);
3139 dbus_message_unref(reply);
3141 r = bus_method_call_with_reply (
3143 "org.freedesktop.systemd1",
3145 "org.freedesktop.systemd1.Snapshot",
3158 static int daemon_reload(DBusConnection *bus, char **args) {
3163 if (arg_action == ACTION_RELOAD)
3165 else if (arg_action == ACTION_REEXEC)
3166 method = "Reexecute";
3168 assert(arg_action == ACTION_SYSTEMCTL);
3171 streq(args[0], "clear-jobs") ||
3172 streq(args[0], "cancel") ? "ClearJobs" :
3173 streq(args[0], "daemon-reexec") ? "Reexecute" :
3174 streq(args[0], "reset-failed") ? "ResetFailed" :
3175 streq(args[0], "halt") ? "Halt" :
3176 streq(args[0], "poweroff") ? "PowerOff" :
3177 streq(args[0], "reboot") ? "Reboot" :
3178 streq(args[0], "kexec") ? "KExec" :
3179 streq(args[0], "exit") ? "Exit" :
3180 /* "daemon-reload" */ "Reload";
3183 r = bus_method_call_with_reply (
3185 "org.freedesktop.systemd1",
3186 "/org/freedesktop/systemd1",
3187 "org.freedesktop.systemd1.Manager",
3193 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
3194 /* There's always a fallback possible for
3195 * legacy actions. */
3197 else if (r == -ETIMEDOUT && streq(method, "Reexecute"))
3198 /* On reexecution, we expect a disconnect, not
3202 log_error("Failed to issue method call: %s", bus_error_message(&error));
3203 dbus_error_free(&error);
3208 static int reset_failed(DBusConnection *bus, char **args) {
3212 if (strv_length(args) <= 1)
3213 return daemon_reload(bus, args);
3215 STRV_FOREACH(name, args+1) {
3216 n = unit_name_mangle(*name);
3217 r = bus_method_call_with_reply (
3219 "org.freedesktop.systemd1",
3220 "/org/freedesktop/systemd1",
3221 "org.freedesktop.systemd1.Manager",
3225 DBUS_TYPE_STRING, n ? &n : name,
3236 static int show_enviroment(DBusConnection *bus, char **args) {
3237 DBusMessage *reply = NULL;
3238 DBusMessageIter iter, sub, sub2;
3241 *interface = "org.freedesktop.systemd1.Manager",
3242 *property = "Environment";
3244 pager_open_if_enabled();
3246 r = bus_method_call_with_reply (
3248 "org.freedesktop.systemd1",
3249 "/org/freedesktop/systemd1",
3250 "org.freedesktop.DBus.Properties",
3254 DBUS_TYPE_STRING, &interface,
3255 DBUS_TYPE_STRING, &property,
3260 if (!dbus_message_iter_init(reply, &iter) ||
3261 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3262 log_error("Failed to parse reply.");
3267 dbus_message_iter_recurse(&iter, &sub);
3269 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3270 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3271 log_error("Failed to parse reply.");
3276 dbus_message_iter_recurse(&sub, &sub2);
3278 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3281 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3282 log_error("Failed to parse reply.");
3287 dbus_message_iter_get_basic(&sub2, &text);
3288 printf("%s\n", text);
3290 dbus_message_iter_next(&sub2);
3297 dbus_message_unref(reply);
3302 static int switch_root(DBusConnection *bus, char **args) {
3304 const char *root, *init;
3306 l = strv_length(args);
3307 if (l < 2 || l > 3) {
3308 log_error("Wrong number of arguments.");
3313 init = l >= 3 ? args[2] : "";
3315 return bus_method_call_with_reply (
3317 "org.freedesktop.systemd1",
3318 "/org/freedesktop/systemd1",
3319 "org.freedesktop.systemd1.Manager",
3323 DBUS_TYPE_STRING, &root,
3324 DBUS_TYPE_STRING, &init,
3328 static int set_environment(DBusConnection *bus, char **args) {
3329 DBusMessage *m = NULL, *reply = NULL;
3333 DBusMessageIter iter, sub;
3336 dbus_error_init(&error);
3338 method = streq(args[0], "set-environment")
3340 : "UnsetEnvironment";
3342 if (!(m = dbus_message_new_method_call(
3343 "org.freedesktop.systemd1",
3344 "/org/freedesktop/systemd1",
3345 "org.freedesktop.systemd1.Manager",
3348 log_error("Could not allocate message.");
3352 dbus_message_iter_init_append(m, &iter);
3354 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3355 log_error("Could not append arguments to message.");
3360 STRV_FOREACH(name, args+1)
3361 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, name)) {
3362 log_error("Could not append arguments to message.");
3367 if (!dbus_message_iter_close_container(&iter, &sub)) {
3368 log_error("Could not append arguments to message.");
3373 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3374 log_error("Failed to issue method call: %s", bus_error_message(&error));
3383 dbus_message_unref(m);
3386 dbus_message_unref(reply);
3388 dbus_error_free(&error);
3393 static int enable_sysv_units(char **args) {
3396 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_ALTLINUX) || defined(TARGET_MAGEIA))
3397 const char *verb = args[0];
3398 unsigned f = 1, t = 1;
3401 if (arg_scope != UNIT_FILE_SYSTEM)
3404 if (!streq(verb, "enable") &&
3405 !streq(verb, "disable") &&
3406 !streq(verb, "is-enabled"))
3409 /* Processes all SysV units, and reshuffles the array so that
3410 * afterwards only the native units remain */
3413 r = lookup_paths_init(&paths, MANAGER_SYSTEM, false, NULL, NULL, NULL);
3418 for (f = 1; args[f]; f++) {
3421 bool found_native = false, found_sysv;
3423 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3424 char **k, *l, *q = NULL;
3431 if (!endswith(name, ".service"))
3434 if (path_is_absolute(name))
3437 STRV_FOREACH(k, paths.unit_path) {
3440 if (!isempty(arg_root))
3441 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3443 asprintf(&p, "%s/%s", *k, name);
3450 found_native = access(p, F_OK) >= 0;
3461 if (!isempty(arg_root))
3462 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3464 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3470 p[strlen(p) - sizeof(".service") + 1] = 0;
3471 found_sysv = access(p, F_OK) >= 0;
3478 /* Mark this entry, so that we don't try enabling it as native unit */
3479 args[f] = (char*) "";
3481 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
3483 if (!isempty(arg_root))
3484 argv[c++] = q = strappend("--root=", arg_root);
3486 argv[c++] = path_get_file_name(p);
3488 streq(verb, "enable") ? "on" :
3489 streq(verb, "disable") ? "off" : "--level=5";
3492 l = strv_join((char**)argv, " ");
3500 log_info("Executing %s", l);
3505 log_error("Failed to fork: %m");
3510 } else if (pid == 0) {
3513 execv(argv[0], (char**) argv);
3514 _exit(EXIT_FAILURE);
3520 j = wait_for_terminate(pid, &status);
3522 log_error("Failed to wait for child: %s", strerror(-r));
3527 if (status.si_code == CLD_EXITED) {
3528 if (streq(verb, "is-enabled")) {
3529 if (status.si_status == 0) {
3538 } else if (status.si_status != 0) {
3549 lookup_paths_free(&paths);
3551 /* Drop all SysV units */
3552 for (f = 1, t = 1; args[f]; f++) {
3554 if (isempty(args[f]))
3557 args[t++] = args[f];
3566 static int mangle_names(char **original_names, char ***mangled_names) {
3567 char **i, **l, **name;
3569 l = new(char*, strv_length(original_names) + 1);
3574 STRV_FOREACH(name, original_names) {
3575 *i = unit_name_mangle(*name);
3590 static int enable_unit(DBusConnection *bus, char **args) {
3591 const char *verb = args[0];
3592 UnitFileChange *changes = NULL;
3593 unsigned n_changes = 0, i;
3594 int carries_install_info = -1;
3595 DBusMessage *m = NULL, *reply = NULL;
3598 char **mangled_names = NULL;
3600 r = enable_sysv_units(args);
3607 dbus_error_init(&error);
3609 if (!bus || avoid_bus()) {
3610 if (streq(verb, "enable")) {
3611 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3612 carries_install_info = r;
3613 } else if (streq(verb, "disable"))
3614 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3615 else if (streq(verb, "reenable")) {
3616 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3617 carries_install_info = r;
3618 } else if (streq(verb, "link"))
3619 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3620 else if (streq(verb, "preset")) {
3621 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3622 carries_install_info = r;
3623 } else if (streq(verb, "mask"))
3624 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3625 else if (streq(verb, "unmask"))
3626 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3628 assert_not_reached("Unknown verb");
3631 log_error("Operation failed: %s", strerror(-r));
3636 for (i = 0; i < n_changes; i++) {
3637 if (changes[i].type == UNIT_FILE_SYMLINK)
3638 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
3640 log_info("rm '%s'", changes[i].path);
3646 bool send_force = true, expect_carries_install_info = false;
3648 DBusMessageIter iter, sub, sub2;
3650 if (streq(verb, "enable")) {
3651 method = "EnableUnitFiles";
3652 expect_carries_install_info = true;
3653 } else if (streq(verb, "disable")) {
3654 method = "DisableUnitFiles";
3656 } else if (streq(verb, "reenable")) {
3657 method = "ReenableUnitFiles";
3658 expect_carries_install_info = true;
3659 } else if (streq(verb, "link"))
3660 method = "LinkUnitFiles";
3661 else if (streq(verb, "preset")) {
3662 method = "PresetUnitFiles";
3663 expect_carries_install_info = true;
3664 } else if (streq(verb, "mask"))
3665 method = "MaskUnitFiles";
3666 else if (streq(verb, "unmask")) {
3667 method = "UnmaskUnitFiles";
3670 assert_not_reached("Unknown verb");
3672 m = dbus_message_new_method_call(
3673 "org.freedesktop.systemd1",
3674 "/org/freedesktop/systemd1",
3675 "org.freedesktop.systemd1.Manager",
3682 dbus_message_iter_init_append(m, &iter);
3684 r = mangle_names(args+1, &mangled_names);
3688 r = bus_append_strv_iter(&iter, mangled_names);
3690 log_error("Failed to append unit files.");
3695 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
3696 log_error("Failed to append runtime boolean.");
3704 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
3705 log_error("Failed to append force boolean.");
3711 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3713 log_error("Failed to issue method call: %s", bus_error_message(&error));
3718 if (!dbus_message_iter_init(reply, &iter)) {
3719 log_error("Failed to initialize iterator.");
3723 if (expect_carries_install_info) {
3724 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
3726 log_error("Failed to parse reply.");
3730 carries_install_info = b;
3733 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3734 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
3735 log_error("Failed to parse reply.");
3740 dbus_message_iter_recurse(&iter, &sub);
3741 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3742 const char *type, *path, *source;
3744 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
3745 log_error("Failed to parse reply.");
3750 dbus_message_iter_recurse(&sub, &sub2);
3752 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
3753 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
3754 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
3755 log_error("Failed to parse reply.");
3761 if (streq(type, "symlink"))
3762 log_info("ln -s '%s' '%s'", source, path);
3764 log_info("rm '%s'", path);
3767 dbus_message_iter_next(&sub);
3770 /* Try to reload if enabeld */
3772 r = daemon_reload(bus, args);
3775 if (carries_install_info == 0)
3776 log_warning("The unit files have no [Install] section. They are not meant to be enabled using systemctl.");
3780 dbus_message_unref(m);
3783 dbus_message_unref(reply);
3785 unit_file_changes_free(changes, n_changes);
3787 dbus_error_free(&error);
3789 strv_free(mangled_names);
3794 static int unit_is_enabled(DBusConnection *bus, char **args) {
3797 DBusMessage *reply = NULL;
3801 dbus_error_init(&error);
3803 r = enable_sysv_units(args);
3809 if (!bus || avoid_bus()) {
3811 STRV_FOREACH(name, args+1) {
3812 UnitFileState state;
3814 state = unit_file_get_state(arg_scope, arg_root, *name);
3820 if (state == UNIT_FILE_ENABLED ||
3821 state == UNIT_FILE_ENABLED_RUNTIME ||
3822 state == UNIT_FILE_STATIC)
3826 puts(unit_file_state_to_string(state));
3830 STRV_FOREACH(name, args+1) {
3833 r = bus_method_call_with_reply (
3835 "org.freedesktop.systemd1",
3836 "/org/freedesktop/systemd1",
3837 "org.freedesktop.systemd1.Manager",
3841 DBUS_TYPE_STRING, name,
3846 if (!dbus_message_get_args(reply, &error,
3847 DBUS_TYPE_STRING, &s,
3848 DBUS_TYPE_INVALID)) {
3849 log_error("Failed to parse reply: %s", bus_error_message(&error));
3854 dbus_message_unref(reply);
3857 if (streq(s, "enabled") ||
3858 streq(s, "enabled-runtime") ||
3867 r = enabled ? 0 : 1;
3871 dbus_message_unref(reply);
3873 dbus_error_free(&error);
3877 static int systemctl_help(void) {
3879 pager_open_if_enabled();
3881 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3882 "Query or send control commands to the systemd manager.\n\n"
3883 " -h --help Show this help\n"
3884 " --version Show package version\n"
3885 " -t --type=TYPE List only units of a particular type\n"
3886 " -p --property=NAME Show only properties by this name\n"
3887 " -a --all Show all units/properties, including dead/empty ones\n"
3888 " --failed Show only failed units\n"
3889 " --full Don't ellipsize unit names on output\n"
3890 " --fail When queueing a new job, fail if conflicting jobs are\n"
3892 " --ignore-dependencies\n"
3893 " When queueing a new job, ignore all its dependencies\n"
3894 " --kill-who=WHO Who to send signal to\n"
3895 " -s --signal=SIGNAL Which signal to send\n"
3896 " -H --host=[USER@]HOST\n"
3897 " Show information for remote host\n"
3898 " -P --privileged Acquire privileges before execution\n"
3899 " -q --quiet Suppress output\n"
3900 " --no-block Do not wait until operation finished\n"
3901 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3902 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3904 " --no-legend Do not print a legend (column headers and hints)\n"
3905 " --no-pager Do not pipe output into a pager\n"
3906 " --no-ask-password\n"
3907 " Do not ask for system passwords\n"
3908 " --order When generating graph for dot, show only order\n"
3909 " --require When generating graph for dot, show only requirement\n"
3910 " --system Connect to system manager\n"
3911 " --user Connect to user service manager\n"
3912 " --global Enable/disable unit files globally\n"
3913 " -f --force When enabling unit files, override existing symlinks\n"
3914 " When shutting down, execute action immediately\n"
3915 " --root=PATH Enable unit files in the specified root directory\n"
3916 " --runtime Enable unit files only temporarily until next reboot\n"
3917 " -n --lines=INTEGER Journal entries to show\n"
3918 " --follow Follow journal\n"
3919 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
3920 " verbose, export, json, json-pretty, cat)\n\n"
3922 " list-units List loaded units\n"
3923 " start [NAME...] Start (activate) one or more units\n"
3924 " stop [NAME...] Stop (deactivate) one or more units\n"
3925 " reload [NAME...] Reload one or more units\n"
3926 " restart [NAME...] Start or restart one or more units\n"
3927 " try-restart [NAME...] Restart one or more units if active\n"
3928 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3929 " otherwise start or restart\n"
3930 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3931 " otherwise restart if active\n"
3932 " isolate [NAME] Start one unit and stop all others\n"
3933 " kill [NAME...] Send signal to processes of a unit\n"
3934 " is-active [NAME...] Check whether units are active\n"
3935 " status [NAME...|PID...] Show runtime status of one or more units\n"
3936 " show [NAME...|JOB...] Show properties of one or more\n"
3937 " units/jobs or the manager\n"
3938 " help [NAME...|PID...] Show manual for one or more units\n"
3939 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3941 " load [NAME...] Load one or more units\n\n"
3942 "Unit File Commands:\n"
3943 " list-unit-files List installed unit files\n"
3944 " enable [NAME...] Enable one or more unit files\n"
3945 " disable [NAME...] Disable one or more unit files\n"
3946 " reenable [NAME...] Reenable one or more unit files\n"
3947 " preset [NAME...] Enable/disable one or more unit files\n"
3948 " based on preset configuration\n"
3949 " mask [NAME...] Mask one or more units\n"
3950 " unmask [NAME...] Unmask one or more units\n"
3951 " link [PATH...] Link one or more units files into\n"
3952 " the search path\n"
3953 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
3955 " list-jobs List jobs\n"
3956 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
3957 "Status Commands:\n"
3958 " dump Dump server status\n"
3959 " dot Dump dependency graph for dot(1)\n\n"
3960 "Snapshot Commands:\n"
3961 " snapshot [NAME] Create a snapshot\n"
3962 " delete [NAME...] Remove one or more snapshots\n\n"
3963 "Environment Commands:\n"
3964 " show-environment Dump environment\n"
3965 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3966 " unset-environment [NAME...] Unset one or more environment variables\n\n"
3967 "Manager Lifecycle Commands:\n"
3968 " daemon-reload Reload systemd manager configuration\n"
3969 " daemon-reexec Reexecute systemd manager\n\n"
3970 "System Commands:\n"
3971 " default Enter system default mode\n"
3972 " rescue Enter system rescue mode\n"
3973 " emergency Enter system emergency mode\n"
3974 " halt Shut down and halt the system\n"
3975 " poweroff Shut down and power-off the system\n"
3976 " reboot Shut down and reboot the system\n"
3977 " kexec Shut down and reboot the system with kexec\n"
3978 " exit Request user instance exit\n"
3979 " switch-root [ROOT] [INIT] Change to a different root file system\n"
3980 " suspend Suspend the system\n"
3981 " hibernate Hibernate the system\n",
3982 program_invocation_short_name);
3987 static int halt_help(void) {
3989 printf("%s [OPTIONS...]\n\n"
3990 "%s the system.\n\n"
3991 " --help Show this help\n"
3992 " --halt Halt the machine\n"
3993 " -p --poweroff Switch off the machine\n"
3994 " --reboot Reboot the machine\n"
3995 " -f --force Force immediate halt/power-off/reboot\n"
3996 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3997 " -d --no-wtmp Don't write wtmp record\n"
3998 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3999 program_invocation_short_name,
4000 arg_action == ACTION_REBOOT ? "Reboot" :
4001 arg_action == ACTION_POWEROFF ? "Power off" :
4007 static int shutdown_help(void) {
4009 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4010 "Shut down the system.\n\n"
4011 " --help Show this help\n"
4012 " -H --halt Halt the machine\n"
4013 " -P --poweroff Power-off the machine\n"
4014 " -r --reboot Reboot the machine\n"
4015 " -h Equivalent to --poweroff, overridden by --halt\n"
4016 " -k Don't halt/power-off/reboot, just send warnings\n"
4017 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4018 " -c Cancel a pending shutdown\n",
4019 program_invocation_short_name);
4024 static int telinit_help(void) {
4026 printf("%s [OPTIONS...] {COMMAND}\n\n"
4027 "Send control commands to the init daemon.\n\n"
4028 " --help Show this help\n"
4029 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4031 " 0 Power-off the machine\n"
4032 " 6 Reboot the machine\n"
4033 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4034 " 1, s, S Enter rescue mode\n"
4035 " q, Q Reload init daemon configuration\n"
4036 " u, U Reexecute init daemon\n",
4037 program_invocation_short_name);
4042 static int runlevel_help(void) {
4044 printf("%s [OPTIONS...]\n\n"
4045 "Prints the previous and current runlevel of the init system.\n\n"
4046 " --help Show this help\n",
4047 program_invocation_short_name);
4052 static int systemctl_parse_argv(int argc, char *argv[]) {
4056 ARG_IGNORE_DEPENDENCIES,
4071 ARG_NO_ASK_PASSWORD,
4078 static const struct option options[] = {
4079 { "help", no_argument, NULL, 'h' },
4080 { "version", no_argument, NULL, ARG_VERSION },
4081 { "type", required_argument, NULL, 't' },
4082 { "property", required_argument, NULL, 'p' },
4083 { "all", no_argument, NULL, 'a' },
4084 { "failed", no_argument, NULL, ARG_FAILED },
4085 { "full", no_argument, NULL, ARG_FULL },
4086 { "fail", no_argument, NULL, ARG_FAIL },
4087 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4088 { "user", no_argument, NULL, ARG_USER },
4089 { "system", no_argument, NULL, ARG_SYSTEM },
4090 { "global", no_argument, NULL, ARG_GLOBAL },
4091 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4092 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4093 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4094 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4095 { "quiet", no_argument, NULL, 'q' },
4096 { "order", no_argument, NULL, ARG_ORDER },
4097 { "require", no_argument, NULL, ARG_REQUIRE },
4098 { "root", required_argument, NULL, ARG_ROOT },
4099 { "force", no_argument, NULL, ARG_FORCE },
4100 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4101 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4102 { "signal", required_argument, NULL, 's' },
4103 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4104 { "host", required_argument, NULL, 'H' },
4105 { "privileged",no_argument, NULL, 'P' },
4106 { "runtime", no_argument, NULL, ARG_RUNTIME },
4107 { "lines", required_argument, NULL, 'n' },
4108 { "follow", no_argument, NULL, ARG_FOLLOW },
4109 { "output", required_argument, NULL, 'o' },
4110 { NULL, 0, NULL, 0 }
4118 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4127 puts(PACKAGE_STRING);
4129 puts(SYSTEMD_FEATURES);
4133 if (unit_type_from_string(optarg) >= 0) {
4137 if (unit_load_state_from_string(optarg) >= 0) {
4138 arg_load_state = optarg;
4141 log_error("Unkown unit type or load state '%s'.",
4147 if (!(l = strv_append(arg_property, optarg)))
4150 strv_free(arg_property);
4153 /* If the user asked for a particular
4154 * property, show it to him, even if it is
4165 arg_job_mode = "fail";
4168 case ARG_IGNORE_DEPENDENCIES:
4169 arg_job_mode = "ignore-dependencies";
4173 arg_scope = UNIT_FILE_USER;
4177 arg_scope = UNIT_FILE_SYSTEM;
4181 arg_scope = UNIT_FILE_GLOBAL;
4185 arg_no_block = true;
4189 arg_no_legend = true;
4193 arg_no_pager = true;
4201 arg_dot = DOT_ORDER;
4205 arg_dot = DOT_REQUIRE;
4233 /* -f is short for both --follow and --force! */
4239 arg_no_reload = true;
4243 arg_kill_who = optarg;
4247 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4248 log_error("Failed to parse signal string %s.", optarg);
4253 case ARG_NO_ASK_PASSWORD:
4254 arg_ask_password = false;
4258 arg_transport = TRANSPORT_POLKIT;
4262 arg_transport = TRANSPORT_SSH;
4271 if (safe_atou(optarg, &arg_lines) < 0) {
4272 log_error("Failed to parse lines '%s'", optarg);
4278 arg_output = output_mode_from_string(optarg);
4279 if (arg_output < 0) {
4280 log_error("Unknown output '%s'.", optarg);
4289 log_error("Unknown option code '%c'.", c);
4294 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4295 log_error("Cannot access user instance remotely.");
4302 static int halt_parse_argv(int argc, char *argv[]) {
4311 static const struct option options[] = {
4312 { "help", no_argument, NULL, ARG_HELP },
4313 { "halt", no_argument, NULL, ARG_HALT },
4314 { "poweroff", no_argument, NULL, 'p' },
4315 { "reboot", no_argument, NULL, ARG_REBOOT },
4316 { "force", no_argument, NULL, 'f' },
4317 { "wtmp-only", no_argument, NULL, 'w' },
4318 { "no-wtmp", no_argument, NULL, 'd' },
4319 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4320 { NULL, 0, NULL, 0 }
4328 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4329 if (runlevel == '0' || runlevel == '6')
4332 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4340 arg_action = ACTION_HALT;
4344 if (arg_action != ACTION_REBOOT)
4345 arg_action = ACTION_POWEROFF;
4349 arg_action = ACTION_REBOOT;
4371 /* Compatibility nops */
4378 log_error("Unknown option code '%c'.", c);
4383 if (optind < argc) {
4384 log_error("Too many arguments.");
4391 static int parse_time_spec(const char *t, usec_t *_u) {
4395 if (streq(t, "now"))
4397 else if (!strchr(t, ':')) {
4400 if (safe_atou64(t, &u) < 0)
4403 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4412 hour = strtol(t, &e, 10);
4413 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4416 minute = strtol(e+1, &e, 10);
4417 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4420 n = now(CLOCK_REALTIME);
4421 s = (time_t) (n / USEC_PER_SEC);
4424 assert_se(localtime_r(&s, &tm));
4426 tm.tm_hour = (int) hour;
4427 tm.tm_min = (int) minute;
4430 assert_se(s = mktime(&tm));
4432 *_u = (usec_t) s * USEC_PER_SEC;
4435 *_u += USEC_PER_DAY;
4441 static int shutdown_parse_argv(int argc, char *argv[]) {
4448 static const struct option options[] = {
4449 { "help", no_argument, NULL, ARG_HELP },
4450 { "halt", no_argument, NULL, 'H' },
4451 { "poweroff", no_argument, NULL, 'P' },
4452 { "reboot", no_argument, NULL, 'r' },
4453 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4454 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4455 { NULL, 0, NULL, 0 }
4463 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4471 arg_action = ACTION_HALT;
4475 arg_action = ACTION_POWEROFF;
4480 arg_action = ACTION_KEXEC;
4482 arg_action = ACTION_REBOOT;
4486 arg_action = ACTION_KEXEC;
4490 if (arg_action != ACTION_HALT)
4491 arg_action = ACTION_POWEROFF;
4504 /* Compatibility nops */
4508 arg_action = ACTION_CANCEL_SHUTDOWN;
4515 log_error("Unknown option code '%c'.", c);
4520 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
4521 r = parse_time_spec(argv[optind], &arg_when);
4523 log_error("Failed to parse time specification: %s", argv[optind]);
4527 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4529 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
4530 /* No time argument for shutdown cancel */
4531 arg_wall = argv + optind;
4532 else if (argc > optind + 1)
4533 /* We skip the time argument */
4534 arg_wall = argv + optind + 1;
4541 static int telinit_parse_argv(int argc, char *argv[]) {
4548 static const struct option options[] = {
4549 { "help", no_argument, NULL, ARG_HELP },
4550 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4551 { NULL, 0, NULL, 0 }
4554 static const struct {
4558 { '0', ACTION_POWEROFF },
4559 { '6', ACTION_REBOOT },
4560 { '1', ACTION_RESCUE },
4561 { '2', ACTION_RUNLEVEL2 },
4562 { '3', ACTION_RUNLEVEL3 },
4563 { '4', ACTION_RUNLEVEL4 },
4564 { '5', ACTION_RUNLEVEL5 },
4565 { 's', ACTION_RESCUE },
4566 { 'S', ACTION_RESCUE },
4567 { 'q', ACTION_RELOAD },
4568 { 'Q', ACTION_RELOAD },
4569 { 'u', ACTION_REEXEC },
4570 { 'U', ACTION_REEXEC }
4579 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4594 log_error("Unknown option code '%c'.", c);
4599 if (optind >= argc) {
4604 if (optind + 1 < argc) {
4605 log_error("Too many arguments.");
4609 if (strlen(argv[optind]) != 1) {
4610 log_error("Expected single character argument.");
4614 for (i = 0; i < ELEMENTSOF(table); i++)
4615 if (table[i].from == argv[optind][0])
4618 if (i >= ELEMENTSOF(table)) {
4619 log_error("Unknown command '%s'.", argv[optind]);
4623 arg_action = table[i].to;
4630 static int runlevel_parse_argv(int argc, char *argv[]) {
4636 static const struct option options[] = {
4637 { "help", no_argument, NULL, ARG_HELP },
4638 { NULL, 0, NULL, 0 }
4646 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4657 log_error("Unknown option code '%c'.", c);
4662 if (optind < argc) {
4663 log_error("Too many arguments.");
4670 static int parse_argv(int argc, char *argv[]) {
4674 if (program_invocation_short_name) {
4676 if (strstr(program_invocation_short_name, "halt")) {
4677 arg_action = ACTION_HALT;
4678 return halt_parse_argv(argc, argv);
4679 } else if (strstr(program_invocation_short_name, "poweroff")) {
4680 arg_action = ACTION_POWEROFF;
4681 return halt_parse_argv(argc, argv);
4682 } else if (strstr(program_invocation_short_name, "reboot")) {
4684 arg_action = ACTION_KEXEC;
4686 arg_action = ACTION_REBOOT;
4687 return halt_parse_argv(argc, argv);
4688 } else if (strstr(program_invocation_short_name, "shutdown")) {
4689 arg_action = ACTION_POWEROFF;
4690 return shutdown_parse_argv(argc, argv);
4691 } else if (strstr(program_invocation_short_name, "init")) {
4693 if (sd_booted() > 0) {
4694 arg_action = ACTION_INVALID;
4695 return telinit_parse_argv(argc, argv);
4697 /* Hmm, so some other init system is
4698 * running, we need to forward this
4699 * request to it. For now we simply
4700 * guess that it is Upstart. */
4702 execv("/lib/upstart/telinit", argv);
4704 log_error("Couldn't find an alternative telinit implementation to spawn.");
4708 } else if (strstr(program_invocation_short_name, "runlevel")) {
4709 arg_action = ACTION_RUNLEVEL;
4710 return runlevel_parse_argv(argc, argv);
4714 arg_action = ACTION_SYSTEMCTL;
4715 return systemctl_parse_argv(argc, argv);
4718 static int action_to_runlevel(void) {
4720 static const char table[_ACTION_MAX] = {
4721 [ACTION_HALT] = '0',
4722 [ACTION_POWEROFF] = '0',
4723 [ACTION_REBOOT] = '6',
4724 [ACTION_RUNLEVEL2] = '2',
4725 [ACTION_RUNLEVEL3] = '3',
4726 [ACTION_RUNLEVEL4] = '4',
4727 [ACTION_RUNLEVEL5] = '5',
4728 [ACTION_RESCUE] = '1'
4731 assert(arg_action < _ACTION_MAX);
4733 return table[arg_action];
4736 static int talk_upstart(void) {
4737 DBusMessage *m = NULL, *reply = NULL;
4739 int previous, rl, r;
4741 env1_buf[] = "RUNLEVEL=X",
4742 env2_buf[] = "PREVLEVEL=X";
4743 char *env1 = env1_buf, *env2 = env2_buf;
4744 const char *emit = "runlevel";
4745 dbus_bool_t b_false = FALSE;
4746 DBusMessageIter iter, sub;
4747 DBusConnection *bus;
4749 dbus_error_init(&error);
4751 if (!(rl = action_to_runlevel()))
4754 if (utmp_get_runlevel(&previous, NULL) < 0)
4757 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4758 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4763 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4768 if ((r = bus_check_peercred(bus)) < 0) {
4769 log_error("Failed to verify owner of bus.");
4773 if (!(m = dbus_message_new_method_call(
4774 "com.ubuntu.Upstart",
4775 "/com/ubuntu/Upstart",
4776 "com.ubuntu.Upstart0_6",
4779 log_error("Could not allocate message.");
4784 dbus_message_iter_init_append(m, &iter);
4786 env1_buf[sizeof(env1_buf)-2] = rl;
4787 env2_buf[sizeof(env2_buf)-2] = previous;
4789 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4790 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4791 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4792 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4793 !dbus_message_iter_close_container(&iter, &sub) ||
4794 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4795 log_error("Could not append arguments to message.");
4800 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4802 if (bus_error_is_no_service(&error)) {
4807 log_error("Failed to issue method call: %s", bus_error_message(&error));
4816 dbus_message_unref(m);
4819 dbus_message_unref(reply);
4822 dbus_connection_flush(bus);
4823 dbus_connection_close(bus);
4824 dbus_connection_unref(bus);
4827 dbus_error_free(&error);
4832 static int talk_initctl(void) {
4833 struct init_request request;
4837 if (!(rl = action_to_runlevel()))
4841 request.magic = INIT_MAGIC;
4842 request.sleeptime = 0;
4843 request.cmd = INIT_CMD_RUNLVL;
4844 request.runlevel = rl;
4846 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4848 if (errno == ENOENT)
4851 log_error("Failed to open "INIT_FIFO": %m");
4856 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4857 close_nointr_nofail(fd);
4860 log_error("Failed to write to "INIT_FIFO": %m");
4861 return errno ? -errno : -EIO;
4867 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4869 static const struct {
4877 int (* const dispatch)(DBusConnection *bus, char **args);
4879 { "list-units", LESS, 1, list_units },
4880 { "list-unit-files", EQUAL, 1, list_unit_files },
4881 { "list-jobs", EQUAL, 1, list_jobs },
4882 { "clear-jobs", EQUAL, 1, daemon_reload },
4883 { "load", MORE, 2, load_unit },
4884 { "cancel", MORE, 2, cancel_job },
4885 { "start", MORE, 2, start_unit },
4886 { "stop", MORE, 2, start_unit },
4887 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4888 { "reload", MORE, 2, start_unit },
4889 { "restart", MORE, 2, start_unit },
4890 { "try-restart", MORE, 2, start_unit },
4891 { "reload-or-restart", MORE, 2, start_unit },
4892 { "reload-or-try-restart", MORE, 2, start_unit },
4893 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4894 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4895 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4896 { "isolate", EQUAL, 2, start_unit },
4897 { "kill", MORE, 2, kill_unit },
4898 { "is-active", MORE, 2, check_unit },
4899 { "check", MORE, 2, check_unit },
4900 { "show", MORE, 1, show },
4901 { "status", MORE, 2, show },
4902 { "help", MORE, 2, show },
4903 { "dump", EQUAL, 1, dump },
4904 { "dot", EQUAL, 1, dot },
4905 { "snapshot", LESS, 2, snapshot },
4906 { "delete", MORE, 2, delete_snapshot },
4907 { "daemon-reload", EQUAL, 1, daemon_reload },
4908 { "daemon-reexec", EQUAL, 1, daemon_reload },
4909 { "show-environment", EQUAL, 1, show_enviroment },
4910 { "set-environment", MORE, 2, set_environment },
4911 { "unset-environment", MORE, 2, set_environment },
4912 { "halt", EQUAL, 1, start_special },
4913 { "poweroff", EQUAL, 1, start_special },
4914 { "reboot", EQUAL, 1, start_special },
4915 { "kexec", EQUAL, 1, start_special },
4916 { "suspend", EQUAL, 1, start_special },
4917 { "hibernate", EQUAL, 1, start_special },
4918 { "default", EQUAL, 1, start_special },
4919 { "rescue", EQUAL, 1, start_special },
4920 { "emergency", EQUAL, 1, start_special },
4921 { "exit", EQUAL, 1, start_special },
4922 { "reset-failed", MORE, 1, reset_failed },
4923 { "enable", MORE, 2, enable_unit },
4924 { "disable", MORE, 2, enable_unit },
4925 { "is-enabled", MORE, 2, unit_is_enabled },
4926 { "reenable", MORE, 2, enable_unit },
4927 { "preset", MORE, 2, enable_unit },
4928 { "mask", MORE, 2, enable_unit },
4929 { "unmask", MORE, 2, enable_unit },
4930 { "link", MORE, 2, enable_unit },
4931 { "switch-root", MORE, 2, switch_root },
4941 left = argc - optind;
4944 /* Special rule: no arguments means "list-units" */
4947 if (streq(argv[optind], "help") && !argv[optind+1]) {
4948 log_error("This command expects one or more "
4949 "unit names. Did you mean --help?");
4953 for (i = 0; i < ELEMENTSOF(verbs); i++)
4954 if (streq(argv[optind], verbs[i].verb))
4957 if (i >= ELEMENTSOF(verbs)) {
4958 log_error("Unknown operation '%s'.", argv[optind]);
4963 switch (verbs[i].argc_cmp) {
4966 if (left != verbs[i].argc) {
4967 log_error("Invalid number of arguments.");
4974 if (left < verbs[i].argc) {
4975 log_error("Too few arguments.");
4982 if (left > verbs[i].argc) {
4983 log_error("Too many arguments.");
4990 assert_not_reached("Unknown comparison operator.");
4993 /* Require a bus connection for all operations but
4995 if (!streq(verbs[i].verb, "enable") &&
4996 !streq(verbs[i].verb, "disable") &&
4997 !streq(verbs[i].verb, "is-enabled") &&
4998 !streq(verbs[i].verb, "list-unit-files") &&
4999 !streq(verbs[i].verb, "reenable") &&
5000 !streq(verbs[i].verb, "preset") &&
5001 !streq(verbs[i].verb, "mask") &&
5002 !streq(verbs[i].verb, "unmask") &&
5003 !streq(verbs[i].verb, "link")) {
5005 if (running_in_chroot() > 0) {
5006 log_info("Running in chroot, ignoring request.");
5010 if (((!streq(verbs[i].verb, "reboot") &&
5011 !streq(verbs[i].verb, "halt") &&
5012 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5013 log_error("Failed to get D-Bus connection: %s",
5014 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5020 if (!bus && !avoid_bus()) {
5021 log_error("Failed to get D-Bus connection: %s",
5022 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5027 return verbs[i].dispatch(bus, argv + optind);
5030 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5032 struct msghdr msghdr;
5033 struct iovec iovec[2];
5034 union sockaddr_union sockaddr;
5035 struct sd_shutdown_command c;
5037 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5044 c.dry_run = dry_run;
5048 sockaddr.sa.sa_family = AF_UNIX;
5049 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5052 msghdr.msg_name = &sockaddr;
5053 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5056 iovec[0].iov_base = (char*) &c;
5057 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5059 if (isempty(message))
5060 msghdr.msg_iovlen = 1;
5062 iovec[1].iov_base = (char*) message;
5063 iovec[1].iov_len = strlen(message);
5064 msghdr.msg_iovlen = 2;
5066 msghdr.msg_iov = iovec;
5068 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5069 close_nointr_nofail(fd);
5073 close_nointr_nofail(fd);
5077 static int reload_with_fallback(DBusConnection *bus) {
5080 /* First, try systemd via D-Bus. */
5081 if (daemon_reload(bus, NULL) >= 0)
5085 /* Nothing else worked, so let's try signals */
5086 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5088 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5089 log_error("kill() failed: %m");
5096 static int start_with_fallback(DBusConnection *bus) {
5099 /* First, try systemd via D-Bus. */
5100 if (start_unit(bus, NULL) >= 0)
5104 /* Hmm, talking to systemd via D-Bus didn't work. Then
5105 * let's try to talk to Upstart via D-Bus. */
5106 if (talk_upstart() > 0)
5109 /* Nothing else worked, so let's try
5111 if (talk_initctl() > 0)
5114 log_error("Failed to talk to init daemon.");
5118 warn_wall(arg_action);
5122 static _noreturn_ void halt_now(enum action a) {
5124 /* Make sure C-A-D is handled by the kernel from this
5126 reboot(RB_ENABLE_CAD);
5131 log_info("Halting.");
5132 reboot(RB_HALT_SYSTEM);
5135 case ACTION_POWEROFF:
5136 log_info("Powering off.");
5137 reboot(RB_POWER_OFF);
5141 log_info("Rebooting.");
5142 reboot(RB_AUTOBOOT);
5146 assert_not_reached("Unknown halt action.");
5149 assert_not_reached("Uh? This shouldn't happen.");
5152 static int halt_main(DBusConnection *bus) {
5155 if (geteuid() != 0) {
5156 /* Try logind if we are a normal user and no special
5157 * mode applies. Maybe PolicyKit allows us to shutdown
5160 if (arg_when <= 0 &&
5163 (arg_action == ACTION_POWEROFF ||
5164 arg_action == ACTION_REBOOT)) {
5165 r = reboot_with_logind(bus, arg_action);
5170 log_error("Must be root.");
5177 m = strv_join(arg_wall, " ");
5178 r = send_shutdownd(arg_when,
5179 arg_action == ACTION_HALT ? 'H' :
5180 arg_action == ACTION_POWEROFF ? 'P' :
5181 arg_action == ACTION_KEXEC ? 'K' :
5189 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5191 char date[FORMAT_TIMESTAMP_MAX];
5193 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5194 format_timestamp(date, sizeof(date), arg_when));
5199 if (!arg_dry && !arg_force)
5200 return start_with_fallback(bus);
5203 if (sd_booted() > 0)
5204 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5206 r = utmp_put_shutdown();
5208 log_warning("Failed to write utmp record: %s", strerror(-r));
5215 halt_now(arg_action);
5216 /* We should never reach this. */
5220 static int runlevel_main(void) {
5221 int r, runlevel, previous;
5223 r = utmp_get_runlevel(&runlevel, &previous);
5230 previous <= 0 ? 'N' : previous,
5231 runlevel <= 0 ? 'N' : runlevel);
5236 int main(int argc, char*argv[]) {
5237 int r, retval = EXIT_FAILURE;
5238 DBusConnection *bus = NULL;
5241 dbus_error_init(&error);
5243 log_parse_environment();
5246 r = parse_argv(argc, argv);
5250 retval = EXIT_SUCCESS;
5254 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5255 * let's shortcut this */
5256 if (arg_action == ACTION_RUNLEVEL) {
5257 r = runlevel_main();
5258 retval = r < 0 ? EXIT_FAILURE : r;
5262 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5263 log_info("Running in chroot, ignoring request.");
5269 if (arg_transport == TRANSPORT_NORMAL)
5270 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5271 else if (arg_transport == TRANSPORT_POLKIT) {
5272 bus_connect_system_polkit(&bus, &error);
5273 private_bus = false;
5274 } else if (arg_transport == TRANSPORT_SSH) {
5275 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5276 private_bus = false;
5278 assert_not_reached("Uh, invalid transport...");
5281 switch (arg_action) {
5283 case ACTION_SYSTEMCTL:
5284 r = systemctl_main(bus, argc, argv, &error);
5288 case ACTION_POWEROFF:
5294 case ACTION_RUNLEVEL2:
5295 case ACTION_RUNLEVEL3:
5296 case ACTION_RUNLEVEL4:
5297 case ACTION_RUNLEVEL5:
5299 case ACTION_EMERGENCY:
5300 case ACTION_DEFAULT:
5301 r = start_with_fallback(bus);
5306 r = reload_with_fallback(bus);
5309 case ACTION_CANCEL_SHUTDOWN: {
5313 m = strv_join(arg_wall, " ");
5315 retval = EXIT_FAILURE;
5319 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
5321 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
5326 case ACTION_INVALID:
5327 case ACTION_RUNLEVEL:
5329 assert_not_reached("Unknown action");
5332 retval = r < 0 ? EXIT_FAILURE : r;
5336 dbus_connection_flush(bus);
5337 dbus_connection_close(bus);
5338 dbus_connection_unref(bus);
5341 dbus_error_free(&error);
5345 strv_free(arg_property);
5348 ask_password_agent_close();
5349 polkit_agent_close();