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);
506 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
507 output_units_list(unit_infos, c);
514 dbus_message_unref(m);
517 dbus_message_unref(reply);
521 dbus_error_free(&error);
526 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
527 static const char * const colors[] = {
528 "Requires", "[color=\"black\"]",
529 "RequiresOverridable", "[color=\"black\"]",
530 "Requisite", "[color=\"darkblue\"]",
531 "RequisiteOverridable", "[color=\"darkblue\"]",
532 "Wants", "[color=\"darkgrey\"]",
533 "Conflicts", "[color=\"red\"]",
534 "ConflictedBy", "[color=\"red\"]",
535 "After", "[color=\"green\"]"
538 const char *c = NULL;
545 for (i = 0; i < ELEMENTSOF(colors); i += 2)
546 if (streq(colors[i], prop)) {
554 if (arg_dot != DOT_ALL)
555 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
558 switch (dbus_message_iter_get_arg_type(iter)) {
560 case DBUS_TYPE_ARRAY:
562 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
565 dbus_message_iter_recurse(iter, &sub);
567 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
570 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
571 dbus_message_iter_get_basic(&sub, &s);
572 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
574 dbus_message_iter_next(&sub);
584 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
585 DBusMessage *m = NULL, *reply = NULL;
586 const char *interface = "org.freedesktop.systemd1.Unit";
589 DBusMessageIter iter, sub, sub2, sub3;
594 dbus_error_init(&error);
596 if (!(m = dbus_message_new_method_call(
597 "org.freedesktop.systemd1",
599 "org.freedesktop.DBus.Properties",
601 log_error("Could not allocate message.");
606 if (!dbus_message_append_args(m,
607 DBUS_TYPE_STRING, &interface,
608 DBUS_TYPE_INVALID)) {
609 log_error("Could not append arguments to message.");
614 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
615 log_error("Failed to issue method call: %s", bus_error_message(&error));
620 if (!dbus_message_iter_init(reply, &iter) ||
621 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
622 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
623 log_error("Failed to parse reply.");
628 dbus_message_iter_recurse(&iter, &sub);
630 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
633 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
634 log_error("Failed to parse reply.");
639 dbus_message_iter_recurse(&sub, &sub2);
641 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
642 log_error("Failed to parse reply.");
647 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
648 log_error("Failed to parse reply.");
653 dbus_message_iter_recurse(&sub2, &sub3);
655 if (dot_one_property(name, prop, &sub3)) {
656 log_error("Failed to parse reply.");
661 dbus_message_iter_next(&sub);
668 dbus_message_unref(m);
671 dbus_message_unref(reply);
673 dbus_error_free(&error);
678 static int dot(DBusConnection *bus, char **args, unsigned n) {
679 DBusMessage *m = NULL, *reply = NULL;
682 DBusMessageIter iter, sub, sub2;
684 dbus_error_init(&error);
688 if (!(m = dbus_message_new_method_call(
689 "org.freedesktop.systemd1",
690 "/org/freedesktop/systemd1",
691 "org.freedesktop.systemd1.Manager",
693 log_error("Could not allocate message.");
697 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
698 log_error("Failed to issue method call: %s", bus_error_message(&error));
703 if (!dbus_message_iter_init(reply, &iter) ||
704 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
705 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
706 log_error("Failed to parse reply.");
711 printf("digraph systemd {\n");
713 dbus_message_iter_recurse(&iter, &sub);
714 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
715 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
717 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
718 log_error("Failed to parse reply.");
723 dbus_message_iter_recurse(&sub, &sub2);
725 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
726 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
727 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
728 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
729 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
730 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
731 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
732 log_error("Failed to parse reply.");
737 if ((r = dot_one(bus, id, unit_path)) < 0)
740 /* printf("\t\"%s\";\n", id); */
741 dbus_message_iter_next(&sub);
746 log_info(" Color legend: black = Requires\n"
747 " dark blue = Requisite\n"
748 " dark grey = Wants\n"
752 if (isatty(fileno(stdout)))
753 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
754 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
760 dbus_message_unref(m);
763 dbus_message_unref(reply);
765 dbus_error_free(&error);
770 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
771 DBusMessage *m = NULL, *reply = NULL;
774 DBusMessageIter iter, sub, sub2;
777 dbus_error_init(&error);
783 if (!(m = dbus_message_new_method_call(
784 "org.freedesktop.systemd1",
785 "/org/freedesktop/systemd1",
786 "org.freedesktop.systemd1.Manager",
788 log_error("Could not allocate message.");
792 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
793 log_error("Failed to issue method call: %s", bus_error_message(&error));
798 if (!dbus_message_iter_init(reply, &iter) ||
799 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
800 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
801 log_error("Failed to parse reply.");
806 dbus_message_iter_recurse(&iter, &sub);
808 if (isatty(STDOUT_FILENO))
809 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
811 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
812 const char *name, *type, *state, *job_path, *unit_path;
816 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
817 log_error("Failed to parse reply.");
822 dbus_message_iter_recurse(&sub, &sub2);
824 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
825 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
826 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
827 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
828 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
829 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
830 log_error("Failed to parse reply.");
835 e = arg_full ? NULL : ellipsize(name, 25, 33);
836 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
841 dbus_message_iter_next(&sub);
844 if (isatty(STDOUT_FILENO))
845 printf("\n%u jobs listed.\n", k);
851 dbus_message_unref(m);
854 dbus_message_unref(reply);
856 dbus_error_free(&error);
861 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
862 DBusMessage *m = NULL, *reply = NULL;
867 dbus_error_init(&error);
872 for (i = 1; i < n; i++) {
874 if (!(m = dbus_message_new_method_call(
875 "org.freedesktop.systemd1",
876 "/org/freedesktop/systemd1",
877 "org.freedesktop.systemd1.Manager",
879 log_error("Could not allocate message.");
884 if (!dbus_message_append_args(m,
885 DBUS_TYPE_STRING, &args[i],
886 DBUS_TYPE_INVALID)) {
887 log_error("Could not append arguments to message.");
892 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
893 log_error("Failed to issue method call: %s", bus_error_message(&error));
898 dbus_message_unref(m);
899 dbus_message_unref(reply);
908 dbus_message_unref(m);
911 dbus_message_unref(reply);
913 dbus_error_free(&error);
918 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
919 DBusMessage *m = NULL, *reply = NULL;
924 dbus_error_init(&error);
930 return daemon_reload(bus, args, n);
932 for (i = 1; i < n; i++) {
936 if (!(m = dbus_message_new_method_call(
937 "org.freedesktop.systemd1",
938 "/org/freedesktop/systemd1",
939 "org.freedesktop.systemd1.Manager",
941 log_error("Could not allocate message.");
946 if ((r = safe_atou(args[i], &id)) < 0) {
947 log_error("Failed to parse job id: %s", strerror(-r));
951 assert_cc(sizeof(uint32_t) == sizeof(id));
952 if (!dbus_message_append_args(m,
953 DBUS_TYPE_UINT32, &id,
954 DBUS_TYPE_INVALID)) {
955 log_error("Could not append arguments to message.");
960 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
961 log_error("Failed to issue method call: %s", bus_error_message(&error));
966 if (!dbus_message_get_args(reply, &error,
967 DBUS_TYPE_OBJECT_PATH, &path,
968 DBUS_TYPE_INVALID)) {
969 log_error("Failed to parse reply: %s", bus_error_message(&error));
974 dbus_message_unref(m);
975 if (!(m = dbus_message_new_method_call(
976 "org.freedesktop.systemd1",
978 "org.freedesktop.systemd1.Job",
980 log_error("Could not allocate message.");
985 dbus_message_unref(reply);
986 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
987 log_error("Failed to issue method call: %s", bus_error_message(&error));
992 dbus_message_unref(m);
993 dbus_message_unref(reply);
1001 dbus_message_unref(m);
1004 dbus_message_unref(reply);
1006 dbus_error_free(&error);
1011 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1012 DBusMessage *m = NULL, *reply = NULL;
1013 dbus_bool_t b = FALSE;
1014 DBusMessageIter iter, sub;
1016 *interface = "org.freedesktop.systemd1.Unit",
1017 *property = "NeedDaemonReload",
1020 /* We ignore all errors here, since this is used to show a warning only */
1022 if (!(m = dbus_message_new_method_call(
1023 "org.freedesktop.systemd1",
1024 "/org/freedesktop/systemd1",
1025 "org.freedesktop.systemd1.Manager",
1029 if (!dbus_message_append_args(m,
1030 DBUS_TYPE_STRING, &unit,
1034 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1037 if (!dbus_message_get_args(reply, NULL,
1038 DBUS_TYPE_OBJECT_PATH, &path,
1042 dbus_message_unref(m);
1043 if (!(m = dbus_message_new_method_call(
1044 "org.freedesktop.systemd1",
1046 "org.freedesktop.DBus.Properties",
1050 if (!dbus_message_append_args(m,
1051 DBUS_TYPE_STRING, &interface,
1052 DBUS_TYPE_STRING, &property,
1053 DBUS_TYPE_INVALID)) {
1057 dbus_message_unref(reply);
1058 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1061 if (!dbus_message_iter_init(reply, &iter) ||
1062 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1065 dbus_message_iter_recurse(&iter, &sub);
1067 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1070 dbus_message_iter_get_basic(&sub, &b);
1074 dbus_message_unref(m);
1077 dbus_message_unref(reply);
1082 typedef struct WaitData {
1087 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1095 dbus_error_init(&error);
1097 log_debug("Got D-Bus request: %s.%s() on %s",
1098 dbus_message_get_interface(message),
1099 dbus_message_get_member(message),
1100 dbus_message_get_path(message));
1102 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1103 log_error("Warning! D-Bus connection terminated.");
1104 dbus_connection_close(connection);
1106 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1109 dbus_bool_t success = true;
1111 if (!dbus_message_get_args(message, &error,
1112 DBUS_TYPE_UINT32, &id,
1113 DBUS_TYPE_OBJECT_PATH, &path,
1114 DBUS_TYPE_BOOLEAN, &success,
1116 log_error("Failed to parse message: %s", bus_error_message(&error));
1120 if ((p = set_remove(d->set, (char*) path)))
1128 dbus_error_free(&error);
1129 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1132 static int enable_wait_for_jobs(DBusConnection *bus) {
1140 dbus_error_init(&error);
1141 dbus_bus_add_match(bus,
1143 "sender='org.freedesktop.systemd1',"
1144 "interface='org.freedesktop.systemd1.Manager',"
1145 "member='JobRemoved',"
1146 "path='/org/freedesktop/systemd1'",
1149 if (dbus_error_is_set(&error)) {
1150 log_error("Failed to add match: %s", bus_error_message(&error));
1151 dbus_error_free(&error);
1155 /* This is slightly dirty, since we don't undo the match registrations. */
1159 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1170 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1171 log_error("Failed to add filter.");
1176 while (!set_isempty(s) &&
1177 dbus_connection_read_write_dispatch(bus, -1))
1180 if (!arg_quiet && d.failed)
1181 log_error("Job failed. See system logs and 'systemctl status' for details.");
1183 r = d.failed ? -EIO : 0;
1186 /* This is slightly dirty, since we don't undo the filter registration. */
1191 static int start_unit_one(
1192 DBusConnection *bus,
1199 DBusMessage *m = NULL, *reply = NULL;
1208 assert(arg_no_block || s);
1210 if (!(m = dbus_message_new_method_call(
1211 "org.freedesktop.systemd1",
1212 "/org/freedesktop/systemd1",
1213 "org.freedesktop.systemd1.Manager",
1215 log_error("Could not allocate message.");
1220 if (!dbus_message_append_args(m,
1221 DBUS_TYPE_STRING, &name,
1222 DBUS_TYPE_STRING, &mode,
1223 DBUS_TYPE_INVALID)) {
1224 log_error("Could not append arguments to message.");
1229 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1231 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1232 /* There's always a fallback possible for
1233 * legacy actions. */
1238 log_error("Failed to issue method call: %s", bus_error_message(error));
1243 if (!dbus_message_get_args(reply, error,
1244 DBUS_TYPE_OBJECT_PATH, &path,
1245 DBUS_TYPE_INVALID)) {
1246 log_error("Failed to parse reply: %s", bus_error_message(error));
1251 if (need_daemon_reload(bus, name))
1252 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1253 arg_user ? "--user" : "--system");
1255 if (!arg_no_block) {
1258 if (!(p = strdup(path))) {
1259 log_error("Failed to duplicate path.");
1264 if ((r = set_put(s, p)) < 0) {
1266 log_error("Failed to add path to set.");
1275 dbus_message_unref(m);
1278 dbus_message_unref(reply);
1283 static enum action verb_to_action(const char *verb) {
1284 if (streq(verb, "halt"))
1286 else if (streq(verb, "poweroff"))
1287 return ACTION_POWEROFF;
1288 else if (streq(verb, "reboot"))
1289 return ACTION_REBOOT;
1290 else if (streq(verb, "kexec"))
1291 return ACTION_KEXEC;
1292 else if (streq(verb, "rescue"))
1293 return ACTION_RESCUE;
1294 else if (streq(verb, "emergency"))
1295 return ACTION_EMERGENCY;
1296 else if (streq(verb, "default"))
1297 return ACTION_DEFAULT;
1298 else if (streq(verb, "exit"))
1301 return ACTION_INVALID;
1304 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1306 static const char * const table[_ACTION_MAX] = {
1307 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1308 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1309 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1310 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1311 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1312 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1313 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1314 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1315 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1316 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1317 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1318 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1323 const char *method, *mode, *one_name;
1327 dbus_error_init(&error);
1331 spawn_ask_password_agent();
1333 if (arg_action == ACTION_SYSTEMCTL) {
1335 streq(args[0], "stop") ? "StopUnit" :
1336 streq(args[0], "reload") ? "ReloadUnit" :
1337 streq(args[0], "restart") ? "RestartUnit" :
1338 streq(args[0], "try-restart") ||
1339 streq(args[0], "condrestart") ? "TryRestartUnit" :
1340 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1341 streq(args[0], "reload-or-try-restart") ||
1342 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1346 (streq(args[0], "isolate") ||
1347 streq(args[0], "rescue") ||
1348 streq(args[0], "emergency")) ? "isolate" :
1352 one_name = table[verb_to_action(args[0])];
1355 assert(arg_action < ELEMENTSOF(table));
1356 assert(table[arg_action]);
1358 method = "StartUnit";
1360 mode = (arg_action == ACTION_EMERGENCY ||
1361 arg_action == ACTION_RESCUE ||
1362 arg_action == ACTION_RUNLEVEL2 ||
1363 arg_action == ACTION_RUNLEVEL3 ||
1364 arg_action == ACTION_RUNLEVEL4 ||
1365 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1367 one_name = table[arg_action];
1370 if (!arg_no_block) {
1371 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1372 log_error("Could not watch jobs: %s", strerror(-ret));
1376 if (!(s = set_new(string_hash_func, string_compare_func))) {
1377 log_error("Failed to allocate set.");
1384 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1387 for (i = 1; i < n; i++)
1388 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1389 ret = translate_bus_error_to_exit_status(r, &error);
1390 dbus_error_free(&error);
1395 if ((r = wait_for_jobs(bus, s)) < 0) {
1404 dbus_error_free(&error);
1409 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1416 (streq(args[0], "halt") ||
1417 streq(args[0], "poweroff") ||
1418 streq(args[0], "reboot") ||
1419 streq(args[0], "kexec") ||
1420 streq(args[0], "exit")))
1421 return daemon_reload(bus, args, n);
1423 r = start_unit(bus, args, n);
1426 warn_wall(verb_to_action(args[0]));
1431 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1432 DBusMessage *m = NULL, *reply = NULL;
1434 *interface = "org.freedesktop.systemd1.Unit",
1435 *property = "ActiveState";
1436 int r = 3; /* According to LSB: "program is not running" */
1443 dbus_error_init(&error);
1445 for (i = 1; i < n; i++) {
1446 const char *path = NULL;
1448 DBusMessageIter iter, sub;
1450 if (!(m = dbus_message_new_method_call(
1451 "org.freedesktop.systemd1",
1452 "/org/freedesktop/systemd1",
1453 "org.freedesktop.systemd1.Manager",
1455 log_error("Could not allocate message.");
1460 if (!dbus_message_append_args(m,
1461 DBUS_TYPE_STRING, &args[i],
1462 DBUS_TYPE_INVALID)) {
1463 log_error("Could not append arguments to message.");
1468 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1470 /* Hmm, cannot figure out anything about this unit... */
1474 dbus_error_free(&error);
1475 dbus_message_unref(m);
1479 if (!dbus_message_get_args(reply, &error,
1480 DBUS_TYPE_OBJECT_PATH, &path,
1481 DBUS_TYPE_INVALID)) {
1482 log_error("Failed to parse reply: %s", bus_error_message(&error));
1487 dbus_message_unref(m);
1488 if (!(m = dbus_message_new_method_call(
1489 "org.freedesktop.systemd1",
1491 "org.freedesktop.DBus.Properties",
1493 log_error("Could not allocate message.");
1498 if (!dbus_message_append_args(m,
1499 DBUS_TYPE_STRING, &interface,
1500 DBUS_TYPE_STRING, &property,
1501 DBUS_TYPE_INVALID)) {
1502 log_error("Could not append arguments to message.");
1507 dbus_message_unref(reply);
1508 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1509 log_error("Failed to issue method call: %s", bus_error_message(&error));
1514 if (!dbus_message_iter_init(reply, &iter) ||
1515 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1516 log_error("Failed to parse reply.");
1521 dbus_message_iter_recurse(&iter, &sub);
1523 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1524 log_error("Failed to parse reply.");
1529 dbus_message_iter_get_basic(&sub, &state);
1534 if (streq(state, "active") || streq(state, "reloading"))
1537 dbus_message_unref(m);
1538 dbus_message_unref(reply);
1544 dbus_message_unref(m);
1547 dbus_message_unref(reply);
1549 dbus_error_free(&error);
1554 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1555 DBusMessage *m = NULL, *reply = NULL;
1563 dbus_error_init(&error);
1566 arg_kill_who = "all";
1569 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1571 for (i = 1; i < n; i++) {
1573 if (!(m = dbus_message_new_method_call(
1574 "org.freedesktop.systemd1",
1575 "/org/freedesktop/systemd1",
1576 "org.freedesktop.systemd1.Manager",
1578 log_error("Could not allocate message.");
1583 if (!dbus_message_append_args(m,
1584 DBUS_TYPE_STRING, &args[i],
1585 DBUS_TYPE_STRING, &arg_kill_who,
1586 DBUS_TYPE_STRING, &arg_kill_mode,
1587 DBUS_TYPE_INT32, &arg_signal,
1588 DBUS_TYPE_INVALID)) {
1589 log_error("Could not append arguments to message.");
1594 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1595 log_error("Failed to issue method call: %s", bus_error_message(&error));
1596 dbus_error_free(&error);
1600 dbus_message_unref(m);
1603 dbus_message_unref(reply);
1609 dbus_message_unref(m);
1612 dbus_message_unref(reply);
1614 dbus_error_free(&error);
1619 typedef struct ExecStatusInfo {
1627 usec_t start_timestamp;
1628 usec_t exit_timestamp;
1633 LIST_FIELDS(struct ExecStatusInfo, exec);
1636 static void exec_status_info_free(ExecStatusInfo *i) {
1645 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1646 uint64_t start_timestamp, exit_timestamp;
1647 DBusMessageIter sub2, sub3;
1651 int32_t code, status;
1657 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1660 dbus_message_iter_recurse(sub, &sub2);
1662 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1665 if (!(i->path = strdup(path)))
1668 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1669 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1673 dbus_message_iter_recurse(&sub2, &sub3);
1674 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1675 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1676 dbus_message_iter_next(&sub3);
1681 if (!(i->argv = new0(char*, n+1)))
1685 dbus_message_iter_recurse(&sub2, &sub3);
1686 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1689 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1690 dbus_message_iter_get_basic(&sub3, &s);
1691 dbus_message_iter_next(&sub3);
1693 if (!(i->argv[n++] = strdup(s)))
1697 if (!dbus_message_iter_next(&sub2) ||
1698 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1699 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1700 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1701 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1702 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1703 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1707 i->start_timestamp = (usec_t) start_timestamp;
1708 i->exit_timestamp = (usec_t) exit_timestamp;
1709 i->pid = (pid_t) pid;
1716 typedef struct UnitStatusInfo {
1718 const char *load_state;
1719 const char *active_state;
1720 const char *sub_state;
1722 const char *description;
1723 const char *following;
1726 const char *default_control_group;
1728 usec_t inactive_exit_timestamp;
1729 usec_t active_enter_timestamp;
1730 usec_t active_exit_timestamp;
1731 usec_t inactive_enter_timestamp;
1733 bool need_daemon_reload;
1738 const char *status_text;
1740 #ifdef HAVE_SYSV_COMPAT
1744 usec_t start_timestamp;
1745 usec_t exit_timestamp;
1747 int exit_code, exit_status;
1750 unsigned n_accepted;
1751 unsigned n_connections;
1755 const char *sysfs_path;
1757 /* Mount, Automount */
1763 LIST_HEAD(ExecStatusInfo, exec);
1766 static void print_status_info(UnitStatusInfo *i) {
1768 const char *on, *off, *ss;
1770 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1771 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1775 /* This shows pretty information about a unit. See
1776 * print_property() for a low-level property printer */
1778 printf("%s", strna(i->id));
1780 if (i->description && !streq_ptr(i->id, i->description))
1781 printf(" - %s", i->description);
1786 printf("\t Follow: unit currently follows state of %s\n", i->following);
1788 if (streq_ptr(i->load_state, "failed") ||
1789 streq_ptr(i->load_state, "banned")) {
1790 on = ansi_highlight(true);
1791 off = ansi_highlight(false);
1796 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1798 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1800 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1802 if (streq_ptr(i->active_state, "failed")) {
1803 on = ansi_highlight(true);
1804 off = ansi_highlight(false);
1805 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1806 on = ansi_highlight_green(true);
1807 off = ansi_highlight_green(false);
1812 printf("\t Active: %s%s (%s)%s",
1814 strna(i->active_state),
1818 printf("\t Active: %s%s%s",
1820 strna(i->active_state),
1823 timestamp = (streq_ptr(i->active_state, "active") ||
1824 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1825 (streq_ptr(i->active_state, "inactive") ||
1826 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1827 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1828 i->active_exit_timestamp;
1830 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1831 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1834 printf(" since %s; %s\n", s2, s1);
1836 printf(" since %s\n", s2);
1841 printf("\t Device: %s\n", i->sysfs_path);
1843 printf("\t Where: %s\n", i->where);
1845 printf("\t What: %s\n", i->what);
1848 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1850 LIST_FOREACH(exec, p, i->exec) {
1854 /* Only show exited processes here */
1858 t = strv_join(p->argv, " ");
1859 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1862 #ifdef HAVE_SYSV_COMPAT
1864 good = is_clean_exit_lsb(p->code, p->status);
1867 good = is_clean_exit(p->code, p->status);
1870 on = ansi_highlight(true);
1871 off = ansi_highlight(false);
1875 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1877 if (p->code == CLD_EXITED) {
1880 printf("status=%i", p->status);
1882 #ifdef HAVE_SYSV_COMPAT
1883 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1885 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1890 printf("signal=%s", signal_to_string(p->status));
1892 printf(")%s\n", off);
1896 if (i->main_pid == p->pid &&
1897 i->start_timestamp == p->start_timestamp &&
1898 i->exit_timestamp == p->start_timestamp)
1899 /* Let's not show this twice */
1902 if (p->pid == i->control_pid)
1906 if (i->main_pid > 0 || i->control_pid > 0) {
1909 if (i->main_pid > 0) {
1910 printf("Main PID: %u", (unsigned) i->main_pid);
1914 get_process_name(i->main_pid, &t);
1919 } else if (i->exit_code > 0) {
1920 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1922 if (i->exit_code == CLD_EXITED) {
1925 printf("status=%i", i->exit_status);
1927 #ifdef HAVE_SYSV_COMPAT
1928 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1930 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1935 printf("signal=%s", signal_to_string(i->exit_status));
1940 if (i->main_pid > 0 && i->control_pid > 0)
1943 if (i->control_pid > 0) {
1946 printf(" Control: %u", (unsigned) i->control_pid);
1948 get_process_name(i->control_pid, &t);
1959 printf("\t Status: \"%s\"\n", i->status_text);
1961 if (i->default_control_group) {
1964 printf("\t CGroup: %s\n", i->default_control_group);
1966 if ((c = columns()) > 18)
1971 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1974 if (i->need_daemon_reload)
1975 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1976 ansi_highlight(true),
1977 ansi_highlight(false),
1978 arg_user ? "--user" : "--system");
1981 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1983 switch (dbus_message_iter_get_arg_type(iter)) {
1985 case DBUS_TYPE_STRING: {
1988 dbus_message_iter_get_basic(iter, &s);
1991 if (streq(name, "Id"))
1993 else if (streq(name, "LoadState"))
1995 else if (streq(name, "ActiveState"))
1996 i->active_state = s;
1997 else if (streq(name, "SubState"))
1999 else if (streq(name, "Description"))
2001 else if (streq(name, "FragmentPath"))
2003 #ifdef HAVE_SYSV_COMPAT
2004 else if (streq(name, "SysVPath")) {
2009 else if (streq(name, "DefaultControlGroup"))
2010 i->default_control_group = s;
2011 else if (streq(name, "StatusText"))
2013 else if (streq(name, "SysFSPath"))
2015 else if (streq(name, "Where"))
2017 else if (streq(name, "What"))
2019 else if (streq(name, "Following"))
2026 case DBUS_TYPE_BOOLEAN: {
2029 dbus_message_iter_get_basic(iter, &b);
2031 if (streq(name, "Accept"))
2033 else if (streq(name, "NeedDaemonReload"))
2034 i->need_daemon_reload = b;
2039 case DBUS_TYPE_UINT32: {
2042 dbus_message_iter_get_basic(iter, &u);
2044 if (streq(name, "MainPID")) {
2046 i->main_pid = (pid_t) u;
2049 } else if (streq(name, "ControlPID"))
2050 i->control_pid = (pid_t) u;
2051 else if (streq(name, "ExecMainPID")) {
2053 i->main_pid = (pid_t) u;
2054 } else if (streq(name, "NAccepted"))
2056 else if (streq(name, "NConnections"))
2057 i->n_connections = u;
2062 case DBUS_TYPE_INT32: {
2065 dbus_message_iter_get_basic(iter, &j);
2067 if (streq(name, "ExecMainCode"))
2068 i->exit_code = (int) j;
2069 else if (streq(name, "ExecMainStatus"))
2070 i->exit_status = (int) j;
2075 case DBUS_TYPE_UINT64: {
2078 dbus_message_iter_get_basic(iter, &u);
2080 if (streq(name, "ExecMainStartTimestamp"))
2081 i->start_timestamp = (usec_t) u;
2082 else if (streq(name, "ExecMainExitTimestamp"))
2083 i->exit_timestamp = (usec_t) u;
2084 else if (streq(name, "ActiveEnterTimestamp"))
2085 i->active_enter_timestamp = (usec_t) u;
2086 else if (streq(name, "InactiveEnterTimestamp"))
2087 i->inactive_enter_timestamp = (usec_t) u;
2088 else if (streq(name, "InactiveExitTimestamp"))
2089 i->inactive_exit_timestamp = (usec_t) u;
2090 else if (streq(name, "ActiveExitTimestamp"))
2091 i->active_exit_timestamp = (usec_t) u;
2096 case DBUS_TYPE_ARRAY: {
2098 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2099 startswith(name, "Exec")) {
2100 DBusMessageIter sub;
2102 dbus_message_iter_recurse(iter, &sub);
2103 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2104 ExecStatusInfo *info;
2107 if (!(info = new0(ExecStatusInfo, 1)))
2110 if (!(info->name = strdup(name))) {
2115 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2120 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2122 dbus_message_iter_next(&sub);
2133 static int print_property(const char *name, DBusMessageIter *iter) {
2137 /* This is a low-level property printer, see
2138 * print_status_info() for the nicer output */
2140 if (arg_property && !strv_find(arg_property, name))
2143 switch (dbus_message_iter_get_arg_type(iter)) {
2145 case DBUS_TYPE_STRING: {
2147 dbus_message_iter_get_basic(iter, &s);
2149 if (arg_all || s[0])
2150 printf("%s=%s\n", name, s);
2155 case DBUS_TYPE_BOOLEAN: {
2157 dbus_message_iter_get_basic(iter, &b);
2158 printf("%s=%s\n", name, yes_no(b));
2163 case DBUS_TYPE_UINT64: {
2165 dbus_message_iter_get_basic(iter, &u);
2167 /* Yes, heuristics! But we can change this check
2168 * should it turn out to not be sufficient */
2170 if (strstr(name, "Timestamp")) {
2171 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2173 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2174 printf("%s=%s\n", name, strempty(t));
2175 } else if (strstr(name, "USec")) {
2176 char timespan[FORMAT_TIMESPAN_MAX];
2178 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2180 printf("%s=%llu\n", name, (unsigned long long) u);
2185 case DBUS_TYPE_UINT32: {
2187 dbus_message_iter_get_basic(iter, &u);
2189 if (strstr(name, "UMask") || strstr(name, "Mode"))
2190 printf("%s=%04o\n", name, u);
2192 printf("%s=%u\n", name, (unsigned) u);
2197 case DBUS_TYPE_INT32: {
2199 dbus_message_iter_get_basic(iter, &i);
2201 printf("%s=%i\n", name, (int) i);
2205 case DBUS_TYPE_DOUBLE: {
2207 dbus_message_iter_get_basic(iter, &d);
2209 printf("%s=%g\n", name, d);
2213 case DBUS_TYPE_STRUCT: {
2214 DBusMessageIter sub;
2215 dbus_message_iter_recurse(iter, &sub);
2217 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2220 dbus_message_iter_get_basic(&sub, &u);
2223 printf("%s=%u\n", name, (unsigned) u);
2225 printf("%s=\n", name);
2228 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2231 dbus_message_iter_get_basic(&sub, &s);
2233 if (arg_all || s[0])
2234 printf("%s=%s\n", name, s);
2242 case DBUS_TYPE_ARRAY:
2244 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2245 DBusMessageIter sub;
2248 dbus_message_iter_recurse(iter, &sub);
2250 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2251 printf("%s=", name);
2253 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2256 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2257 dbus_message_iter_get_basic(&sub, &s);
2258 printf("%s%s", space ? " " : "", s);
2261 dbus_message_iter_next(&sub);
2269 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2270 DBusMessageIter sub;
2272 dbus_message_iter_recurse(iter, &sub);
2274 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2275 printf("%s=", name);
2277 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2280 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2281 dbus_message_iter_get_basic(&sub, &u);
2284 dbus_message_iter_next(&sub);
2292 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2293 DBusMessageIter sub, sub2;
2295 dbus_message_iter_recurse(iter, &sub);
2296 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2297 const char *type, *path;
2299 dbus_message_iter_recurse(&sub, &sub2);
2301 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2302 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2303 printf("%s=%s\n", type, path);
2305 dbus_message_iter_next(&sub);
2310 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2311 DBusMessageIter sub, sub2;
2313 dbus_message_iter_recurse(iter, &sub);
2314 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2316 uint64_t value, next_elapse;
2318 dbus_message_iter_recurse(&sub, &sub2);
2320 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2321 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2322 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2323 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2325 printf("%s={ value=%s ; next_elapse=%s }\n",
2327 format_timespan(timespan1, sizeof(timespan1), value),
2328 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2331 dbus_message_iter_next(&sub);
2336 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2337 DBusMessageIter sub;
2339 dbus_message_iter_recurse(iter, &sub);
2340 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2341 ExecStatusInfo info;
2344 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2345 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2348 t = strv_join(info.argv, " ");
2350 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2354 yes_no(info.ignore),
2355 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2356 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2357 (unsigned) info. pid,
2358 sigchld_code_to_string(info.code),
2360 info.code == CLD_EXITED ? "" : "/",
2361 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2367 strv_free(info.argv);
2369 dbus_message_iter_next(&sub);
2379 printf("%s=[unprintable]\n", name);
2384 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2385 DBusMessage *m = NULL, *reply = NULL;
2386 const char *interface = "";
2389 DBusMessageIter iter, sub, sub2, sub3;
2390 UnitStatusInfo info;
2398 dbus_error_init(&error);
2400 if (!(m = dbus_message_new_method_call(
2401 "org.freedesktop.systemd1",
2403 "org.freedesktop.DBus.Properties",
2405 log_error("Could not allocate message.");
2410 if (!dbus_message_append_args(m,
2411 DBUS_TYPE_STRING, &interface,
2412 DBUS_TYPE_INVALID)) {
2413 log_error("Could not append arguments to message.");
2418 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2419 log_error("Failed to issue method call: %s", bus_error_message(&error));
2424 if (!dbus_message_iter_init(reply, &iter) ||
2425 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2426 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2427 log_error("Failed to parse reply.");
2432 dbus_message_iter_recurse(&iter, &sub);
2439 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2442 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2443 log_error("Failed to parse reply.");
2448 dbus_message_iter_recurse(&sub, &sub2);
2450 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2451 log_error("Failed to parse reply.");
2456 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2457 log_error("Failed to parse reply.");
2462 dbus_message_iter_recurse(&sub2, &sub3);
2464 if (show_properties)
2465 r = print_property(name, &sub3);
2467 r = status_property(name, &sub3, &info);
2470 log_error("Failed to parse reply.");
2475 dbus_message_iter_next(&sub);
2480 if (!show_properties)
2481 print_status_info(&info);
2483 if (!streq_ptr(info.active_state, "active") &&
2484 !streq_ptr(info.active_state, "reloading") &&
2485 streq(verb, "status"))
2486 /* According to LSB: "program not running" */
2489 while ((p = info.exec)) {
2490 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2491 exec_status_info_free(p);
2496 dbus_message_unref(m);
2499 dbus_message_unref(reply);
2501 dbus_error_free(&error);
2506 static int show(DBusConnection *bus, char **args, unsigned n) {
2507 DBusMessage *m = NULL, *reply = NULL;
2511 bool show_properties, new_line = false;
2516 dbus_error_init(&error);
2518 show_properties = !streq(args[0], "status");
2520 if (show_properties)
2523 if (show_properties && n <= 1) {
2524 /* If not argument is specified inspect the manager
2527 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2531 for (i = 1; i < n; i++) {
2532 const char *path = NULL;
2535 if (safe_atou32(args[i], &id) < 0) {
2537 /* Interpret as unit name */
2539 if (!(m = dbus_message_new_method_call(
2540 "org.freedesktop.systemd1",
2541 "/org/freedesktop/systemd1",
2542 "org.freedesktop.systemd1.Manager",
2544 log_error("Could not allocate message.");
2549 if (!dbus_message_append_args(m,
2550 DBUS_TYPE_STRING, &args[i],
2551 DBUS_TYPE_INVALID)) {
2552 log_error("Could not append arguments to message.");
2557 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2559 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2560 log_error("Failed to issue method call: %s", bus_error_message(&error));
2565 dbus_error_free(&error);
2567 dbus_message_unref(m);
2568 if (!(m = dbus_message_new_method_call(
2569 "org.freedesktop.systemd1",
2570 "/org/freedesktop/systemd1",
2571 "org.freedesktop.systemd1.Manager",
2573 log_error("Could not allocate message.");
2578 if (!dbus_message_append_args(m,
2579 DBUS_TYPE_STRING, &args[i],
2580 DBUS_TYPE_INVALID)) {
2581 log_error("Could not append arguments to message.");
2586 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2587 log_error("Failed to issue method call: %s", bus_error_message(&error));
2589 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2590 ret = 4; /* According to LSB: "program or service status is unknown" */
2597 } else if (show_properties) {
2599 /* Interpret as job id */
2601 if (!(m = dbus_message_new_method_call(
2602 "org.freedesktop.systemd1",
2603 "/org/freedesktop/systemd1",
2604 "org.freedesktop.systemd1.Manager",
2606 log_error("Could not allocate message.");
2611 if (!dbus_message_append_args(m,
2612 DBUS_TYPE_UINT32, &id,
2613 DBUS_TYPE_INVALID)) {
2614 log_error("Could not append arguments to message.");
2619 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2620 log_error("Failed to issue method call: %s", bus_error_message(&error));
2626 /* Interpret as PID */
2628 if (!(m = dbus_message_new_method_call(
2629 "org.freedesktop.systemd1",
2630 "/org/freedesktop/systemd1",
2631 "org.freedesktop.systemd1.Manager",
2633 log_error("Could not allocate message.");
2638 if (!dbus_message_append_args(m,
2639 DBUS_TYPE_UINT32, &id,
2640 DBUS_TYPE_INVALID)) {
2641 log_error("Could not append arguments to message.");
2646 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2647 log_error("Failed to issue method call: %s", bus_error_message(&error));
2653 if (!dbus_message_get_args(reply, &error,
2654 DBUS_TYPE_OBJECT_PATH, &path,
2655 DBUS_TYPE_INVALID)) {
2656 log_error("Failed to parse reply: %s", bus_error_message(&error));
2661 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2664 dbus_message_unref(m);
2665 dbus_message_unref(reply);
2671 dbus_message_unref(m);
2674 dbus_message_unref(reply);
2676 dbus_error_free(&error);
2681 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2683 DBusMessage *m = NULL, *reply = NULL;
2688 dbus_error_init(&error);
2690 log_debug("Got D-Bus request: %s.%s() on %s",
2691 dbus_message_get_interface(message),
2692 dbus_message_get_member(message),
2693 dbus_message_get_path(message));
2695 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2696 log_error("Warning! D-Bus connection terminated.");
2697 dbus_connection_close(connection);
2699 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2700 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2701 const char *id, *path;
2703 if (!dbus_message_get_args(message, &error,
2704 DBUS_TYPE_STRING, &id,
2705 DBUS_TYPE_OBJECT_PATH, &path,
2707 log_error("Failed to parse message: %s", bus_error_message(&error));
2708 else if (streq(dbus_message_get_member(message), "UnitNew"))
2709 printf("Unit %s added.\n", id);
2711 printf("Unit %s removed.\n", id);
2713 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2714 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2718 if (!dbus_message_get_args(message, &error,
2719 DBUS_TYPE_UINT32, &id,
2720 DBUS_TYPE_OBJECT_PATH, &path,
2722 log_error("Failed to parse message: %s", bus_error_message(&error));
2723 else if (streq(dbus_message_get_member(message), "JobNew"))
2724 printf("Job %u added.\n", id);
2726 printf("Job %u removed.\n", id);
2729 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2731 const char *path, *interface, *property = "Id";
2732 DBusMessageIter iter, sub;
2734 path = dbus_message_get_path(message);
2736 if (!dbus_message_get_args(message, &error,
2737 DBUS_TYPE_STRING, &interface,
2738 DBUS_TYPE_INVALID)) {
2739 log_error("Failed to parse message: %s", bus_error_message(&error));
2743 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2744 !streq(interface, "org.freedesktop.systemd1.Unit"))
2747 if (!(m = dbus_message_new_method_call(
2748 "org.freedesktop.systemd1",
2750 "org.freedesktop.DBus.Properties",
2752 log_error("Could not allocate message.");
2756 if (!dbus_message_append_args(m,
2757 DBUS_TYPE_STRING, &interface,
2758 DBUS_TYPE_STRING, &property,
2759 DBUS_TYPE_INVALID)) {
2760 log_error("Could not append arguments to message.");
2764 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2765 log_error("Failed to issue method call: %s", bus_error_message(&error));
2769 if (!dbus_message_iter_init(reply, &iter) ||
2770 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2771 log_error("Failed to parse reply.");
2775 dbus_message_iter_recurse(&iter, &sub);
2777 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2780 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2781 log_error("Failed to parse reply.");
2785 dbus_message_iter_get_basic(&sub, &id);
2786 printf("Unit %s changed.\n", id);
2790 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2791 log_error("Failed to parse reply.");
2795 dbus_message_iter_get_basic(&sub, &id);
2796 printf("Job %u changed.\n", id);
2802 dbus_message_unref(m);
2805 dbus_message_unref(reply);
2807 dbus_error_free(&error);
2808 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2812 dbus_message_unref(m);
2815 dbus_message_unref(reply);
2817 dbus_error_free(&error);
2818 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2821 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2822 DBusMessage *m = NULL, *reply = NULL;
2826 dbus_error_init(&error);
2829 dbus_bus_add_match(bus,
2831 "sender='org.freedesktop.systemd1',"
2832 "interface='org.freedesktop.systemd1.Manager',"
2833 "path='/org/freedesktop/systemd1'",
2836 if (dbus_error_is_set(&error)) {
2837 log_error("Failed to add match: %s", bus_error_message(&error));
2842 dbus_bus_add_match(bus,
2844 "sender='org.freedesktop.systemd1',"
2845 "interface='org.freedesktop.DBus.Properties',"
2846 "member='PropertiesChanged'",
2849 if (dbus_error_is_set(&error)) {
2850 log_error("Failed to add match: %s", bus_error_message(&error));
2856 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2857 log_error("Failed to add filter.");
2862 if (!(m = dbus_message_new_method_call(
2863 "org.freedesktop.systemd1",
2864 "/org/freedesktop/systemd1",
2865 "org.freedesktop.systemd1.Manager",
2867 log_error("Could not allocate message.");
2872 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2873 log_error("Failed to issue method call: %s", bus_error_message(&error));
2878 while (dbus_connection_read_write_dispatch(bus, -1))
2885 /* This is slightly dirty, since we don't undo the filter or the matches. */
2888 dbus_message_unref(m);
2891 dbus_message_unref(reply);
2893 dbus_error_free(&error);
2898 static int dump(DBusConnection *bus, char **args, unsigned n) {
2899 DBusMessage *m = NULL, *reply = NULL;
2904 dbus_error_init(&error);
2908 if (!(m = dbus_message_new_method_call(
2909 "org.freedesktop.systemd1",
2910 "/org/freedesktop/systemd1",
2911 "org.freedesktop.systemd1.Manager",
2913 log_error("Could not allocate message.");
2917 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2918 log_error("Failed to issue method call: %s", bus_error_message(&error));
2923 if (!dbus_message_get_args(reply, &error,
2924 DBUS_TYPE_STRING, &text,
2925 DBUS_TYPE_INVALID)) {
2926 log_error("Failed to parse reply: %s", bus_error_message(&error));
2931 fputs(text, stdout);
2937 dbus_message_unref(m);
2940 dbus_message_unref(reply);
2942 dbus_error_free(&error);
2947 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2948 DBusMessage *m = NULL, *reply = NULL;
2951 const char *name = "", *path, *id;
2952 dbus_bool_t cleanup = FALSE;
2953 DBusMessageIter iter, sub;
2955 *interface = "org.freedesktop.systemd1.Unit",
2958 dbus_error_init(&error);
2960 if (!(m = dbus_message_new_method_call(
2961 "org.freedesktop.systemd1",
2962 "/org/freedesktop/systemd1",
2963 "org.freedesktop.systemd1.Manager",
2964 "CreateSnapshot"))) {
2965 log_error("Could not allocate message.");
2972 if (!dbus_message_append_args(m,
2973 DBUS_TYPE_STRING, &name,
2974 DBUS_TYPE_BOOLEAN, &cleanup,
2975 DBUS_TYPE_INVALID)) {
2976 log_error("Could not append arguments to message.");
2981 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2982 log_error("Failed to issue method call: %s", bus_error_message(&error));
2987 if (!dbus_message_get_args(reply, &error,
2988 DBUS_TYPE_OBJECT_PATH, &path,
2989 DBUS_TYPE_INVALID)) {
2990 log_error("Failed to parse reply: %s", bus_error_message(&error));
2995 dbus_message_unref(m);
2996 if (!(m = dbus_message_new_method_call(
2997 "org.freedesktop.systemd1",
2999 "org.freedesktop.DBus.Properties",
3001 log_error("Could not allocate message.");
3005 if (!dbus_message_append_args(m,
3006 DBUS_TYPE_STRING, &interface,
3007 DBUS_TYPE_STRING, &property,
3008 DBUS_TYPE_INVALID)) {
3009 log_error("Could not append arguments to message.");
3014 dbus_message_unref(reply);
3015 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3016 log_error("Failed to issue method call: %s", bus_error_message(&error));
3021 if (!dbus_message_iter_init(reply, &iter) ||
3022 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3023 log_error("Failed to parse reply.");
3028 dbus_message_iter_recurse(&iter, &sub);
3030 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3031 log_error("Failed to parse reply.");
3036 dbus_message_iter_get_basic(&sub, &id);
3044 dbus_message_unref(m);
3047 dbus_message_unref(reply);
3049 dbus_error_free(&error);
3054 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3055 DBusMessage *m = NULL, *reply = NULL;
3063 dbus_error_init(&error);
3065 for (i = 1; i < n; i++) {
3066 const char *path = NULL;
3068 if (!(m = dbus_message_new_method_call(
3069 "org.freedesktop.systemd1",
3070 "/org/freedesktop/systemd1",
3071 "org.freedesktop.systemd1.Manager",
3073 log_error("Could not allocate message.");
3078 if (!dbus_message_append_args(m,
3079 DBUS_TYPE_STRING, &args[i],
3080 DBUS_TYPE_INVALID)) {
3081 log_error("Could not append arguments to message.");
3086 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3087 log_error("Failed to issue method call: %s", bus_error_message(&error));
3092 if (!dbus_message_get_args(reply, &error,
3093 DBUS_TYPE_OBJECT_PATH, &path,
3094 DBUS_TYPE_INVALID)) {
3095 log_error("Failed to parse reply: %s", bus_error_message(&error));
3100 dbus_message_unref(m);
3101 if (!(m = dbus_message_new_method_call(
3102 "org.freedesktop.systemd1",
3104 "org.freedesktop.systemd1.Snapshot",
3106 log_error("Could not allocate message.");
3111 dbus_message_unref(reply);
3112 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3113 log_error("Failed to issue method call: %s", bus_error_message(&error));
3118 dbus_message_unref(m);
3119 dbus_message_unref(reply);
3127 dbus_message_unref(m);
3130 dbus_message_unref(reply);
3132 dbus_error_free(&error);
3137 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3138 DBusMessage *m = NULL, *reply = NULL;
3143 dbus_error_init(&error);
3145 if (arg_action == ACTION_RELOAD)
3147 else if (arg_action == ACTION_REEXEC)
3148 method = "Reexecute";
3150 assert(arg_action == ACTION_SYSTEMCTL);
3153 streq(args[0], "clear-jobs") ||
3154 streq(args[0], "cancel") ? "ClearJobs" :
3155 streq(args[0], "daemon-reexec") ? "Reexecute" :
3156 streq(args[0], "reset-failed") ? "ResetFailed" :
3157 streq(args[0], "halt") ? "Halt" :
3158 streq(args[0], "poweroff") ? "PowerOff" :
3159 streq(args[0], "reboot") ? "Reboot" :
3160 streq(args[0], "kexec") ? "KExec" :
3161 streq(args[0], "exit") ? "Exit" :
3162 /* "daemon-reload" */ "Reload";
3165 if (!(m = dbus_message_new_method_call(
3166 "org.freedesktop.systemd1",
3167 "/org/freedesktop/systemd1",
3168 "org.freedesktop.systemd1.Manager",
3170 log_error("Could not allocate message.");
3174 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3176 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3177 /* There's always a fallback possible for
3178 * legacy actions. */
3183 log_error("Failed to issue method call: %s", bus_error_message(&error));
3192 dbus_message_unref(m);
3195 dbus_message_unref(reply);
3197 dbus_error_free(&error);
3202 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3203 DBusMessage *m = NULL, *reply = NULL;
3209 dbus_error_init(&error);
3212 return daemon_reload(bus, args, n);
3214 for (i = 1; i < n; i++) {
3216 if (!(m = dbus_message_new_method_call(
3217 "org.freedesktop.systemd1",
3218 "/org/freedesktop/systemd1",
3219 "org.freedesktop.systemd1.Manager",
3220 "ResetFailedUnit"))) {
3221 log_error("Could not allocate message.");
3226 if (!dbus_message_append_args(m,
3227 DBUS_TYPE_STRING, args + i,
3228 DBUS_TYPE_INVALID)) {
3229 log_error("Could not append arguments to message.");
3234 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3235 log_error("Failed to issue method call: %s", bus_error_message(&error));
3240 dbus_message_unref(m);
3241 dbus_message_unref(reply);
3249 dbus_message_unref(m);
3252 dbus_message_unref(reply);
3254 dbus_error_free(&error);
3259 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3260 DBusMessage *m = NULL, *reply = NULL;
3262 DBusMessageIter iter, sub, sub2;
3265 *interface = "org.freedesktop.systemd1.Manager",
3266 *property = "Environment";
3268 dbus_error_init(&error);
3272 if (!(m = dbus_message_new_method_call(
3273 "org.freedesktop.systemd1",
3274 "/org/freedesktop/systemd1",
3275 "org.freedesktop.DBus.Properties",
3277 log_error("Could not allocate message.");
3281 if (!dbus_message_append_args(m,
3282 DBUS_TYPE_STRING, &interface,
3283 DBUS_TYPE_STRING, &property,
3284 DBUS_TYPE_INVALID)) {
3285 log_error("Could not append arguments to message.");
3290 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3291 log_error("Failed to issue method call: %s", bus_error_message(&error));
3296 if (!dbus_message_iter_init(reply, &iter) ||
3297 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3298 log_error("Failed to parse reply.");
3303 dbus_message_iter_recurse(&iter, &sub);
3305 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3306 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3307 log_error("Failed to parse reply.");
3312 dbus_message_iter_recurse(&sub, &sub2);
3314 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3317 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3318 log_error("Failed to parse reply.");
3323 dbus_message_iter_get_basic(&sub2, &text);
3324 printf("%s\n", text);
3326 dbus_message_iter_next(&sub2);
3333 dbus_message_unref(m);
3336 dbus_message_unref(reply);
3338 dbus_error_free(&error);
3343 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3344 DBusMessage *m = NULL, *reply = NULL;
3348 DBusMessageIter iter, sub;
3351 dbus_error_init(&error);
3353 method = streq(args[0], "set-environment")
3355 : "UnsetEnvironment";
3357 if (!(m = dbus_message_new_method_call(
3358 "org.freedesktop.systemd1",
3359 "/org/freedesktop/systemd1",
3360 "org.freedesktop.systemd1.Manager",
3363 log_error("Could not allocate message.");
3367 dbus_message_iter_init_append(m, &iter);
3369 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3370 log_error("Could not append arguments to message.");
3375 for (i = 1; i < n; i++)
3376 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3377 log_error("Could not append arguments to message.");
3382 if (!dbus_message_iter_close_container(&iter, &sub)) {
3383 log_error("Could not append arguments to message.");
3388 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3389 log_error("Failed to issue method call: %s", bus_error_message(&error));
3398 dbus_message_unref(m);
3401 dbus_message_unref(reply);
3403 dbus_error_free(&error);
3416 static Hashmap *will_install = NULL, *have_installed = NULL;
3417 static Set *remove_symlinks_to = NULL;
3418 static unsigned n_symlinks = 0;
3420 static void install_info_free(InstallInfo *i) {
3425 strv_free(i->aliases);
3426 strv_free(i->wanted_by);
3430 static void install_info_hashmap_free(Hashmap *m) {
3433 while ((i = hashmap_steal_first(m)))
3434 install_info_free(i);
3439 static int install_info_add(const char *name) {
3443 assert(will_install);
3445 if (!unit_name_is_valid_no_type(name, true)) {
3446 log_warning("Unit name %s is not a valid unit name.", name);
3450 if (hashmap_get(have_installed, name) ||
3451 hashmap_get(will_install, name))
3454 if (!(i = new0(InstallInfo, 1))) {
3459 if (!(i->name = strdup(name))) {
3464 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3471 install_info_free(i);
3476 static int config_parse_also(
3477 const char *filename,
3479 const char *section,
3493 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3497 if (!(n = strndup(w, l)))
3500 if ((r = install_info_add(n)) < 0) {
3501 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3512 static int mark_symlink_for_removal(const char *p) {
3517 assert(path_is_absolute(p));
3519 if (!remove_symlinks_to)
3522 if (!(n = strdup(p)))
3525 path_kill_slashes(n);
3527 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3529 return r == -EEXIST ? 0 : r;
3535 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3544 if (!(d = fdopendir(fd))) {
3545 close_nointr_nofail(fd);
3551 while ((de = readdir(d))) {
3552 bool is_dir = false, is_link = false;
3554 if (ignore_file(de->d_name))
3557 if (de->d_type == DT_LNK)
3559 else if (de->d_type == DT_DIR)
3561 else if (de->d_type == DT_UNKNOWN) {
3564 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3565 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3572 is_link = S_ISLNK(st.st_mode);
3573 is_dir = S_ISDIR(st.st_mode);
3581 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3582 log_error("Failed to open %s/%s: %m", root, de->d_name);
3589 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3590 log_error("Failed to allocate directory string.");
3591 close_nointr_nofail(nfd);
3596 /* This will close nfd, regardless whether it succeeds or not */
3597 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3603 } else if (is_link) {
3607 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3608 log_error("Failed to allocate symlink string.");
3613 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3614 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3622 if ((c = canonicalize_file_name(dest))) {
3623 /* This might fail if the destination
3624 * is already removed */
3630 path_kill_slashes(dest);
3631 if (set_get(remove_symlinks_to, dest)) {
3634 log_info("rm '%s'", p);
3636 if (unlink(p) < 0) {
3637 log_error("Cannot unlink symlink %s: %m", p);
3642 rmdir_parents(p, config_path);
3643 path_kill_slashes(p);
3645 if (!set_get(remove_symlinks_to, p)) {
3647 if ((r = mark_symlink_for_removal(p)) < 0) {
3666 static int remove_marked_symlinks(const char *config_path) {
3670 assert(config_path);
3672 if (set_size(remove_symlinks_to) <= 0)
3675 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3682 if ((cfd = dup(fd)) < 0) {
3687 /* This takes possession of cfd and closes it */
3688 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3694 close_nointr_nofail(fd);
3699 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3706 if (streq(verb, "enable")) {
3709 mkdir_parents(new_path, 0755);
3711 if (symlink(old_path, new_path) >= 0) {
3714 log_info("ln -s '%s' '%s'", old_path, new_path);
3719 if (errno != EEXIST) {
3720 log_error("Cannot link %s to %s: %m", old_path, new_path);
3724 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3726 if (errno == EINVAL) {
3727 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3731 log_error("readlink() failed: %s", strerror(-r));
3735 if (streq(dest, old_path)) {
3741 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3750 log_info("ln -s '%s' '%s'", old_path, new_path);
3752 if (symlink(old_path, new_path) >= 0)
3755 log_error("Cannot link %s to %s: %m", old_path, new_path);
3758 } else if (streq(verb, "disable")) {
3761 if ((r = mark_symlink_for_removal(old_path)) < 0)
3764 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3765 if (errno == ENOENT)
3768 if (errno == EINVAL) {
3769 log_warning("File %s not a symlink, ignoring.", old_path);
3773 log_error("readlink() failed: %s", strerror(-r));
3777 if (!streq(dest, old_path)) {
3778 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3785 if ((r = mark_symlink_for_removal(new_path)) < 0)
3789 log_info("rm '%s'", new_path);
3791 if (unlink(new_path) >= 0)
3794 log_error("Cannot unlink %s: %m", new_path);
3797 } else if (streq(verb, "is-enabled")) {
3800 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3802 if (errno == ENOENT || errno == EINVAL)
3805 log_error("readlink() failed: %s", strerror(-r));
3809 if (streq(dest, old_path)) {
3817 assert_not_reached("Unknown action.");
3820 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3822 char *alias_path = NULL;
3827 assert(config_path);
3829 STRV_FOREACH(s, i->aliases) {
3832 if (!(alias_path = path_make_absolute(*s, config_path))) {
3833 log_error("Out of memory");
3838 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3841 if (streq(verb, "disable"))
3842 rmdir_parents(alias_path, config_path);
3852 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3854 char *alias_path = NULL;
3859 assert(config_path);
3861 STRV_FOREACH(s, i->wanted_by) {
3862 if (!unit_name_is_valid_no_type(*s, true)) {
3863 log_error("Invalid name %s.", *s);
3871 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3872 log_error("Out of memory");
3877 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3880 if (streq(verb, "disable"))
3881 rmdir_parents(alias_path, config_path);
3892 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3894 const ConfigItem items[] = {
3895 { "Alias", config_parse_strv, &i->aliases, "Install" },
3896 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3897 { "Also", config_parse_also, NULL, "Install" },
3899 { NULL, NULL, NULL, NULL }
3903 char *filename = NULL;
3910 STRV_FOREACH(p, paths->unit_path) {
3913 if (!(filename = path_make_absolute(i->name, *p))) {
3914 log_error("Out of memory");
3918 /* Ensure that we don't follow symlinks */
3919 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3920 if ((f = fdopen(fd, "re")))
3923 if (errno == ELOOP) {
3924 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3929 if (errno != ENOENT) {
3930 log_error("Failed to open %s: %m", filename);
3940 #if defined(TARGET_FEDORA) && defined (HAVE_SYSV_COMPAT)
3942 if (endswith(i->name, ".service")) {
3946 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
3947 log_error("Out of memory");
3951 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
3952 exists = access(sysv, F_OK) >= 0;
3958 const char *argv[] = {
3965 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
3967 argv[1] = file_name_from_path(sysv);
3969 streq(verb, "enable") ? "on" :
3970 streq(verb, "disable") ? "off" : NULL;
3972 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
3974 if ((pid = fork()) < 0) {
3975 log_error("Failed to fork: %m");
3978 } else if (pid == 0) {
3979 execv(argv[0], (char**) argv);
3980 _exit(EXIT_FAILURE);
3985 if ((r = wait_for_terminate(pid, &status)) < 0)
3988 if (status.si_code == CLD_EXITED) {
3989 if (status.si_status == 0 && (streq(verb, "enable") || streq(verb, "disable")))
3992 return status.si_status == 0 ? 0 : -EINVAL;
4002 log_error("Couldn't find %s.", i->name);
4008 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4013 n_symlinks += strv_length(i->aliases);
4014 n_symlinks += strv_length(i->wanted_by);
4018 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4021 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4024 if ((r = mark_symlink_for_removal(filename)) < 0)
4027 if ((r = remove_marked_symlinks(config_path)) < 0)
4033 static char *get_config_path(void) {
4035 if (arg_user && arg_global)
4036 return strdup(USER_CONFIG_UNIT_PATH);
4041 if (user_config_home(&p) < 0)
4047 return strdup(SYSTEM_CONFIG_UNIT_PATH);
4050 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4054 char *config_path = NULL;
4057 const char *verb = args[0];
4059 dbus_error_init(&error);
4062 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4063 log_error("Failed to determine lookup paths: %s", strerror(-r));
4067 if (!(config_path = get_config_path())) {
4068 log_error("Failed to determine config path");
4073 will_install = hashmap_new(string_hash_func, string_compare_func);
4074 have_installed = hashmap_new(string_hash_func, string_compare_func);
4076 if (!will_install || !have_installed) {
4077 log_error("Failed to allocate unit sets.");
4082 if (!arg_defaults && streq(verb, "disable"))
4083 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4084 log_error("Failed to allocate symlink sets.");
4089 for (j = 1; j < n; j++)
4090 if ((r = install_info_add(args[j])) < 0) {
4091 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4095 while ((i = hashmap_first(will_install))) {
4098 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4100 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4108 /* In test mode and found something */
4114 if (streq(verb, "is-enabled"))
4115 r = r > 0 ? 0 : -ENOENT;
4117 if (n_symlinks <= 0)
4118 log_warning("Unit files contain no applicable installation information. Ignoring.");
4121 /* Don't try to reload anything if the user asked us to not do this */
4123 /* Don't try to reload anything when updating a unit globally */
4125 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4126 (arg_user || sd_booted() > 0) &&
4127 /* Don't try to reload anything if we are running in a chroot environment */
4128 (arg_user || running_in_chroot() <= 0) ) {
4131 if ((q = daemon_reload(bus, args, n)) < 0)
4137 install_info_hashmap_free(will_install);
4138 install_info_hashmap_free(have_installed);
4140 set_free_free(remove_symlinks_to);
4142 lookup_paths_free(&paths);
4149 static int systemctl_help(void) {
4151 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4152 "Send control commands to or query the systemd manager.\n\n"
4153 " -h --help Show this help\n"
4154 " --version Show package version\n"
4155 " -t --type=TYPE List only units of a particular type\n"
4156 " -p --property=NAME Show only properties by this name\n"
4157 " -a --all Show all units/properties, including dead/empty ones\n"
4158 " --full Don't ellipsize unit names on output\n"
4159 " --fail When queueing a new job, fail if conflicting jobs are\n"
4161 " -q --quiet Suppress output\n"
4162 " --no-block Do not wait until operation finished\n"
4163 " --no-pager Do not pipe output into a pager.\n"
4164 " --system Connect to system manager\n"
4165 " --user Connect to user service manager\n"
4166 " --order When generating graph for dot, show only order\n"
4167 " --require When generating graph for dot, show only requirement\n"
4168 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4169 " --global Enable/disable unit files globally\n"
4170 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4172 " --no-ask-password\n"
4173 " Do not ask for system passwords\n"
4174 " --kill-mode=MODE How to send signal\n"
4175 " --kill-who=WHO Who to send signal to\n"
4176 " -s --signal=SIGNAL Which signal to send\n"
4177 " -f --force When enabling unit files, override existing symlinks\n"
4178 " When shutting down, execute action immediately\n"
4179 " --defaults When disabling unit files, remove default symlinks only\n\n"
4181 " list-units List units\n"
4182 " start [NAME...] Start (activate) one or more units\n"
4183 " stop [NAME...] Stop (deactivate) one or more units\n"
4184 " reload [NAME...] Reload one or more units\n"
4185 " restart [NAME...] Start or restart one or more units\n"
4186 " try-restart [NAME...] Restart one or more units if active\n"
4187 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4188 " otherwise start or restart\n"
4189 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4190 " otherwise restart if active\n"
4191 " isolate [NAME] Start one unit and stop all others\n"
4192 " kill [NAME...] Send signal to processes of a unit\n"
4193 " is-active [NAME...] Check whether units are active\n"
4194 " status [NAME...|PID...] Show runtime status of one or more units\n"
4195 " show [NAME...|JOB...] Show properties of one or more\n"
4196 " units/jobs or the manager\n"
4197 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4199 " enable [NAME...] Enable one or more unit files\n"
4200 " disable [NAME...] Disable one or more unit files\n"
4201 " is-enabled [NAME...] Check whether unit files are enabled\n"
4202 " load [NAME...] Load one or more units\n"
4203 " list-jobs List jobs\n"
4204 " cancel [JOB...] Cancel all, one, or more jobs\n"
4205 " monitor Monitor unit/job changes\n"
4206 " dump Dump server status\n"
4207 " dot Dump dependency graph for dot(1)\n"
4208 " snapshot [NAME] Create a snapshot\n"
4209 " delete [NAME...] Remove one or more snapshots\n"
4210 " daemon-reload Reload systemd manager configuration\n"
4211 " daemon-reexec Reexecute systemd manager\n"
4212 " show-environment Dump environment\n"
4213 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4214 " unset-environment [NAME...] Unset one or more environment variables\n"
4215 " default Enter system default mode\n"
4216 " rescue Enter system rescue mode\n"
4217 " emergency Enter system emergency mode\n"
4218 " halt Shut down and halt the system\n"
4219 " poweroff Shut down and power-off the system\n"
4220 " reboot Shut down and reboot the system\n"
4221 " kexec Shut down and reboot the system with kexec\n"
4222 " exit Ask for user instance termination\n",
4223 program_invocation_short_name);
4228 static int halt_help(void) {
4230 printf("%s [OPTIONS...]\n\n"
4231 "%s the system.\n\n"
4232 " --help Show this help\n"
4233 " --halt Halt the machine\n"
4234 " -p --poweroff Switch off the machine\n"
4235 " --reboot Reboot the machine\n"
4236 " -f --force Force immediate halt/power-off/reboot\n"
4237 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4238 " -d --no-wtmp Don't write wtmp record\n"
4239 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4240 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4241 program_invocation_short_name,
4242 arg_action == ACTION_REBOOT ? "Reboot" :
4243 arg_action == ACTION_POWEROFF ? "Power off" :
4249 static int shutdown_help(void) {
4251 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4252 "Shut down the system.\n\n"
4253 " --help Show this help\n"
4254 " -H --halt Halt the machine\n"
4255 " -P --poweroff Power-off the machine\n"
4256 " -r --reboot Reboot the machine\n"
4257 " -h Equivalent to --poweroff, overriden by --halt\n"
4258 " -k Don't halt/power-off/reboot, just send warnings\n"
4259 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4260 " -c Cancel a pending shutdown\n",
4261 program_invocation_short_name);
4266 static int telinit_help(void) {
4268 printf("%s [OPTIONS...] {COMMAND}\n\n"
4269 "Send control commands to the init daemon.\n\n"
4270 " --help Show this help\n"
4271 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4273 " 0 Power-off the machine\n"
4274 " 6 Reboot the machine\n"
4275 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4276 " 1, s, S Enter rescue mode\n"
4277 " q, Q Reload init daemon configuration\n"
4278 " u, U Reexecute init daemon\n",
4279 program_invocation_short_name);
4284 static int runlevel_help(void) {
4286 printf("%s [OPTIONS...]\n\n"
4287 "Prints the previous and current runlevel of the init system.\n\n"
4288 " --help Show this help\n",
4289 program_invocation_short_name);
4294 static int systemctl_parse_argv(int argc, char *argv[]) {
4315 static const struct option options[] = {
4316 { "help", no_argument, NULL, 'h' },
4317 { "version", no_argument, NULL, ARG_VERSION },
4318 { "type", required_argument, NULL, 't' },
4319 { "property", required_argument, NULL, 'p' },
4320 { "all", no_argument, NULL, 'a' },
4321 { "full", no_argument, NULL, ARG_FULL },
4322 { "fail", no_argument, NULL, ARG_FAIL },
4323 { "user", no_argument, NULL, ARG_USER },
4324 { "system", no_argument, NULL, ARG_SYSTEM },
4325 { "global", no_argument, NULL, ARG_GLOBAL },
4326 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4327 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4328 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4329 { "quiet", no_argument, NULL, 'q' },
4330 { "order", no_argument, NULL, ARG_ORDER },
4331 { "require", no_argument, NULL, ARG_REQUIRE },
4332 { "force", no_argument, NULL, 'f' },
4333 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4334 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4335 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4336 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4337 { "signal", required_argument, NULL, 's' },
4338 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4339 { NULL, 0, NULL, 0 }
4347 /* Only when running as systemctl we ask for passwords */
4348 arg_ask_password = true;
4350 while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4359 puts(PACKAGE_STRING);
4361 puts(SYSTEMD_FEATURES);
4371 if (!(l = strv_append(arg_property, optarg)))
4374 strv_free(arg_property);
4377 /* If the user asked for a particular
4378 * property, show it to him, even if it is
4401 arg_no_block = true;
4405 arg_no_pager = true;
4413 arg_dot = DOT_ORDER;
4417 arg_dot = DOT_REQUIRE;
4433 arg_no_reload = true;
4442 arg_defaults = true;
4446 arg_kill_who = optarg;
4450 arg_kill_mode = optarg;
4454 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4455 log_error("Failed to parse signal string %s.", optarg);
4460 case ARG_NO_ASK_PASSWORD:
4461 arg_ask_password = false;
4468 log_error("Unknown option code %c", c);
4476 static int halt_parse_argv(int argc, char *argv[]) {
4485 static const struct option options[] = {
4486 { "help", no_argument, NULL, ARG_HELP },
4487 { "halt", no_argument, NULL, ARG_HALT },
4488 { "poweroff", no_argument, NULL, 'p' },
4489 { "reboot", no_argument, NULL, ARG_REBOOT },
4490 { "force", no_argument, NULL, 'f' },
4491 { "wtmp-only", no_argument, NULL, 'w' },
4492 { "no-wtmp", no_argument, NULL, 'd' },
4493 { "no-sync", no_argument, NULL, 'n' },
4494 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4495 { NULL, 0, NULL, 0 }
4503 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4504 if (runlevel == '0' || runlevel == '6')
4505 arg_immediate = true;
4507 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4515 arg_action = ACTION_HALT;
4519 if (arg_action != ACTION_REBOOT)
4520 arg_action = ACTION_POWEROFF;
4524 arg_action = ACTION_REBOOT;
4528 arg_immediate = true;
4549 /* Compatibility nops */
4556 log_error("Unknown option code %c", c);
4561 if (optind < argc) {
4562 log_error("Too many arguments.");
4569 static int parse_time_spec(const char *t, usec_t *_u) {
4573 if (streq(t, "now"))
4575 else if (t[0] == '+') {
4578 if (safe_atou64(t + 1, &u) < 0)
4581 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4590 hour = strtol(t, &e, 10);
4591 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4594 minute = strtol(e+1, &e, 10);
4595 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4598 n = now(CLOCK_REALTIME);
4599 s = (time_t) (n / USEC_PER_SEC);
4602 assert_se(localtime_r(&s, &tm));
4604 tm.tm_hour = (int) hour;
4605 tm.tm_min = (int) minute;
4608 assert_se(s = mktime(&tm));
4610 *_u = (usec_t) s * USEC_PER_SEC;
4613 *_u += USEC_PER_DAY;
4619 static int shutdown_parse_argv(int argc, char *argv[]) {
4626 static const struct option options[] = {
4627 { "help", no_argument, NULL, ARG_HELP },
4628 { "halt", no_argument, NULL, 'H' },
4629 { "poweroff", no_argument, NULL, 'P' },
4630 { "reboot", no_argument, NULL, 'r' },
4631 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4632 { NULL, 0, NULL, 0 }
4640 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4648 arg_action = ACTION_HALT;
4652 arg_action = ACTION_POWEROFF;
4656 arg_action = ACTION_REBOOT;
4660 if (arg_action != ACTION_HALT)
4661 arg_action = ACTION_POWEROFF;
4674 /* Compatibility nops */
4678 arg_action = ACTION_CANCEL_SHUTDOWN;
4685 log_error("Unknown option code %c", c);
4690 if (argc > optind) {
4691 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4692 log_error("Failed to parse time specification: %s", argv[optind]);
4696 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4698 /* We skip the time argument */
4699 if (argc > optind + 1)
4700 arg_wall = argv + optind + 1;
4707 static int telinit_parse_argv(int argc, char *argv[]) {
4714 static const struct option options[] = {
4715 { "help", no_argument, NULL, ARG_HELP },
4716 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4717 { NULL, 0, NULL, 0 }
4720 static const struct {
4724 { '0', ACTION_POWEROFF },
4725 { '6', ACTION_REBOOT },
4726 { '1', ACTION_RESCUE },
4727 { '2', ACTION_RUNLEVEL2 },
4728 { '3', ACTION_RUNLEVEL3 },
4729 { '4', ACTION_RUNLEVEL4 },
4730 { '5', ACTION_RUNLEVEL5 },
4731 { 's', ACTION_RESCUE },
4732 { 'S', ACTION_RESCUE },
4733 { 'q', ACTION_RELOAD },
4734 { 'Q', ACTION_RELOAD },
4735 { 'u', ACTION_REEXEC },
4736 { 'U', ACTION_REEXEC }
4745 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4760 log_error("Unknown option code %c", c);
4765 if (optind >= argc) {
4770 if (optind + 1 < argc) {
4771 log_error("Too many arguments.");
4775 if (strlen(argv[optind]) != 1) {
4776 log_error("Expected single character argument.");
4780 for (i = 0; i < ELEMENTSOF(table); i++)
4781 if (table[i].from == argv[optind][0])
4784 if (i >= ELEMENTSOF(table)) {
4785 log_error("Unknown command %s.", argv[optind]);
4789 arg_action = table[i].to;
4796 static int runlevel_parse_argv(int argc, char *argv[]) {
4802 static const struct option options[] = {
4803 { "help", no_argument, NULL, ARG_HELP },
4804 { NULL, 0, NULL, 0 }
4812 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4823 log_error("Unknown option code %c", c);
4828 if (optind < argc) {
4829 log_error("Too many arguments.");
4836 static int parse_argv(int argc, char *argv[]) {
4840 if (program_invocation_short_name) {
4842 if (strstr(program_invocation_short_name, "halt")) {
4843 arg_action = ACTION_HALT;
4844 return halt_parse_argv(argc, argv);
4845 } else if (strstr(program_invocation_short_name, "poweroff")) {
4846 arg_action = ACTION_POWEROFF;
4847 return halt_parse_argv(argc, argv);
4848 } else if (strstr(program_invocation_short_name, "reboot")) {
4849 arg_action = ACTION_REBOOT;
4850 return halt_parse_argv(argc, argv);
4851 } else if (strstr(program_invocation_short_name, "shutdown")) {
4852 arg_action = ACTION_POWEROFF;
4853 return shutdown_parse_argv(argc, argv);
4854 } else if (strstr(program_invocation_short_name, "init")) {
4856 if (sd_booted() > 0) {
4857 arg_action = ACTION_INVALID;
4858 return telinit_parse_argv(argc, argv);
4860 /* Hmm, so some other init system is
4861 * running, we need to forward this
4862 * request to it. For now we simply
4863 * guess that it is Upstart. */
4865 execv("/lib/upstart/telinit", argv);
4867 log_error("Couldn't find an alternative telinit implementation to spawn.");
4871 } else if (strstr(program_invocation_short_name, "runlevel")) {
4872 arg_action = ACTION_RUNLEVEL;
4873 return runlevel_parse_argv(argc, argv);
4877 arg_action = ACTION_SYSTEMCTL;
4878 return systemctl_parse_argv(argc, argv);
4881 static int action_to_runlevel(void) {
4883 static const char table[_ACTION_MAX] = {
4884 [ACTION_HALT] = '0',
4885 [ACTION_POWEROFF] = '0',
4886 [ACTION_REBOOT] = '6',
4887 [ACTION_RUNLEVEL2] = '2',
4888 [ACTION_RUNLEVEL3] = '3',
4889 [ACTION_RUNLEVEL4] = '4',
4890 [ACTION_RUNLEVEL5] = '5',
4891 [ACTION_RESCUE] = '1'
4894 assert(arg_action < _ACTION_MAX);
4896 return table[arg_action];
4899 static int talk_upstart(void) {
4900 DBusMessage *m = NULL, *reply = NULL;
4902 int previous, rl, r;
4904 env1_buf[] = "RUNLEVEL=X",
4905 env2_buf[] = "PREVLEVEL=X";
4906 char *env1 = env1_buf, *env2 = env2_buf;
4907 const char *emit = "runlevel";
4908 dbus_bool_t b_false = FALSE;
4909 DBusMessageIter iter, sub;
4910 DBusConnection *bus;
4912 dbus_error_init(&error);
4914 if (!(rl = action_to_runlevel()))
4917 if (utmp_get_runlevel(&previous, NULL) < 0)
4920 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4921 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4926 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4931 if ((r = bus_check_peercred(bus)) < 0) {
4932 log_error("Failed to verify owner of bus.");
4936 if (!(m = dbus_message_new_method_call(
4937 "com.ubuntu.Upstart",
4938 "/com/ubuntu/Upstart",
4939 "com.ubuntu.Upstart0_6",
4942 log_error("Could not allocate message.");
4947 dbus_message_iter_init_append(m, &iter);
4949 env1_buf[sizeof(env1_buf)-2] = rl;
4950 env2_buf[sizeof(env2_buf)-2] = previous;
4952 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4953 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4954 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4955 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4956 !dbus_message_iter_close_container(&iter, &sub) ||
4957 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4958 log_error("Could not append arguments to message.");
4963 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4965 if (error_is_no_service(&error)) {
4970 log_error("Failed to issue method call: %s", bus_error_message(&error));
4979 dbus_message_unref(m);
4982 dbus_message_unref(reply);
4985 dbus_connection_flush(bus);
4986 dbus_connection_close(bus);
4987 dbus_connection_unref(bus);
4990 dbus_error_free(&error);
4995 static int talk_initctl(void) {
4996 struct init_request request;
5000 if (!(rl = action_to_runlevel()))
5004 request.magic = INIT_MAGIC;
5005 request.sleeptime = 0;
5006 request.cmd = INIT_CMD_RUNLVL;
5007 request.runlevel = rl;
5009 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5011 if (errno == ENOENT)
5014 log_error("Failed to open "INIT_FIFO": %m");
5019 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5020 close_nointr_nofail(fd);
5023 log_error("Failed to write to "INIT_FIFO": %m");
5024 return errno ? -errno : -EIO;
5030 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5032 static const struct {
5040 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5042 { "list-units", LESS, 1, list_units },
5043 { "list-jobs", EQUAL, 1, list_jobs },
5044 { "clear-jobs", EQUAL, 1, daemon_reload },
5045 { "load", MORE, 2, load_unit },
5046 { "cancel", MORE, 2, cancel_job },
5047 { "start", MORE, 2, start_unit },
5048 { "stop", MORE, 2, start_unit },
5049 { "reload", MORE, 2, start_unit },
5050 { "restart", MORE, 2, start_unit },
5051 { "try-restart", MORE, 2, start_unit },
5052 { "reload-or-restart", MORE, 2, start_unit },
5053 { "reload-or-try-restart", MORE, 2, start_unit },
5054 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5055 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5056 { "isolate", EQUAL, 2, start_unit },
5057 { "kill", MORE, 2, kill_unit },
5058 { "is-active", MORE, 2, check_unit },
5059 { "check", MORE, 2, check_unit },
5060 { "show", MORE, 1, show },
5061 { "status", MORE, 2, show },
5062 { "monitor", EQUAL, 1, monitor },
5063 { "dump", EQUAL, 1, dump },
5064 { "dot", EQUAL, 1, dot },
5065 { "snapshot", LESS, 2, snapshot },
5066 { "delete", MORE, 2, delete_snapshot },
5067 { "daemon-reload", EQUAL, 1, daemon_reload },
5068 { "daemon-reexec", EQUAL, 1, daemon_reload },
5069 { "show-environment", EQUAL, 1, show_enviroment },
5070 { "set-environment", MORE, 2, set_environment },
5071 { "unset-environment", MORE, 2, set_environment },
5072 { "halt", EQUAL, 1, start_special },
5073 { "poweroff", EQUAL, 1, start_special },
5074 { "reboot", EQUAL, 1, start_special },
5075 { "kexec", EQUAL, 1, start_special },
5076 { "default", EQUAL, 1, start_special },
5077 { "rescue", EQUAL, 1, start_special },
5078 { "emergency", EQUAL, 1, start_special },
5079 { "exit", EQUAL, 1, start_special },
5080 { "reset-failed", MORE, 1, reset_failed },
5081 { "enable", MORE, 2, enable_unit },
5082 { "disable", MORE, 2, enable_unit },
5083 { "is-enabled", MORE, 2, enable_unit }
5093 left = argc - optind;
5096 /* Special rule: no arguments means "list-units" */
5099 if (streq(argv[optind], "help")) {
5104 for (i = 0; i < ELEMENTSOF(verbs); i++)
5105 if (streq(argv[optind], verbs[i].verb))
5108 if (i >= ELEMENTSOF(verbs)) {
5109 log_error("Unknown operation %s", argv[optind]);
5114 switch (verbs[i].argc_cmp) {
5117 if (left != verbs[i].argc) {
5118 log_error("Invalid number of arguments.");
5125 if (left < verbs[i].argc) {
5126 log_error("Too few arguments.");
5133 if (left > verbs[i].argc) {
5134 log_error("Too many arguments.");
5141 assert_not_reached("Unknown comparison operator.");
5144 /* Require a bus connection for all operations but
5146 if (!streq(verbs[i].verb, "enable") &&
5147 !streq(verbs[i].verb, "disable") &&
5149 log_error("Failed to get D-Bus connection: %s", error->message);
5153 return verbs[i].dispatch(bus, argv + optind, left);
5156 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5158 struct msghdr msghdr;
5160 union sockaddr_union sockaddr;
5161 struct shutdownd_command c;
5169 strncpy(c.wall_message, message, sizeof(c.wall_message));
5171 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5175 sockaddr.sa.sa_family = AF_UNIX;
5176 sockaddr.un.sun_path[0] = 0;
5177 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5180 iovec.iov_base = (char*) &c;
5181 iovec.iov_len = sizeof(c);
5184 msghdr.msg_name = &sockaddr;
5185 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5187 msghdr.msg_iov = &iovec;
5188 msghdr.msg_iovlen = 1;
5190 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5191 close_nointr_nofail(fd);
5195 close_nointr_nofail(fd);
5199 static int reload_with_fallback(DBusConnection *bus) {
5202 /* First, try systemd via D-Bus. */
5203 if (daemon_reload(bus, NULL, 0) > 0)
5207 /* Nothing else worked, so let's try signals */
5208 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5210 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5211 log_error("kill() failed: %m");
5218 static int start_with_fallback(DBusConnection *bus) {
5221 /* First, try systemd via D-Bus. */
5222 if (start_unit(bus, NULL, 0) >= 0)
5226 /* Hmm, talking to systemd via D-Bus didn't work. Then
5227 * let's try to talk to Upstart via D-Bus. */
5228 if (talk_upstart() > 0)
5231 /* Nothing else worked, so let's try
5233 if (talk_initctl() > 0)
5236 log_error("Failed to talk to init daemon.");
5240 warn_wall(arg_action);
5244 static int halt_main(DBusConnection *bus) {
5247 if (geteuid() != 0) {
5248 log_error("Must be root.");
5254 char date[FORMAT_TIMESTAMP_MAX];
5256 m = strv_join(arg_wall, " ");
5257 r = send_shutdownd(arg_when,
5258 arg_action == ACTION_HALT ? 'H' :
5259 arg_action == ACTION_POWEROFF ? 'P' :
5266 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5268 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5269 format_timestamp(date, sizeof(date), arg_when));
5274 if (!arg_dry && !arg_immediate)
5275 return start_with_fallback(bus);
5278 if (sd_booted() > 0)
5279 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5280 else if ((r = utmp_put_shutdown(0)) < 0)
5281 log_warning("Failed to write utmp record: %s", strerror(-r));
5290 /* Make sure C-A-D is handled by the kernel from this
5292 reboot(RB_ENABLE_CAD);
5294 switch (arg_action) {
5297 log_info("Halting.");
5298 reboot(RB_HALT_SYSTEM);
5301 case ACTION_POWEROFF:
5302 log_info("Powering off.");
5303 reboot(RB_POWER_OFF);
5307 log_info("Rebooting.");
5308 reboot(RB_AUTOBOOT);
5312 assert_not_reached("Unknown halt action.");
5315 /* We should never reach this. */
5319 static int runlevel_main(void) {
5320 int r, runlevel, previous;
5322 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5323 printf("unknown\n");
5328 previous <= 0 ? 'N' : previous,
5329 runlevel <= 0 ? 'N' : runlevel);
5334 static void pager_open(void) {
5341 if (!on_tty() || arg_no_pager)
5344 if ((pager = getenv("PAGER")))
5345 if (!*pager || streq(pager, "cat"))
5348 /* Determine and cache number of columns before we spawn the
5349 * pager so that we get the value from the actual tty */
5353 log_error("Failed to create pager pipe: %m");
5358 if (pager_pid < 0) {
5359 log_error("Failed to fork pager: %m");
5364 /* In the child start the pager */
5365 if (pager_pid == 0) {
5367 dup2(fd[0], STDIN_FILENO);
5370 setenv("LESS", "FRSX", 0);
5372 prctl(PR_SET_PDEATHSIG, SIGTERM);
5375 execlp(pager, pager, NULL);
5376 execl("/bin/sh", "sh", "-c", pager, NULL);
5378 /* Debian's alternatives command for pagers is
5379 * called 'pager'. Note that we do not call
5380 * sensible-pagers here, since that is just a
5381 * shell script that implements a logic that
5382 * is similar to this one anyway, but is
5383 * Debian-specific. */
5384 execlp("pager", "pager", NULL);
5386 execlp("less", "less", NULL);
5387 execlp("more", "more", NULL);
5390 log_error("Unable to execute pager: %m");
5391 _exit(EXIT_FAILURE);
5394 /* Return in the parent */
5395 if (dup2(fd[1], STDOUT_FILENO) < 0)
5396 log_error("Failed to duplicate pager pipe: %m");
5401 static void pager_close(void) {
5407 /* Inform pager that we are done */
5409 wait_for_terminate(pager_pid, &dummy);
5413 int main(int argc, char*argv[]) {
5414 int r, retval = EXIT_FAILURE;
5415 DBusConnection *bus = NULL;
5418 dbus_error_init(&error);
5420 log_parse_environment();
5423 if ((r = parse_argv(argc, argv)) < 0)
5426 retval = EXIT_SUCCESS;
5430 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5431 * let's shortcut this */
5432 if (arg_action == ACTION_RUNLEVEL) {
5433 r = runlevel_main();
5434 retval = r < 0 ? EXIT_FAILURE : r;
5438 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5440 switch (arg_action) {
5442 case ACTION_SYSTEMCTL:
5443 r = systemctl_main(bus, argc, argv, &error);
5447 case ACTION_POWEROFF:
5452 case ACTION_RUNLEVEL2:
5453 case ACTION_RUNLEVEL3:
5454 case ACTION_RUNLEVEL4:
5455 case ACTION_RUNLEVEL5:
5457 case ACTION_EMERGENCY:
5458 case ACTION_DEFAULT:
5459 r = start_with_fallback(bus);
5464 r = reload_with_fallback(bus);
5467 case ACTION_CANCEL_SHUTDOWN:
5468 r = send_shutdownd(0, 0, false, NULL);
5471 case ACTION_INVALID:
5472 case ACTION_RUNLEVEL:
5474 assert_not_reached("Unknown action");
5477 retval = r < 0 ? EXIT_FAILURE : r;
5482 dbus_connection_flush(bus);
5483 dbus_connection_close(bus);
5484 dbus_connection_unref(bus);
5487 dbus_error_free(&error);
5491 strv_free(arg_property);