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 {
1181 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1189 dbus_error_init(&error);
1191 log_debug("Got D-Bus request: %s.%s() on %s",
1192 dbus_message_get_interface(message),
1193 dbus_message_get_member(message),
1194 dbus_message_get_path(message));
1196 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1197 log_error("Warning! D-Bus connection terminated.");
1198 dbus_connection_close(connection);
1200 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1202 const char *path, *result, *unit;
1203 dbus_bool_t success = true;
1205 if (dbus_message_get_args(message, &error,
1206 DBUS_TYPE_UINT32, &id,
1207 DBUS_TYPE_OBJECT_PATH, &path,
1208 DBUS_TYPE_STRING, &unit,
1209 DBUS_TYPE_STRING, &result,
1210 DBUS_TYPE_INVALID)) {
1213 p = set_remove(d->set, (char*) path);
1217 d->result = strdup(result);
1222 dbus_error_free(&error);
1223 if (dbus_message_get_args(message, &error,
1224 DBUS_TYPE_UINT32, &id,
1225 DBUS_TYPE_OBJECT_PATH, &path,
1226 DBUS_TYPE_STRING, &result,
1227 DBUS_TYPE_INVALID)) {
1230 /* Compatibility with older systemd versions <
1231 * 183 during upgrades. This should be dropped
1233 p = set_remove(d->set, (char*) path);
1237 d->result = strdup(result);
1242 dbus_error_free(&error);
1243 if (dbus_message_get_args(message, &error,
1244 DBUS_TYPE_UINT32, &id,
1245 DBUS_TYPE_OBJECT_PATH, &path,
1246 DBUS_TYPE_BOOLEAN, &success,
1247 DBUS_TYPE_INVALID)) {
1250 /* Compatibility with older systemd versions <
1251 * 19 during upgrades. This should be dropped
1254 p = set_remove(d->set, (char*) path);
1258 d->result = strdup("failed");
1264 log_error("Failed to parse message: %s", bus_error_message(&error));
1268 dbus_error_free(&error);
1269 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1272 static int enable_wait_for_jobs(DBusConnection *bus) {
1280 dbus_error_init(&error);
1281 dbus_bus_add_match(bus,
1283 "sender='org.freedesktop.systemd1',"
1284 "interface='org.freedesktop.systemd1.Manager',"
1285 "member='JobRemoved',"
1286 "path='/org/freedesktop/systemd1'",
1289 if (dbus_error_is_set(&error)) {
1290 log_error("Failed to add match: %s", bus_error_message(&error));
1291 dbus_error_free(&error);
1295 /* This is slightly dirty, since we don't undo the match registrations. */
1299 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1309 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1310 log_error("Failed to add filter.");
1315 while (!set_isempty(s) &&
1316 dbus_connection_read_write_dispatch(bus, -1))
1319 if (!arg_quiet && d.result) {
1320 if (streq(d.result, "timeout"))
1321 log_error("Job timed out.");
1322 else if (streq(d.result, "canceled"))
1323 log_error("Job canceled.");
1324 else if (streq(d.result, "dependency"))
1325 log_error("A dependency job failed. See system journal for details.");
1326 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1327 log_error("Job failed. See system journal and 'systemctl status' for details.");
1330 if (streq_ptr(d.result, "timeout"))
1332 else if (streq_ptr(d.result, "canceled"))
1334 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1342 /* This is slightly dirty, since we don't undo the filter registration. */
1347 static int check_one_unit(DBusConnection *bus, char *name, bool quiet) {
1348 DBusMessage *reply = NULL;
1349 DBusMessageIter iter, sub;
1351 *interface = "org.freedesktop.systemd1.Unit",
1352 *property = "ActiveState";
1353 const char *path = NULL;
1360 n = unit_name_mangle(name);
1361 r = bus_method_call_with_reply (
1363 "org.freedesktop.systemd1",
1364 "/org/freedesktop/systemd1",
1365 "org.freedesktop.systemd1.Manager",
1369 DBUS_TYPE_STRING, n ? &n : &name,
1373 if ((r != -ENOMEM) && (!quiet))
1378 if (!dbus_message_get_args(reply, NULL,
1379 DBUS_TYPE_OBJECT_PATH, &path,
1380 DBUS_TYPE_INVALID)) {
1381 log_error("Failed to parse reply.");
1386 dbus_message_unref(reply);
1387 r = bus_method_call_with_reply (
1389 "org.freedesktop.systemd1",
1391 "org.freedesktop.DBus.Properties",
1395 DBUS_TYPE_STRING, &interface,
1396 DBUS_TYPE_STRING, &property,
1401 if (!dbus_message_iter_init(reply, &iter) ||
1402 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1403 log_error("Failed to parse reply.");
1408 dbus_message_iter_recurse(&iter, &sub);
1410 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1411 log_error("Failed to parse reply.");
1416 dbus_message_iter_get_basic(&sub, &state);
1421 if (streq(state, "active") || streq(state, "reloading"))
1424 r = 3; /* According to LSB: "program is not running" */
1428 dbus_message_unref(reply);
1433 static void check_triggering_units(
1434 DBusConnection *bus,
1435 const char *unit_name) {
1437 DBusMessage *reply = NULL;
1438 DBusMessageIter iter, sub;
1439 char *service_trigger = NULL;
1440 const char *interface = "org.freedesktop.systemd1.Unit",
1441 *triggered_by_property = "TriggeredBy";
1443 char *unit_path = NULL, *n = NULL;
1444 bool print_warning_label = true;
1447 n = unit_name_mangle(unit_name);
1448 unit_path = unit_dbus_path_from_name(n ? n : unit_name);
1451 log_error("Could not allocate dbus path.");
1455 r = bus_method_call_with_reply (
1457 "org.freedesktop.systemd1",
1459 "org.freedesktop.DBus.Properties",
1463 DBUS_TYPE_STRING, &interface,
1464 DBUS_TYPE_STRING, &triggered_by_property,
1469 if (!dbus_message_iter_init(reply, &iter) ||
1470 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1471 log_error("Failed to parse reply.");
1476 dbus_message_iter_recurse(&iter, &sub);
1477 dbus_message_iter_recurse(&sub, &iter);
1480 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1482 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1483 log_error("Failed to parse reply.");
1487 dbus_message_iter_get_basic(&sub, &service_trigger);
1489 r = check_one_unit(bus, service_trigger, true);
1493 if (print_warning_label) {
1494 log_warning("Warning: Stopping %s, but it can still be activated by:", unit_name);
1495 print_warning_label = false;
1497 log_warning(" %s", service_trigger);
1500 dbus_message_iter_next(&sub);
1504 dbus_message_unref(reply);
1509 static int start_unit_one(
1510 DBusConnection *bus,
1517 DBusMessage *reply = NULL;
1526 assert(arg_no_block || s);
1528 n = unit_name_mangle(name);
1529 r = bus_method_call_with_reply (
1531 "org.freedesktop.systemd1",
1532 "/org/freedesktop/systemd1",
1533 "org.freedesktop.systemd1.Manager",
1537 DBUS_TYPE_STRING, n ? (const char **) &n : &name,
1538 DBUS_TYPE_STRING, &mode,
1542 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL )
1543 /* There's always a fallback possible for
1544 * legacy actions. */
1547 log_error("Failed to issue method call: %s", bus_error_message(error));
1551 if (!dbus_message_get_args(reply, error,
1552 DBUS_TYPE_OBJECT_PATH, &path,
1553 DBUS_TYPE_INVALID)) {
1554 log_error("Failed to parse reply: %s", bus_error_message(error));
1559 if (need_daemon_reload(bus, name))
1560 log_warning("Warning: Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1561 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
1563 if (!arg_no_block) {
1566 if (!(p = strdup(path))) {
1567 log_error("Failed to duplicate path.");
1572 if ((r = set_put(s, p)) < 0) {
1574 log_error("Failed to add path to set.");
1579 /* When stopping a unit warn if it can still be triggered by
1580 * another active unit (socket, path, timer) */
1581 if (!arg_quiet && streq(method, "StopUnit"))
1582 check_triggering_units(bus, name);
1588 dbus_message_unref(reply);
1593 static enum action verb_to_action(const char *verb) {
1594 if (streq(verb, "halt"))
1596 else if (streq(verb, "poweroff"))
1597 return ACTION_POWEROFF;
1598 else if (streq(verb, "reboot"))
1599 return ACTION_REBOOT;
1600 else if (streq(verb, "kexec"))
1601 return ACTION_KEXEC;
1602 else if (streq(verb, "rescue"))
1603 return ACTION_RESCUE;
1604 else if (streq(verb, "emergency"))
1605 return ACTION_EMERGENCY;
1606 else if (streq(verb, "default"))
1607 return ACTION_DEFAULT;
1608 else if (streq(verb, "exit"))
1610 else if (streq(verb, "suspend"))
1611 return ACTION_SUSPEND;
1612 else if (streq(verb, "hibernate"))
1613 return ACTION_HIBERNATE;
1615 return ACTION_INVALID;
1618 static int start_unit(DBusConnection *bus, char **args) {
1620 static const char * const table[_ACTION_MAX] = {
1621 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1622 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1623 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1624 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1625 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1626 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1627 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1628 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1629 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1630 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1631 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1632 [ACTION_EXIT] = SPECIAL_EXIT_TARGET,
1633 [ACTION_SUSPEND] = SPECIAL_SUSPEND_TARGET,
1634 [ACTION_HIBERNATE] = SPECIAL_HIBERNATE_TARGET
1638 const char *method, *mode, *one_name;
1643 dbus_error_init(&error);
1647 ask_password_agent_open_if_enabled();
1649 if (arg_action == ACTION_SYSTEMCTL) {
1651 streq(args[0], "stop") ||
1652 streq(args[0], "condstop") ? "StopUnit" :
1653 streq(args[0], "reload") ? "ReloadUnit" :
1654 streq(args[0], "restart") ? "RestartUnit" :
1656 streq(args[0], "try-restart") ||
1657 streq(args[0], "condrestart") ? "TryRestartUnit" :
1659 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1661 streq(args[0], "reload-or-try-restart") ||
1662 streq(args[0], "condreload") ||
1664 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1668 (streq(args[0], "isolate") ||
1669 streq(args[0], "rescue") ||
1670 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1672 one_name = table[verb_to_action(args[0])];
1675 assert(arg_action < ELEMENTSOF(table));
1676 assert(table[arg_action]);
1678 method = "StartUnit";
1680 mode = (arg_action == ACTION_EMERGENCY ||
1681 arg_action == ACTION_RESCUE ||
1682 arg_action == ACTION_RUNLEVEL2 ||
1683 arg_action == ACTION_RUNLEVEL3 ||
1684 arg_action == ACTION_RUNLEVEL4 ||
1685 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1687 one_name = table[arg_action];
1690 if (!arg_no_block) {
1691 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1692 log_error("Could not watch jobs: %s", strerror(-ret));
1696 if (!(s = set_new(string_hash_func, string_compare_func))) {
1697 log_error("Failed to allocate set.");
1704 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1707 STRV_FOREACH(name, args+1)
1708 if ((r = start_unit_one(bus, method, *name, mode, &error, s)) != 0) {
1709 ret = translate_bus_error_to_exit_status(r, &error);
1710 dbus_error_free(&error);
1715 if ((r = wait_for_jobs(bus, s)) < 0) {
1724 dbus_error_free(&error);
1729 /* Ask systemd-logind, which might grant access to unprivileged users
1730 * through PolicyKit */
1731 static int reboot_with_logind(DBusConnection *bus, enum action a) {
1734 dbus_bool_t interactive = true;
1736 polkit_agent_open_if_enabled();
1744 case ACTION_POWEROFF:
1745 method = "PowerOff";
1748 case ACTION_SUSPEND:
1752 case ACTION_HIBERNATE:
1753 method = "Hibernate";
1760 return bus_method_call_with_reply (
1762 "org.freedesktop.login1",
1763 "/org/freedesktop/login1",
1764 "org.freedesktop.login1.Manager",
1768 DBUS_TYPE_BOOLEAN, &interactive,
1775 static int start_special(DBusConnection *bus, char **args) {
1781 a = verb_to_action(args[0]);
1783 if (arg_force >= 2 && geteuid() != 0) {
1784 log_error("Must be root.");
1788 if (arg_force >= 2 &&
1789 (a == ACTION_HALT ||
1790 a == ACTION_POWEROFF ||
1791 a == ACTION_REBOOT))
1794 if (arg_force >= 1 &&
1795 (a == ACTION_HALT ||
1796 a == ACTION_POWEROFF ||
1797 a == ACTION_REBOOT ||
1798 a == ACTION_KEXEC ||
1800 return daemon_reload(bus, args);
1802 /* first try logind, to allow authentication with polkit */
1803 if (geteuid() != 0 &&
1804 (a == ACTION_POWEROFF ||
1805 a == ACTION_REBOOT ||
1806 a == ACTION_SUSPEND ||
1807 a == ACTION_HIBERNATE)) {
1808 r = reboot_with_logind(bus, a);
1813 r = start_unit(bus, args);
1820 static int check_unit(DBusConnection *bus, char **args) {
1822 int r = 3; /* According to LSB: "program is not running" */
1827 STRV_FOREACH(name, args+1) {
1828 int state = check_one_unit(bus, *name, arg_quiet);
1838 static int kill_unit(DBusConnection *bus, char **args) {
1845 arg_kill_who = "all";
1847 STRV_FOREACH(name, args+1) {
1848 n = unit_name_mangle(*name);
1849 r = bus_method_call_with_reply (
1851 "org.freedesktop.systemd1",
1852 "/org/freedesktop/systemd1",
1853 "org.freedesktop.systemd1.Manager",
1857 DBUS_TYPE_STRING, n ? &n : name,
1858 DBUS_TYPE_STRING, &arg_kill_who,
1859 DBUS_TYPE_INT32, &arg_signal,
1868 typedef struct ExecStatusInfo {
1876 usec_t start_timestamp;
1877 usec_t exit_timestamp;
1882 LIST_FIELDS(struct ExecStatusInfo, exec);
1885 static void exec_status_info_free(ExecStatusInfo *i) {
1894 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1895 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
1896 DBusMessageIter sub2, sub3;
1900 int32_t code, status;
1906 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1909 dbus_message_iter_recurse(sub, &sub2);
1911 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1914 if (!(i->path = strdup(path)))
1917 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1918 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1922 dbus_message_iter_recurse(&sub2, &sub3);
1923 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1924 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1925 dbus_message_iter_next(&sub3);
1930 if (!(i->argv = new0(char*, n+1)))
1934 dbus_message_iter_recurse(&sub2, &sub3);
1935 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1938 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1939 dbus_message_iter_get_basic(&sub3, &s);
1940 dbus_message_iter_next(&sub3);
1942 if (!(i->argv[n++] = strdup(s)))
1946 if (!dbus_message_iter_next(&sub2) ||
1947 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1948 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1949 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
1950 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1951 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
1952 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1953 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1954 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1958 i->start_timestamp = (usec_t) start_timestamp;
1959 i->exit_timestamp = (usec_t) exit_timestamp;
1960 i->pid = (pid_t) pid;
1967 typedef struct UnitStatusInfo {
1969 const char *load_state;
1970 const char *active_state;
1971 const char *sub_state;
1972 const char *unit_file_state;
1974 const char *description;
1975 const char *following;
1977 char **documentation;
1979 const char *fragment_path;
1980 const char *source_path;
1981 const char *default_control_group;
1983 const char *load_error;
1986 usec_t inactive_exit_timestamp;
1987 usec_t inactive_exit_timestamp_monotonic;
1988 usec_t active_enter_timestamp;
1989 usec_t active_exit_timestamp;
1990 usec_t inactive_enter_timestamp;
1992 bool need_daemon_reload;
1997 const char *status_text;
2000 usec_t start_timestamp;
2001 usec_t exit_timestamp;
2003 int exit_code, exit_status;
2005 usec_t condition_timestamp;
2006 bool condition_result;
2009 unsigned n_accepted;
2010 unsigned n_connections;
2014 const char *sysfs_path;
2016 /* Mount, Automount */
2022 LIST_HEAD(ExecStatusInfo, exec);
2025 static void print_status_info(UnitStatusInfo *i) {
2027 const char *on, *off, *ss;
2029 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
2030 char since2[FORMAT_TIMESTAMP_MAX], *s2;
2035 /* This shows pretty information about a unit. See
2036 * print_property() for a low-level property printer */
2038 printf("%s", strna(i->id));
2040 if (i->description && !streq_ptr(i->id, i->description))
2041 printf(" - %s", i->description);
2046 printf("\t Follow: unit currently follows state of %s\n", i->following);
2048 if (streq_ptr(i->load_state, "error")) {
2049 on = ansi_highlight_red(true);
2050 off = ansi_highlight_red(false);
2054 path = i->source_path ? i->source_path : i->fragment_path;
2057 printf("\t Loaded: %s%s%s (Reason: %s)\n", on, strna(i->load_state), off, i->load_error);
2058 else if (path && i->unit_file_state)
2059 printf("\t Loaded: %s%s%s (%s; %s)\n", on, strna(i->load_state), off, path, i->unit_file_state);
2061 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, path);
2063 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
2065 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2067 if (streq_ptr(i->active_state, "failed")) {
2068 on = ansi_highlight_red(true);
2069 off = ansi_highlight_red(false);
2070 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
2071 on = ansi_highlight_green(true);
2072 off = ansi_highlight_green(false);
2077 printf("\t Active: %s%s (%s)%s",
2079 strna(i->active_state),
2083 printf("\t Active: %s%s%s",
2085 strna(i->active_state),
2088 if (!isempty(i->result) && !streq(i->result, "success"))
2089 printf(" (Result: %s)", i->result);
2091 timestamp = (streq_ptr(i->active_state, "active") ||
2092 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
2093 (streq_ptr(i->active_state, "inactive") ||
2094 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
2095 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
2096 i->active_exit_timestamp;
2098 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
2099 s2 = format_timestamp(since2, sizeof(since2), timestamp);
2102 printf(" since %s; %s\n", s2, s1);
2104 printf(" since %s\n", s2);
2108 if (!i->condition_result && i->condition_timestamp > 0) {
2109 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
2110 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
2113 printf("\t start condition failed at %s; %s\n", s2, s1);
2115 printf("\t start condition failed at %s\n", s2);
2119 printf("\t Device: %s\n", i->sysfs_path);
2121 printf("\t Where: %s\n", i->where);
2123 printf("\t What: %s\n", i->what);
2125 if (!strv_isempty(i->documentation)) {
2129 STRV_FOREACH(t, i->documentation) {
2131 printf("\t Docs: %s\n", *t);
2134 printf("\t %s\n", *t);
2139 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
2141 LIST_FOREACH(exec, p, i->exec) {
2145 /* Only show exited processes here */
2149 t = strv_join(p->argv, " ");
2150 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
2153 good = is_clean_exit_lsb(p->code, p->status, NULL);
2155 on = ansi_highlight_red(true);
2156 off = ansi_highlight_red(false);
2160 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
2162 if (p->code == CLD_EXITED) {
2165 printf("status=%i", p->status);
2167 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
2172 printf("signal=%s", signal_to_string(p->status));
2174 printf(")%s\n", off);
2176 if (i->main_pid == p->pid &&
2177 i->start_timestamp == p->start_timestamp &&
2178 i->exit_timestamp == p->start_timestamp)
2179 /* Let's not show this twice */
2182 if (p->pid == i->control_pid)
2186 if (i->main_pid > 0 || i->control_pid > 0) {
2189 if (i->main_pid > 0) {
2190 printf("Main PID: %u", (unsigned) i->main_pid);
2194 get_process_comm(i->main_pid, &t);
2199 } else if (i->exit_code > 0) {
2200 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2202 if (i->exit_code == CLD_EXITED) {
2205 printf("status=%i", i->exit_status);
2207 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
2212 printf("signal=%s", signal_to_string(i->exit_status));
2217 if (i->main_pid > 0 && i->control_pid > 0)
2220 if (i->control_pid > 0) {
2223 printf(" Control: %u", (unsigned) i->control_pid);
2225 get_process_comm(i->control_pid, &t);
2236 printf("\t Status: \"%s\"\n", i->status_text);
2238 if (i->default_control_group) {
2241 printf("\t CGroup: %s\n", i->default_control_group);
2243 if (arg_transport != TRANSPORT_SSH) {
2253 if (i->main_pid > 0)
2254 extra[k++] = i->main_pid;
2256 if (i->control_pid > 0)
2257 extra[k++] = i->control_pid;
2259 show_cgroup_and_extra_by_spec(i->default_control_group, "\t\t ", c, false, arg_all, extra, k);
2263 if (i->id && arg_transport != TRANSPORT_SSH) {
2265 arg_all * OUTPUT_SHOW_ALL |
2266 arg_follow * OUTPUT_FOLLOW |
2267 !arg_quiet * OUTPUT_WARN_CUTOFF |
2268 on_tty() * OUTPUT_COLOR;
2271 show_journal_by_unit(i->id, arg_output, 0,
2272 i->inactive_exit_timestamp_monotonic,
2276 if (i->need_daemon_reload)
2277 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2278 ansi_highlight_red(true),
2279 ansi_highlight_red(false),
2280 arg_scope == UNIT_FILE_SYSTEM ? "--system" : "--user");
2283 static void show_unit_help(UnitStatusInfo *i) {
2288 if (!i->documentation) {
2289 log_info("Documentation for %s not known.", i->id);
2293 STRV_FOREACH(p, i->documentation) {
2295 if (startswith(*p, "man:")) {
2298 char *page = NULL, *section = NULL;
2299 const char *args[4] = { "man", NULL, NULL, NULL };
2304 if ((*p)[k-1] == ')')
2305 e = strrchr(*p, '(');
2308 page = strndup((*p) + 4, e - *p - 4);
2314 section = strndup(e + 1, *p + k - e - 2);
2328 log_error("Failed to fork: %m");
2336 execvp(args[0], (char**) args);
2337 log_error("Failed to execute man: %m");
2338 _exit(EXIT_FAILURE);
2344 wait_for_terminate(pid, NULL);
2346 log_info("Can't show: %s", *p);
2350 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2356 switch (dbus_message_iter_get_arg_type(iter)) {
2358 case DBUS_TYPE_STRING: {
2361 dbus_message_iter_get_basic(iter, &s);
2364 if (streq(name, "Id"))
2366 else if (streq(name, "LoadState"))
2368 else if (streq(name, "ActiveState"))
2369 i->active_state = s;
2370 else if (streq(name, "SubState"))
2372 else if (streq(name, "Description"))
2374 else if (streq(name, "FragmentPath"))
2375 i->fragment_path = s;
2376 else if (streq(name, "SourcePath"))
2378 else if (streq(name, "DefaultControlGroup"))
2379 i->default_control_group = s;
2380 else if (streq(name, "StatusText"))
2382 else if (streq(name, "SysFSPath"))
2384 else if (streq(name, "Where"))
2386 else if (streq(name, "What"))
2388 else if (streq(name, "Following"))
2390 else if (streq(name, "UnitFileState"))
2391 i->unit_file_state = s;
2392 else if (streq(name, "Result"))
2399 case DBUS_TYPE_BOOLEAN: {
2402 dbus_message_iter_get_basic(iter, &b);
2404 if (streq(name, "Accept"))
2406 else if (streq(name, "NeedDaemonReload"))
2407 i->need_daemon_reload = b;
2408 else if (streq(name, "ConditionResult"))
2409 i->condition_result = b;
2414 case DBUS_TYPE_UINT32: {
2417 dbus_message_iter_get_basic(iter, &u);
2419 if (streq(name, "MainPID")) {
2421 i->main_pid = (pid_t) u;
2424 } else if (streq(name, "ControlPID"))
2425 i->control_pid = (pid_t) u;
2426 else if (streq(name, "ExecMainPID")) {
2428 i->main_pid = (pid_t) u;
2429 } else if (streq(name, "NAccepted"))
2431 else if (streq(name, "NConnections"))
2432 i->n_connections = u;
2437 case DBUS_TYPE_INT32: {
2440 dbus_message_iter_get_basic(iter, &j);
2442 if (streq(name, "ExecMainCode"))
2443 i->exit_code = (int) j;
2444 else if (streq(name, "ExecMainStatus"))
2445 i->exit_status = (int) j;
2450 case DBUS_TYPE_UINT64: {
2453 dbus_message_iter_get_basic(iter, &u);
2455 if (streq(name, "ExecMainStartTimestamp"))
2456 i->start_timestamp = (usec_t) u;
2457 else if (streq(name, "ExecMainExitTimestamp"))
2458 i->exit_timestamp = (usec_t) u;
2459 else if (streq(name, "ActiveEnterTimestamp"))
2460 i->active_enter_timestamp = (usec_t) u;
2461 else if (streq(name, "InactiveEnterTimestamp"))
2462 i->inactive_enter_timestamp = (usec_t) u;
2463 else if (streq(name, "InactiveExitTimestamp"))
2464 i->inactive_exit_timestamp = (usec_t) u;
2465 else if (streq(name, "InactiveExitTimestampMonotonic"))
2466 i->inactive_exit_timestamp_monotonic = (usec_t) u;
2467 else if (streq(name, "ActiveExitTimestamp"))
2468 i->active_exit_timestamp = (usec_t) u;
2469 else if (streq(name, "ConditionTimestamp"))
2470 i->condition_timestamp = (usec_t) u;
2475 case DBUS_TYPE_ARRAY: {
2477 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2478 startswith(name, "Exec")) {
2479 DBusMessageIter sub;
2481 dbus_message_iter_recurse(iter, &sub);
2482 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2483 ExecStatusInfo *info;
2486 if (!(info = new0(ExecStatusInfo, 1)))
2489 if (!(info->name = strdup(name))) {
2494 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2499 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2501 dbus_message_iter_next(&sub);
2503 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING &&
2504 streq(name, "Documentation")) {
2506 DBusMessageIter sub;
2508 dbus_message_iter_recurse(iter, &sub);
2509 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
2513 dbus_message_iter_get_basic(&sub, &s);
2515 l = strv_append(i->documentation, s);
2519 strv_free(i->documentation);
2520 i->documentation = l;
2522 dbus_message_iter_next(&sub);
2529 case DBUS_TYPE_STRUCT: {
2531 if (streq(name, "LoadError")) {
2532 DBusMessageIter sub;
2533 const char *n, *message;
2536 dbus_message_iter_recurse(iter, &sub);
2538 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &n, true);
2542 r = bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &message, false);
2546 if (!isempty(message))
2547 i->load_error = message;
2557 static int print_property(const char *name, DBusMessageIter *iter) {
2561 /* This is a low-level property printer, see
2562 * print_status_info() for the nicer output */
2564 if (arg_property && !strv_find(arg_property, name))
2567 switch (dbus_message_iter_get_arg_type(iter)) {
2569 case DBUS_TYPE_STRUCT: {
2570 DBusMessageIter sub;
2571 dbus_message_iter_recurse(iter, &sub);
2573 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2576 dbus_message_iter_get_basic(&sub, &u);
2579 printf("%s=%u\n", name, (unsigned) u);
2581 printf("%s=\n", name);
2584 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2587 dbus_message_iter_get_basic(&sub, &s);
2589 if (arg_all || s[0])
2590 printf("%s=%s\n", name, s);
2593 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "LoadError")) {
2594 const char *a = NULL, *b = NULL;
2596 if (bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &a, true) >= 0)
2597 bus_iter_get_basic_and_next(&sub, DBUS_TYPE_STRING, &b, false);
2599 if (arg_all || !isempty(a) || !isempty(b))
2600 printf("%s=%s \"%s\"\n", name, strempty(a), strempty(b));
2608 case DBUS_TYPE_ARRAY:
2610 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2611 DBusMessageIter sub, sub2;
2613 dbus_message_iter_recurse(iter, &sub);
2614 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2618 dbus_message_iter_recurse(&sub, &sub2);
2620 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2621 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2622 printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2624 dbus_message_iter_next(&sub);
2629 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2630 DBusMessageIter sub, sub2;
2632 dbus_message_iter_recurse(iter, &sub);
2633 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2634 const char *type, *path;
2636 dbus_message_iter_recurse(&sub, &sub2);
2638 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2639 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2640 printf("%s=%s\n", type, path);
2642 dbus_message_iter_next(&sub);
2647 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2648 DBusMessageIter sub, sub2;
2650 dbus_message_iter_recurse(iter, &sub);
2651 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2653 uint64_t value, next_elapse;
2655 dbus_message_iter_recurse(&sub, &sub2);
2657 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2658 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2659 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2660 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2662 printf("%s={ value=%s ; next_elapse=%s }\n",
2664 format_timespan(timespan1, sizeof(timespan1), value),
2665 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2668 dbus_message_iter_next(&sub);
2673 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "ControlGroupAttributes")) {
2674 DBusMessageIter sub, sub2;
2676 dbus_message_iter_recurse(iter, &sub);
2677 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2678 const char *controller, *attr, *value;
2680 dbus_message_iter_recurse(&sub, &sub2);
2682 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &controller, true) >= 0 &&
2683 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &attr, true) >= 0 &&
2684 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &value, false) >= 0) {
2686 printf("ControlGroupAttribute={ controller=%s ; attribute=%s ; value=\"%s\" }\n",
2692 dbus_message_iter_next(&sub);
2697 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2698 DBusMessageIter sub;
2700 dbus_message_iter_recurse(iter, &sub);
2701 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2702 ExecStatusInfo info;
2705 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2706 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2709 t = strv_join(info.argv, " ");
2711 printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2715 yes_no(info.ignore),
2716 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2717 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2718 (unsigned) info. pid,
2719 sigchld_code_to_string(info.code),
2721 info.code == CLD_EXITED ? "" : "/",
2722 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2728 strv_free(info.argv);
2730 dbus_message_iter_next(&sub);
2739 if (generic_print_property(name, iter, arg_all) > 0)
2743 printf("%s=[unprintable]\n", name);
2748 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2749 DBusMessage *reply = NULL;
2750 const char *interface = "";
2752 DBusMessageIter iter, sub, sub2, sub3;
2753 UnitStatusInfo info;
2761 r = bus_method_call_with_reply (
2763 "org.freedesktop.systemd1",
2765 "org.freedesktop.DBus.Properties",
2769 DBUS_TYPE_STRING, &interface,
2774 if (!dbus_message_iter_init(reply, &iter) ||
2775 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2776 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2777 log_error("Failed to parse reply.");
2782 dbus_message_iter_recurse(&iter, &sub);
2789 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2792 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2793 log_error("Failed to parse reply.");
2798 dbus_message_iter_recurse(&sub, &sub2);
2800 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2801 log_error("Failed to parse reply.");
2806 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2807 log_error("Failed to parse reply.");
2812 dbus_message_iter_recurse(&sub2, &sub3);
2814 if (show_properties)
2815 r = print_property(name, &sub3);
2817 r = status_property(name, &sub3, &info);
2820 log_error("Failed to parse reply.");
2825 dbus_message_iter_next(&sub);
2830 if (!show_properties) {
2831 if (streq(verb, "help"))
2832 show_unit_help(&info);
2834 print_status_info(&info);
2837 strv_free(info.documentation);
2839 if (!streq_ptr(info.active_state, "active") &&
2840 !streq_ptr(info.active_state, "reloading") &&
2841 streq(verb, "status"))
2842 /* According to LSB: "program not running" */
2845 while ((p = info.exec)) {
2846 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2847 exec_status_info_free(p);
2852 dbus_message_unref(reply);
2857 static int show_one_by_pid(const char *verb, DBusConnection *bus, uint32_t pid, bool *new_line) {
2858 DBusMessage *reply = NULL;
2859 const char *path = NULL;
2863 dbus_error_init(&error);
2865 r = bus_method_call_with_reply (
2867 "org.freedesktop.systemd1",
2868 "/org/freedesktop/systemd1",
2869 "org.freedesktop.systemd1.Manager",
2873 DBUS_TYPE_UINT32, &pid,
2878 if (!dbus_message_get_args(reply, &error,
2879 DBUS_TYPE_OBJECT_PATH, &path,
2880 DBUS_TYPE_INVALID)) {
2881 log_error("Failed to parse reply: %s", bus_error_message(&error));
2886 r = show_one(verb, bus, path, false, new_line);
2890 dbus_message_unref(reply);
2892 dbus_error_free(&error);
2897 static int show(DBusConnection *bus, char **args) {
2899 bool show_properties, new_line = false;
2905 show_properties = streq(args[0], "show");
2907 if (show_properties)
2908 pager_open_if_enabled();
2910 if (show_properties && strv_length(args) <= 1) {
2911 /* If not argument is specified inspect the manager
2914 return show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2917 STRV_FOREACH(name, args+1) {
2920 if (safe_atou32(*name, &id) < 0) {
2922 /* Interpret as unit name */
2924 n = unit_name_mangle(*name);
2925 p = unit_dbus_path_from_name(n ? n : *name);
2930 r = show_one(args[0], bus, p, show_properties, &new_line);
2936 } else if (show_properties) {
2938 /* Interpret as job id */
2941 if (asprintf(&p, "/org/freedesktop/systemd1/job/%u", id) < 0)
2944 r = show_one(args[0], bus, p, show_properties, &new_line);
2952 /* Interpret as PID */
2954 r = show_one_by_pid(args[0], bus, id, &new_line);
2963 static int dump(DBusConnection *bus, char **args) {
2964 DBusMessage *reply = NULL;
2969 dbus_error_init(&error);
2971 pager_open_if_enabled();
2973 r = bus_method_call_with_reply (
2975 "org.freedesktop.systemd1",
2976 "/org/freedesktop/systemd1",
2977 "org.freedesktop.systemd1.Manager",
2985 if (!dbus_message_get_args(reply, &error,
2986 DBUS_TYPE_STRING, &text,
2987 DBUS_TYPE_INVALID)) {
2988 log_error("Failed to parse reply: %s", bus_error_message(&error));
2993 fputs(text, stdout);
2997 dbus_message_unref(reply);
2999 dbus_error_free(&error);
3004 static int snapshot(DBusConnection *bus, char **args) {
3005 DBusMessage *reply = NULL;
3008 dbus_bool_t cleanup = FALSE;
3009 DBusMessageIter iter, sub;
3011 *name = "", *path, *id,
3012 *interface = "org.freedesktop.systemd1.Unit",
3016 dbus_error_init(&error);
3018 if (strv_length(args) > 1)
3021 n = unit_name_mangle(name);
3022 r = bus_method_call_with_reply (
3024 "org.freedesktop.systemd1",
3025 "/org/freedesktop/systemd1",
3026 "org.freedesktop.systemd1.Manager",
3030 DBUS_TYPE_STRING, n ? (const char**) &n : &name,
3031 DBUS_TYPE_BOOLEAN, &cleanup,
3037 if (!dbus_message_get_args(reply, &error,
3038 DBUS_TYPE_OBJECT_PATH, &path,
3039 DBUS_TYPE_INVALID)) {
3040 log_error("Failed to parse reply: %s", bus_error_message(&error));
3045 dbus_message_unref(reply);
3046 r = bus_method_call_with_reply (
3048 "org.freedesktop.systemd1",
3050 "org.freedesktop.DBus.Properties",
3054 DBUS_TYPE_STRING, &interface,
3055 DBUS_TYPE_STRING, &property,
3060 if (!dbus_message_iter_init(reply, &iter) ||
3061 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3062 log_error("Failed to parse reply.");
3067 dbus_message_iter_recurse(&iter, &sub);
3069 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3070 log_error("Failed to parse reply.");
3075 dbus_message_iter_get_basic(&sub, &id);
3082 dbus_message_unref(reply);
3084 dbus_error_free(&error);
3089 static int delete_snapshot(DBusConnection *bus, char **args) {
3090 DBusMessage *reply = NULL;
3097 dbus_error_init(&error);
3099 STRV_FOREACH(name, args+1) {
3100 const char *path = NULL;
3103 n = unit_name_mangle(*name);
3104 r = bus_method_call_with_reply (
3106 "org.freedesktop.systemd1",
3107 "/org/freedesktop/systemd1",
3108 "org.freedesktop.systemd1.Manager",
3112 DBUS_TYPE_STRING, n ? &n : name,
3118 if (!dbus_message_get_args(reply, &error,
3119 DBUS_TYPE_OBJECT_PATH, &path,
3120 DBUS_TYPE_INVALID)) {
3121 log_error("Failed to parse reply: %s", bus_error_message(&error));
3123 dbus_message_unref(reply);
3124 dbus_error_free(&error);
3127 dbus_message_unref(reply);
3129 r = bus_method_call_with_reply (
3131 "org.freedesktop.systemd1",
3133 "org.freedesktop.systemd1.Snapshot",
3146 static int daemon_reload(DBusConnection *bus, char **args) {
3151 if (arg_action == ACTION_RELOAD)
3153 else if (arg_action == ACTION_REEXEC)
3154 method = "Reexecute";
3156 assert(arg_action == ACTION_SYSTEMCTL);
3159 streq(args[0], "clear-jobs") ||
3160 streq(args[0], "cancel") ? "ClearJobs" :
3161 streq(args[0], "daemon-reexec") ? "Reexecute" :
3162 streq(args[0], "reset-failed") ? "ResetFailed" :
3163 streq(args[0], "halt") ? "Halt" :
3164 streq(args[0], "poweroff") ? "PowerOff" :
3165 streq(args[0], "reboot") ? "Reboot" :
3166 streq(args[0], "kexec") ? "KExec" :
3167 streq(args[0], "exit") ? "Exit" :
3168 /* "daemon-reload" */ "Reload";
3171 r = bus_method_call_with_reply (
3173 "org.freedesktop.systemd1",
3174 "/org/freedesktop/systemd1",
3175 "org.freedesktop.systemd1.Manager",
3181 if (r == -ENOENT && arg_action != ACTION_SYSTEMCTL)
3182 /* There's always a fallback possible for
3183 * legacy actions. */
3185 else if (r == -ETIMEDOUT && streq(method, "Reexecute"))
3186 /* On reexecution, we expect a disconnect, not
3190 log_error("Failed to issue method call: %s", bus_error_message(&error));
3191 dbus_error_free(&error);
3196 static int reset_failed(DBusConnection *bus, char **args) {
3200 if (strv_length(args) <= 1)
3201 return daemon_reload(bus, args);
3203 STRV_FOREACH(name, args+1) {
3204 n = unit_name_mangle(*name);
3205 r = bus_method_call_with_reply (
3207 "org.freedesktop.systemd1",
3208 "/org/freedesktop/systemd1",
3209 "org.freedesktop.systemd1.Manager",
3213 DBUS_TYPE_STRING, n ? &n : name,
3224 static int show_enviroment(DBusConnection *bus, char **args) {
3225 DBusMessage *reply = NULL;
3226 DBusMessageIter iter, sub, sub2;
3229 *interface = "org.freedesktop.systemd1.Manager",
3230 *property = "Environment";
3232 pager_open_if_enabled();
3234 r = bus_method_call_with_reply (
3236 "org.freedesktop.systemd1",
3237 "/org/freedesktop/systemd1",
3238 "org.freedesktop.DBus.Properties",
3242 DBUS_TYPE_STRING, &interface,
3243 DBUS_TYPE_STRING, &property,
3248 if (!dbus_message_iter_init(reply, &iter) ||
3249 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3250 log_error("Failed to parse reply.");
3255 dbus_message_iter_recurse(&iter, &sub);
3257 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3258 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3259 log_error("Failed to parse reply.");
3264 dbus_message_iter_recurse(&sub, &sub2);
3266 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3269 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3270 log_error("Failed to parse reply.");
3275 dbus_message_iter_get_basic(&sub2, &text);
3276 printf("%s\n", text);
3278 dbus_message_iter_next(&sub2);
3285 dbus_message_unref(reply);
3290 static int switch_root(DBusConnection *bus, char **args) {
3292 const char *root, *init;
3294 l = strv_length(args);
3295 if (l < 2 || l > 3) {
3296 log_error("Wrong number of arguments.");
3301 init = l >= 3 ? args[2] : "";
3303 return bus_method_call_with_reply (
3305 "org.freedesktop.systemd1",
3306 "/org/freedesktop/systemd1",
3307 "org.freedesktop.systemd1.Manager",
3311 DBUS_TYPE_STRING, &root,
3312 DBUS_TYPE_STRING, &init,
3316 static int set_environment(DBusConnection *bus, char **args) {
3317 DBusMessage *m = NULL, *reply = NULL;
3321 DBusMessageIter iter, sub;
3324 dbus_error_init(&error);
3326 method = streq(args[0], "set-environment")
3328 : "UnsetEnvironment";
3330 if (!(m = dbus_message_new_method_call(
3331 "org.freedesktop.systemd1",
3332 "/org/freedesktop/systemd1",
3333 "org.freedesktop.systemd1.Manager",
3336 log_error("Could not allocate message.");
3340 dbus_message_iter_init_append(m, &iter);
3342 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3343 log_error("Could not append arguments to message.");
3348 STRV_FOREACH(name, args+1)
3349 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, name)) {
3350 log_error("Could not append arguments to message.");
3355 if (!dbus_message_iter_close_container(&iter, &sub)) {
3356 log_error("Could not append arguments to message.");
3361 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3362 log_error("Failed to issue method call: %s", bus_error_message(&error));
3371 dbus_message_unref(m);
3374 dbus_message_unref(reply);
3376 dbus_error_free(&error);
3381 static int enable_sysv_units(char **args) {
3384 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_ALTLINUX) || defined(TARGET_MAGEIA))
3385 const char *verb = args[0];
3386 unsigned f = 1, t = 1;
3389 if (arg_scope != UNIT_FILE_SYSTEM)
3392 if (!streq(verb, "enable") &&
3393 !streq(verb, "disable") &&
3394 !streq(verb, "is-enabled"))
3397 /* Processes all SysV units, and reshuffles the array so that
3398 * afterwards only the native units remain */
3401 r = lookup_paths_init(&paths, MANAGER_SYSTEM, false, NULL, NULL, NULL);
3406 for (f = 1; args[f]; f++) {
3409 bool found_native = false, found_sysv;
3411 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3412 char **k, *l, *q = NULL;
3419 if (!endswith(name, ".service"))
3422 if (path_is_absolute(name))
3425 STRV_FOREACH(k, paths.unit_path) {
3428 if (!isempty(arg_root))
3429 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3431 asprintf(&p, "%s/%s", *k, name);
3438 found_native = access(p, F_OK) >= 0;
3449 if (!isempty(arg_root))
3450 asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3452 asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3458 p[strlen(p) - sizeof(".service") + 1] = 0;
3459 found_sysv = access(p, F_OK) >= 0;
3466 /* Mark this entry, so that we don't try enabling it as native unit */
3467 args[f] = (char*) "";
3469 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
3471 if (!isempty(arg_root))
3472 argv[c++] = q = strappend("--root=", arg_root);
3474 argv[c++] = path_get_file_name(p);
3476 streq(verb, "enable") ? "on" :
3477 streq(verb, "disable") ? "off" : "--level=5";
3480 l = strv_join((char**)argv, " ");
3488 log_info("Executing %s", l);
3493 log_error("Failed to fork: %m");
3498 } else if (pid == 0) {
3501 execv(argv[0], (char**) argv);
3502 _exit(EXIT_FAILURE);
3508 j = wait_for_terminate(pid, &status);
3510 log_error("Failed to wait for child: %s", strerror(-r));
3515 if (status.si_code == CLD_EXITED) {
3516 if (streq(verb, "is-enabled")) {
3517 if (status.si_status == 0) {
3526 } else if (status.si_status != 0) {
3537 lookup_paths_free(&paths);
3539 /* Drop all SysV units */
3540 for (f = 1, t = 1; args[f]; f++) {
3542 if (isempty(args[f]))
3545 args[t++] = args[f];
3554 static int mangle_names(char **original_names, char ***mangled_names) {
3555 char **i, **l, **name;
3557 l = new(char*, strv_length(original_names) + 1);
3562 STRV_FOREACH(name, original_names) {
3563 *i = unit_name_mangle(*name);
3578 static int enable_unit(DBusConnection *bus, char **args) {
3579 const char *verb = args[0];
3580 UnitFileChange *changes = NULL;
3581 unsigned n_changes = 0, i;
3582 int carries_install_info = -1;
3583 DBusMessage *m = NULL, *reply = NULL;
3586 char **mangled_names = NULL;
3588 r = enable_sysv_units(args);
3595 dbus_error_init(&error);
3597 if (!bus || avoid_bus()) {
3598 if (streq(verb, "enable")) {
3599 r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3600 carries_install_info = r;
3601 } else if (streq(verb, "disable"))
3602 r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3603 else if (streq(verb, "reenable")) {
3604 r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3605 carries_install_info = r;
3606 } else if (streq(verb, "link"))
3607 r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3608 else if (streq(verb, "preset")) {
3609 r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3610 carries_install_info = r;
3611 } else if (streq(verb, "mask"))
3612 r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3613 else if (streq(verb, "unmask"))
3614 r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3616 assert_not_reached("Unknown verb");
3619 log_error("Operation failed: %s", strerror(-r));
3624 for (i = 0; i < n_changes; i++) {
3625 if (changes[i].type == UNIT_FILE_SYMLINK)
3626 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
3628 log_info("rm '%s'", changes[i].path);
3634 bool send_force = true, expect_carries_install_info = false;
3636 DBusMessageIter iter, sub, sub2;
3638 if (streq(verb, "enable")) {
3639 method = "EnableUnitFiles";
3640 expect_carries_install_info = true;
3641 } else if (streq(verb, "disable")) {
3642 method = "DisableUnitFiles";
3644 } else if (streq(verb, "reenable")) {
3645 method = "ReenableUnitFiles";
3646 expect_carries_install_info = true;
3647 } else if (streq(verb, "link"))
3648 method = "LinkUnitFiles";
3649 else if (streq(verb, "preset")) {
3650 method = "PresetUnitFiles";
3651 expect_carries_install_info = true;
3652 } else if (streq(verb, "mask"))
3653 method = "MaskUnitFiles";
3654 else if (streq(verb, "unmask")) {
3655 method = "UnmaskUnitFiles";
3658 assert_not_reached("Unknown verb");
3660 m = dbus_message_new_method_call(
3661 "org.freedesktop.systemd1",
3662 "/org/freedesktop/systemd1",
3663 "org.freedesktop.systemd1.Manager",
3670 dbus_message_iter_init_append(m, &iter);
3672 r = mangle_names(args+1, &mangled_names);
3676 r = bus_append_strv_iter(&iter, mangled_names);
3678 log_error("Failed to append unit files.");
3683 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
3684 log_error("Failed to append runtime boolean.");
3692 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
3693 log_error("Failed to append force boolean.");
3699 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3701 log_error("Failed to issue method call: %s", bus_error_message(&error));
3706 if (!dbus_message_iter_init(reply, &iter)) {
3707 log_error("Failed to initialize iterator.");
3711 if (expect_carries_install_info) {
3712 r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
3714 log_error("Failed to parse reply.");
3718 carries_install_info = b;
3721 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3722 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
3723 log_error("Failed to parse reply.");
3728 dbus_message_iter_recurse(&iter, &sub);
3729 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3730 const char *type, *path, *source;
3732 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
3733 log_error("Failed to parse reply.");
3738 dbus_message_iter_recurse(&sub, &sub2);
3740 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
3741 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
3742 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
3743 log_error("Failed to parse reply.");
3749 if (streq(type, "symlink"))
3750 log_info("ln -s '%s' '%s'", source, path);
3752 log_info("rm '%s'", path);
3755 dbus_message_iter_next(&sub);
3758 /* Try to reload if enabeld */
3760 r = daemon_reload(bus, args);
3763 if (carries_install_info == 0)
3764 log_warning("The unit files have no [Install] section. They are not meant to be enabled using systemctl.");
3768 dbus_message_unref(m);
3771 dbus_message_unref(reply);
3773 unit_file_changes_free(changes, n_changes);
3775 dbus_error_free(&error);
3777 strv_free(mangled_names);
3782 static int unit_is_enabled(DBusConnection *bus, char **args) {
3785 DBusMessage *reply = NULL;
3789 dbus_error_init(&error);
3791 r = enable_sysv_units(args);
3797 if (!bus || avoid_bus()) {
3799 STRV_FOREACH(name, args+1) {
3800 UnitFileState state;
3802 state = unit_file_get_state(arg_scope, arg_root, *name);
3808 if (state == UNIT_FILE_ENABLED ||
3809 state == UNIT_FILE_ENABLED_RUNTIME ||
3810 state == UNIT_FILE_STATIC)
3814 puts(unit_file_state_to_string(state));
3818 STRV_FOREACH(name, args+1) {
3821 r = bus_method_call_with_reply (
3823 "org.freedesktop.systemd1",
3824 "/org/freedesktop/systemd1",
3825 "org.freedesktop.systemd1.Manager",
3829 DBUS_TYPE_STRING, name,
3834 if (!dbus_message_get_args(reply, &error,
3835 DBUS_TYPE_STRING, &s,
3836 DBUS_TYPE_INVALID)) {
3837 log_error("Failed to parse reply: %s", bus_error_message(&error));
3842 dbus_message_unref(reply);
3845 if (streq(s, "enabled") ||
3846 streq(s, "enabled-runtime") ||
3855 r = enabled ? 0 : 1;
3859 dbus_message_unref(reply);
3861 dbus_error_free(&error);
3865 static int systemctl_help(void) {
3867 pager_open_if_enabled();
3869 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3870 "Query or send control commands to the systemd manager.\n\n"
3871 " -h --help Show this help\n"
3872 " --version Show package version\n"
3873 " -t --type=TYPE List only units of a particular type\n"
3874 " -p --property=NAME Show only properties by this name\n"
3875 " -a --all Show all units/properties, including dead/empty ones\n"
3876 " --failed Show only failed units\n"
3877 " --full Don't ellipsize unit names on output\n"
3878 " --fail When queueing a new job, fail if conflicting jobs are\n"
3880 " --ignore-dependencies\n"
3881 " When queueing a new job, ignore all its dependencies\n"
3882 " --kill-who=WHO Who to send signal to\n"
3883 " -s --signal=SIGNAL Which signal to send\n"
3884 " -H --host=[USER@]HOST\n"
3885 " Show information for remote host\n"
3886 " -P --privileged Acquire privileges before execution\n"
3887 " -q --quiet Suppress output\n"
3888 " --no-block Do not wait until operation finished\n"
3889 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3890 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3892 " --no-legend Do not print a legend (column headers and hints)\n"
3893 " --no-pager Do not pipe output into a pager\n"
3894 " --no-ask-password\n"
3895 " Do not ask for system passwords\n"
3896 " --order When generating graph for dot, show only order\n"
3897 " --require When generating graph for dot, show only requirement\n"
3898 " --system Connect to system manager\n"
3899 " --user Connect to user service manager\n"
3900 " --global Enable/disable unit files globally\n"
3901 " -f --force When enabling unit files, override existing symlinks\n"
3902 " When shutting down, execute action immediately\n"
3903 " --root=PATH Enable unit files in the specified root directory\n"
3904 " --runtime Enable unit files only temporarily until next reboot\n"
3905 " -n --lines=INTEGER Journal entries to show\n"
3906 " --follow Follow journal\n"
3907 " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
3908 " verbose, export, json, json-pretty, cat)\n\n"
3910 " list-units List loaded units\n"
3911 " start [NAME...] Start (activate) one or more units\n"
3912 " stop [NAME...] Stop (deactivate) one or more units\n"
3913 " reload [NAME...] Reload one or more units\n"
3914 " restart [NAME...] Start or restart one or more units\n"
3915 " try-restart [NAME...] Restart one or more units if active\n"
3916 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3917 " otherwise start or restart\n"
3918 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3919 " otherwise restart if active\n"
3920 " isolate [NAME] Start one unit and stop all others\n"
3921 " kill [NAME...] Send signal to processes of a unit\n"
3922 " is-active [NAME...] Check whether units are active\n"
3923 " status [NAME...|PID...] Show runtime status of one or more units\n"
3924 " show [NAME...|JOB...] Show properties of one or more\n"
3925 " units/jobs or the manager\n"
3926 " help [NAME...|PID...] Show manual for one or more units\n"
3927 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3929 " load [NAME...] Load one or more units\n\n"
3930 "Unit File Commands:\n"
3931 " list-unit-files List installed unit files\n"
3932 " enable [NAME...] Enable one or more unit files\n"
3933 " disable [NAME...] Disable one or more unit files\n"
3934 " reenable [NAME...] Reenable one or more unit files\n"
3935 " preset [NAME...] Enable/disable one or more unit files\n"
3936 " based on preset configuration\n"
3937 " mask [NAME...] Mask one or more units\n"
3938 " unmask [NAME...] Unmask one or more units\n"
3939 " link [PATH...] Link one or more units files into\n"
3940 " the search path\n"
3941 " is-enabled [NAME...] Check whether unit files are enabled\n\n"
3943 " list-jobs List jobs\n"
3944 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
3945 "Status Commands:\n"
3946 " dump Dump server status\n"
3947 " dot Dump dependency graph for dot(1)\n\n"
3948 "Snapshot Commands:\n"
3949 " snapshot [NAME] Create a snapshot\n"
3950 " delete [NAME...] Remove one or more snapshots\n\n"
3951 "Environment Commands:\n"
3952 " show-environment Dump environment\n"
3953 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3954 " unset-environment [NAME...] Unset one or more environment variables\n\n"
3955 "Manager Lifecycle Commands:\n"
3956 " daemon-reload Reload systemd manager configuration\n"
3957 " daemon-reexec Reexecute systemd manager\n\n"
3958 "System Commands:\n"
3959 " default Enter system default mode\n"
3960 " rescue Enter system rescue mode\n"
3961 " emergency Enter system emergency mode\n"
3962 " halt Shut down and halt the system\n"
3963 " poweroff Shut down and power-off the system\n"
3964 " reboot Shut down and reboot the system\n"
3965 " kexec Shut down and reboot the system with kexec\n"
3966 " exit Request user instance exit\n"
3967 " switch-root [ROOT] [INIT] Change to a different root file system\n"
3968 " suspend Suspend the system\n"
3969 " hibernate Hibernate the system\n",
3970 program_invocation_short_name);
3975 static int halt_help(void) {
3977 printf("%s [OPTIONS...]\n\n"
3978 "%s the system.\n\n"
3979 " --help Show this help\n"
3980 " --halt Halt the machine\n"
3981 " -p --poweroff Switch off the machine\n"
3982 " --reboot Reboot the machine\n"
3983 " -f --force Force immediate halt/power-off/reboot\n"
3984 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3985 " -d --no-wtmp Don't write wtmp record\n"
3986 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3987 program_invocation_short_name,
3988 arg_action == ACTION_REBOOT ? "Reboot" :
3989 arg_action == ACTION_POWEROFF ? "Power off" :
3995 static int shutdown_help(void) {
3997 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3998 "Shut down the system.\n\n"
3999 " --help Show this help\n"
4000 " -H --halt Halt the machine\n"
4001 " -P --poweroff Power-off the machine\n"
4002 " -r --reboot Reboot the machine\n"
4003 " -h Equivalent to --poweroff, overridden by --halt\n"
4004 " -k Don't halt/power-off/reboot, just send warnings\n"
4005 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4006 " -c Cancel a pending shutdown\n",
4007 program_invocation_short_name);
4012 static int telinit_help(void) {
4014 printf("%s [OPTIONS...] {COMMAND}\n\n"
4015 "Send control commands to the init daemon.\n\n"
4016 " --help Show this help\n"
4017 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4019 " 0 Power-off the machine\n"
4020 " 6 Reboot the machine\n"
4021 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4022 " 1, s, S Enter rescue mode\n"
4023 " q, Q Reload init daemon configuration\n"
4024 " u, U Reexecute init daemon\n",
4025 program_invocation_short_name);
4030 static int runlevel_help(void) {
4032 printf("%s [OPTIONS...]\n\n"
4033 "Prints the previous and current runlevel of the init system.\n\n"
4034 " --help Show this help\n",
4035 program_invocation_short_name);
4040 static int systemctl_parse_argv(int argc, char *argv[]) {
4044 ARG_IGNORE_DEPENDENCIES,
4059 ARG_NO_ASK_PASSWORD,
4066 static const struct option options[] = {
4067 { "help", no_argument, NULL, 'h' },
4068 { "version", no_argument, NULL, ARG_VERSION },
4069 { "type", required_argument, NULL, 't' },
4070 { "property", required_argument, NULL, 'p' },
4071 { "all", no_argument, NULL, 'a' },
4072 { "failed", no_argument, NULL, ARG_FAILED },
4073 { "full", no_argument, NULL, ARG_FULL },
4074 { "fail", no_argument, NULL, ARG_FAIL },
4075 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4076 { "user", no_argument, NULL, ARG_USER },
4077 { "system", no_argument, NULL, ARG_SYSTEM },
4078 { "global", no_argument, NULL, ARG_GLOBAL },
4079 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4080 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
4081 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4082 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4083 { "quiet", no_argument, NULL, 'q' },
4084 { "order", no_argument, NULL, ARG_ORDER },
4085 { "require", no_argument, NULL, ARG_REQUIRE },
4086 { "root", required_argument, NULL, ARG_ROOT },
4087 { "force", no_argument, NULL, ARG_FORCE },
4088 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4089 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4090 { "signal", required_argument, NULL, 's' },
4091 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4092 { "host", required_argument, NULL, 'H' },
4093 { "privileged",no_argument, NULL, 'P' },
4094 { "runtime", no_argument, NULL, ARG_RUNTIME },
4095 { "lines", required_argument, NULL, 'n' },
4096 { "follow", no_argument, NULL, ARG_FOLLOW },
4097 { "output", required_argument, NULL, 'o' },
4098 { NULL, 0, NULL, 0 }
4106 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:Pn:o:", options, NULL)) >= 0) {
4115 puts(PACKAGE_STRING);
4117 puts(SYSTEMD_FEATURES);
4121 if (unit_type_from_string(optarg) >= 0) {
4125 if (unit_load_state_from_string(optarg) >= 0) {
4126 arg_load_state = optarg;
4129 log_error("Unkown unit type or load state '%s'.",
4135 if (!(l = strv_append(arg_property, optarg)))
4138 strv_free(arg_property);
4141 /* If the user asked for a particular
4142 * property, show it to him, even if it is
4153 arg_job_mode = "fail";
4156 case ARG_IGNORE_DEPENDENCIES:
4157 arg_job_mode = "ignore-dependencies";
4161 arg_scope = UNIT_FILE_USER;
4165 arg_scope = UNIT_FILE_SYSTEM;
4169 arg_scope = UNIT_FILE_GLOBAL;
4173 arg_no_block = true;
4177 arg_no_legend = true;
4181 arg_no_pager = true;
4189 arg_dot = DOT_ORDER;
4193 arg_dot = DOT_REQUIRE;
4221 /* -f is short for both --follow and --force! */
4227 arg_no_reload = true;
4231 arg_kill_who = optarg;
4235 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4236 log_error("Failed to parse signal string %s.", optarg);
4241 case ARG_NO_ASK_PASSWORD:
4242 arg_ask_password = false;
4246 arg_transport = TRANSPORT_POLKIT;
4250 arg_transport = TRANSPORT_SSH;
4259 if (safe_atou(optarg, &arg_lines) < 0) {
4260 log_error("Failed to parse lines '%s'", optarg);
4266 arg_output = output_mode_from_string(optarg);
4267 if (arg_output < 0) {
4268 log_error("Unknown output '%s'.", optarg);
4277 log_error("Unknown option code '%c'.", c);
4282 if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4283 log_error("Cannot access user instance remotely.");
4290 static int halt_parse_argv(int argc, char *argv[]) {
4299 static const struct option options[] = {
4300 { "help", no_argument, NULL, ARG_HELP },
4301 { "halt", no_argument, NULL, ARG_HALT },
4302 { "poweroff", no_argument, NULL, 'p' },
4303 { "reboot", no_argument, NULL, ARG_REBOOT },
4304 { "force", no_argument, NULL, 'f' },
4305 { "wtmp-only", no_argument, NULL, 'w' },
4306 { "no-wtmp", no_argument, NULL, 'd' },
4307 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4308 { NULL, 0, NULL, 0 }
4316 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4317 if (runlevel == '0' || runlevel == '6')
4320 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4328 arg_action = ACTION_HALT;
4332 if (arg_action != ACTION_REBOOT)
4333 arg_action = ACTION_POWEROFF;
4337 arg_action = ACTION_REBOOT;
4359 /* Compatibility nops */
4366 log_error("Unknown option code '%c'.", c);
4371 if (optind < argc) {
4372 log_error("Too many arguments.");
4379 static int parse_time_spec(const char *t, usec_t *_u) {
4383 if (streq(t, "now"))
4385 else if (!strchr(t, ':')) {
4388 if (safe_atou64(t, &u) < 0)
4391 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4400 hour = strtol(t, &e, 10);
4401 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4404 minute = strtol(e+1, &e, 10);
4405 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4408 n = now(CLOCK_REALTIME);
4409 s = (time_t) (n / USEC_PER_SEC);
4412 assert_se(localtime_r(&s, &tm));
4414 tm.tm_hour = (int) hour;
4415 tm.tm_min = (int) minute;
4418 assert_se(s = mktime(&tm));
4420 *_u = (usec_t) s * USEC_PER_SEC;
4423 *_u += USEC_PER_DAY;
4429 static int shutdown_parse_argv(int argc, char *argv[]) {
4436 static const struct option options[] = {
4437 { "help", no_argument, NULL, ARG_HELP },
4438 { "halt", no_argument, NULL, 'H' },
4439 { "poweroff", no_argument, NULL, 'P' },
4440 { "reboot", no_argument, NULL, 'r' },
4441 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
4442 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4443 { NULL, 0, NULL, 0 }
4451 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4459 arg_action = ACTION_HALT;
4463 arg_action = ACTION_POWEROFF;
4468 arg_action = ACTION_KEXEC;
4470 arg_action = ACTION_REBOOT;
4474 arg_action = ACTION_KEXEC;
4478 if (arg_action != ACTION_HALT)
4479 arg_action = ACTION_POWEROFF;
4492 /* Compatibility nops */
4496 arg_action = ACTION_CANCEL_SHUTDOWN;
4503 log_error("Unknown option code '%c'.", c);
4508 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
4509 r = parse_time_spec(argv[optind], &arg_when);
4511 log_error("Failed to parse time specification: %s", argv[optind]);
4515 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4517 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
4518 /* No time argument for shutdown cancel */
4519 arg_wall = argv + optind;
4520 else if (argc > optind + 1)
4521 /* We skip the time argument */
4522 arg_wall = argv + optind + 1;
4529 static int telinit_parse_argv(int argc, char *argv[]) {
4536 static const struct option options[] = {
4537 { "help", no_argument, NULL, ARG_HELP },
4538 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4539 { NULL, 0, NULL, 0 }
4542 static const struct {
4546 { '0', ACTION_POWEROFF },
4547 { '6', ACTION_REBOOT },
4548 { '1', ACTION_RESCUE },
4549 { '2', ACTION_RUNLEVEL2 },
4550 { '3', ACTION_RUNLEVEL3 },
4551 { '4', ACTION_RUNLEVEL4 },
4552 { '5', ACTION_RUNLEVEL5 },
4553 { 's', ACTION_RESCUE },
4554 { 'S', ACTION_RESCUE },
4555 { 'q', ACTION_RELOAD },
4556 { 'Q', ACTION_RELOAD },
4557 { 'u', ACTION_REEXEC },
4558 { 'U', ACTION_REEXEC }
4567 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4582 log_error("Unknown option code '%c'.", c);
4587 if (optind >= argc) {
4592 if (optind + 1 < argc) {
4593 log_error("Too many arguments.");
4597 if (strlen(argv[optind]) != 1) {
4598 log_error("Expected single character argument.");
4602 for (i = 0; i < ELEMENTSOF(table); i++)
4603 if (table[i].from == argv[optind][0])
4606 if (i >= ELEMENTSOF(table)) {
4607 log_error("Unknown command '%s'.", argv[optind]);
4611 arg_action = table[i].to;
4618 static int runlevel_parse_argv(int argc, char *argv[]) {
4624 static const struct option options[] = {
4625 { "help", no_argument, NULL, ARG_HELP },
4626 { NULL, 0, NULL, 0 }
4634 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4645 log_error("Unknown option code '%c'.", c);
4650 if (optind < argc) {
4651 log_error("Too many arguments.");
4658 static int parse_argv(int argc, char *argv[]) {
4662 if (program_invocation_short_name) {
4664 if (strstr(program_invocation_short_name, "halt")) {
4665 arg_action = ACTION_HALT;
4666 return halt_parse_argv(argc, argv);
4667 } else if (strstr(program_invocation_short_name, "poweroff")) {
4668 arg_action = ACTION_POWEROFF;
4669 return halt_parse_argv(argc, argv);
4670 } else if (strstr(program_invocation_short_name, "reboot")) {
4672 arg_action = ACTION_KEXEC;
4674 arg_action = ACTION_REBOOT;
4675 return halt_parse_argv(argc, argv);
4676 } else if (strstr(program_invocation_short_name, "shutdown")) {
4677 arg_action = ACTION_POWEROFF;
4678 return shutdown_parse_argv(argc, argv);
4679 } else if (strstr(program_invocation_short_name, "init")) {
4681 if (sd_booted() > 0) {
4682 arg_action = ACTION_INVALID;
4683 return telinit_parse_argv(argc, argv);
4685 /* Hmm, so some other init system is
4686 * running, we need to forward this
4687 * request to it. For now we simply
4688 * guess that it is Upstart. */
4690 execv("/lib/upstart/telinit", argv);
4692 log_error("Couldn't find an alternative telinit implementation to spawn.");
4696 } else if (strstr(program_invocation_short_name, "runlevel")) {
4697 arg_action = ACTION_RUNLEVEL;
4698 return runlevel_parse_argv(argc, argv);
4702 arg_action = ACTION_SYSTEMCTL;
4703 return systemctl_parse_argv(argc, argv);
4706 static int action_to_runlevel(void) {
4708 static const char table[_ACTION_MAX] = {
4709 [ACTION_HALT] = '0',
4710 [ACTION_POWEROFF] = '0',
4711 [ACTION_REBOOT] = '6',
4712 [ACTION_RUNLEVEL2] = '2',
4713 [ACTION_RUNLEVEL3] = '3',
4714 [ACTION_RUNLEVEL4] = '4',
4715 [ACTION_RUNLEVEL5] = '5',
4716 [ACTION_RESCUE] = '1'
4719 assert(arg_action < _ACTION_MAX);
4721 return table[arg_action];
4724 static int talk_upstart(void) {
4725 DBusMessage *m = NULL, *reply = NULL;
4727 int previous, rl, r;
4729 env1_buf[] = "RUNLEVEL=X",
4730 env2_buf[] = "PREVLEVEL=X";
4731 char *env1 = env1_buf, *env2 = env2_buf;
4732 const char *emit = "runlevel";
4733 dbus_bool_t b_false = FALSE;
4734 DBusMessageIter iter, sub;
4735 DBusConnection *bus;
4737 dbus_error_init(&error);
4739 if (!(rl = action_to_runlevel()))
4742 if (utmp_get_runlevel(&previous, NULL) < 0)
4745 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4746 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4751 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4756 if ((r = bus_check_peercred(bus)) < 0) {
4757 log_error("Failed to verify owner of bus.");
4761 if (!(m = dbus_message_new_method_call(
4762 "com.ubuntu.Upstart",
4763 "/com/ubuntu/Upstart",
4764 "com.ubuntu.Upstart0_6",
4767 log_error("Could not allocate message.");
4772 dbus_message_iter_init_append(m, &iter);
4774 env1_buf[sizeof(env1_buf)-2] = rl;
4775 env2_buf[sizeof(env2_buf)-2] = previous;
4777 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4778 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4779 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4780 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4781 !dbus_message_iter_close_container(&iter, &sub) ||
4782 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4783 log_error("Could not append arguments to message.");
4788 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4790 if (bus_error_is_no_service(&error)) {
4795 log_error("Failed to issue method call: %s", bus_error_message(&error));
4804 dbus_message_unref(m);
4807 dbus_message_unref(reply);
4810 dbus_connection_flush(bus);
4811 dbus_connection_close(bus);
4812 dbus_connection_unref(bus);
4815 dbus_error_free(&error);
4820 static int talk_initctl(void) {
4821 struct init_request request;
4825 if (!(rl = action_to_runlevel()))
4829 request.magic = INIT_MAGIC;
4830 request.sleeptime = 0;
4831 request.cmd = INIT_CMD_RUNLVL;
4832 request.runlevel = rl;
4834 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4836 if (errno == ENOENT)
4839 log_error("Failed to open "INIT_FIFO": %m");
4844 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4845 close_nointr_nofail(fd);
4848 log_error("Failed to write to "INIT_FIFO": %m");
4849 return errno ? -errno : -EIO;
4855 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4857 static const struct {
4865 int (* const dispatch)(DBusConnection *bus, char **args);
4867 { "list-units", LESS, 1, list_units },
4868 { "list-unit-files", EQUAL, 1, list_unit_files },
4869 { "list-jobs", EQUAL, 1, list_jobs },
4870 { "clear-jobs", EQUAL, 1, daemon_reload },
4871 { "load", MORE, 2, load_unit },
4872 { "cancel", MORE, 2, cancel_job },
4873 { "start", MORE, 2, start_unit },
4874 { "stop", MORE, 2, start_unit },
4875 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4876 { "reload", MORE, 2, start_unit },
4877 { "restart", MORE, 2, start_unit },
4878 { "try-restart", MORE, 2, start_unit },
4879 { "reload-or-restart", MORE, 2, start_unit },
4880 { "reload-or-try-restart", MORE, 2, start_unit },
4881 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4882 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
4883 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4884 { "isolate", EQUAL, 2, start_unit },
4885 { "kill", MORE, 2, kill_unit },
4886 { "is-active", MORE, 2, check_unit },
4887 { "check", MORE, 2, check_unit },
4888 { "show", MORE, 1, show },
4889 { "status", MORE, 2, show },
4890 { "help", MORE, 2, show },
4891 { "dump", EQUAL, 1, dump },
4892 { "dot", EQUAL, 1, dot },
4893 { "snapshot", LESS, 2, snapshot },
4894 { "delete", MORE, 2, delete_snapshot },
4895 { "daemon-reload", EQUAL, 1, daemon_reload },
4896 { "daemon-reexec", EQUAL, 1, daemon_reload },
4897 { "show-environment", EQUAL, 1, show_enviroment },
4898 { "set-environment", MORE, 2, set_environment },
4899 { "unset-environment", MORE, 2, set_environment },
4900 { "halt", EQUAL, 1, start_special },
4901 { "poweroff", EQUAL, 1, start_special },
4902 { "reboot", EQUAL, 1, start_special },
4903 { "kexec", EQUAL, 1, start_special },
4904 { "suspend", EQUAL, 1, start_special },
4905 { "hibernate", EQUAL, 1, start_special },
4906 { "default", EQUAL, 1, start_special },
4907 { "rescue", EQUAL, 1, start_special },
4908 { "emergency", EQUAL, 1, start_special },
4909 { "exit", EQUAL, 1, start_special },
4910 { "reset-failed", MORE, 1, reset_failed },
4911 { "enable", MORE, 2, enable_unit },
4912 { "disable", MORE, 2, enable_unit },
4913 { "is-enabled", MORE, 2, unit_is_enabled },
4914 { "reenable", MORE, 2, enable_unit },
4915 { "preset", MORE, 2, enable_unit },
4916 { "mask", MORE, 2, enable_unit },
4917 { "unmask", MORE, 2, enable_unit },
4918 { "link", MORE, 2, enable_unit },
4919 { "switch-root", MORE, 2, switch_root },
4929 left = argc - optind;
4932 /* Special rule: no arguments means "list-units" */
4935 if (streq(argv[optind], "help") && !argv[optind+1]) {
4936 log_error("This command expects one or more "
4937 "unit names. Did you mean --help?");
4941 for (i = 0; i < ELEMENTSOF(verbs); i++)
4942 if (streq(argv[optind], verbs[i].verb))
4945 if (i >= ELEMENTSOF(verbs)) {
4946 log_error("Unknown operation '%s'.", argv[optind]);
4951 switch (verbs[i].argc_cmp) {
4954 if (left != verbs[i].argc) {
4955 log_error("Invalid number of arguments.");
4962 if (left < verbs[i].argc) {
4963 log_error("Too few arguments.");
4970 if (left > verbs[i].argc) {
4971 log_error("Too many arguments.");
4978 assert_not_reached("Unknown comparison operator.");
4981 /* Require a bus connection for all operations but
4983 if (!streq(verbs[i].verb, "enable") &&
4984 !streq(verbs[i].verb, "disable") &&
4985 !streq(verbs[i].verb, "is-enabled") &&
4986 !streq(verbs[i].verb, "list-unit-files") &&
4987 !streq(verbs[i].verb, "reenable") &&
4988 !streq(verbs[i].verb, "preset") &&
4989 !streq(verbs[i].verb, "mask") &&
4990 !streq(verbs[i].verb, "unmask") &&
4991 !streq(verbs[i].verb, "link")) {
4993 if (running_in_chroot() > 0) {
4994 log_info("Running in chroot, ignoring request.");
4998 if (((!streq(verbs[i].verb, "reboot") &&
4999 !streq(verbs[i].verb, "halt") &&
5000 !streq(verbs[i].verb, "poweroff")) || arg_force <= 0) && !bus) {
5001 log_error("Failed to get D-Bus connection: %s",
5002 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5008 if (!bus && !avoid_bus()) {
5009 log_error("Failed to get D-Bus connection: %s",
5010 dbus_error_is_set(error) ? error->message : "No connection to service manager.");
5015 return verbs[i].dispatch(bus, argv + optind);
5018 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5020 struct msghdr msghdr;
5021 struct iovec iovec[2];
5022 union sockaddr_union sockaddr;
5023 struct sd_shutdown_command c;
5025 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
5032 c.dry_run = dry_run;
5036 sockaddr.sa.sa_family = AF_UNIX;
5037 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5040 msghdr.msg_name = &sockaddr;
5041 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5044 iovec[0].iov_base = (char*) &c;
5045 iovec[0].iov_len = offsetof(struct sd_shutdown_command, wall_message);
5047 if (isempty(message))
5048 msghdr.msg_iovlen = 1;
5050 iovec[1].iov_base = (char*) message;
5051 iovec[1].iov_len = strlen(message);
5052 msghdr.msg_iovlen = 2;
5054 msghdr.msg_iov = iovec;
5056 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5057 close_nointr_nofail(fd);
5061 close_nointr_nofail(fd);
5065 static int reload_with_fallback(DBusConnection *bus) {
5068 /* First, try systemd via D-Bus. */
5069 if (daemon_reload(bus, NULL) >= 0)
5073 /* Nothing else worked, so let's try signals */
5074 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5076 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5077 log_error("kill() failed: %m");
5084 static int start_with_fallback(DBusConnection *bus) {
5087 /* First, try systemd via D-Bus. */
5088 if (start_unit(bus, NULL) >= 0)
5092 /* Hmm, talking to systemd via D-Bus didn't work. Then
5093 * let's try to talk to Upstart via D-Bus. */
5094 if (talk_upstart() > 0)
5097 /* Nothing else worked, so let's try
5099 if (talk_initctl() > 0)
5102 log_error("Failed to talk to init daemon.");
5106 warn_wall(arg_action);
5110 static _noreturn_ void halt_now(enum action a) {
5112 /* Make sure C-A-D is handled by the kernel from this
5114 reboot(RB_ENABLE_CAD);
5119 log_info("Halting.");
5120 reboot(RB_HALT_SYSTEM);
5123 case ACTION_POWEROFF:
5124 log_info("Powering off.");
5125 reboot(RB_POWER_OFF);
5129 log_info("Rebooting.");
5130 reboot(RB_AUTOBOOT);
5134 assert_not_reached("Unknown halt action.");
5137 assert_not_reached("Uh? This shouldn't happen.");
5140 static int halt_main(DBusConnection *bus) {
5143 if (geteuid() != 0) {
5144 /* Try logind if we are a normal user and no special
5145 * mode applies. Maybe PolicyKit allows us to shutdown
5148 if (arg_when <= 0 &&
5151 (arg_action == ACTION_POWEROFF ||
5152 arg_action == ACTION_REBOOT)) {
5153 r = reboot_with_logind(bus, arg_action);
5158 log_error("Must be root.");
5165 m = strv_join(arg_wall, " ");
5166 r = send_shutdownd(arg_when,
5167 arg_action == ACTION_HALT ? 'H' :
5168 arg_action == ACTION_POWEROFF ? 'P' :
5169 arg_action == ACTION_KEXEC ? 'K' :
5177 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5179 char date[FORMAT_TIMESTAMP_MAX];
5181 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5182 format_timestamp(date, sizeof(date), arg_when));
5187 if (!arg_dry && !arg_force)
5188 return start_with_fallback(bus);
5191 if (sd_booted() > 0)
5192 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5194 r = utmp_put_shutdown();
5196 log_warning("Failed to write utmp record: %s", strerror(-r));
5203 halt_now(arg_action);
5204 /* We should never reach this. */
5208 static int runlevel_main(void) {
5209 int r, runlevel, previous;
5211 r = utmp_get_runlevel(&runlevel, &previous);
5218 previous <= 0 ? 'N' : previous,
5219 runlevel <= 0 ? 'N' : runlevel);
5224 int main(int argc, char*argv[]) {
5225 int r, retval = EXIT_FAILURE;
5226 DBusConnection *bus = NULL;
5229 dbus_error_init(&error);
5231 log_parse_environment();
5234 r = parse_argv(argc, argv);
5238 retval = EXIT_SUCCESS;
5242 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5243 * let's shortcut this */
5244 if (arg_action == ACTION_RUNLEVEL) {
5245 r = runlevel_main();
5246 retval = r < 0 ? EXIT_FAILURE : r;
5250 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5251 log_info("Running in chroot, ignoring request.");
5257 if (arg_transport == TRANSPORT_NORMAL)
5258 bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5259 else if (arg_transport == TRANSPORT_POLKIT) {
5260 bus_connect_system_polkit(&bus, &error);
5261 private_bus = false;
5262 } else if (arg_transport == TRANSPORT_SSH) {
5263 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5264 private_bus = false;
5266 assert_not_reached("Uh, invalid transport...");
5269 switch (arg_action) {
5271 case ACTION_SYSTEMCTL:
5272 r = systemctl_main(bus, argc, argv, &error);
5276 case ACTION_POWEROFF:
5282 case ACTION_RUNLEVEL2:
5283 case ACTION_RUNLEVEL3:
5284 case ACTION_RUNLEVEL4:
5285 case ACTION_RUNLEVEL5:
5287 case ACTION_EMERGENCY:
5288 case ACTION_DEFAULT:
5289 r = start_with_fallback(bus);
5294 r = reload_with_fallback(bus);
5297 case ACTION_CANCEL_SHUTDOWN: {
5301 m = strv_join(arg_wall, " ");
5303 retval = EXIT_FAILURE;
5307 r = send_shutdownd(arg_when, SD_SHUTDOWN_NONE, false, !arg_no_wall, m);
5309 log_warning("Failed to talk to shutdownd, shutdown hasn't been cancelled: %s", strerror(-r));
5314 case ACTION_INVALID:
5315 case ACTION_RUNLEVEL:
5317 assert_not_reached("Unknown action");
5320 retval = r < 0 ? EXIT_FAILURE : r;
5324 dbus_connection_flush(bus);
5325 dbus_connection_close(bus);
5326 dbus_connection_unref(bus);
5329 dbus_error_free(&error);
5333 strv_free(arg_property);
5336 ask_password_agent_close();
5337 polkit_agent_close();