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 General Public License as published by
10 the Free Software Foundation; either version 2 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 General Public License for more details.
18 You should have received a copy of the GNU 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>
37 #include <dbus/dbus.h>
43 #include "utmp-wtmp.h"
47 #include "dbus-common.h"
48 #include "cgroup-show.h"
49 #include "cgroup-util.h"
51 #include "path-lookup.h"
52 #include "conf-parser.h"
53 #include "sd-daemon.h"
54 #include "shutdownd.h"
55 #include "exit-status.h"
56 #include "bus-errors.h"
58 #include "unit-name.h"
60 static const char *arg_type = NULL;
61 static char **arg_property = NULL;
62 static bool arg_all = false;
63 static bool arg_fail = false;
64 static bool arg_user = false;
65 static bool arg_global = false;
66 static bool arg_immediate = false;
67 static bool arg_no_block = false;
68 static bool arg_no_pager = false;
69 static bool arg_no_wtmp = false;
70 static bool arg_no_sync = false;
71 static bool arg_no_wall = false;
72 static bool arg_no_reload = false;
73 static bool arg_dry = false;
74 static bool arg_quiet = false;
75 static bool arg_full = false;
76 static bool arg_force = false;
77 static bool arg_defaults = false;
78 static bool arg_ask_password = false;
79 static char **arg_wall = NULL;
80 static const char *arg_kill_who = NULL;
81 static const char *arg_kill_mode = NULL;
82 static int arg_signal = SIGTERM;
83 static usec_t arg_when = 0;
102 ACTION_CANCEL_SHUTDOWN,
104 } arg_action = ACTION_SYSTEMCTL;
111 static bool private_bus = false;
113 static pid_t pager_pid = 0;
115 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
116 static void pager_open(void);
118 static bool on_tty(void) {
121 /* Note that this is invoked relatively early, before we start
122 * the pager. That means the value we return reflects whether
123 * we originally were started on a tty, not if we currently
124 * are. But this is intended, since we want color, and so on
125 * when run in our own pager. */
127 if (_unlikely_(t < 0))
128 t = isatty(STDOUT_FILENO) > 0;
133 static void spawn_ask_password_agent(void) {
136 /* We check STDIN here, not STDOUT, since this is about input,
138 if (!isatty(STDIN_FILENO))
141 if (!arg_ask_password)
146 /* Spawns a temporary TTY agent, making sure it goes away when
149 if ((child = fork()) < 0)
155 const char * const args[] = {
156 SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH,
161 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
164 /* Check whether our parent died before we were able
165 * to set the death signal */
166 if (getppid() != parent)
169 execv(args[0], (char **) args);
174 static const char *ansi_highlight(bool b) {
179 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
182 static const char *ansi_highlight_green(bool b) {
187 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
190 static bool error_is_no_service(const DBusError *error) {
193 if (!dbus_error_is_set(error))
196 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
199 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
202 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
205 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
208 if (!dbus_error_is_set(error))
211 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
212 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
213 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
214 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
215 return EXIT_NOPERMISSION;
217 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
218 return EXIT_NOTINSTALLED;
220 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
221 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
222 return EXIT_NOTIMPLEMENTED;
224 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
225 return EXIT_NOTCONFIGURED;
233 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
238 if (dbus_message_iter_get_arg_type(iter) != type)
241 dbus_message_iter_get_basic(iter, data);
243 if (!dbus_message_iter_next(iter) != !next)
249 static void warn_wall(enum action action) {
250 static const char *table[_ACTION_MAX] = {
251 [ACTION_HALT] = "The system is going down for system halt NOW!",
252 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
253 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
254 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
255 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
256 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
265 if (!(p = strv_join(arg_wall, " "))) {
266 log_error("Failed to join strings.");
282 utmp_wall(table[action], NULL);
287 const char *description;
288 const char *load_state;
289 const char *active_state;
290 const char *sub_state;
291 const char *following;
292 const char *unit_path;
294 const char *job_type;
295 const char *job_path;
298 static int compare_unit_info(const void *a, const void *b) {
300 const struct unit_info *u = a, *v = b;
302 d1 = strrchr(u->id, '.');
303 d2 = strrchr(v->id, '.');
308 if ((r = strcasecmp(d1, d2)) != 0)
312 return strcasecmp(u->id, v->id);
315 static bool output_show_job(const struct unit_info *u) {
318 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
319 streq(dot+1, arg_type))) &&
320 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
323 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
324 unsigned active_len, sub_len, job_len, n_shown = 0;
325 const struct unit_info *u;
327 active_len = sizeof("ACTIVE")-1;
328 sub_len = sizeof("SUB")-1;
329 job_len = sizeof("JOB")-1;
331 for (u = unit_infos; u < unit_infos + c; u++) {
332 if (!output_show_job(u))
335 active_len = MAX(active_len, strlen(u->active_state));
336 sub_len = MAX(sub_len, strlen(u->sub_state));
338 job_len = MAX(job_len, strlen(u->job_type));
342 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
343 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
344 if (columns() >= 80+12 || arg_full)
345 printf(" %s\n", "DESCRIPTION");
350 for (u = unit_infos; u < unit_infos + c; u++) {
353 const char *on_loaded, *off_loaded;
354 const char *on_active, *off_active;
356 if (!output_show_job(u))
361 if (!streq(u->load_state, "loaded") &&
362 !streq(u->load_state, "banned")) {
363 on_loaded = ansi_highlight(true);
364 off_loaded = ansi_highlight(false);
366 on_loaded = off_loaded = "";
368 if (streq(u->active_state, "failed")) {
369 on_active = ansi_highlight(true);
370 off_active = ansi_highlight(false);
372 on_active = off_active = "";
374 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
376 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
378 on_loaded, u->load_state, off_loaded,
379 on_active, active_len, u->active_state,
380 sub_len, u->sub_state, off_active,
385 a -= strlen(on_loaded) + strlen(off_loaded);
386 a -= strlen(on_active) + strlen(off_active);
389 printf(" %-*s", job_len, u->job_type);
393 if (a + b + 1 < columns()) {
395 printf(" %-*s", job_len, "");
398 printf(" %s", u->description);
400 printf(" %.*s", columns() - a - b - 1, u->description);
407 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
408 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
409 "SUB = The low-level unit activation state, values depend on unit type.\n"
410 "JOB = Pending job for the unit.\n");
413 printf("\n%u units listed.\n", n_shown);
415 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
419 static int list_units(DBusConnection *bus, char **args, unsigned n) {
420 DBusMessage *m = NULL, *reply = NULL;
423 DBusMessageIter iter, sub, sub2;
424 unsigned c = 0, n_units = 0;
425 struct unit_info *unit_infos = NULL;
427 dbus_error_init(&error);
433 if (!(m = dbus_message_new_method_call(
434 "org.freedesktop.systemd1",
435 "/org/freedesktop/systemd1",
436 "org.freedesktop.systemd1.Manager",
438 log_error("Could not allocate message.");
442 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
443 log_error("Failed to issue method call: %s", bus_error_message(&error));
448 if (!dbus_message_iter_init(reply, &iter) ||
449 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
450 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
451 log_error("Failed to parse reply.");
456 dbus_message_iter_recurse(&iter, &sub);
458 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
461 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
462 log_error("Failed to parse reply.");
470 n_units = MAX(2*c, 16);
471 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
474 log_error("Failed to allocate unit array.");
484 dbus_message_iter_recurse(&sub, &sub2);
486 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
487 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
488 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
489 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
490 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
491 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
492 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
493 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
494 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
495 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
496 log_error("Failed to parse reply.");
501 dbus_message_iter_next(&sub);
505 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
506 output_units_list(unit_infos, c);
512 dbus_message_unref(m);
515 dbus_message_unref(reply);
519 dbus_error_free(&error);
524 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
525 static const char * const colors[] = {
526 "Requires", "[color=\"black\"]",
527 "RequiresOverridable", "[color=\"black\"]",
528 "Requisite", "[color=\"darkblue\"]",
529 "RequisiteOverridable", "[color=\"darkblue\"]",
530 "Wants", "[color=\"darkgrey\"]",
531 "Conflicts", "[color=\"red\"]",
532 "ConflictedBy", "[color=\"red\"]",
533 "After", "[color=\"green\"]"
536 const char *c = NULL;
543 for (i = 0; i < ELEMENTSOF(colors); i += 2)
544 if (streq(colors[i], prop)) {
552 if (arg_dot != DOT_ALL)
553 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
556 switch (dbus_message_iter_get_arg_type(iter)) {
558 case DBUS_TYPE_ARRAY:
560 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
563 dbus_message_iter_recurse(iter, &sub);
565 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
568 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
569 dbus_message_iter_get_basic(&sub, &s);
570 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
572 dbus_message_iter_next(&sub);
582 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
583 DBusMessage *m = NULL, *reply = NULL;
584 const char *interface = "org.freedesktop.systemd1.Unit";
587 DBusMessageIter iter, sub, sub2, sub3;
592 dbus_error_init(&error);
594 if (!(m = dbus_message_new_method_call(
595 "org.freedesktop.systemd1",
597 "org.freedesktop.DBus.Properties",
599 log_error("Could not allocate message.");
604 if (!dbus_message_append_args(m,
605 DBUS_TYPE_STRING, &interface,
606 DBUS_TYPE_INVALID)) {
607 log_error("Could not append arguments to message.");
612 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
613 log_error("Failed to issue method call: %s", bus_error_message(&error));
618 if (!dbus_message_iter_init(reply, &iter) ||
619 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
620 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
621 log_error("Failed to parse reply.");
626 dbus_message_iter_recurse(&iter, &sub);
628 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
631 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
632 log_error("Failed to parse reply.");
637 dbus_message_iter_recurse(&sub, &sub2);
639 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
640 log_error("Failed to parse reply.");
645 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
646 log_error("Failed to parse reply.");
651 dbus_message_iter_recurse(&sub2, &sub3);
653 if (dot_one_property(name, prop, &sub3)) {
654 log_error("Failed to parse reply.");
659 dbus_message_iter_next(&sub);
666 dbus_message_unref(m);
669 dbus_message_unref(reply);
671 dbus_error_free(&error);
676 static int dot(DBusConnection *bus, char **args, unsigned n) {
677 DBusMessage *m = NULL, *reply = NULL;
680 DBusMessageIter iter, sub, sub2;
682 dbus_error_init(&error);
686 if (!(m = dbus_message_new_method_call(
687 "org.freedesktop.systemd1",
688 "/org/freedesktop/systemd1",
689 "org.freedesktop.systemd1.Manager",
691 log_error("Could not allocate message.");
695 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
696 log_error("Failed to issue method call: %s", bus_error_message(&error));
701 if (!dbus_message_iter_init(reply, &iter) ||
702 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
703 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
704 log_error("Failed to parse reply.");
709 printf("digraph systemd {\n");
711 dbus_message_iter_recurse(&iter, &sub);
712 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
713 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
715 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
716 log_error("Failed to parse reply.");
721 dbus_message_iter_recurse(&sub, &sub2);
723 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
724 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
725 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
726 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
727 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
728 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
729 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
730 log_error("Failed to parse reply.");
735 if ((r = dot_one(bus, id, unit_path)) < 0)
738 /* printf("\t\"%s\";\n", id); */
739 dbus_message_iter_next(&sub);
744 log_info(" Color legend: black = Requires\n"
745 " dark blue = Requisite\n"
746 " dark grey = Wants\n"
750 if (isatty(fileno(stdout)))
751 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
752 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
758 dbus_message_unref(m);
761 dbus_message_unref(reply);
763 dbus_error_free(&error);
768 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
769 DBusMessage *m = NULL, *reply = NULL;
772 DBusMessageIter iter, sub, sub2;
775 dbus_error_init(&error);
781 if (!(m = dbus_message_new_method_call(
782 "org.freedesktop.systemd1",
783 "/org/freedesktop/systemd1",
784 "org.freedesktop.systemd1.Manager",
786 log_error("Could not allocate message.");
790 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
791 log_error("Failed to issue method call: %s", bus_error_message(&error));
796 if (!dbus_message_iter_init(reply, &iter) ||
797 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
798 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
799 log_error("Failed to parse reply.");
804 dbus_message_iter_recurse(&iter, &sub);
806 if (isatty(STDOUT_FILENO))
807 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
809 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
810 const char *name, *type, *state, *job_path, *unit_path;
814 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
815 log_error("Failed to parse reply.");
820 dbus_message_iter_recurse(&sub, &sub2);
822 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
823 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
824 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
825 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
826 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
827 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
828 log_error("Failed to parse reply.");
833 e = arg_full ? NULL : ellipsize(name, 25, 33);
834 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
839 dbus_message_iter_next(&sub);
842 if (isatty(STDOUT_FILENO))
843 printf("\n%u jobs listed.\n", k);
849 dbus_message_unref(m);
852 dbus_message_unref(reply);
854 dbus_error_free(&error);
859 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
860 DBusMessage *m = NULL, *reply = NULL;
865 dbus_error_init(&error);
870 for (i = 1; i < n; i++) {
872 if (!(m = dbus_message_new_method_call(
873 "org.freedesktop.systemd1",
874 "/org/freedesktop/systemd1",
875 "org.freedesktop.systemd1.Manager",
877 log_error("Could not allocate message.");
882 if (!dbus_message_append_args(m,
883 DBUS_TYPE_STRING, &args[i],
884 DBUS_TYPE_INVALID)) {
885 log_error("Could not append arguments to message.");
890 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
891 log_error("Failed to issue method call: %s", bus_error_message(&error));
896 dbus_message_unref(m);
897 dbus_message_unref(reply);
906 dbus_message_unref(m);
909 dbus_message_unref(reply);
911 dbus_error_free(&error);
916 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
917 DBusMessage *m = NULL, *reply = NULL;
922 dbus_error_init(&error);
928 return daemon_reload(bus, args, n);
930 for (i = 1; i < n; i++) {
934 if (!(m = dbus_message_new_method_call(
935 "org.freedesktop.systemd1",
936 "/org/freedesktop/systemd1",
937 "org.freedesktop.systemd1.Manager",
939 log_error("Could not allocate message.");
944 if ((r = safe_atou(args[i], &id)) < 0) {
945 log_error("Failed to parse job id: %s", strerror(-r));
949 assert_cc(sizeof(uint32_t) == sizeof(id));
950 if (!dbus_message_append_args(m,
951 DBUS_TYPE_UINT32, &id,
952 DBUS_TYPE_INVALID)) {
953 log_error("Could not append arguments to message.");
958 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
959 log_error("Failed to issue method call: %s", bus_error_message(&error));
964 if (!dbus_message_get_args(reply, &error,
965 DBUS_TYPE_OBJECT_PATH, &path,
966 DBUS_TYPE_INVALID)) {
967 log_error("Failed to parse reply: %s", bus_error_message(&error));
972 dbus_message_unref(m);
973 if (!(m = dbus_message_new_method_call(
974 "org.freedesktop.systemd1",
976 "org.freedesktop.systemd1.Job",
978 log_error("Could not allocate message.");
983 dbus_message_unref(reply);
984 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
985 log_error("Failed to issue method call: %s", bus_error_message(&error));
990 dbus_message_unref(m);
991 dbus_message_unref(reply);
999 dbus_message_unref(m);
1002 dbus_message_unref(reply);
1004 dbus_error_free(&error);
1009 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1010 DBusMessage *m = NULL, *reply = NULL;
1011 dbus_bool_t b = FALSE;
1012 DBusMessageIter iter, sub;
1014 *interface = "org.freedesktop.systemd1.Unit",
1015 *property = "NeedDaemonReload",
1018 /* We ignore all errors here, since this is used to show a warning only */
1020 if (!(m = dbus_message_new_method_call(
1021 "org.freedesktop.systemd1",
1022 "/org/freedesktop/systemd1",
1023 "org.freedesktop.systemd1.Manager",
1027 if (!dbus_message_append_args(m,
1028 DBUS_TYPE_STRING, &unit,
1032 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1035 if (!dbus_message_get_args(reply, NULL,
1036 DBUS_TYPE_OBJECT_PATH, &path,
1040 dbus_message_unref(m);
1041 if (!(m = dbus_message_new_method_call(
1042 "org.freedesktop.systemd1",
1044 "org.freedesktop.DBus.Properties",
1048 if (!dbus_message_append_args(m,
1049 DBUS_TYPE_STRING, &interface,
1050 DBUS_TYPE_STRING, &property,
1051 DBUS_TYPE_INVALID)) {
1055 dbus_message_unref(reply);
1056 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1059 if (!dbus_message_iter_init(reply, &iter) ||
1060 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1063 dbus_message_iter_recurse(&iter, &sub);
1065 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1068 dbus_message_iter_get_basic(&sub, &b);
1072 dbus_message_unref(m);
1075 dbus_message_unref(reply);
1080 typedef struct WaitData {
1085 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1093 dbus_error_init(&error);
1095 log_debug("Got D-Bus request: %s.%s() on %s",
1096 dbus_message_get_interface(message),
1097 dbus_message_get_member(message),
1098 dbus_message_get_path(message));
1100 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1101 log_error("Warning! D-Bus connection terminated.");
1102 dbus_connection_close(connection);
1104 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1107 dbus_bool_t success = true;
1109 if (!dbus_message_get_args(message, &error,
1110 DBUS_TYPE_UINT32, &id,
1111 DBUS_TYPE_OBJECT_PATH, &path,
1112 DBUS_TYPE_BOOLEAN, &success,
1114 log_error("Failed to parse message: %s", bus_error_message(&error));
1118 if ((p = set_remove(d->set, (char*) path)))
1126 dbus_error_free(&error);
1127 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1130 static int enable_wait_for_jobs(DBusConnection *bus) {
1138 dbus_error_init(&error);
1139 dbus_bus_add_match(bus,
1141 "sender='org.freedesktop.systemd1',"
1142 "interface='org.freedesktop.systemd1.Manager',"
1143 "member='JobRemoved',"
1144 "path='/org/freedesktop/systemd1'",
1147 if (dbus_error_is_set(&error)) {
1148 log_error("Failed to add match: %s", bus_error_message(&error));
1149 dbus_error_free(&error);
1153 /* This is slightly dirty, since we don't undo the match registrations. */
1157 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1168 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1169 log_error("Failed to add filter.");
1174 while (!set_isempty(s) &&
1175 dbus_connection_read_write_dispatch(bus, -1))
1178 if (!arg_quiet && d.failed)
1179 log_error("Job failed. See system logs and 'systemctl status' for details.");
1181 r = d.failed ? -EIO : 0;
1184 /* This is slightly dirty, since we don't undo the filter registration. */
1189 static int start_unit_one(
1190 DBusConnection *bus,
1197 DBusMessage *m = NULL, *reply = NULL;
1206 assert(arg_no_block || s);
1208 if (!(m = dbus_message_new_method_call(
1209 "org.freedesktop.systemd1",
1210 "/org/freedesktop/systemd1",
1211 "org.freedesktop.systemd1.Manager",
1213 log_error("Could not allocate message.");
1218 if (!dbus_message_append_args(m,
1219 DBUS_TYPE_STRING, &name,
1220 DBUS_TYPE_STRING, &mode,
1221 DBUS_TYPE_INVALID)) {
1222 log_error("Could not append arguments to message.");
1227 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1229 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1230 /* There's always a fallback possible for
1231 * legacy actions. */
1236 log_error("Failed to issue method call: %s", bus_error_message(error));
1241 if (!dbus_message_get_args(reply, error,
1242 DBUS_TYPE_OBJECT_PATH, &path,
1243 DBUS_TYPE_INVALID)) {
1244 log_error("Failed to parse reply: %s", bus_error_message(error));
1249 if (need_daemon_reload(bus, name))
1250 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1251 arg_user ? "--user" : "--system");
1253 if (!arg_no_block) {
1256 if (!(p = strdup(path))) {
1257 log_error("Failed to duplicate path.");
1262 if ((r = set_put(s, p)) < 0) {
1264 log_error("Failed to add path to set.");
1273 dbus_message_unref(m);
1276 dbus_message_unref(reply);
1281 static enum action verb_to_action(const char *verb) {
1282 if (streq(verb, "halt"))
1284 else if (streq(verb, "poweroff"))
1285 return ACTION_POWEROFF;
1286 else if (streq(verb, "reboot"))
1287 return ACTION_REBOOT;
1288 else if (streq(verb, "kexec"))
1289 return ACTION_KEXEC;
1290 else if (streq(verb, "rescue"))
1291 return ACTION_RESCUE;
1292 else if (streq(verb, "emergency"))
1293 return ACTION_EMERGENCY;
1294 else if (streq(verb, "default"))
1295 return ACTION_DEFAULT;
1296 else if (streq(verb, "exit"))
1299 return ACTION_INVALID;
1302 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1304 static const char * const table[_ACTION_MAX] = {
1305 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1306 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1307 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1308 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1309 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1310 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1311 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1312 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1313 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1314 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1315 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1316 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1321 const char *method, *mode, *one_name;
1325 dbus_error_init(&error);
1329 spawn_ask_password_agent();
1331 if (arg_action == ACTION_SYSTEMCTL) {
1333 streq(args[0], "stop") ? "StopUnit" :
1334 streq(args[0], "reload") ? "ReloadUnit" :
1335 streq(args[0], "restart") ? "RestartUnit" :
1336 streq(args[0], "try-restart") ||
1337 streq(args[0], "condrestart") ? "TryRestartUnit" :
1338 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1339 streq(args[0], "reload-or-try-restart") ||
1340 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1344 (streq(args[0], "isolate") ||
1345 streq(args[0], "rescue") ||
1346 streq(args[0], "emergency")) ? "isolate" :
1350 one_name = table[verb_to_action(args[0])];
1353 assert(arg_action < ELEMENTSOF(table));
1354 assert(table[arg_action]);
1356 method = "StartUnit";
1358 mode = (arg_action == ACTION_EMERGENCY ||
1359 arg_action == ACTION_RESCUE ||
1360 arg_action == ACTION_RUNLEVEL2 ||
1361 arg_action == ACTION_RUNLEVEL3 ||
1362 arg_action == ACTION_RUNLEVEL4 ||
1363 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1365 one_name = table[arg_action];
1368 if (!arg_no_block) {
1369 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1370 log_error("Could not watch jobs: %s", strerror(-ret));
1374 if (!(s = set_new(string_hash_func, string_compare_func))) {
1375 log_error("Failed to allocate set.");
1382 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1385 for (i = 1; i < n; i++)
1386 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1387 ret = translate_bus_error_to_exit_status(r, &error);
1388 dbus_error_free(&error);
1393 if ((r = wait_for_jobs(bus, s)) < 0) {
1402 dbus_error_free(&error);
1407 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1414 (streq(args[0], "halt") ||
1415 streq(args[0], "poweroff") ||
1416 streq(args[0], "reboot") ||
1417 streq(args[0], "kexec") ||
1418 streq(args[0], "exit")))
1419 return daemon_reload(bus, args, n);
1421 r = start_unit(bus, args, n);
1424 warn_wall(verb_to_action(args[0]));
1429 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1430 DBusMessage *m = NULL, *reply = NULL;
1432 *interface = "org.freedesktop.systemd1.Unit",
1433 *property = "ActiveState";
1434 int r = 3; /* According to LSB: "program is not running" */
1441 dbus_error_init(&error);
1443 for (i = 1; i < n; i++) {
1444 const char *path = NULL;
1446 DBusMessageIter iter, sub;
1448 if (!(m = dbus_message_new_method_call(
1449 "org.freedesktop.systemd1",
1450 "/org/freedesktop/systemd1",
1451 "org.freedesktop.systemd1.Manager",
1453 log_error("Could not allocate message.");
1458 if (!dbus_message_append_args(m,
1459 DBUS_TYPE_STRING, &args[i],
1460 DBUS_TYPE_INVALID)) {
1461 log_error("Could not append arguments to message.");
1466 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1468 /* Hmm, cannot figure out anything about this unit... */
1472 dbus_error_free(&error);
1473 dbus_message_unref(m);
1477 if (!dbus_message_get_args(reply, &error,
1478 DBUS_TYPE_OBJECT_PATH, &path,
1479 DBUS_TYPE_INVALID)) {
1480 log_error("Failed to parse reply: %s", bus_error_message(&error));
1485 dbus_message_unref(m);
1486 if (!(m = dbus_message_new_method_call(
1487 "org.freedesktop.systemd1",
1489 "org.freedesktop.DBus.Properties",
1491 log_error("Could not allocate message.");
1496 if (!dbus_message_append_args(m,
1497 DBUS_TYPE_STRING, &interface,
1498 DBUS_TYPE_STRING, &property,
1499 DBUS_TYPE_INVALID)) {
1500 log_error("Could not append arguments to message.");
1505 dbus_message_unref(reply);
1506 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1507 log_error("Failed to issue method call: %s", bus_error_message(&error));
1512 if (!dbus_message_iter_init(reply, &iter) ||
1513 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1514 log_error("Failed to parse reply.");
1519 dbus_message_iter_recurse(&iter, &sub);
1521 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1522 log_error("Failed to parse reply.");
1527 dbus_message_iter_get_basic(&sub, &state);
1532 if (streq(state, "active") || streq(state, "reloading"))
1535 dbus_message_unref(m);
1536 dbus_message_unref(reply);
1542 dbus_message_unref(m);
1545 dbus_message_unref(reply);
1547 dbus_error_free(&error);
1552 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1553 DBusMessage *m = NULL, *reply = NULL;
1561 dbus_error_init(&error);
1564 arg_kill_who = "all";
1567 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1569 for (i = 1; i < n; i++) {
1571 if (!(m = dbus_message_new_method_call(
1572 "org.freedesktop.systemd1",
1573 "/org/freedesktop/systemd1",
1574 "org.freedesktop.systemd1.Manager",
1576 log_error("Could not allocate message.");
1581 if (!dbus_message_append_args(m,
1582 DBUS_TYPE_STRING, &args[i],
1583 DBUS_TYPE_STRING, &arg_kill_who,
1584 DBUS_TYPE_STRING, &arg_kill_mode,
1585 DBUS_TYPE_INT32, &arg_signal,
1586 DBUS_TYPE_INVALID)) {
1587 log_error("Could not append arguments to message.");
1592 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1593 log_error("Failed to issue method call: %s", bus_error_message(&error));
1594 dbus_error_free(&error);
1598 dbus_message_unref(m);
1601 dbus_message_unref(reply);
1607 dbus_message_unref(m);
1610 dbus_message_unref(reply);
1612 dbus_error_free(&error);
1617 typedef struct ExecStatusInfo {
1625 usec_t start_timestamp;
1626 usec_t exit_timestamp;
1631 LIST_FIELDS(struct ExecStatusInfo, exec);
1634 static void exec_status_info_free(ExecStatusInfo *i) {
1643 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1644 uint64_t start_timestamp, exit_timestamp;
1645 DBusMessageIter sub2, sub3;
1649 int32_t code, status;
1655 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1658 dbus_message_iter_recurse(sub, &sub2);
1660 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1663 if (!(i->path = strdup(path)))
1666 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1667 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1671 dbus_message_iter_recurse(&sub2, &sub3);
1672 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1673 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1674 dbus_message_iter_next(&sub3);
1679 if (!(i->argv = new0(char*, n+1)))
1683 dbus_message_iter_recurse(&sub2, &sub3);
1684 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1687 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1688 dbus_message_iter_get_basic(&sub3, &s);
1689 dbus_message_iter_next(&sub3);
1691 if (!(i->argv[n++] = strdup(s)))
1695 if (!dbus_message_iter_next(&sub2) ||
1696 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1697 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1698 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1699 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1700 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1701 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1705 i->start_timestamp = (usec_t) start_timestamp;
1706 i->exit_timestamp = (usec_t) exit_timestamp;
1707 i->pid = (pid_t) pid;
1714 typedef struct UnitStatusInfo {
1716 const char *load_state;
1717 const char *active_state;
1718 const char *sub_state;
1720 const char *description;
1721 const char *following;
1724 const char *default_control_group;
1726 usec_t inactive_exit_timestamp;
1727 usec_t active_enter_timestamp;
1728 usec_t active_exit_timestamp;
1729 usec_t inactive_enter_timestamp;
1731 bool need_daemon_reload;
1736 const char *status_text;
1738 #ifdef HAVE_SYSV_COMPAT
1742 usec_t start_timestamp;
1743 usec_t exit_timestamp;
1745 int exit_code, exit_status;
1748 unsigned n_accepted;
1749 unsigned n_connections;
1753 const char *sysfs_path;
1755 /* Mount, Automount */
1761 LIST_HEAD(ExecStatusInfo, exec);
1764 static void print_status_info(UnitStatusInfo *i) {
1766 const char *on, *off, *ss;
1768 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1769 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1773 /* This shows pretty information about a unit. See
1774 * print_property() for a low-level property printer */
1776 printf("%s", strna(i->id));
1778 if (i->description && !streq_ptr(i->id, i->description))
1779 printf(" - %s", i->description);
1784 printf("\t Follow: unit currently follows state of %s\n", i->following);
1786 if (streq_ptr(i->load_state, "failed") ||
1787 streq_ptr(i->load_state, "banned")) {
1788 on = ansi_highlight(true);
1789 off = ansi_highlight(false);
1794 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1796 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1798 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1800 if (streq_ptr(i->active_state, "failed")) {
1801 on = ansi_highlight(true);
1802 off = ansi_highlight(false);
1803 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1804 on = ansi_highlight_green(true);
1805 off = ansi_highlight_green(false);
1810 printf("\t Active: %s%s (%s)%s",
1812 strna(i->active_state),
1816 printf("\t Active: %s%s%s",
1818 strna(i->active_state),
1821 timestamp = (streq_ptr(i->active_state, "active") ||
1822 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1823 (streq_ptr(i->active_state, "inactive") ||
1824 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1825 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1826 i->active_exit_timestamp;
1828 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1829 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1832 printf(" since %s; %s\n", s2, s1);
1834 printf(" since %s\n", s2);
1839 printf("\t Device: %s\n", i->sysfs_path);
1841 printf("\t Where: %s\n", i->where);
1843 printf("\t What: %s\n", i->what);
1846 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1848 LIST_FOREACH(exec, p, i->exec) {
1852 /* Only show exited processes here */
1856 t = strv_join(p->argv, " ");
1857 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1860 #ifdef HAVE_SYSV_COMPAT
1862 good = is_clean_exit_lsb(p->code, p->status);
1865 good = is_clean_exit(p->code, p->status);
1868 on = ansi_highlight(true);
1869 off = ansi_highlight(false);
1873 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1875 if (p->code == CLD_EXITED) {
1878 printf("status=%i", p->status);
1880 #ifdef HAVE_SYSV_COMPAT
1881 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1883 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1888 printf("signal=%s", signal_to_string(p->status));
1890 printf(")%s\n", off);
1894 if (i->main_pid == p->pid &&
1895 i->start_timestamp == p->start_timestamp &&
1896 i->exit_timestamp == p->start_timestamp)
1897 /* Let's not show this twice */
1900 if (p->pid == i->control_pid)
1904 if (i->main_pid > 0 || i->control_pid > 0) {
1907 if (i->main_pid > 0) {
1908 printf("Main PID: %u", (unsigned) i->main_pid);
1912 get_process_name(i->main_pid, &t);
1917 } else if (i->exit_code > 0) {
1918 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1920 if (i->exit_code == CLD_EXITED) {
1923 printf("status=%i", i->exit_status);
1925 #ifdef HAVE_SYSV_COMPAT
1926 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1928 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1933 printf("signal=%s", signal_to_string(i->exit_status));
1938 if (i->main_pid > 0 && i->control_pid > 0)
1941 if (i->control_pid > 0) {
1944 printf(" Control: %u", (unsigned) i->control_pid);
1946 get_process_name(i->control_pid, &t);
1957 printf("\t Status: \"%s\"\n", i->status_text);
1959 if (i->default_control_group) {
1962 printf("\t CGroup: %s\n", i->default_control_group);
1964 if ((c = columns()) > 18)
1969 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1972 if (i->need_daemon_reload)
1973 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1974 ansi_highlight(true),
1975 ansi_highlight(false),
1976 arg_user ? "--user" : "--system");
1979 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1981 switch (dbus_message_iter_get_arg_type(iter)) {
1983 case DBUS_TYPE_STRING: {
1986 dbus_message_iter_get_basic(iter, &s);
1989 if (streq(name, "Id"))
1991 else if (streq(name, "LoadState"))
1993 else if (streq(name, "ActiveState"))
1994 i->active_state = s;
1995 else if (streq(name, "SubState"))
1997 else if (streq(name, "Description"))
1999 else if (streq(name, "FragmentPath"))
2001 #ifdef HAVE_SYSV_COMPAT
2002 else if (streq(name, "SysVPath")) {
2007 else if (streq(name, "DefaultControlGroup"))
2008 i->default_control_group = s;
2009 else if (streq(name, "StatusText"))
2011 else if (streq(name, "SysFSPath"))
2013 else if (streq(name, "Where"))
2015 else if (streq(name, "What"))
2017 else if (streq(name, "Following"))
2024 case DBUS_TYPE_BOOLEAN: {
2027 dbus_message_iter_get_basic(iter, &b);
2029 if (streq(name, "Accept"))
2031 else if (streq(name, "NeedDaemonReload"))
2032 i->need_daemon_reload = b;
2037 case DBUS_TYPE_UINT32: {
2040 dbus_message_iter_get_basic(iter, &u);
2042 if (streq(name, "MainPID")) {
2044 i->main_pid = (pid_t) u;
2047 } else if (streq(name, "ControlPID"))
2048 i->control_pid = (pid_t) u;
2049 else if (streq(name, "ExecMainPID")) {
2051 i->main_pid = (pid_t) u;
2052 } else if (streq(name, "NAccepted"))
2054 else if (streq(name, "NConnections"))
2055 i->n_connections = u;
2060 case DBUS_TYPE_INT32: {
2063 dbus_message_iter_get_basic(iter, &j);
2065 if (streq(name, "ExecMainCode"))
2066 i->exit_code = (int) j;
2067 else if (streq(name, "ExecMainStatus"))
2068 i->exit_status = (int) j;
2073 case DBUS_TYPE_UINT64: {
2076 dbus_message_iter_get_basic(iter, &u);
2078 if (streq(name, "ExecMainStartTimestamp"))
2079 i->start_timestamp = (usec_t) u;
2080 else if (streq(name, "ExecMainExitTimestamp"))
2081 i->exit_timestamp = (usec_t) u;
2082 else if (streq(name, "ActiveEnterTimestamp"))
2083 i->active_enter_timestamp = (usec_t) u;
2084 else if (streq(name, "InactiveEnterTimestamp"))
2085 i->inactive_enter_timestamp = (usec_t) u;
2086 else if (streq(name, "InactiveExitTimestamp"))
2087 i->inactive_exit_timestamp = (usec_t) u;
2088 else if (streq(name, "ActiveExitTimestamp"))
2089 i->active_exit_timestamp = (usec_t) u;
2094 case DBUS_TYPE_ARRAY: {
2096 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2097 startswith(name, "Exec")) {
2098 DBusMessageIter sub;
2100 dbus_message_iter_recurse(iter, &sub);
2101 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2102 ExecStatusInfo *info;
2105 if (!(info = new0(ExecStatusInfo, 1)))
2108 if (!(info->name = strdup(name))) {
2113 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2118 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2120 dbus_message_iter_next(&sub);
2131 static int print_property(const char *name, DBusMessageIter *iter) {
2135 /* This is a low-level property printer, see
2136 * print_status_info() for the nicer output */
2138 if (arg_property && !strv_find(arg_property, name))
2141 switch (dbus_message_iter_get_arg_type(iter)) {
2143 case DBUS_TYPE_STRING: {
2145 dbus_message_iter_get_basic(iter, &s);
2147 if (arg_all || s[0])
2148 printf("%s=%s\n", name, s);
2153 case DBUS_TYPE_BOOLEAN: {
2155 dbus_message_iter_get_basic(iter, &b);
2156 printf("%s=%s\n", name, yes_no(b));
2161 case DBUS_TYPE_UINT64: {
2163 dbus_message_iter_get_basic(iter, &u);
2165 /* Yes, heuristics! But we can change this check
2166 * should it turn out to not be sufficient */
2168 if (strstr(name, "Timestamp")) {
2169 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2171 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2172 printf("%s=%s\n", name, strempty(t));
2173 } else if (strstr(name, "USec")) {
2174 char timespan[FORMAT_TIMESPAN_MAX];
2176 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2178 printf("%s=%llu\n", name, (unsigned long long) u);
2183 case DBUS_TYPE_UINT32: {
2185 dbus_message_iter_get_basic(iter, &u);
2187 if (strstr(name, "UMask") || strstr(name, "Mode"))
2188 printf("%s=%04o\n", name, u);
2190 printf("%s=%u\n", name, (unsigned) u);
2195 case DBUS_TYPE_INT32: {
2197 dbus_message_iter_get_basic(iter, &i);
2199 printf("%s=%i\n", name, (int) i);
2203 case DBUS_TYPE_DOUBLE: {
2205 dbus_message_iter_get_basic(iter, &d);
2207 printf("%s=%g\n", name, d);
2211 case DBUS_TYPE_STRUCT: {
2212 DBusMessageIter sub;
2213 dbus_message_iter_recurse(iter, &sub);
2215 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2218 dbus_message_iter_get_basic(&sub, &u);
2221 printf("%s=%u\n", name, (unsigned) u);
2223 printf("%s=\n", name);
2226 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2229 dbus_message_iter_get_basic(&sub, &s);
2231 if (arg_all || s[0])
2232 printf("%s=%s\n", name, s);
2240 case DBUS_TYPE_ARRAY:
2242 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2243 DBusMessageIter sub;
2246 dbus_message_iter_recurse(iter, &sub);
2248 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2249 printf("%s=", name);
2251 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2254 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2255 dbus_message_iter_get_basic(&sub, &s);
2256 printf("%s%s", space ? " " : "", s);
2259 dbus_message_iter_next(&sub);
2267 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2268 DBusMessageIter sub;
2270 dbus_message_iter_recurse(iter, &sub);
2272 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2273 printf("%s=", name);
2275 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2278 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2279 dbus_message_iter_get_basic(&sub, &u);
2282 dbus_message_iter_next(&sub);
2290 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2291 DBusMessageIter sub, sub2;
2293 dbus_message_iter_recurse(iter, &sub);
2294 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2295 const char *type, *path;
2297 dbus_message_iter_recurse(&sub, &sub2);
2299 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2300 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2301 printf("%s=%s\n", type, path);
2303 dbus_message_iter_next(&sub);
2308 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2309 DBusMessageIter sub, sub2;
2311 dbus_message_iter_recurse(iter, &sub);
2312 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2314 uint64_t value, next_elapse;
2316 dbus_message_iter_recurse(&sub, &sub2);
2318 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2319 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2320 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2321 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2323 printf("%s={ value=%s ; next_elapse=%s }\n",
2325 format_timespan(timespan1, sizeof(timespan1), value),
2326 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2329 dbus_message_iter_next(&sub);
2334 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2335 DBusMessageIter sub;
2337 dbus_message_iter_recurse(iter, &sub);
2338 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2339 ExecStatusInfo info;
2342 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2343 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2346 t = strv_join(info.argv, " ");
2348 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2352 yes_no(info.ignore),
2353 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2354 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2355 (unsigned) info. pid,
2356 sigchld_code_to_string(info.code),
2358 info.code == CLD_EXITED ? "" : "/",
2359 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2365 strv_free(info.argv);
2367 dbus_message_iter_next(&sub);
2377 printf("%s=[unprintable]\n", name);
2382 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2383 DBusMessage *m = NULL, *reply = NULL;
2384 const char *interface = "";
2387 DBusMessageIter iter, sub, sub2, sub3;
2388 UnitStatusInfo info;
2396 dbus_error_init(&error);
2398 if (!(m = dbus_message_new_method_call(
2399 "org.freedesktop.systemd1",
2401 "org.freedesktop.DBus.Properties",
2403 log_error("Could not allocate message.");
2408 if (!dbus_message_append_args(m,
2409 DBUS_TYPE_STRING, &interface,
2410 DBUS_TYPE_INVALID)) {
2411 log_error("Could not append arguments to message.");
2416 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2417 log_error("Failed to issue method call: %s", bus_error_message(&error));
2422 if (!dbus_message_iter_init(reply, &iter) ||
2423 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2424 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2425 log_error("Failed to parse reply.");
2430 dbus_message_iter_recurse(&iter, &sub);
2437 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2440 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2441 log_error("Failed to parse reply.");
2446 dbus_message_iter_recurse(&sub, &sub2);
2448 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2449 log_error("Failed to parse reply.");
2454 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2455 log_error("Failed to parse reply.");
2460 dbus_message_iter_recurse(&sub2, &sub3);
2462 if (show_properties)
2463 r = print_property(name, &sub3);
2465 r = status_property(name, &sub3, &info);
2468 log_error("Failed to parse reply.");
2473 dbus_message_iter_next(&sub);
2478 if (!show_properties)
2479 print_status_info(&info);
2481 if (!streq_ptr(info.active_state, "active") &&
2482 !streq_ptr(info.active_state, "reloading") &&
2483 streq(verb, "status"))
2484 /* According to LSB: "program not running" */
2487 while ((p = info.exec)) {
2488 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2489 exec_status_info_free(p);
2494 dbus_message_unref(m);
2497 dbus_message_unref(reply);
2499 dbus_error_free(&error);
2504 static int show(DBusConnection *bus, char **args, unsigned n) {
2505 DBusMessage *m = NULL, *reply = NULL;
2509 bool show_properties, new_line = false;
2514 dbus_error_init(&error);
2516 show_properties = !streq(args[0], "status");
2518 if (show_properties)
2521 if (show_properties && n <= 1) {
2522 /* If not argument is specified inspect the manager
2525 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2529 for (i = 1; i < n; i++) {
2530 const char *path = NULL;
2533 if (safe_atou32(args[i], &id) < 0) {
2535 /* Interpret as unit name */
2537 if (!(m = dbus_message_new_method_call(
2538 "org.freedesktop.systemd1",
2539 "/org/freedesktop/systemd1",
2540 "org.freedesktop.systemd1.Manager",
2542 log_error("Could not allocate message.");
2547 if (!dbus_message_append_args(m,
2548 DBUS_TYPE_STRING, &args[i],
2549 DBUS_TYPE_INVALID)) {
2550 log_error("Could not append arguments to message.");
2555 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2557 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2558 log_error("Failed to issue method call: %s", bus_error_message(&error));
2563 dbus_error_free(&error);
2565 dbus_message_unref(m);
2566 if (!(m = dbus_message_new_method_call(
2567 "org.freedesktop.systemd1",
2568 "/org/freedesktop/systemd1",
2569 "org.freedesktop.systemd1.Manager",
2571 log_error("Could not allocate message.");
2576 if (!dbus_message_append_args(m,
2577 DBUS_TYPE_STRING, &args[i],
2578 DBUS_TYPE_INVALID)) {
2579 log_error("Could not append arguments to message.");
2584 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2585 log_error("Failed to issue method call: %s", bus_error_message(&error));
2587 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2588 ret = 4; /* According to LSB: "program or service status is unknown" */
2595 } else if (show_properties) {
2597 /* Interpret as job id */
2599 if (!(m = dbus_message_new_method_call(
2600 "org.freedesktop.systemd1",
2601 "/org/freedesktop/systemd1",
2602 "org.freedesktop.systemd1.Manager",
2604 log_error("Could not allocate message.");
2609 if (!dbus_message_append_args(m,
2610 DBUS_TYPE_UINT32, &id,
2611 DBUS_TYPE_INVALID)) {
2612 log_error("Could not append arguments to message.");
2617 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2618 log_error("Failed to issue method call: %s", bus_error_message(&error));
2624 /* Interpret as PID */
2626 if (!(m = dbus_message_new_method_call(
2627 "org.freedesktop.systemd1",
2628 "/org/freedesktop/systemd1",
2629 "org.freedesktop.systemd1.Manager",
2631 log_error("Could not allocate message.");
2636 if (!dbus_message_append_args(m,
2637 DBUS_TYPE_UINT32, &id,
2638 DBUS_TYPE_INVALID)) {
2639 log_error("Could not append arguments to message.");
2644 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2645 log_error("Failed to issue method call: %s", bus_error_message(&error));
2651 if (!dbus_message_get_args(reply, &error,
2652 DBUS_TYPE_OBJECT_PATH, &path,
2653 DBUS_TYPE_INVALID)) {
2654 log_error("Failed to parse reply: %s", bus_error_message(&error));
2659 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2662 dbus_message_unref(m);
2663 dbus_message_unref(reply);
2669 dbus_message_unref(m);
2672 dbus_message_unref(reply);
2674 dbus_error_free(&error);
2679 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2681 DBusMessage *m = NULL, *reply = NULL;
2686 dbus_error_init(&error);
2688 log_debug("Got D-Bus request: %s.%s() on %s",
2689 dbus_message_get_interface(message),
2690 dbus_message_get_member(message),
2691 dbus_message_get_path(message));
2693 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2694 log_error("Warning! D-Bus connection terminated.");
2695 dbus_connection_close(connection);
2697 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2698 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2699 const char *id, *path;
2701 if (!dbus_message_get_args(message, &error,
2702 DBUS_TYPE_STRING, &id,
2703 DBUS_TYPE_OBJECT_PATH, &path,
2705 log_error("Failed to parse message: %s", bus_error_message(&error));
2706 else if (streq(dbus_message_get_member(message), "UnitNew"))
2707 printf("Unit %s added.\n", id);
2709 printf("Unit %s removed.\n", id);
2711 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2712 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2716 if (!dbus_message_get_args(message, &error,
2717 DBUS_TYPE_UINT32, &id,
2718 DBUS_TYPE_OBJECT_PATH, &path,
2720 log_error("Failed to parse message: %s", bus_error_message(&error));
2721 else if (streq(dbus_message_get_member(message), "JobNew"))
2722 printf("Job %u added.\n", id);
2724 printf("Job %u removed.\n", id);
2727 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2729 const char *path, *interface, *property = "Id";
2730 DBusMessageIter iter, sub;
2732 path = dbus_message_get_path(message);
2734 if (!dbus_message_get_args(message, &error,
2735 DBUS_TYPE_STRING, &interface,
2736 DBUS_TYPE_INVALID)) {
2737 log_error("Failed to parse message: %s", bus_error_message(&error));
2741 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2742 !streq(interface, "org.freedesktop.systemd1.Unit"))
2745 if (!(m = dbus_message_new_method_call(
2746 "org.freedesktop.systemd1",
2748 "org.freedesktop.DBus.Properties",
2750 log_error("Could not allocate message.");
2754 if (!dbus_message_append_args(m,
2755 DBUS_TYPE_STRING, &interface,
2756 DBUS_TYPE_STRING, &property,
2757 DBUS_TYPE_INVALID)) {
2758 log_error("Could not append arguments to message.");
2762 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2763 log_error("Failed to issue method call: %s", bus_error_message(&error));
2767 if (!dbus_message_iter_init(reply, &iter) ||
2768 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2769 log_error("Failed to parse reply.");
2773 dbus_message_iter_recurse(&iter, &sub);
2775 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2778 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2779 log_error("Failed to parse reply.");
2783 dbus_message_iter_get_basic(&sub, &id);
2784 printf("Unit %s changed.\n", id);
2788 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2789 log_error("Failed to parse reply.");
2793 dbus_message_iter_get_basic(&sub, &id);
2794 printf("Job %u changed.\n", id);
2800 dbus_message_unref(m);
2803 dbus_message_unref(reply);
2805 dbus_error_free(&error);
2806 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2810 dbus_message_unref(m);
2813 dbus_message_unref(reply);
2815 dbus_error_free(&error);
2816 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2819 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2820 DBusMessage *m = NULL, *reply = NULL;
2824 dbus_error_init(&error);
2827 dbus_bus_add_match(bus,
2829 "sender='org.freedesktop.systemd1',"
2830 "interface='org.freedesktop.systemd1.Manager',"
2831 "path='/org/freedesktop/systemd1'",
2834 if (dbus_error_is_set(&error)) {
2835 log_error("Failed to add match: %s", bus_error_message(&error));
2840 dbus_bus_add_match(bus,
2842 "sender='org.freedesktop.systemd1',"
2843 "interface='org.freedesktop.DBus.Properties',"
2844 "member='PropertiesChanged'",
2847 if (dbus_error_is_set(&error)) {
2848 log_error("Failed to add match: %s", bus_error_message(&error));
2854 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2855 log_error("Failed to add filter.");
2860 if (!(m = dbus_message_new_method_call(
2861 "org.freedesktop.systemd1",
2862 "/org/freedesktop/systemd1",
2863 "org.freedesktop.systemd1.Manager",
2865 log_error("Could not allocate message.");
2870 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2871 log_error("Failed to issue method call: %s", bus_error_message(&error));
2876 while (dbus_connection_read_write_dispatch(bus, -1))
2883 /* This is slightly dirty, since we don't undo the filter or the matches. */
2886 dbus_message_unref(m);
2889 dbus_message_unref(reply);
2891 dbus_error_free(&error);
2896 static int dump(DBusConnection *bus, char **args, unsigned n) {
2897 DBusMessage *m = NULL, *reply = NULL;
2902 dbus_error_init(&error);
2906 if (!(m = dbus_message_new_method_call(
2907 "org.freedesktop.systemd1",
2908 "/org/freedesktop/systemd1",
2909 "org.freedesktop.systemd1.Manager",
2911 log_error("Could not allocate message.");
2915 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2916 log_error("Failed to issue method call: %s", bus_error_message(&error));
2921 if (!dbus_message_get_args(reply, &error,
2922 DBUS_TYPE_STRING, &text,
2923 DBUS_TYPE_INVALID)) {
2924 log_error("Failed to parse reply: %s", bus_error_message(&error));
2929 fputs(text, stdout);
2935 dbus_message_unref(m);
2938 dbus_message_unref(reply);
2940 dbus_error_free(&error);
2945 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2946 DBusMessage *m = NULL, *reply = NULL;
2949 const char *name = "", *path, *id;
2950 dbus_bool_t cleanup = FALSE;
2951 DBusMessageIter iter, sub;
2953 *interface = "org.freedesktop.systemd1.Unit",
2956 dbus_error_init(&error);
2958 if (!(m = dbus_message_new_method_call(
2959 "org.freedesktop.systemd1",
2960 "/org/freedesktop/systemd1",
2961 "org.freedesktop.systemd1.Manager",
2962 "CreateSnapshot"))) {
2963 log_error("Could not allocate message.");
2970 if (!dbus_message_append_args(m,
2971 DBUS_TYPE_STRING, &name,
2972 DBUS_TYPE_BOOLEAN, &cleanup,
2973 DBUS_TYPE_INVALID)) {
2974 log_error("Could not append arguments to message.");
2979 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2980 log_error("Failed to issue method call: %s", bus_error_message(&error));
2985 if (!dbus_message_get_args(reply, &error,
2986 DBUS_TYPE_OBJECT_PATH, &path,
2987 DBUS_TYPE_INVALID)) {
2988 log_error("Failed to parse reply: %s", bus_error_message(&error));
2993 dbus_message_unref(m);
2994 if (!(m = dbus_message_new_method_call(
2995 "org.freedesktop.systemd1",
2997 "org.freedesktop.DBus.Properties",
2999 log_error("Could not allocate message.");
3003 if (!dbus_message_append_args(m,
3004 DBUS_TYPE_STRING, &interface,
3005 DBUS_TYPE_STRING, &property,
3006 DBUS_TYPE_INVALID)) {
3007 log_error("Could not append arguments to message.");
3012 dbus_message_unref(reply);
3013 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3014 log_error("Failed to issue method call: %s", bus_error_message(&error));
3019 if (!dbus_message_iter_init(reply, &iter) ||
3020 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3021 log_error("Failed to parse reply.");
3026 dbus_message_iter_recurse(&iter, &sub);
3028 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3029 log_error("Failed to parse reply.");
3034 dbus_message_iter_get_basic(&sub, &id);
3042 dbus_message_unref(m);
3045 dbus_message_unref(reply);
3047 dbus_error_free(&error);
3052 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3053 DBusMessage *m = NULL, *reply = NULL;
3061 dbus_error_init(&error);
3063 for (i = 1; i < n; i++) {
3064 const char *path = NULL;
3066 if (!(m = dbus_message_new_method_call(
3067 "org.freedesktop.systemd1",
3068 "/org/freedesktop/systemd1",
3069 "org.freedesktop.systemd1.Manager",
3071 log_error("Could not allocate message.");
3076 if (!dbus_message_append_args(m,
3077 DBUS_TYPE_STRING, &args[i],
3078 DBUS_TYPE_INVALID)) {
3079 log_error("Could not append arguments to message.");
3084 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3085 log_error("Failed to issue method call: %s", bus_error_message(&error));
3090 if (!dbus_message_get_args(reply, &error,
3091 DBUS_TYPE_OBJECT_PATH, &path,
3092 DBUS_TYPE_INVALID)) {
3093 log_error("Failed to parse reply: %s", bus_error_message(&error));
3098 dbus_message_unref(m);
3099 if (!(m = dbus_message_new_method_call(
3100 "org.freedesktop.systemd1",
3102 "org.freedesktop.systemd1.Snapshot",
3104 log_error("Could not allocate message.");
3109 dbus_message_unref(reply);
3110 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3111 log_error("Failed to issue method call: %s", bus_error_message(&error));
3116 dbus_message_unref(m);
3117 dbus_message_unref(reply);
3125 dbus_message_unref(m);
3128 dbus_message_unref(reply);
3130 dbus_error_free(&error);
3135 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3136 DBusMessage *m = NULL, *reply = NULL;
3141 dbus_error_init(&error);
3143 if (arg_action == ACTION_RELOAD)
3145 else if (arg_action == ACTION_REEXEC)
3146 method = "Reexecute";
3148 assert(arg_action == ACTION_SYSTEMCTL);
3151 streq(args[0], "clear-jobs") ||
3152 streq(args[0], "cancel") ? "ClearJobs" :
3153 streq(args[0], "daemon-reexec") ? "Reexecute" :
3154 streq(args[0], "reset-failed") ? "ResetFailed" :
3155 streq(args[0], "halt") ? "Halt" :
3156 streq(args[0], "poweroff") ? "PowerOff" :
3157 streq(args[0], "reboot") ? "Reboot" :
3158 streq(args[0], "kexec") ? "KExec" :
3159 streq(args[0], "exit") ? "Exit" :
3160 /* "daemon-reload" */ "Reload";
3163 if (!(m = dbus_message_new_method_call(
3164 "org.freedesktop.systemd1",
3165 "/org/freedesktop/systemd1",
3166 "org.freedesktop.systemd1.Manager",
3168 log_error("Could not allocate message.");
3172 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3174 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3175 /* There's always a fallback possible for
3176 * legacy actions. */
3181 log_error("Failed to issue method call: %s", bus_error_message(&error));
3190 dbus_message_unref(m);
3193 dbus_message_unref(reply);
3195 dbus_error_free(&error);
3200 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3201 DBusMessage *m = NULL, *reply = NULL;
3207 dbus_error_init(&error);
3210 return daemon_reload(bus, args, n);
3212 for (i = 1; i < n; i++) {
3214 if (!(m = dbus_message_new_method_call(
3215 "org.freedesktop.systemd1",
3216 "/org/freedesktop/systemd1",
3217 "org.freedesktop.systemd1.Manager",
3218 "ResetFailedUnit"))) {
3219 log_error("Could not allocate message.");
3224 if (!dbus_message_append_args(m,
3225 DBUS_TYPE_STRING, args + i,
3226 DBUS_TYPE_INVALID)) {
3227 log_error("Could not append arguments to message.");
3232 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3233 log_error("Failed to issue method call: %s", bus_error_message(&error));
3238 dbus_message_unref(m);
3239 dbus_message_unref(reply);
3247 dbus_message_unref(m);
3250 dbus_message_unref(reply);
3252 dbus_error_free(&error);
3257 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3258 DBusMessage *m = NULL, *reply = NULL;
3260 DBusMessageIter iter, sub, sub2;
3263 *interface = "org.freedesktop.systemd1.Manager",
3264 *property = "Environment";
3266 dbus_error_init(&error);
3270 if (!(m = dbus_message_new_method_call(
3271 "org.freedesktop.systemd1",
3272 "/org/freedesktop/systemd1",
3273 "org.freedesktop.DBus.Properties",
3275 log_error("Could not allocate message.");
3279 if (!dbus_message_append_args(m,
3280 DBUS_TYPE_STRING, &interface,
3281 DBUS_TYPE_STRING, &property,
3282 DBUS_TYPE_INVALID)) {
3283 log_error("Could not append arguments to message.");
3288 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3289 log_error("Failed to issue method call: %s", bus_error_message(&error));
3294 if (!dbus_message_iter_init(reply, &iter) ||
3295 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3296 log_error("Failed to parse reply.");
3301 dbus_message_iter_recurse(&iter, &sub);
3303 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3304 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3305 log_error("Failed to parse reply.");
3310 dbus_message_iter_recurse(&sub, &sub2);
3312 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3315 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3316 log_error("Failed to parse reply.");
3321 dbus_message_iter_get_basic(&sub2, &text);
3322 printf("%s\n", text);
3324 dbus_message_iter_next(&sub2);
3331 dbus_message_unref(m);
3334 dbus_message_unref(reply);
3336 dbus_error_free(&error);
3341 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3342 DBusMessage *m = NULL, *reply = NULL;
3346 DBusMessageIter iter, sub;
3349 dbus_error_init(&error);
3351 method = streq(args[0], "set-environment")
3353 : "UnsetEnvironment";
3355 if (!(m = dbus_message_new_method_call(
3356 "org.freedesktop.systemd1",
3357 "/org/freedesktop/systemd1",
3358 "org.freedesktop.systemd1.Manager",
3361 log_error("Could not allocate message.");
3365 dbus_message_iter_init_append(m, &iter);
3367 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3368 log_error("Could not append arguments to message.");
3373 for (i = 1; i < n; i++)
3374 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3375 log_error("Could not append arguments to message.");
3380 if (!dbus_message_iter_close_container(&iter, &sub)) {
3381 log_error("Could not append arguments to message.");
3386 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3387 log_error("Failed to issue method call: %s", bus_error_message(&error));
3396 dbus_message_unref(m);
3399 dbus_message_unref(reply);
3401 dbus_error_free(&error);
3414 static Hashmap *will_install = NULL, *have_installed = NULL;
3415 static Set *remove_symlinks_to = NULL;
3416 static unsigned n_symlinks = 0;
3418 static void install_info_free(InstallInfo *i) {
3423 strv_free(i->aliases);
3424 strv_free(i->wanted_by);
3428 static void install_info_hashmap_free(Hashmap *m) {
3431 while ((i = hashmap_steal_first(m)))
3432 install_info_free(i);
3437 static int install_info_add(const char *name) {
3441 assert(will_install);
3443 if (!unit_name_is_valid_no_type(name, true)) {
3444 log_warning("Unit name %s is not a valid unit name.", name);
3448 if (hashmap_get(have_installed, name) ||
3449 hashmap_get(will_install, name))
3452 if (!(i = new0(InstallInfo, 1))) {
3457 if (!(i->name = strdup(name))) {
3462 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3469 install_info_free(i);
3474 static int config_parse_also(
3475 const char *filename,
3477 const char *section,
3491 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3495 if (!(n = strndup(w, l)))
3498 if ((r = install_info_add(n)) < 0) {
3499 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3510 static int mark_symlink_for_removal(const char *p) {
3515 assert(path_is_absolute(p));
3517 if (!remove_symlinks_to)
3520 if (!(n = strdup(p)))
3523 path_kill_slashes(n);
3525 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3527 return r == -EEXIST ? 0 : r;
3533 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3542 if (!(d = fdopendir(fd))) {
3543 close_nointr_nofail(fd);
3549 while ((de = readdir(d))) {
3550 bool is_dir = false, is_link = false;
3552 if (ignore_file(de->d_name))
3555 if (de->d_type == DT_LNK)
3557 else if (de->d_type == DT_DIR)
3559 else if (de->d_type == DT_UNKNOWN) {
3562 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3563 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3570 is_link = S_ISLNK(st.st_mode);
3571 is_dir = S_ISDIR(st.st_mode);
3579 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3580 log_error("Failed to open %s/%s: %m", root, de->d_name);
3587 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3588 log_error("Failed to allocate directory string.");
3589 close_nointr_nofail(nfd);
3594 /* This will close nfd, regardless whether it succeeds or not */
3595 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3601 } else if (is_link) {
3605 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3606 log_error("Failed to allocate symlink string.");
3611 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3612 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3620 if ((c = canonicalize_file_name(dest))) {
3621 /* This might fail if the destination
3622 * is already removed */
3628 path_kill_slashes(dest);
3629 if (set_get(remove_symlinks_to, dest)) {
3632 log_info("rm '%s'", p);
3634 if (unlink(p) < 0) {
3635 log_error("Cannot unlink symlink %s: %m", p);
3640 rmdir_parents(p, config_path);
3641 path_kill_slashes(p);
3643 if (!set_get(remove_symlinks_to, p)) {
3645 if ((r = mark_symlink_for_removal(p)) < 0) {
3664 static int remove_marked_symlinks(const char *config_path) {
3668 assert(config_path);
3670 if (set_size(remove_symlinks_to) <= 0)
3673 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3680 if ((cfd = dup(fd)) < 0) {
3685 /* This takes possession of cfd and closes it */
3686 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3692 close_nointr_nofail(fd);
3697 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3704 if (streq(verb, "enable")) {
3707 mkdir_parents(new_path, 0755);
3709 if (symlink(old_path, new_path) >= 0) {
3712 log_info("ln -s '%s' '%s'", old_path, new_path);
3717 if (errno != EEXIST) {
3718 log_error("Cannot link %s to %s: %m", old_path, new_path);
3722 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3724 if (errno == EINVAL) {
3725 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3729 log_error("readlink() failed: %s", strerror(-r));
3733 if (streq(dest, old_path)) {
3739 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3748 log_info("ln -s '%s' '%s'", old_path, new_path);
3750 if (symlink(old_path, new_path) >= 0)
3753 log_error("Cannot link %s to %s: %m", old_path, new_path);
3756 } else if (streq(verb, "disable")) {
3759 if ((r = mark_symlink_for_removal(old_path)) < 0)
3762 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3763 if (errno == ENOENT)
3766 if (errno == EINVAL) {
3767 log_warning("File %s not a symlink, ignoring.", old_path);
3771 log_error("readlink() failed: %s", strerror(-r));
3775 if (!streq(dest, old_path)) {
3776 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3783 if ((r = mark_symlink_for_removal(new_path)) < 0)
3787 log_info("rm '%s'", new_path);
3789 if (unlink(new_path) >= 0)
3792 log_error("Cannot unlink %s: %m", new_path);
3795 } else if (streq(verb, "is-enabled")) {
3798 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3800 if (errno == ENOENT || errno == EINVAL)
3803 log_error("readlink() failed: %s", strerror(-r));
3807 if (streq(dest, old_path)) {
3815 assert_not_reached("Unknown action.");
3818 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3820 char *alias_path = NULL;
3825 assert(config_path);
3827 STRV_FOREACH(s, i->aliases) {
3830 if (!(alias_path = path_make_absolute(*s, config_path))) {
3831 log_error("Out of memory");
3836 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3839 if (streq(verb, "disable"))
3840 rmdir_parents(alias_path, config_path);
3850 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3852 char *alias_path = NULL;
3857 assert(config_path);
3859 STRV_FOREACH(s, i->wanted_by) {
3860 if (!unit_name_is_valid_no_type(*s, true)) {
3861 log_error("Invalid name %s.", *s);
3869 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3870 log_error("Out of memory");
3875 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3878 if (streq(verb, "disable"))
3879 rmdir_parents(alias_path, config_path);
3890 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3892 const ConfigItem items[] = {
3893 { "Alias", config_parse_strv, &i->aliases, "Install" },
3894 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3895 { "Also", config_parse_also, NULL, "Install" },
3897 { NULL, NULL, NULL, NULL }
3901 char *filename = NULL;
3908 STRV_FOREACH(p, paths->unit_path) {
3911 if (!(filename = path_make_absolute(i->name, *p))) {
3912 log_error("Out of memory");
3916 /* Ensure that we don't follow symlinks */
3917 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3918 if ((f = fdopen(fd, "re")))
3921 if (errno == ELOOP) {
3922 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3927 if (errno != ENOENT) {
3928 log_error("Failed to open %s: %m", filename);
3938 #if defined(TARGET_FEDORA) && defined (HAVE_SYSV_COMPAT)
3940 if (endswith(i->name, ".service")) {
3944 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
3945 log_error("Out of memory");
3949 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
3950 exists = access(sysv, F_OK) >= 0;
3956 const char *argv[] = {
3963 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
3965 argv[1] = file_name_from_path(sysv);
3967 streq(verb, "enable") ? "on" :
3968 streq(verb, "disable") ? "off" : NULL;
3970 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
3972 if ((pid = fork()) < 0) {
3973 log_error("Failed to fork: %m");
3976 } else if (pid == 0) {
3977 execv(argv[0], (char**) argv);
3978 _exit(EXIT_FAILURE);
3983 if ((r = wait_for_terminate(pid, &status)) < 0)
3986 if (status.si_code == CLD_EXITED) {
3987 if (status.si_status == 0 && (streq(verb, "enable") || streq(verb, "disable")))
3990 return status.si_status == 0 ? 0 : -EINVAL;
4000 log_error("Couldn't find %s.", i->name);
4006 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4011 n_symlinks += strv_length(i->aliases);
4012 n_symlinks += strv_length(i->wanted_by);
4016 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4019 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4022 if ((r = mark_symlink_for_removal(filename)) < 0)
4025 if ((r = remove_marked_symlinks(config_path)) < 0)
4031 static char *get_config_path(void) {
4033 if (arg_user && arg_global)
4034 return strdup(USER_CONFIG_UNIT_PATH);
4039 if (user_config_home(&p) < 0)
4045 return strdup(SYSTEM_CONFIG_UNIT_PATH);
4048 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4052 char *config_path = NULL;
4055 const char *verb = args[0];
4057 dbus_error_init(&error);
4060 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4061 log_error("Failed to determine lookup paths: %s", strerror(-r));
4065 if (!(config_path = get_config_path())) {
4066 log_error("Failed to determine config path");
4071 will_install = hashmap_new(string_hash_func, string_compare_func);
4072 have_installed = hashmap_new(string_hash_func, string_compare_func);
4074 if (!will_install || !have_installed) {
4075 log_error("Failed to allocate unit sets.");
4080 if (!arg_defaults && streq(verb, "disable"))
4081 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4082 log_error("Failed to allocate symlink sets.");
4087 for (j = 1; j < n; j++)
4088 if ((r = install_info_add(args[j])) < 0) {
4089 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4093 while ((i = hashmap_first(will_install))) {
4096 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4098 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4106 /* In test mode and found something */
4112 if (streq(verb, "is-enabled"))
4113 r = r > 0 ? 0 : -ENOENT;
4115 if (n_symlinks <= 0)
4116 log_warning("Unit files contain no applicable installation information. Ignoring.");
4119 /* Don't try to reload anything if the user asked us to not do this */
4121 /* Don't try to reload anything when updating a unit globally */
4123 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4124 (arg_user || sd_booted() > 0) &&
4125 /* Don't try to reload anything if we are running in a chroot environment */
4126 (arg_user || running_in_chroot() <= 0) ) {
4129 if ((q = daemon_reload(bus, args, n)) < 0)
4135 install_info_hashmap_free(will_install);
4136 install_info_hashmap_free(have_installed);
4138 set_free_free(remove_symlinks_to);
4140 lookup_paths_free(&paths);
4147 static int systemctl_help(void) {
4149 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4150 "Send control commands to or query the systemd manager.\n\n"
4151 " -h --help Show this help\n"
4152 " --version Show package version\n"
4153 " -t --type=TYPE List only units of a particular type\n"
4154 " -p --property=NAME Show only properties by this name\n"
4155 " -a --all Show all units/properties, including dead/empty ones\n"
4156 " --full Don't ellipsize unit names on output\n"
4157 " --fail When queueing a new job, fail if conflicting jobs are\n"
4159 " -q --quiet Suppress output\n"
4160 " --no-block Do not wait until operation finished\n"
4161 " --no-pager Do not pipe output into a pager.\n"
4162 " --system Connect to system manager\n"
4163 " --user Connect to user service manager\n"
4164 " --order When generating graph for dot, show only order\n"
4165 " --require When generating graph for dot, show only requirement\n"
4166 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4167 " --global Enable/disable unit files globally\n"
4168 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4170 " --no-ask-password\n"
4171 " Do not ask for system passwords\n"
4172 " --kill-mode=MODE How to send signal\n"
4173 " --kill-who=WHO Who to send signal to\n"
4174 " -s --signal=SIGNAL Which signal to send\n"
4175 " -f --force When enabling unit files, override existing symlinks\n"
4176 " When shutting down, execute action immediately\n"
4177 " --defaults When disabling unit files, remove default symlinks only\n\n"
4179 " list-units List units\n"
4180 " start [NAME...] Start (activate) one or more units\n"
4181 " stop [NAME...] Stop (deactivate) one or more units\n"
4182 " reload [NAME...] Reload one or more units\n"
4183 " restart [NAME...] Start or restart one or more units\n"
4184 " try-restart [NAME...] Restart one or more units if active\n"
4185 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4186 " otherwise start or restart\n"
4187 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4188 " otherwise restart if active\n"
4189 " isolate [NAME] Start one unit and stop all others\n"
4190 " kill [NAME...] Send signal to processes of a unit\n"
4191 " is-active [NAME...] Check whether units are active\n"
4192 " status [NAME...|PID...] Show runtime status of one or more units\n"
4193 " show [NAME...|JOB...] Show properties of one or more\n"
4194 " units/jobs or the manager\n"
4195 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4197 " enable [NAME...] Enable one or more unit files\n"
4198 " disable [NAME...] Disable one or more unit files\n"
4199 " is-enabled [NAME...] Check whether unit files are enabled\n"
4200 " load [NAME...] Load one or more units\n"
4201 " list-jobs List jobs\n"
4202 " cancel [JOB...] Cancel all, one, or more jobs\n"
4203 " monitor Monitor unit/job changes\n"
4204 " dump Dump server status\n"
4205 " dot Dump dependency graph for dot(1)\n"
4206 " snapshot [NAME] Create a snapshot\n"
4207 " delete [NAME...] Remove one or more snapshots\n"
4208 " daemon-reload Reload systemd manager configuration\n"
4209 " daemon-reexec Reexecute systemd manager\n"
4210 " show-environment Dump environment\n"
4211 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4212 " unset-environment [NAME...] Unset one or more environment variables\n"
4213 " default Enter system default mode\n"
4214 " rescue Enter system rescue mode\n"
4215 " emergency Enter system emergency mode\n"
4216 " halt Shut down and halt the system\n"
4217 " poweroff Shut down and power-off the system\n"
4218 " reboot Shut down and reboot the system\n"
4219 " kexec Shut down and reboot the system with kexec\n"
4220 " exit Ask for user instance termination\n",
4221 program_invocation_short_name);
4226 static int halt_help(void) {
4228 printf("%s [OPTIONS...]\n\n"
4229 "%s the system.\n\n"
4230 " --help Show this help\n"
4231 " --halt Halt the machine\n"
4232 " -p --poweroff Switch off the machine\n"
4233 " --reboot Reboot the machine\n"
4234 " -f --force Force immediate halt/power-off/reboot\n"
4235 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4236 " -d --no-wtmp Don't write wtmp record\n"
4237 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4238 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4239 program_invocation_short_name,
4240 arg_action == ACTION_REBOOT ? "Reboot" :
4241 arg_action == ACTION_POWEROFF ? "Power off" :
4247 static int shutdown_help(void) {
4249 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4250 "Shut down the system.\n\n"
4251 " --help Show this help\n"
4252 " -H --halt Halt the machine\n"
4253 " -P --poweroff Power-off the machine\n"
4254 " -r --reboot Reboot the machine\n"
4255 " -h Equivalent to --poweroff, overriden by --halt\n"
4256 " -k Don't halt/power-off/reboot, just send warnings\n"
4257 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4258 " -c Cancel a pending shutdown\n",
4259 program_invocation_short_name);
4264 static int telinit_help(void) {
4266 printf("%s [OPTIONS...] {COMMAND}\n\n"
4267 "Send control commands to the init daemon.\n\n"
4268 " --help Show this help\n"
4269 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4271 " 0 Power-off the machine\n"
4272 " 6 Reboot the machine\n"
4273 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4274 " 1, s, S Enter rescue mode\n"
4275 " q, Q Reload init daemon configuration\n"
4276 " u, U Reexecute init daemon\n",
4277 program_invocation_short_name);
4282 static int runlevel_help(void) {
4284 printf("%s [OPTIONS...]\n\n"
4285 "Prints the previous and current runlevel of the init system.\n\n"
4286 " --help Show this help\n",
4287 program_invocation_short_name);
4292 static int systemctl_parse_argv(int argc, char *argv[]) {
4313 static const struct option options[] = {
4314 { "help", no_argument, NULL, 'h' },
4315 { "version", no_argument, NULL, ARG_VERSION },
4316 { "type", required_argument, NULL, 't' },
4317 { "property", required_argument, NULL, 'p' },
4318 { "all", no_argument, NULL, 'a' },
4319 { "full", no_argument, NULL, ARG_FULL },
4320 { "fail", no_argument, NULL, ARG_FAIL },
4321 { "user", no_argument, NULL, ARG_USER },
4322 { "system", no_argument, NULL, ARG_SYSTEM },
4323 { "global", no_argument, NULL, ARG_GLOBAL },
4324 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4325 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4326 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4327 { "quiet", no_argument, NULL, 'q' },
4328 { "order", no_argument, NULL, ARG_ORDER },
4329 { "require", no_argument, NULL, ARG_REQUIRE },
4330 { "force", no_argument, NULL, 'f' },
4331 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4332 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4333 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4334 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4335 { "signal", required_argument, NULL, 's' },
4336 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4337 { NULL, 0, NULL, 0 }
4345 /* Only when running as systemctl we ask for passwords */
4346 arg_ask_password = true;
4348 while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4357 puts(PACKAGE_STRING);
4359 puts(SYSTEMD_FEATURES);
4369 if (!(l = strv_append(arg_property, optarg)))
4372 strv_free(arg_property);
4375 /* If the user asked for a particular
4376 * property, show it to him, even if it is
4399 arg_no_block = true;
4403 arg_no_pager = true;
4411 arg_dot = DOT_ORDER;
4415 arg_dot = DOT_REQUIRE;
4431 arg_no_reload = true;
4440 arg_defaults = true;
4444 arg_kill_who = optarg;
4448 arg_kill_mode = optarg;
4452 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4453 log_error("Failed to parse signal string %s.", optarg);
4458 case ARG_NO_ASK_PASSWORD:
4459 arg_ask_password = false;
4466 log_error("Unknown option code %c", c);
4474 static int halt_parse_argv(int argc, char *argv[]) {
4483 static const struct option options[] = {
4484 { "help", no_argument, NULL, ARG_HELP },
4485 { "halt", no_argument, NULL, ARG_HALT },
4486 { "poweroff", no_argument, NULL, 'p' },
4487 { "reboot", no_argument, NULL, ARG_REBOOT },
4488 { "force", no_argument, NULL, 'f' },
4489 { "wtmp-only", no_argument, NULL, 'w' },
4490 { "no-wtmp", no_argument, NULL, 'd' },
4491 { "no-sync", no_argument, NULL, 'n' },
4492 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4493 { NULL, 0, NULL, 0 }
4501 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4502 if (runlevel == '0' || runlevel == '6')
4503 arg_immediate = true;
4505 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4513 arg_action = ACTION_HALT;
4517 if (arg_action != ACTION_REBOOT)
4518 arg_action = ACTION_POWEROFF;
4522 arg_action = ACTION_REBOOT;
4526 arg_immediate = true;
4547 /* Compatibility nops */
4554 log_error("Unknown option code %c", c);
4559 if (optind < argc) {
4560 log_error("Too many arguments.");
4567 static int parse_time_spec(const char *t, usec_t *_u) {
4571 if (streq(t, "now"))
4573 else if (t[0] == '+') {
4576 if (safe_atou64(t + 1, &u) < 0)
4579 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4588 hour = strtol(t, &e, 10);
4589 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4592 minute = strtol(e+1, &e, 10);
4593 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4596 n = now(CLOCK_REALTIME);
4597 s = (time_t) (n / USEC_PER_SEC);
4600 assert_se(localtime_r(&s, &tm));
4602 tm.tm_hour = (int) hour;
4603 tm.tm_min = (int) minute;
4606 assert_se(s = mktime(&tm));
4608 *_u = (usec_t) s * USEC_PER_SEC;
4611 *_u += USEC_PER_DAY;
4617 static int shutdown_parse_argv(int argc, char *argv[]) {
4624 static const struct option options[] = {
4625 { "help", no_argument, NULL, ARG_HELP },
4626 { "halt", no_argument, NULL, 'H' },
4627 { "poweroff", no_argument, NULL, 'P' },
4628 { "reboot", no_argument, NULL, 'r' },
4629 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4630 { NULL, 0, NULL, 0 }
4638 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4646 arg_action = ACTION_HALT;
4650 arg_action = ACTION_POWEROFF;
4654 arg_action = ACTION_REBOOT;
4658 if (arg_action != ACTION_HALT)
4659 arg_action = ACTION_POWEROFF;
4672 /* Compatibility nops */
4676 arg_action = ACTION_CANCEL_SHUTDOWN;
4683 log_error("Unknown option code %c", c);
4688 if (argc > optind) {
4689 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4690 log_error("Failed to parse time specification: %s", argv[optind]);
4694 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4696 /* We skip the time argument */
4697 if (argc > optind + 1)
4698 arg_wall = argv + optind + 1;
4705 static int telinit_parse_argv(int argc, char *argv[]) {
4712 static const struct option options[] = {
4713 { "help", no_argument, NULL, ARG_HELP },
4714 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4715 { NULL, 0, NULL, 0 }
4718 static const struct {
4722 { '0', ACTION_POWEROFF },
4723 { '6', ACTION_REBOOT },
4724 { '1', ACTION_RESCUE },
4725 { '2', ACTION_RUNLEVEL2 },
4726 { '3', ACTION_RUNLEVEL3 },
4727 { '4', ACTION_RUNLEVEL4 },
4728 { '5', ACTION_RUNLEVEL5 },
4729 { 's', ACTION_RESCUE },
4730 { 'S', ACTION_RESCUE },
4731 { 'q', ACTION_RELOAD },
4732 { 'Q', ACTION_RELOAD },
4733 { 'u', ACTION_REEXEC },
4734 { 'U', ACTION_REEXEC }
4743 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4758 log_error("Unknown option code %c", c);
4763 if (optind >= argc) {
4768 if (optind + 1 < argc) {
4769 log_error("Too many arguments.");
4773 if (strlen(argv[optind]) != 1) {
4774 log_error("Expected single character argument.");
4778 for (i = 0; i < ELEMENTSOF(table); i++)
4779 if (table[i].from == argv[optind][0])
4782 if (i >= ELEMENTSOF(table)) {
4783 log_error("Unknown command %s.", argv[optind]);
4787 arg_action = table[i].to;
4794 static int runlevel_parse_argv(int argc, char *argv[]) {
4800 static const struct option options[] = {
4801 { "help", no_argument, NULL, ARG_HELP },
4802 { NULL, 0, NULL, 0 }
4810 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4821 log_error("Unknown option code %c", c);
4826 if (optind < argc) {
4827 log_error("Too many arguments.");
4834 static int parse_argv(int argc, char *argv[]) {
4838 if (program_invocation_short_name) {
4840 if (strstr(program_invocation_short_name, "halt")) {
4841 arg_action = ACTION_HALT;
4842 return halt_parse_argv(argc, argv);
4843 } else if (strstr(program_invocation_short_name, "poweroff")) {
4844 arg_action = ACTION_POWEROFF;
4845 return halt_parse_argv(argc, argv);
4846 } else if (strstr(program_invocation_short_name, "reboot")) {
4847 arg_action = ACTION_REBOOT;
4848 return halt_parse_argv(argc, argv);
4849 } else if (strstr(program_invocation_short_name, "shutdown")) {
4850 arg_action = ACTION_POWEROFF;
4851 return shutdown_parse_argv(argc, argv);
4852 } else if (strstr(program_invocation_short_name, "init")) {
4854 if (sd_booted() > 0) {
4855 arg_action = ACTION_INVALID;
4856 return telinit_parse_argv(argc, argv);
4858 /* Hmm, so some other init system is
4859 * running, we need to forward this
4860 * request to it. For now we simply
4861 * guess that it is Upstart. */
4863 execv("/lib/upstart/telinit", argv);
4865 log_error("Couldn't find an alternative telinit implementation to spawn.");
4869 } else if (strstr(program_invocation_short_name, "runlevel")) {
4870 arg_action = ACTION_RUNLEVEL;
4871 return runlevel_parse_argv(argc, argv);
4875 arg_action = ACTION_SYSTEMCTL;
4876 return systemctl_parse_argv(argc, argv);
4879 static int action_to_runlevel(void) {
4881 static const char table[_ACTION_MAX] = {
4882 [ACTION_HALT] = '0',
4883 [ACTION_POWEROFF] = '0',
4884 [ACTION_REBOOT] = '6',
4885 [ACTION_RUNLEVEL2] = '2',
4886 [ACTION_RUNLEVEL3] = '3',
4887 [ACTION_RUNLEVEL4] = '4',
4888 [ACTION_RUNLEVEL5] = '5',
4889 [ACTION_RESCUE] = '1'
4892 assert(arg_action < _ACTION_MAX);
4894 return table[arg_action];
4897 static int talk_upstart(void) {
4898 DBusMessage *m = NULL, *reply = NULL;
4900 int previous, rl, r;
4902 env1_buf[] = "RUNLEVEL=X",
4903 env2_buf[] = "PREVLEVEL=X";
4904 char *env1 = env1_buf, *env2 = env2_buf;
4905 const char *emit = "runlevel";
4906 dbus_bool_t b_false = FALSE;
4907 DBusMessageIter iter, sub;
4908 DBusConnection *bus;
4910 dbus_error_init(&error);
4912 if (!(rl = action_to_runlevel()))
4915 if (utmp_get_runlevel(&previous, NULL) < 0)
4918 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4919 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4924 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4929 if ((r = bus_check_peercred(bus)) < 0) {
4930 log_error("Failed to verify owner of bus.");
4934 if (!(m = dbus_message_new_method_call(
4935 "com.ubuntu.Upstart",
4936 "/com/ubuntu/Upstart",
4937 "com.ubuntu.Upstart0_6",
4940 log_error("Could not allocate message.");
4945 dbus_message_iter_init_append(m, &iter);
4947 env1_buf[sizeof(env1_buf)-2] = rl;
4948 env2_buf[sizeof(env2_buf)-2] = previous;
4950 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4951 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4952 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4953 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4954 !dbus_message_iter_close_container(&iter, &sub) ||
4955 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4956 log_error("Could not append arguments to message.");
4961 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4963 if (error_is_no_service(&error)) {
4968 log_error("Failed to issue method call: %s", bus_error_message(&error));
4977 dbus_message_unref(m);
4980 dbus_message_unref(reply);
4983 dbus_connection_flush(bus);
4984 dbus_connection_close(bus);
4985 dbus_connection_unref(bus);
4988 dbus_error_free(&error);
4993 static int talk_initctl(void) {
4994 struct init_request request;
4998 if (!(rl = action_to_runlevel()))
5002 request.magic = INIT_MAGIC;
5003 request.sleeptime = 0;
5004 request.cmd = INIT_CMD_RUNLVL;
5005 request.runlevel = rl;
5007 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5009 if (errno == ENOENT)
5012 log_error("Failed to open "INIT_FIFO": %m");
5017 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5018 close_nointr_nofail(fd);
5021 log_error("Failed to write to "INIT_FIFO": %m");
5022 return errno ? -errno : -EIO;
5028 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5030 static const struct {
5038 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5040 { "list-units", LESS, 1, list_units },
5041 { "list-jobs", EQUAL, 1, list_jobs },
5042 { "clear-jobs", EQUAL, 1, daemon_reload },
5043 { "load", MORE, 2, load_unit },
5044 { "cancel", MORE, 2, cancel_job },
5045 { "start", MORE, 2, start_unit },
5046 { "stop", MORE, 2, start_unit },
5047 { "reload", MORE, 2, start_unit },
5048 { "restart", MORE, 2, start_unit },
5049 { "try-restart", MORE, 2, start_unit },
5050 { "reload-or-restart", MORE, 2, start_unit },
5051 { "reload-or-try-restart", MORE, 2, start_unit },
5052 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5053 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5054 { "isolate", EQUAL, 2, start_unit },
5055 { "kill", MORE, 2, kill_unit },
5056 { "is-active", MORE, 2, check_unit },
5057 { "check", MORE, 2, check_unit },
5058 { "show", MORE, 1, show },
5059 { "status", MORE, 2, show },
5060 { "monitor", EQUAL, 1, monitor },
5061 { "dump", EQUAL, 1, dump },
5062 { "dot", EQUAL, 1, dot },
5063 { "snapshot", LESS, 2, snapshot },
5064 { "delete", MORE, 2, delete_snapshot },
5065 { "daemon-reload", EQUAL, 1, daemon_reload },
5066 { "daemon-reexec", EQUAL, 1, daemon_reload },
5067 { "show-environment", EQUAL, 1, show_enviroment },
5068 { "set-environment", MORE, 2, set_environment },
5069 { "unset-environment", MORE, 2, set_environment },
5070 { "halt", EQUAL, 1, start_special },
5071 { "poweroff", EQUAL, 1, start_special },
5072 { "reboot", EQUAL, 1, start_special },
5073 { "kexec", EQUAL, 1, start_special },
5074 { "default", EQUAL, 1, start_special },
5075 { "rescue", EQUAL, 1, start_special },
5076 { "emergency", EQUAL, 1, start_special },
5077 { "exit", EQUAL, 1, start_special },
5078 { "reset-failed", MORE, 1, reset_failed },
5079 { "enable", MORE, 2, enable_unit },
5080 { "disable", MORE, 2, enable_unit },
5081 { "is-enabled", MORE, 2, enable_unit }
5091 left = argc - optind;
5094 /* Special rule: no arguments means "list-units" */
5097 if (streq(argv[optind], "help")) {
5102 for (i = 0; i < ELEMENTSOF(verbs); i++)
5103 if (streq(argv[optind], verbs[i].verb))
5106 if (i >= ELEMENTSOF(verbs)) {
5107 log_error("Unknown operation %s", argv[optind]);
5112 switch (verbs[i].argc_cmp) {
5115 if (left != verbs[i].argc) {
5116 log_error("Invalid number of arguments.");
5123 if (left < verbs[i].argc) {
5124 log_error("Too few arguments.");
5131 if (left > verbs[i].argc) {
5132 log_error("Too many arguments.");
5139 assert_not_reached("Unknown comparison operator.");
5142 /* Require a bus connection for all operations but
5144 if (!streq(verbs[i].verb, "enable") &&
5145 !streq(verbs[i].verb, "disable") &&
5147 log_error("Failed to get D-Bus connection: %s", error->message);
5151 return verbs[i].dispatch(bus, argv + optind, left);
5154 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5156 struct msghdr msghdr;
5158 union sockaddr_union sockaddr;
5159 struct shutdownd_command c;
5167 strncpy(c.wall_message, message, sizeof(c.wall_message));
5169 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5173 sockaddr.sa.sa_family = AF_UNIX;
5174 sockaddr.un.sun_path[0] = 0;
5175 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5178 iovec.iov_base = (char*) &c;
5179 iovec.iov_len = sizeof(c);
5182 msghdr.msg_name = &sockaddr;
5183 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5185 msghdr.msg_iov = &iovec;
5186 msghdr.msg_iovlen = 1;
5188 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5189 close_nointr_nofail(fd);
5193 close_nointr_nofail(fd);
5197 static int reload_with_fallback(DBusConnection *bus) {
5200 /* First, try systemd via D-Bus. */
5201 if (daemon_reload(bus, NULL, 0) > 0)
5205 /* Nothing else worked, so let's try signals */
5206 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5208 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5209 log_error("kill() failed: %m");
5216 static int start_with_fallback(DBusConnection *bus) {
5219 /* First, try systemd via D-Bus. */
5220 if (start_unit(bus, NULL, 0) >= 0)
5224 /* Hmm, talking to systemd via D-Bus didn't work. Then
5225 * let's try to talk to Upstart via D-Bus. */
5226 if (talk_upstart() > 0)
5229 /* Nothing else worked, so let's try
5231 if (talk_initctl() > 0)
5234 log_error("Failed to talk to init daemon.");
5238 warn_wall(arg_action);
5242 static int halt_main(DBusConnection *bus) {
5245 if (geteuid() != 0) {
5246 log_error("Must be root.");
5252 char date[FORMAT_TIMESTAMP_MAX];
5254 m = strv_join(arg_wall, " ");
5255 r = send_shutdownd(arg_when,
5256 arg_action == ACTION_HALT ? 'H' :
5257 arg_action == ACTION_POWEROFF ? 'P' :
5264 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5266 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5267 format_timestamp(date, sizeof(date), arg_when));
5272 if (!arg_dry && !arg_immediate)
5273 return start_with_fallback(bus);
5276 if (sd_booted() > 0)
5277 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5278 else if ((r = utmp_put_shutdown(0)) < 0)
5279 log_warning("Failed to write utmp record: %s", strerror(-r));
5288 /* Make sure C-A-D is handled by the kernel from this
5290 reboot(RB_ENABLE_CAD);
5292 switch (arg_action) {
5295 log_info("Halting.");
5296 reboot(RB_HALT_SYSTEM);
5299 case ACTION_POWEROFF:
5300 log_info("Powering off.");
5301 reboot(RB_POWER_OFF);
5305 log_info("Rebooting.");
5306 reboot(RB_AUTOBOOT);
5310 assert_not_reached("Unknown halt action.");
5313 /* We should never reach this. */
5317 static int runlevel_main(void) {
5318 int r, runlevel, previous;
5320 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5321 printf("unknown\n");
5326 previous <= 0 ? 'N' : previous,
5327 runlevel <= 0 ? 'N' : runlevel);
5332 static void pager_open(void) {
5339 if (!on_tty() || arg_no_pager)
5342 if ((pager = getenv("PAGER")))
5343 if (!*pager || streq(pager, "cat"))
5346 /* Determine and cache number of columns before we spawn the
5347 * pager so that we get the value from the actual tty */
5351 log_error("Failed to create pager pipe: %m");
5356 if (pager_pid < 0) {
5357 log_error("Failed to fork pager: %m");
5362 /* In the child start the pager */
5363 if (pager_pid == 0) {
5365 dup2(fd[0], STDIN_FILENO);
5368 setenv("LESS", "FRSX", 0);
5370 prctl(PR_SET_PDEATHSIG, SIGTERM);
5373 execlp(pager, pager, NULL);
5374 execl("/bin/sh", "sh", "-c", pager, NULL);
5376 /* Debian's alternatives command for pagers is
5377 * called 'pager'. Note that we do not call
5378 * sensible-pagers here, since that is just a
5379 * shell script that implements a logic that
5380 * is similar to this one anyway, but is
5381 * Debian-specific. */
5382 execlp("pager", "pager", NULL);
5384 execlp("less", "less", NULL);
5385 execlp("more", "more", NULL);
5388 log_error("Unable to execute pager: %m");
5389 _exit(EXIT_FAILURE);
5392 /* Return in the parent */
5393 if (dup2(fd[1], STDOUT_FILENO) < 0)
5394 log_error("Failed to duplicate pager pipe: %m");
5399 static void pager_close(void) {
5405 /* Inform pager that we are done */
5407 wait_for_terminate(pager_pid, &dummy);
5411 int main(int argc, char*argv[]) {
5412 int r, retval = EXIT_FAILURE;
5413 DBusConnection *bus = NULL;
5416 dbus_error_init(&error);
5418 log_parse_environment();
5421 if ((r = parse_argv(argc, argv)) < 0)
5424 retval = EXIT_SUCCESS;
5428 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5429 * let's shortcut this */
5430 if (arg_action == ACTION_RUNLEVEL) {
5431 r = runlevel_main();
5432 retval = r < 0 ? EXIT_FAILURE : r;
5436 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5438 switch (arg_action) {
5440 case ACTION_SYSTEMCTL:
5441 r = systemctl_main(bus, argc, argv, &error);
5445 case ACTION_POWEROFF:
5450 case ACTION_RUNLEVEL2:
5451 case ACTION_RUNLEVEL3:
5452 case ACTION_RUNLEVEL4:
5453 case ACTION_RUNLEVEL5:
5455 case ACTION_EMERGENCY:
5456 case ACTION_DEFAULT:
5457 r = start_with_fallback(bus);
5462 r = reload_with_fallback(bus);
5465 case ACTION_CANCEL_SHUTDOWN:
5466 r = send_shutdownd(0, 0, false, NULL);
5469 case ACTION_INVALID:
5470 case ACTION_RUNLEVEL:
5472 assert_not_reached("Unknown action");
5475 retval = r < 0 ? EXIT_FAILURE : r;
5480 dbus_connection_flush(bus);
5481 dbus_connection_close(bus);
5482 dbus_connection_unref(bus);
5485 dbus_error_free(&error);
5489 strv_free(arg_property);