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)
149 /* Spawns a temporary TTY agent, making sure it goes away when
152 if ((child = fork()) < 0)
157 const char * const args[] = {
158 SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH,
165 /* Make sure the agent goes away when the parent dies */
166 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
169 /* Check whether our parent died before we were able
170 * to set the death signal */
171 if (getppid() != parent)
174 /* Don't leak fds to the agent */
175 close_all_fds(NULL, 0);
177 /* Detach from stdin/stdout/stderr. and reopen
178 * /dev/tty for them. This is important to ensure that
179 * when systemctl is started via popen() or a similar
180 * call that expects to read EOF we actually do
181 * generate EOF and not delay this indefinitely by
182 * because we keep an unused copy of stdin around. */
183 if ((fd = open("/dev/tty", O_RDWR)) < 0) {
184 log_error("Failed to open /dev/tty: %m");
189 close(STDOUT_FILENO);
190 close(STDERR_FILENO);
192 dup2(fd, STDIN_FILENO);
193 dup2(fd, STDOUT_FILENO);
194 dup2(fd, STDERR_FILENO);
199 execv(args[0], (char **) args);
204 static const char *ansi_highlight(bool b) {
209 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
212 static const char *ansi_highlight_green(bool b) {
217 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
220 static bool error_is_no_service(const DBusError *error) {
223 if (!dbus_error_is_set(error))
226 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
229 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
232 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
235 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
238 if (!dbus_error_is_set(error))
241 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
242 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
243 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
244 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
245 return EXIT_NOPERMISSION;
247 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
248 return EXIT_NOTINSTALLED;
250 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
251 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
252 return EXIT_NOTIMPLEMENTED;
254 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
255 return EXIT_NOTCONFIGURED;
263 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
268 if (dbus_message_iter_get_arg_type(iter) != type)
271 dbus_message_iter_get_basic(iter, data);
273 if (!dbus_message_iter_next(iter) != !next)
279 static void warn_wall(enum action action) {
280 static const char *table[_ACTION_MAX] = {
281 [ACTION_HALT] = "The system is going down for system halt NOW!",
282 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
283 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
284 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
285 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
286 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
295 if (!(p = strv_join(arg_wall, " "))) {
296 log_error("Failed to join strings.");
312 utmp_wall(table[action], NULL);
317 const char *description;
318 const char *load_state;
319 const char *active_state;
320 const char *sub_state;
321 const char *following;
322 const char *unit_path;
324 const char *job_type;
325 const char *job_path;
328 static int compare_unit_info(const void *a, const void *b) {
330 const struct unit_info *u = a, *v = b;
332 d1 = strrchr(u->id, '.');
333 d2 = strrchr(v->id, '.');
338 if ((r = strcasecmp(d1, d2)) != 0)
342 return strcasecmp(u->id, v->id);
345 static bool output_show_job(const struct unit_info *u) {
348 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
349 streq(dot+1, arg_type))) &&
350 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
353 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
354 unsigned active_len, sub_len, job_len, n_shown = 0;
355 const struct unit_info *u;
357 active_len = sizeof("ACTIVE")-1;
358 sub_len = sizeof("SUB")-1;
359 job_len = sizeof("JOB")-1;
361 for (u = unit_infos; u < unit_infos + c; u++) {
362 if (!output_show_job(u))
365 active_len = MAX(active_len, strlen(u->active_state));
366 sub_len = MAX(sub_len, strlen(u->sub_state));
368 job_len = MAX(job_len, strlen(u->job_type));
372 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
373 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
374 if (columns() >= 80+12 || arg_full)
375 printf(" %s\n", "DESCRIPTION");
380 for (u = unit_infos; u < unit_infos + c; u++) {
383 const char *on_loaded, *off_loaded;
384 const char *on_active, *off_active;
386 if (!output_show_job(u))
391 if (!streq(u->load_state, "loaded") &&
392 !streq(u->load_state, "banned")) {
393 on_loaded = ansi_highlight(true);
394 off_loaded = ansi_highlight(false);
396 on_loaded = off_loaded = "";
398 if (streq(u->active_state, "failed")) {
399 on_active = ansi_highlight(true);
400 off_active = ansi_highlight(false);
402 on_active = off_active = "";
404 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
406 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
408 on_loaded, u->load_state, off_loaded,
409 on_active, active_len, u->active_state,
410 sub_len, u->sub_state, off_active,
415 a -= strlen(on_loaded) + strlen(off_loaded);
416 a -= strlen(on_active) + strlen(off_active);
419 printf(" %-*s", job_len, u->job_type);
423 if (a + b + 1 < columns()) {
425 printf(" %-*s", job_len, "");
428 printf(" %s", u->description);
430 printf(" %.*s", columns() - a - b - 1, u->description);
437 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
438 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
439 "SUB = The low-level unit activation state, values depend on unit type.\n"
440 "JOB = Pending job for the unit.\n");
443 printf("\n%u units listed.\n", n_shown);
445 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
449 static int list_units(DBusConnection *bus, char **args, unsigned n) {
450 DBusMessage *m = NULL, *reply = NULL;
453 DBusMessageIter iter, sub, sub2;
454 unsigned c = 0, n_units = 0;
455 struct unit_info *unit_infos = NULL;
457 dbus_error_init(&error);
463 if (!(m = dbus_message_new_method_call(
464 "org.freedesktop.systemd1",
465 "/org/freedesktop/systemd1",
466 "org.freedesktop.systemd1.Manager",
468 log_error("Could not allocate message.");
472 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
473 log_error("Failed to issue method call: %s", bus_error_message(&error));
478 if (!dbus_message_iter_init(reply, &iter) ||
479 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
480 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
481 log_error("Failed to parse reply.");
486 dbus_message_iter_recurse(&iter, &sub);
488 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
491 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
492 log_error("Failed to parse reply.");
500 n_units = MAX(2*c, 16);
501 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
504 log_error("Failed to allocate unit array.");
514 dbus_message_iter_recurse(&sub, &sub2);
516 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
517 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
518 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
519 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
520 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
521 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
522 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
523 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
524 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
525 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
526 log_error("Failed to parse reply.");
531 dbus_message_iter_next(&sub);
536 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
537 output_units_list(unit_infos, c);
544 dbus_message_unref(m);
547 dbus_message_unref(reply);
551 dbus_error_free(&error);
556 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
557 static const char * const colors[] = {
558 "Requires", "[color=\"black\"]",
559 "RequiresOverridable", "[color=\"black\"]",
560 "Requisite", "[color=\"darkblue\"]",
561 "RequisiteOverridable", "[color=\"darkblue\"]",
562 "Wants", "[color=\"darkgrey\"]",
563 "Conflicts", "[color=\"red\"]",
564 "ConflictedBy", "[color=\"red\"]",
565 "After", "[color=\"green\"]"
568 const char *c = NULL;
575 for (i = 0; i < ELEMENTSOF(colors); i += 2)
576 if (streq(colors[i], prop)) {
584 if (arg_dot != DOT_ALL)
585 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
588 switch (dbus_message_iter_get_arg_type(iter)) {
590 case DBUS_TYPE_ARRAY:
592 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
595 dbus_message_iter_recurse(iter, &sub);
597 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
600 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
601 dbus_message_iter_get_basic(&sub, &s);
602 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
604 dbus_message_iter_next(&sub);
614 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
615 DBusMessage *m = NULL, *reply = NULL;
616 const char *interface = "org.freedesktop.systemd1.Unit";
619 DBusMessageIter iter, sub, sub2, sub3;
624 dbus_error_init(&error);
626 if (!(m = dbus_message_new_method_call(
627 "org.freedesktop.systemd1",
629 "org.freedesktop.DBus.Properties",
631 log_error("Could not allocate message.");
636 if (!dbus_message_append_args(m,
637 DBUS_TYPE_STRING, &interface,
638 DBUS_TYPE_INVALID)) {
639 log_error("Could not append arguments to message.");
644 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
645 log_error("Failed to issue method call: %s", bus_error_message(&error));
650 if (!dbus_message_iter_init(reply, &iter) ||
651 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
652 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
653 log_error("Failed to parse reply.");
658 dbus_message_iter_recurse(&iter, &sub);
660 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
663 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
664 log_error("Failed to parse reply.");
669 dbus_message_iter_recurse(&sub, &sub2);
671 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
672 log_error("Failed to parse reply.");
677 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
678 log_error("Failed to parse reply.");
683 dbus_message_iter_recurse(&sub2, &sub3);
685 if (dot_one_property(name, prop, &sub3)) {
686 log_error("Failed to parse reply.");
691 dbus_message_iter_next(&sub);
698 dbus_message_unref(m);
701 dbus_message_unref(reply);
703 dbus_error_free(&error);
708 static int dot(DBusConnection *bus, char **args, unsigned n) {
709 DBusMessage *m = NULL, *reply = NULL;
712 DBusMessageIter iter, sub, sub2;
714 dbus_error_init(&error);
718 if (!(m = dbus_message_new_method_call(
719 "org.freedesktop.systemd1",
720 "/org/freedesktop/systemd1",
721 "org.freedesktop.systemd1.Manager",
723 log_error("Could not allocate message.");
727 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
728 log_error("Failed to issue method call: %s", bus_error_message(&error));
733 if (!dbus_message_iter_init(reply, &iter) ||
734 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
735 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
736 log_error("Failed to parse reply.");
741 printf("digraph systemd {\n");
743 dbus_message_iter_recurse(&iter, &sub);
744 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
745 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
747 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
748 log_error("Failed to parse reply.");
753 dbus_message_iter_recurse(&sub, &sub2);
755 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
756 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
757 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
758 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
759 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
760 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
761 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
762 log_error("Failed to parse reply.");
767 if ((r = dot_one(bus, id, unit_path)) < 0)
770 /* printf("\t\"%s\";\n", id); */
771 dbus_message_iter_next(&sub);
776 log_info(" Color legend: black = Requires\n"
777 " dark blue = Requisite\n"
778 " dark grey = Wants\n"
782 if (isatty(fileno(stdout)))
783 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
784 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
790 dbus_message_unref(m);
793 dbus_message_unref(reply);
795 dbus_error_free(&error);
800 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
801 DBusMessage *m = NULL, *reply = NULL;
804 DBusMessageIter iter, sub, sub2;
807 dbus_error_init(&error);
813 if (!(m = dbus_message_new_method_call(
814 "org.freedesktop.systemd1",
815 "/org/freedesktop/systemd1",
816 "org.freedesktop.systemd1.Manager",
818 log_error("Could not allocate message.");
822 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
823 log_error("Failed to issue method call: %s", bus_error_message(&error));
828 if (!dbus_message_iter_init(reply, &iter) ||
829 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
830 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
831 log_error("Failed to parse reply.");
836 dbus_message_iter_recurse(&iter, &sub);
838 if (isatty(STDOUT_FILENO))
839 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
841 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
842 const char *name, *type, *state, *job_path, *unit_path;
846 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
847 log_error("Failed to parse reply.");
852 dbus_message_iter_recurse(&sub, &sub2);
854 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
855 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
856 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
857 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
858 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
859 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
860 log_error("Failed to parse reply.");
865 e = arg_full ? NULL : ellipsize(name, 25, 33);
866 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
871 dbus_message_iter_next(&sub);
874 if (isatty(STDOUT_FILENO))
875 printf("\n%u jobs listed.\n", k);
881 dbus_message_unref(m);
884 dbus_message_unref(reply);
886 dbus_error_free(&error);
891 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
892 DBusMessage *m = NULL, *reply = NULL;
897 dbus_error_init(&error);
902 for (i = 1; i < n; i++) {
904 if (!(m = dbus_message_new_method_call(
905 "org.freedesktop.systemd1",
906 "/org/freedesktop/systemd1",
907 "org.freedesktop.systemd1.Manager",
909 log_error("Could not allocate message.");
914 if (!dbus_message_append_args(m,
915 DBUS_TYPE_STRING, &args[i],
916 DBUS_TYPE_INVALID)) {
917 log_error("Could not append arguments to message.");
922 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
923 log_error("Failed to issue method call: %s", bus_error_message(&error));
928 dbus_message_unref(m);
929 dbus_message_unref(reply);
938 dbus_message_unref(m);
941 dbus_message_unref(reply);
943 dbus_error_free(&error);
948 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
949 DBusMessage *m = NULL, *reply = NULL;
954 dbus_error_init(&error);
960 return daemon_reload(bus, args, n);
962 for (i = 1; i < n; i++) {
966 if (!(m = dbus_message_new_method_call(
967 "org.freedesktop.systemd1",
968 "/org/freedesktop/systemd1",
969 "org.freedesktop.systemd1.Manager",
971 log_error("Could not allocate message.");
976 if ((r = safe_atou(args[i], &id)) < 0) {
977 log_error("Failed to parse job id: %s", strerror(-r));
981 assert_cc(sizeof(uint32_t) == sizeof(id));
982 if (!dbus_message_append_args(m,
983 DBUS_TYPE_UINT32, &id,
984 DBUS_TYPE_INVALID)) {
985 log_error("Could not append arguments to message.");
990 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
991 log_error("Failed to issue method call: %s", bus_error_message(&error));
996 if (!dbus_message_get_args(reply, &error,
997 DBUS_TYPE_OBJECT_PATH, &path,
998 DBUS_TYPE_INVALID)) {
999 log_error("Failed to parse reply: %s", bus_error_message(&error));
1004 dbus_message_unref(m);
1005 if (!(m = dbus_message_new_method_call(
1006 "org.freedesktop.systemd1",
1008 "org.freedesktop.systemd1.Job",
1010 log_error("Could not allocate message.");
1015 dbus_message_unref(reply);
1016 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1017 log_error("Failed to issue method call: %s", bus_error_message(&error));
1022 dbus_message_unref(m);
1023 dbus_message_unref(reply);
1031 dbus_message_unref(m);
1034 dbus_message_unref(reply);
1036 dbus_error_free(&error);
1041 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1042 DBusMessage *m = NULL, *reply = NULL;
1043 dbus_bool_t b = FALSE;
1044 DBusMessageIter iter, sub;
1046 *interface = "org.freedesktop.systemd1.Unit",
1047 *property = "NeedDaemonReload",
1050 /* We ignore all errors here, since this is used to show a warning only */
1052 if (!(m = dbus_message_new_method_call(
1053 "org.freedesktop.systemd1",
1054 "/org/freedesktop/systemd1",
1055 "org.freedesktop.systemd1.Manager",
1059 if (!dbus_message_append_args(m,
1060 DBUS_TYPE_STRING, &unit,
1064 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1067 if (!dbus_message_get_args(reply, NULL,
1068 DBUS_TYPE_OBJECT_PATH, &path,
1072 dbus_message_unref(m);
1073 if (!(m = dbus_message_new_method_call(
1074 "org.freedesktop.systemd1",
1076 "org.freedesktop.DBus.Properties",
1080 if (!dbus_message_append_args(m,
1081 DBUS_TYPE_STRING, &interface,
1082 DBUS_TYPE_STRING, &property,
1083 DBUS_TYPE_INVALID)) {
1087 dbus_message_unref(reply);
1088 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1091 if (!dbus_message_iter_init(reply, &iter) ||
1092 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1095 dbus_message_iter_recurse(&iter, &sub);
1097 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1100 dbus_message_iter_get_basic(&sub, &b);
1104 dbus_message_unref(m);
1107 dbus_message_unref(reply);
1112 typedef struct WaitData {
1117 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1125 dbus_error_init(&error);
1127 log_debug("Got D-Bus request: %s.%s() on %s",
1128 dbus_message_get_interface(message),
1129 dbus_message_get_member(message),
1130 dbus_message_get_path(message));
1132 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1133 log_error("Warning! D-Bus connection terminated.");
1134 dbus_connection_close(connection);
1136 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1139 dbus_bool_t success = true;
1141 if (!dbus_message_get_args(message, &error,
1142 DBUS_TYPE_UINT32, &id,
1143 DBUS_TYPE_OBJECT_PATH, &path,
1144 DBUS_TYPE_BOOLEAN, &success,
1146 log_error("Failed to parse message: %s", bus_error_message(&error));
1150 if ((p = set_remove(d->set, (char*) path)))
1158 dbus_error_free(&error);
1159 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1162 static int enable_wait_for_jobs(DBusConnection *bus) {
1170 dbus_error_init(&error);
1171 dbus_bus_add_match(bus,
1173 "sender='org.freedesktop.systemd1',"
1174 "interface='org.freedesktop.systemd1.Manager',"
1175 "member='JobRemoved',"
1176 "path='/org/freedesktop/systemd1'",
1179 if (dbus_error_is_set(&error)) {
1180 log_error("Failed to add match: %s", bus_error_message(&error));
1181 dbus_error_free(&error);
1185 /* This is slightly dirty, since we don't undo the match registrations. */
1189 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1200 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1201 log_error("Failed to add filter.");
1206 while (!set_isempty(s) &&
1207 dbus_connection_read_write_dispatch(bus, -1))
1210 if (!arg_quiet && d.failed)
1211 log_error("Job failed. See system logs and 'systemctl status' for details.");
1213 r = d.failed ? -EIO : 0;
1216 /* This is slightly dirty, since we don't undo the filter registration. */
1221 static int start_unit_one(
1222 DBusConnection *bus,
1229 DBusMessage *m = NULL, *reply = NULL;
1238 assert(arg_no_block || s);
1240 if (!(m = dbus_message_new_method_call(
1241 "org.freedesktop.systemd1",
1242 "/org/freedesktop/systemd1",
1243 "org.freedesktop.systemd1.Manager",
1245 log_error("Could not allocate message.");
1250 if (!dbus_message_append_args(m,
1251 DBUS_TYPE_STRING, &name,
1252 DBUS_TYPE_STRING, &mode,
1253 DBUS_TYPE_INVALID)) {
1254 log_error("Could not append arguments to message.");
1259 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1261 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1262 /* There's always a fallback possible for
1263 * legacy actions. */
1268 log_error("Failed to issue method call: %s", bus_error_message(error));
1273 if (!dbus_message_get_args(reply, error,
1274 DBUS_TYPE_OBJECT_PATH, &path,
1275 DBUS_TYPE_INVALID)) {
1276 log_error("Failed to parse reply: %s", bus_error_message(error));
1281 if (need_daemon_reload(bus, name))
1282 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1283 arg_user ? "--user" : "--system");
1285 if (!arg_no_block) {
1288 if (!(p = strdup(path))) {
1289 log_error("Failed to duplicate path.");
1294 if ((r = set_put(s, p)) < 0) {
1296 log_error("Failed to add path to set.");
1305 dbus_message_unref(m);
1308 dbus_message_unref(reply);
1313 static enum action verb_to_action(const char *verb) {
1314 if (streq(verb, "halt"))
1316 else if (streq(verb, "poweroff"))
1317 return ACTION_POWEROFF;
1318 else if (streq(verb, "reboot"))
1319 return ACTION_REBOOT;
1320 else if (streq(verb, "kexec"))
1321 return ACTION_KEXEC;
1322 else if (streq(verb, "rescue"))
1323 return ACTION_RESCUE;
1324 else if (streq(verb, "emergency"))
1325 return ACTION_EMERGENCY;
1326 else if (streq(verb, "default"))
1327 return ACTION_DEFAULT;
1328 else if (streq(verb, "exit"))
1331 return ACTION_INVALID;
1334 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1336 static const char * const table[_ACTION_MAX] = {
1337 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1338 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1339 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1340 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1341 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1342 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1343 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1344 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1345 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1346 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1347 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1348 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1353 const char *method, *mode, *one_name;
1357 dbus_error_init(&error);
1361 spawn_ask_password_agent();
1363 if (arg_action == ACTION_SYSTEMCTL) {
1365 streq(args[0], "stop") ? "StopUnit" :
1366 streq(args[0], "reload") ? "ReloadUnit" :
1367 streq(args[0], "restart") ? "RestartUnit" :
1368 streq(args[0], "try-restart") ||
1369 streq(args[0], "condrestart") ? "TryRestartUnit" :
1370 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1371 streq(args[0], "reload-or-try-restart") ||
1372 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1376 (streq(args[0], "isolate") ||
1377 streq(args[0], "rescue") ||
1378 streq(args[0], "emergency")) ? "isolate" :
1382 one_name = table[verb_to_action(args[0])];
1385 assert(arg_action < ELEMENTSOF(table));
1386 assert(table[arg_action]);
1388 method = "StartUnit";
1390 mode = (arg_action == ACTION_EMERGENCY ||
1391 arg_action == ACTION_RESCUE ||
1392 arg_action == ACTION_RUNLEVEL2 ||
1393 arg_action == ACTION_RUNLEVEL3 ||
1394 arg_action == ACTION_RUNLEVEL4 ||
1395 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1397 one_name = table[arg_action];
1400 if (!arg_no_block) {
1401 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1402 log_error("Could not watch jobs: %s", strerror(-ret));
1406 if (!(s = set_new(string_hash_func, string_compare_func))) {
1407 log_error("Failed to allocate set.");
1414 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1417 for (i = 1; i < n; i++)
1418 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1419 ret = translate_bus_error_to_exit_status(r, &error);
1420 dbus_error_free(&error);
1425 if ((r = wait_for_jobs(bus, s)) < 0) {
1434 dbus_error_free(&error);
1439 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1446 (streq(args[0], "halt") ||
1447 streq(args[0], "poweroff") ||
1448 streq(args[0], "reboot") ||
1449 streq(args[0], "kexec") ||
1450 streq(args[0], "exit")))
1451 return daemon_reload(bus, args, n);
1453 r = start_unit(bus, args, n);
1456 warn_wall(verb_to_action(args[0]));
1461 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1462 DBusMessage *m = NULL, *reply = NULL;
1464 *interface = "org.freedesktop.systemd1.Unit",
1465 *property = "ActiveState";
1466 int r = 3; /* According to LSB: "program is not running" */
1473 dbus_error_init(&error);
1475 for (i = 1; i < n; i++) {
1476 const char *path = NULL;
1478 DBusMessageIter iter, sub;
1480 if (!(m = dbus_message_new_method_call(
1481 "org.freedesktop.systemd1",
1482 "/org/freedesktop/systemd1",
1483 "org.freedesktop.systemd1.Manager",
1485 log_error("Could not allocate message.");
1490 if (!dbus_message_append_args(m,
1491 DBUS_TYPE_STRING, &args[i],
1492 DBUS_TYPE_INVALID)) {
1493 log_error("Could not append arguments to message.");
1498 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1500 /* Hmm, cannot figure out anything about this unit... */
1504 dbus_error_free(&error);
1505 dbus_message_unref(m);
1509 if (!dbus_message_get_args(reply, &error,
1510 DBUS_TYPE_OBJECT_PATH, &path,
1511 DBUS_TYPE_INVALID)) {
1512 log_error("Failed to parse reply: %s", bus_error_message(&error));
1517 dbus_message_unref(m);
1518 if (!(m = dbus_message_new_method_call(
1519 "org.freedesktop.systemd1",
1521 "org.freedesktop.DBus.Properties",
1523 log_error("Could not allocate message.");
1528 if (!dbus_message_append_args(m,
1529 DBUS_TYPE_STRING, &interface,
1530 DBUS_TYPE_STRING, &property,
1531 DBUS_TYPE_INVALID)) {
1532 log_error("Could not append arguments to message.");
1537 dbus_message_unref(reply);
1538 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1539 log_error("Failed to issue method call: %s", bus_error_message(&error));
1544 if (!dbus_message_iter_init(reply, &iter) ||
1545 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1546 log_error("Failed to parse reply.");
1551 dbus_message_iter_recurse(&iter, &sub);
1553 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1554 log_error("Failed to parse reply.");
1559 dbus_message_iter_get_basic(&sub, &state);
1564 if (streq(state, "active") || streq(state, "reloading"))
1567 dbus_message_unref(m);
1568 dbus_message_unref(reply);
1574 dbus_message_unref(m);
1577 dbus_message_unref(reply);
1579 dbus_error_free(&error);
1584 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1585 DBusMessage *m = NULL, *reply = NULL;
1593 dbus_error_init(&error);
1596 arg_kill_who = "all";
1599 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1601 for (i = 1; i < n; i++) {
1603 if (!(m = dbus_message_new_method_call(
1604 "org.freedesktop.systemd1",
1605 "/org/freedesktop/systemd1",
1606 "org.freedesktop.systemd1.Manager",
1608 log_error("Could not allocate message.");
1613 if (!dbus_message_append_args(m,
1614 DBUS_TYPE_STRING, &args[i],
1615 DBUS_TYPE_STRING, &arg_kill_who,
1616 DBUS_TYPE_STRING, &arg_kill_mode,
1617 DBUS_TYPE_INT32, &arg_signal,
1618 DBUS_TYPE_INVALID)) {
1619 log_error("Could not append arguments to message.");
1624 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1625 log_error("Failed to issue method call: %s", bus_error_message(&error));
1626 dbus_error_free(&error);
1630 dbus_message_unref(m);
1633 dbus_message_unref(reply);
1639 dbus_message_unref(m);
1642 dbus_message_unref(reply);
1644 dbus_error_free(&error);
1649 typedef struct ExecStatusInfo {
1657 usec_t start_timestamp;
1658 usec_t exit_timestamp;
1663 LIST_FIELDS(struct ExecStatusInfo, exec);
1666 static void exec_status_info_free(ExecStatusInfo *i) {
1675 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1676 uint64_t start_timestamp, exit_timestamp;
1677 DBusMessageIter sub2, sub3;
1681 int32_t code, status;
1687 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1690 dbus_message_iter_recurse(sub, &sub2);
1692 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1695 if (!(i->path = strdup(path)))
1698 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1699 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1703 dbus_message_iter_recurse(&sub2, &sub3);
1704 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1705 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1706 dbus_message_iter_next(&sub3);
1711 if (!(i->argv = new0(char*, n+1)))
1715 dbus_message_iter_recurse(&sub2, &sub3);
1716 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1719 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1720 dbus_message_iter_get_basic(&sub3, &s);
1721 dbus_message_iter_next(&sub3);
1723 if (!(i->argv[n++] = strdup(s)))
1727 if (!dbus_message_iter_next(&sub2) ||
1728 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1729 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1730 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1731 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1732 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1733 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1737 i->start_timestamp = (usec_t) start_timestamp;
1738 i->exit_timestamp = (usec_t) exit_timestamp;
1739 i->pid = (pid_t) pid;
1746 typedef struct UnitStatusInfo {
1748 const char *load_state;
1749 const char *active_state;
1750 const char *sub_state;
1752 const char *description;
1753 const char *following;
1756 const char *default_control_group;
1758 usec_t inactive_exit_timestamp;
1759 usec_t active_enter_timestamp;
1760 usec_t active_exit_timestamp;
1761 usec_t inactive_enter_timestamp;
1763 bool need_daemon_reload;
1768 const char *status_text;
1770 #ifdef HAVE_SYSV_COMPAT
1774 usec_t start_timestamp;
1775 usec_t exit_timestamp;
1777 int exit_code, exit_status;
1780 unsigned n_accepted;
1781 unsigned n_connections;
1785 const char *sysfs_path;
1787 /* Mount, Automount */
1793 LIST_HEAD(ExecStatusInfo, exec);
1796 static void print_status_info(UnitStatusInfo *i) {
1798 const char *on, *off, *ss;
1800 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1801 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1805 /* This shows pretty information about a unit. See
1806 * print_property() for a low-level property printer */
1808 printf("%s", strna(i->id));
1810 if (i->description && !streq_ptr(i->id, i->description))
1811 printf(" - %s", i->description);
1816 printf("\t Follow: unit currently follows state of %s\n", i->following);
1818 if (streq_ptr(i->load_state, "failed") ||
1819 streq_ptr(i->load_state, "banned")) {
1820 on = ansi_highlight(true);
1821 off = ansi_highlight(false);
1826 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1828 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1830 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1832 if (streq_ptr(i->active_state, "failed")) {
1833 on = ansi_highlight(true);
1834 off = ansi_highlight(false);
1835 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1836 on = ansi_highlight_green(true);
1837 off = ansi_highlight_green(false);
1842 printf("\t Active: %s%s (%s)%s",
1844 strna(i->active_state),
1848 printf("\t Active: %s%s%s",
1850 strna(i->active_state),
1853 timestamp = (streq_ptr(i->active_state, "active") ||
1854 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1855 (streq_ptr(i->active_state, "inactive") ||
1856 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1857 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1858 i->active_exit_timestamp;
1860 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1861 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1864 printf(" since %s; %s\n", s2, s1);
1866 printf(" since %s\n", s2);
1871 printf("\t Device: %s\n", i->sysfs_path);
1873 printf("\t Where: %s\n", i->where);
1875 printf("\t What: %s\n", i->what);
1878 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1880 LIST_FOREACH(exec, p, i->exec) {
1884 /* Only show exited processes here */
1888 t = strv_join(p->argv, " ");
1889 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1892 #ifdef HAVE_SYSV_COMPAT
1894 good = is_clean_exit_lsb(p->code, p->status);
1897 good = is_clean_exit(p->code, p->status);
1900 on = ansi_highlight(true);
1901 off = ansi_highlight(false);
1905 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1907 if (p->code == CLD_EXITED) {
1910 printf("status=%i", p->status);
1912 #ifdef HAVE_SYSV_COMPAT
1913 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1915 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1920 printf("signal=%s", signal_to_string(p->status));
1922 printf(")%s\n", off);
1926 if (i->main_pid == p->pid &&
1927 i->start_timestamp == p->start_timestamp &&
1928 i->exit_timestamp == p->start_timestamp)
1929 /* Let's not show this twice */
1932 if (p->pid == i->control_pid)
1936 if (i->main_pid > 0 || i->control_pid > 0) {
1939 if (i->main_pid > 0) {
1940 printf("Main PID: %u", (unsigned) i->main_pid);
1944 get_process_name(i->main_pid, &t);
1949 } else if (i->exit_code > 0) {
1950 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1952 if (i->exit_code == CLD_EXITED) {
1955 printf("status=%i", i->exit_status);
1957 #ifdef HAVE_SYSV_COMPAT
1958 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1960 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1965 printf("signal=%s", signal_to_string(i->exit_status));
1970 if (i->main_pid > 0 && i->control_pid > 0)
1973 if (i->control_pid > 0) {
1976 printf(" Control: %u", (unsigned) i->control_pid);
1978 get_process_name(i->control_pid, &t);
1989 printf("\t Status: \"%s\"\n", i->status_text);
1991 if (i->default_control_group) {
1994 printf("\t CGroup: %s\n", i->default_control_group);
1996 if ((c = columns()) > 18)
2001 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2004 if (i->need_daemon_reload)
2005 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2006 ansi_highlight(true),
2007 ansi_highlight(false),
2008 arg_user ? "--user" : "--system");
2011 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2013 switch (dbus_message_iter_get_arg_type(iter)) {
2015 case DBUS_TYPE_STRING: {
2018 dbus_message_iter_get_basic(iter, &s);
2021 if (streq(name, "Id"))
2023 else if (streq(name, "LoadState"))
2025 else if (streq(name, "ActiveState"))
2026 i->active_state = s;
2027 else if (streq(name, "SubState"))
2029 else if (streq(name, "Description"))
2031 else if (streq(name, "FragmentPath"))
2033 #ifdef HAVE_SYSV_COMPAT
2034 else if (streq(name, "SysVPath")) {
2039 else if (streq(name, "DefaultControlGroup"))
2040 i->default_control_group = s;
2041 else if (streq(name, "StatusText"))
2043 else if (streq(name, "SysFSPath"))
2045 else if (streq(name, "Where"))
2047 else if (streq(name, "What"))
2049 else if (streq(name, "Following"))
2056 case DBUS_TYPE_BOOLEAN: {
2059 dbus_message_iter_get_basic(iter, &b);
2061 if (streq(name, "Accept"))
2063 else if (streq(name, "NeedDaemonReload"))
2064 i->need_daemon_reload = b;
2069 case DBUS_TYPE_UINT32: {
2072 dbus_message_iter_get_basic(iter, &u);
2074 if (streq(name, "MainPID")) {
2076 i->main_pid = (pid_t) u;
2079 } else if (streq(name, "ControlPID"))
2080 i->control_pid = (pid_t) u;
2081 else if (streq(name, "ExecMainPID")) {
2083 i->main_pid = (pid_t) u;
2084 } else if (streq(name, "NAccepted"))
2086 else if (streq(name, "NConnections"))
2087 i->n_connections = u;
2092 case DBUS_TYPE_INT32: {
2095 dbus_message_iter_get_basic(iter, &j);
2097 if (streq(name, "ExecMainCode"))
2098 i->exit_code = (int) j;
2099 else if (streq(name, "ExecMainStatus"))
2100 i->exit_status = (int) j;
2105 case DBUS_TYPE_UINT64: {
2108 dbus_message_iter_get_basic(iter, &u);
2110 if (streq(name, "ExecMainStartTimestamp"))
2111 i->start_timestamp = (usec_t) u;
2112 else if (streq(name, "ExecMainExitTimestamp"))
2113 i->exit_timestamp = (usec_t) u;
2114 else if (streq(name, "ActiveEnterTimestamp"))
2115 i->active_enter_timestamp = (usec_t) u;
2116 else if (streq(name, "InactiveEnterTimestamp"))
2117 i->inactive_enter_timestamp = (usec_t) u;
2118 else if (streq(name, "InactiveExitTimestamp"))
2119 i->inactive_exit_timestamp = (usec_t) u;
2120 else if (streq(name, "ActiveExitTimestamp"))
2121 i->active_exit_timestamp = (usec_t) u;
2126 case DBUS_TYPE_ARRAY: {
2128 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2129 startswith(name, "Exec")) {
2130 DBusMessageIter sub;
2132 dbus_message_iter_recurse(iter, &sub);
2133 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2134 ExecStatusInfo *info;
2137 if (!(info = new0(ExecStatusInfo, 1)))
2140 if (!(info->name = strdup(name))) {
2145 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2150 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2152 dbus_message_iter_next(&sub);
2163 static int print_property(const char *name, DBusMessageIter *iter) {
2167 /* This is a low-level property printer, see
2168 * print_status_info() for the nicer output */
2170 if (arg_property && !strv_find(arg_property, name))
2173 switch (dbus_message_iter_get_arg_type(iter)) {
2175 case DBUS_TYPE_STRING: {
2177 dbus_message_iter_get_basic(iter, &s);
2179 if (arg_all || s[0])
2180 printf("%s=%s\n", name, s);
2185 case DBUS_TYPE_BOOLEAN: {
2187 dbus_message_iter_get_basic(iter, &b);
2188 printf("%s=%s\n", name, yes_no(b));
2193 case DBUS_TYPE_UINT64: {
2195 dbus_message_iter_get_basic(iter, &u);
2197 /* Yes, heuristics! But we can change this check
2198 * should it turn out to not be sufficient */
2200 if (strstr(name, "Timestamp")) {
2201 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2203 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2204 printf("%s=%s\n", name, strempty(t));
2205 } else if (strstr(name, "USec")) {
2206 char timespan[FORMAT_TIMESPAN_MAX];
2208 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2210 printf("%s=%llu\n", name, (unsigned long long) u);
2215 case DBUS_TYPE_UINT32: {
2217 dbus_message_iter_get_basic(iter, &u);
2219 if (strstr(name, "UMask") || strstr(name, "Mode"))
2220 printf("%s=%04o\n", name, u);
2222 printf("%s=%u\n", name, (unsigned) u);
2227 case DBUS_TYPE_INT32: {
2229 dbus_message_iter_get_basic(iter, &i);
2231 printf("%s=%i\n", name, (int) i);
2235 case DBUS_TYPE_DOUBLE: {
2237 dbus_message_iter_get_basic(iter, &d);
2239 printf("%s=%g\n", name, d);
2243 case DBUS_TYPE_STRUCT: {
2244 DBusMessageIter sub;
2245 dbus_message_iter_recurse(iter, &sub);
2247 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2250 dbus_message_iter_get_basic(&sub, &u);
2253 printf("%s=%u\n", name, (unsigned) u);
2255 printf("%s=\n", name);
2258 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2261 dbus_message_iter_get_basic(&sub, &s);
2263 if (arg_all || s[0])
2264 printf("%s=%s\n", name, s);
2272 case DBUS_TYPE_ARRAY:
2274 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2275 DBusMessageIter sub;
2278 dbus_message_iter_recurse(iter, &sub);
2280 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2281 printf("%s=", name);
2283 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2286 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2287 dbus_message_iter_get_basic(&sub, &s);
2288 printf("%s%s", space ? " " : "", s);
2291 dbus_message_iter_next(&sub);
2299 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2300 DBusMessageIter sub;
2302 dbus_message_iter_recurse(iter, &sub);
2304 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2305 printf("%s=", name);
2307 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2310 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2311 dbus_message_iter_get_basic(&sub, &u);
2314 dbus_message_iter_next(&sub);
2322 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2323 DBusMessageIter sub, sub2;
2325 dbus_message_iter_recurse(iter, &sub);
2326 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2327 const char *type, *path;
2329 dbus_message_iter_recurse(&sub, &sub2);
2331 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2332 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2333 printf("%s=%s\n", type, path);
2335 dbus_message_iter_next(&sub);
2340 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2341 DBusMessageIter sub, sub2;
2343 dbus_message_iter_recurse(iter, &sub);
2344 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2346 uint64_t value, next_elapse;
2348 dbus_message_iter_recurse(&sub, &sub2);
2350 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2351 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2352 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2353 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2355 printf("%s={ value=%s ; next_elapse=%s }\n",
2357 format_timespan(timespan1, sizeof(timespan1), value),
2358 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2361 dbus_message_iter_next(&sub);
2366 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2367 DBusMessageIter sub;
2369 dbus_message_iter_recurse(iter, &sub);
2370 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2371 ExecStatusInfo info;
2374 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2375 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2378 t = strv_join(info.argv, " ");
2380 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2384 yes_no(info.ignore),
2385 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2386 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2387 (unsigned) info. pid,
2388 sigchld_code_to_string(info.code),
2390 info.code == CLD_EXITED ? "" : "/",
2391 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2397 strv_free(info.argv);
2399 dbus_message_iter_next(&sub);
2409 printf("%s=[unprintable]\n", name);
2414 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2415 DBusMessage *m = NULL, *reply = NULL;
2416 const char *interface = "";
2419 DBusMessageIter iter, sub, sub2, sub3;
2420 UnitStatusInfo info;
2428 dbus_error_init(&error);
2430 if (!(m = dbus_message_new_method_call(
2431 "org.freedesktop.systemd1",
2433 "org.freedesktop.DBus.Properties",
2435 log_error("Could not allocate message.");
2440 if (!dbus_message_append_args(m,
2441 DBUS_TYPE_STRING, &interface,
2442 DBUS_TYPE_INVALID)) {
2443 log_error("Could not append arguments to message.");
2448 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2449 log_error("Failed to issue method call: %s", bus_error_message(&error));
2454 if (!dbus_message_iter_init(reply, &iter) ||
2455 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2456 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2457 log_error("Failed to parse reply.");
2462 dbus_message_iter_recurse(&iter, &sub);
2469 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2472 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2473 log_error("Failed to parse reply.");
2478 dbus_message_iter_recurse(&sub, &sub2);
2480 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2481 log_error("Failed to parse reply.");
2486 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2487 log_error("Failed to parse reply.");
2492 dbus_message_iter_recurse(&sub2, &sub3);
2494 if (show_properties)
2495 r = print_property(name, &sub3);
2497 r = status_property(name, &sub3, &info);
2500 log_error("Failed to parse reply.");
2505 dbus_message_iter_next(&sub);
2510 if (!show_properties)
2511 print_status_info(&info);
2513 if (!streq_ptr(info.active_state, "active") &&
2514 !streq_ptr(info.active_state, "reloading") &&
2515 streq(verb, "status"))
2516 /* According to LSB: "program not running" */
2519 while ((p = info.exec)) {
2520 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2521 exec_status_info_free(p);
2526 dbus_message_unref(m);
2529 dbus_message_unref(reply);
2531 dbus_error_free(&error);
2536 static int show(DBusConnection *bus, char **args, unsigned n) {
2537 DBusMessage *m = NULL, *reply = NULL;
2541 bool show_properties, new_line = false;
2546 dbus_error_init(&error);
2548 show_properties = !streq(args[0], "status");
2550 if (show_properties)
2553 if (show_properties && n <= 1) {
2554 /* If not argument is specified inspect the manager
2557 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2561 for (i = 1; i < n; i++) {
2562 const char *path = NULL;
2565 if (safe_atou32(args[i], &id) < 0) {
2567 /* Interpret as unit name */
2569 if (!(m = dbus_message_new_method_call(
2570 "org.freedesktop.systemd1",
2571 "/org/freedesktop/systemd1",
2572 "org.freedesktop.systemd1.Manager",
2574 log_error("Could not allocate message.");
2579 if (!dbus_message_append_args(m,
2580 DBUS_TYPE_STRING, &args[i],
2581 DBUS_TYPE_INVALID)) {
2582 log_error("Could not append arguments to message.");
2587 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2589 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2590 log_error("Failed to issue method call: %s", bus_error_message(&error));
2595 dbus_error_free(&error);
2597 dbus_message_unref(m);
2598 if (!(m = dbus_message_new_method_call(
2599 "org.freedesktop.systemd1",
2600 "/org/freedesktop/systemd1",
2601 "org.freedesktop.systemd1.Manager",
2603 log_error("Could not allocate message.");
2608 if (!dbus_message_append_args(m,
2609 DBUS_TYPE_STRING, &args[i],
2610 DBUS_TYPE_INVALID)) {
2611 log_error("Could not append arguments to message.");
2616 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2617 log_error("Failed to issue method call: %s", bus_error_message(&error));
2619 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2620 ret = 4; /* According to LSB: "program or service status is unknown" */
2627 } else if (show_properties) {
2629 /* Interpret as job id */
2631 if (!(m = dbus_message_new_method_call(
2632 "org.freedesktop.systemd1",
2633 "/org/freedesktop/systemd1",
2634 "org.freedesktop.systemd1.Manager",
2636 log_error("Could not allocate message.");
2641 if (!dbus_message_append_args(m,
2642 DBUS_TYPE_UINT32, &id,
2643 DBUS_TYPE_INVALID)) {
2644 log_error("Could not append arguments to message.");
2649 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2650 log_error("Failed to issue method call: %s", bus_error_message(&error));
2656 /* Interpret as PID */
2658 if (!(m = dbus_message_new_method_call(
2659 "org.freedesktop.systemd1",
2660 "/org/freedesktop/systemd1",
2661 "org.freedesktop.systemd1.Manager",
2663 log_error("Could not allocate message.");
2668 if (!dbus_message_append_args(m,
2669 DBUS_TYPE_UINT32, &id,
2670 DBUS_TYPE_INVALID)) {
2671 log_error("Could not append arguments to message.");
2676 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2677 log_error("Failed to issue method call: %s", bus_error_message(&error));
2683 if (!dbus_message_get_args(reply, &error,
2684 DBUS_TYPE_OBJECT_PATH, &path,
2685 DBUS_TYPE_INVALID)) {
2686 log_error("Failed to parse reply: %s", bus_error_message(&error));
2691 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2694 dbus_message_unref(m);
2695 dbus_message_unref(reply);
2701 dbus_message_unref(m);
2704 dbus_message_unref(reply);
2706 dbus_error_free(&error);
2711 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2713 DBusMessage *m = NULL, *reply = NULL;
2718 dbus_error_init(&error);
2720 log_debug("Got D-Bus request: %s.%s() on %s",
2721 dbus_message_get_interface(message),
2722 dbus_message_get_member(message),
2723 dbus_message_get_path(message));
2725 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2726 log_error("Warning! D-Bus connection terminated.");
2727 dbus_connection_close(connection);
2729 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2730 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2731 const char *id, *path;
2733 if (!dbus_message_get_args(message, &error,
2734 DBUS_TYPE_STRING, &id,
2735 DBUS_TYPE_OBJECT_PATH, &path,
2737 log_error("Failed to parse message: %s", bus_error_message(&error));
2738 else if (streq(dbus_message_get_member(message), "UnitNew"))
2739 printf("Unit %s added.\n", id);
2741 printf("Unit %s removed.\n", id);
2743 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2744 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2748 if (!dbus_message_get_args(message, &error,
2749 DBUS_TYPE_UINT32, &id,
2750 DBUS_TYPE_OBJECT_PATH, &path,
2752 log_error("Failed to parse message: %s", bus_error_message(&error));
2753 else if (streq(dbus_message_get_member(message), "JobNew"))
2754 printf("Job %u added.\n", id);
2756 printf("Job %u removed.\n", id);
2759 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2761 const char *path, *interface, *property = "Id";
2762 DBusMessageIter iter, sub;
2764 path = dbus_message_get_path(message);
2766 if (!dbus_message_get_args(message, &error,
2767 DBUS_TYPE_STRING, &interface,
2768 DBUS_TYPE_INVALID)) {
2769 log_error("Failed to parse message: %s", bus_error_message(&error));
2773 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2774 !streq(interface, "org.freedesktop.systemd1.Unit"))
2777 if (!(m = dbus_message_new_method_call(
2778 "org.freedesktop.systemd1",
2780 "org.freedesktop.DBus.Properties",
2782 log_error("Could not allocate message.");
2786 if (!dbus_message_append_args(m,
2787 DBUS_TYPE_STRING, &interface,
2788 DBUS_TYPE_STRING, &property,
2789 DBUS_TYPE_INVALID)) {
2790 log_error("Could not append arguments to message.");
2794 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2795 log_error("Failed to issue method call: %s", bus_error_message(&error));
2799 if (!dbus_message_iter_init(reply, &iter) ||
2800 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2801 log_error("Failed to parse reply.");
2805 dbus_message_iter_recurse(&iter, &sub);
2807 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2810 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2811 log_error("Failed to parse reply.");
2815 dbus_message_iter_get_basic(&sub, &id);
2816 printf("Unit %s changed.\n", id);
2820 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2821 log_error("Failed to parse reply.");
2825 dbus_message_iter_get_basic(&sub, &id);
2826 printf("Job %u changed.\n", id);
2832 dbus_message_unref(m);
2835 dbus_message_unref(reply);
2837 dbus_error_free(&error);
2838 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2842 dbus_message_unref(m);
2845 dbus_message_unref(reply);
2847 dbus_error_free(&error);
2848 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2851 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2852 DBusMessage *m = NULL, *reply = NULL;
2856 dbus_error_init(&error);
2859 dbus_bus_add_match(bus,
2861 "sender='org.freedesktop.systemd1',"
2862 "interface='org.freedesktop.systemd1.Manager',"
2863 "path='/org/freedesktop/systemd1'",
2866 if (dbus_error_is_set(&error)) {
2867 log_error("Failed to add match: %s", bus_error_message(&error));
2872 dbus_bus_add_match(bus,
2874 "sender='org.freedesktop.systemd1',"
2875 "interface='org.freedesktop.DBus.Properties',"
2876 "member='PropertiesChanged'",
2879 if (dbus_error_is_set(&error)) {
2880 log_error("Failed to add match: %s", bus_error_message(&error));
2886 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2887 log_error("Failed to add filter.");
2892 if (!(m = dbus_message_new_method_call(
2893 "org.freedesktop.systemd1",
2894 "/org/freedesktop/systemd1",
2895 "org.freedesktop.systemd1.Manager",
2897 log_error("Could not allocate message.");
2902 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2903 log_error("Failed to issue method call: %s", bus_error_message(&error));
2908 while (dbus_connection_read_write_dispatch(bus, -1))
2915 /* This is slightly dirty, since we don't undo the filter or the matches. */
2918 dbus_message_unref(m);
2921 dbus_message_unref(reply);
2923 dbus_error_free(&error);
2928 static int dump(DBusConnection *bus, char **args, unsigned n) {
2929 DBusMessage *m = NULL, *reply = NULL;
2934 dbus_error_init(&error);
2938 if (!(m = dbus_message_new_method_call(
2939 "org.freedesktop.systemd1",
2940 "/org/freedesktop/systemd1",
2941 "org.freedesktop.systemd1.Manager",
2943 log_error("Could not allocate message.");
2947 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2948 log_error("Failed to issue method call: %s", bus_error_message(&error));
2953 if (!dbus_message_get_args(reply, &error,
2954 DBUS_TYPE_STRING, &text,
2955 DBUS_TYPE_INVALID)) {
2956 log_error("Failed to parse reply: %s", bus_error_message(&error));
2961 fputs(text, stdout);
2967 dbus_message_unref(m);
2970 dbus_message_unref(reply);
2972 dbus_error_free(&error);
2977 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2978 DBusMessage *m = NULL, *reply = NULL;
2981 const char *name = "", *path, *id;
2982 dbus_bool_t cleanup = FALSE;
2983 DBusMessageIter iter, sub;
2985 *interface = "org.freedesktop.systemd1.Unit",
2988 dbus_error_init(&error);
2990 if (!(m = dbus_message_new_method_call(
2991 "org.freedesktop.systemd1",
2992 "/org/freedesktop/systemd1",
2993 "org.freedesktop.systemd1.Manager",
2994 "CreateSnapshot"))) {
2995 log_error("Could not allocate message.");
3002 if (!dbus_message_append_args(m,
3003 DBUS_TYPE_STRING, &name,
3004 DBUS_TYPE_BOOLEAN, &cleanup,
3005 DBUS_TYPE_INVALID)) {
3006 log_error("Could not append arguments to message.");
3011 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3012 log_error("Failed to issue method call: %s", bus_error_message(&error));
3017 if (!dbus_message_get_args(reply, &error,
3018 DBUS_TYPE_OBJECT_PATH, &path,
3019 DBUS_TYPE_INVALID)) {
3020 log_error("Failed to parse reply: %s", bus_error_message(&error));
3025 dbus_message_unref(m);
3026 if (!(m = dbus_message_new_method_call(
3027 "org.freedesktop.systemd1",
3029 "org.freedesktop.DBus.Properties",
3031 log_error("Could not allocate message.");
3035 if (!dbus_message_append_args(m,
3036 DBUS_TYPE_STRING, &interface,
3037 DBUS_TYPE_STRING, &property,
3038 DBUS_TYPE_INVALID)) {
3039 log_error("Could not append arguments to message.");
3044 dbus_message_unref(reply);
3045 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3046 log_error("Failed to issue method call: %s", bus_error_message(&error));
3051 if (!dbus_message_iter_init(reply, &iter) ||
3052 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3053 log_error("Failed to parse reply.");
3058 dbus_message_iter_recurse(&iter, &sub);
3060 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3061 log_error("Failed to parse reply.");
3066 dbus_message_iter_get_basic(&sub, &id);
3074 dbus_message_unref(m);
3077 dbus_message_unref(reply);
3079 dbus_error_free(&error);
3084 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3085 DBusMessage *m = NULL, *reply = NULL;
3093 dbus_error_init(&error);
3095 for (i = 1; i < n; i++) {
3096 const char *path = NULL;
3098 if (!(m = dbus_message_new_method_call(
3099 "org.freedesktop.systemd1",
3100 "/org/freedesktop/systemd1",
3101 "org.freedesktop.systemd1.Manager",
3103 log_error("Could not allocate message.");
3108 if (!dbus_message_append_args(m,
3109 DBUS_TYPE_STRING, &args[i],
3110 DBUS_TYPE_INVALID)) {
3111 log_error("Could not append arguments to message.");
3116 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3117 log_error("Failed to issue method call: %s", bus_error_message(&error));
3122 if (!dbus_message_get_args(reply, &error,
3123 DBUS_TYPE_OBJECT_PATH, &path,
3124 DBUS_TYPE_INVALID)) {
3125 log_error("Failed to parse reply: %s", bus_error_message(&error));
3130 dbus_message_unref(m);
3131 if (!(m = dbus_message_new_method_call(
3132 "org.freedesktop.systemd1",
3134 "org.freedesktop.systemd1.Snapshot",
3136 log_error("Could not allocate message.");
3141 dbus_message_unref(reply);
3142 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3143 log_error("Failed to issue method call: %s", bus_error_message(&error));
3148 dbus_message_unref(m);
3149 dbus_message_unref(reply);
3157 dbus_message_unref(m);
3160 dbus_message_unref(reply);
3162 dbus_error_free(&error);
3167 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3168 DBusMessage *m = NULL, *reply = NULL;
3173 dbus_error_init(&error);
3175 if (arg_action == ACTION_RELOAD)
3177 else if (arg_action == ACTION_REEXEC)
3178 method = "Reexecute";
3180 assert(arg_action == ACTION_SYSTEMCTL);
3183 streq(args[0], "clear-jobs") ||
3184 streq(args[0], "cancel") ? "ClearJobs" :
3185 streq(args[0], "daemon-reexec") ? "Reexecute" :
3186 streq(args[0], "reset-failed") ? "ResetFailed" :
3187 streq(args[0], "halt") ? "Halt" :
3188 streq(args[0], "poweroff") ? "PowerOff" :
3189 streq(args[0], "reboot") ? "Reboot" :
3190 streq(args[0], "kexec") ? "KExec" :
3191 streq(args[0], "exit") ? "Exit" :
3192 /* "daemon-reload" */ "Reload";
3195 if (!(m = dbus_message_new_method_call(
3196 "org.freedesktop.systemd1",
3197 "/org/freedesktop/systemd1",
3198 "org.freedesktop.systemd1.Manager",
3200 log_error("Could not allocate message.");
3204 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3206 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3207 /* There's always a fallback possible for
3208 * legacy actions. */
3213 log_error("Failed to issue method call: %s", bus_error_message(&error));
3222 dbus_message_unref(m);
3225 dbus_message_unref(reply);
3227 dbus_error_free(&error);
3232 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3233 DBusMessage *m = NULL, *reply = NULL;
3239 dbus_error_init(&error);
3242 return daemon_reload(bus, args, n);
3244 for (i = 1; i < n; i++) {
3246 if (!(m = dbus_message_new_method_call(
3247 "org.freedesktop.systemd1",
3248 "/org/freedesktop/systemd1",
3249 "org.freedesktop.systemd1.Manager",
3250 "ResetFailedUnit"))) {
3251 log_error("Could not allocate message.");
3256 if (!dbus_message_append_args(m,
3257 DBUS_TYPE_STRING, args + i,
3258 DBUS_TYPE_INVALID)) {
3259 log_error("Could not append arguments to message.");
3264 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3265 log_error("Failed to issue method call: %s", bus_error_message(&error));
3270 dbus_message_unref(m);
3271 dbus_message_unref(reply);
3279 dbus_message_unref(m);
3282 dbus_message_unref(reply);
3284 dbus_error_free(&error);
3289 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3290 DBusMessage *m = NULL, *reply = NULL;
3292 DBusMessageIter iter, sub, sub2;
3295 *interface = "org.freedesktop.systemd1.Manager",
3296 *property = "Environment";
3298 dbus_error_init(&error);
3302 if (!(m = dbus_message_new_method_call(
3303 "org.freedesktop.systemd1",
3304 "/org/freedesktop/systemd1",
3305 "org.freedesktop.DBus.Properties",
3307 log_error("Could not allocate message.");
3311 if (!dbus_message_append_args(m,
3312 DBUS_TYPE_STRING, &interface,
3313 DBUS_TYPE_STRING, &property,
3314 DBUS_TYPE_INVALID)) {
3315 log_error("Could not append arguments to message.");
3320 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3321 log_error("Failed to issue method call: %s", bus_error_message(&error));
3326 if (!dbus_message_iter_init(reply, &iter) ||
3327 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3328 log_error("Failed to parse reply.");
3333 dbus_message_iter_recurse(&iter, &sub);
3335 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3336 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3337 log_error("Failed to parse reply.");
3342 dbus_message_iter_recurse(&sub, &sub2);
3344 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3347 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3348 log_error("Failed to parse reply.");
3353 dbus_message_iter_get_basic(&sub2, &text);
3354 printf("%s\n", text);
3356 dbus_message_iter_next(&sub2);
3363 dbus_message_unref(m);
3366 dbus_message_unref(reply);
3368 dbus_error_free(&error);
3373 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3374 DBusMessage *m = NULL, *reply = NULL;
3378 DBusMessageIter iter, sub;
3381 dbus_error_init(&error);
3383 method = streq(args[0], "set-environment")
3385 : "UnsetEnvironment";
3387 if (!(m = dbus_message_new_method_call(
3388 "org.freedesktop.systemd1",
3389 "/org/freedesktop/systemd1",
3390 "org.freedesktop.systemd1.Manager",
3393 log_error("Could not allocate message.");
3397 dbus_message_iter_init_append(m, &iter);
3399 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3400 log_error("Could not append arguments to message.");
3405 for (i = 1; i < n; i++)
3406 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3407 log_error("Could not append arguments to message.");
3412 if (!dbus_message_iter_close_container(&iter, &sub)) {
3413 log_error("Could not append arguments to message.");
3418 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3419 log_error("Failed to issue method call: %s", bus_error_message(&error));
3428 dbus_message_unref(m);
3431 dbus_message_unref(reply);
3433 dbus_error_free(&error);
3446 static Hashmap *will_install = NULL, *have_installed = NULL;
3447 static Set *remove_symlinks_to = NULL;
3448 static unsigned n_symlinks = 0;
3450 static void install_info_free(InstallInfo *i) {
3455 strv_free(i->aliases);
3456 strv_free(i->wanted_by);
3460 static void install_info_hashmap_free(Hashmap *m) {
3463 while ((i = hashmap_steal_first(m)))
3464 install_info_free(i);
3469 static int install_info_add(const char *name) {
3473 assert(will_install);
3475 if (!unit_name_is_valid_no_type(name, true)) {
3476 log_warning("Unit name %s is not a valid unit name.", name);
3480 if (hashmap_get(have_installed, name) ||
3481 hashmap_get(will_install, name))
3484 if (!(i = new0(InstallInfo, 1))) {
3489 if (!(i->name = strdup(name))) {
3494 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3501 install_info_free(i);
3506 static int config_parse_also(
3507 const char *filename,
3509 const char *section,
3523 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3527 if (!(n = strndup(w, l)))
3530 if ((r = install_info_add(n)) < 0) {
3531 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3542 static int mark_symlink_for_removal(const char *p) {
3547 assert(path_is_absolute(p));
3549 if (!remove_symlinks_to)
3552 if (!(n = strdup(p)))
3555 path_kill_slashes(n);
3557 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3559 return r == -EEXIST ? 0 : r;
3565 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3574 if (!(d = fdopendir(fd))) {
3575 close_nointr_nofail(fd);
3581 while ((de = readdir(d))) {
3582 bool is_dir = false, is_link = false;
3584 if (ignore_file(de->d_name))
3587 if (de->d_type == DT_LNK)
3589 else if (de->d_type == DT_DIR)
3591 else if (de->d_type == DT_UNKNOWN) {
3594 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3595 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3602 is_link = S_ISLNK(st.st_mode);
3603 is_dir = S_ISDIR(st.st_mode);
3611 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3612 log_error("Failed to open %s/%s: %m", root, de->d_name);
3619 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3620 log_error("Failed to allocate directory string.");
3621 close_nointr_nofail(nfd);
3626 /* This will close nfd, regardless whether it succeeds or not */
3627 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3633 } else if (is_link) {
3637 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3638 log_error("Failed to allocate symlink string.");
3643 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3644 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3652 if ((c = canonicalize_file_name(dest))) {
3653 /* This might fail if the destination
3654 * is already removed */
3660 path_kill_slashes(dest);
3661 if (set_get(remove_symlinks_to, dest)) {
3664 log_info("rm '%s'", p);
3666 if (unlink(p) < 0) {
3667 log_error("Cannot unlink symlink %s: %m", p);
3672 rmdir_parents(p, config_path);
3673 path_kill_slashes(p);
3675 if (!set_get(remove_symlinks_to, p)) {
3677 if ((r = mark_symlink_for_removal(p)) < 0) {
3696 static int remove_marked_symlinks(const char *config_path) {
3700 assert(config_path);
3702 if (set_size(remove_symlinks_to) <= 0)
3705 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3712 if ((cfd = dup(fd)) < 0) {
3717 /* This takes possession of cfd and closes it */
3718 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3724 close_nointr_nofail(fd);
3729 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3736 if (streq(verb, "enable")) {
3739 mkdir_parents(new_path, 0755);
3741 if (symlink(old_path, new_path) >= 0) {
3744 log_info("ln -s '%s' '%s'", old_path, new_path);
3749 if (errno != EEXIST) {
3750 log_error("Cannot link %s to %s: %m", old_path, new_path);
3754 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3756 if (errno == EINVAL) {
3757 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3761 log_error("readlink() failed: %s", strerror(-r));
3765 if (streq(dest, old_path)) {
3771 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3780 log_info("ln -s '%s' '%s'", old_path, new_path);
3782 if (symlink(old_path, new_path) >= 0)
3785 log_error("Cannot link %s to %s: %m", old_path, new_path);
3788 } else if (streq(verb, "disable")) {
3791 if ((r = mark_symlink_for_removal(old_path)) < 0)
3794 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3795 if (errno == ENOENT)
3798 if (errno == EINVAL) {
3799 log_warning("File %s not a symlink, ignoring.", old_path);
3803 log_error("readlink() failed: %s", strerror(-r));
3807 if (!streq(dest, old_path)) {
3808 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3815 if ((r = mark_symlink_for_removal(new_path)) < 0)
3819 log_info("rm '%s'", new_path);
3821 if (unlink(new_path) >= 0)
3824 log_error("Cannot unlink %s: %m", new_path);
3827 } else if (streq(verb, "is-enabled")) {
3830 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3832 if (errno == ENOENT || errno == EINVAL)
3835 log_error("readlink() failed: %s", strerror(-r));
3839 if (streq(dest, old_path)) {
3847 assert_not_reached("Unknown action.");
3850 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3852 char *alias_path = NULL;
3857 assert(config_path);
3859 STRV_FOREACH(s, i->aliases) {
3862 if (!(alias_path = path_make_absolute(*s, config_path))) {
3863 log_error("Out of memory");
3868 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3871 if (streq(verb, "disable"))
3872 rmdir_parents(alias_path, config_path);
3882 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3884 char *alias_path = NULL;
3889 assert(config_path);
3891 STRV_FOREACH(s, i->wanted_by) {
3892 if (!unit_name_is_valid_no_type(*s, true)) {
3893 log_error("Invalid name %s.", *s);
3901 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3902 log_error("Out of memory");
3907 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3910 if (streq(verb, "disable"))
3911 rmdir_parents(alias_path, config_path);
3922 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3924 const ConfigItem items[] = {
3925 { "Alias", config_parse_strv, &i->aliases, "Install" },
3926 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3927 { "Also", config_parse_also, NULL, "Install" },
3929 { NULL, NULL, NULL, NULL }
3933 char *filename = NULL;
3940 STRV_FOREACH(p, paths->unit_path) {
3943 if (!(filename = path_make_absolute(i->name, *p))) {
3944 log_error("Out of memory");
3948 /* Ensure that we don't follow symlinks */
3949 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3950 if ((f = fdopen(fd, "re")))
3953 if (errno == ELOOP) {
3954 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3959 if (errno != ENOENT) {
3960 log_error("Failed to open %s: %m", filename);
3970 #if defined(TARGET_FEDORA) && defined (HAVE_SYSV_COMPAT)
3972 if (endswith(i->name, ".service")) {
3976 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
3977 log_error("Out of memory");
3981 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
3982 exists = access(sysv, F_OK) >= 0;
3988 const char *argv[] = {
3995 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
3997 argv[1] = file_name_from_path(sysv);
3999 streq(verb, "enable") ? "on" :
4000 streq(verb, "disable") ? "off" : NULL;
4002 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
4004 if ((pid = fork()) < 0) {
4005 log_error("Failed to fork: %m");
4008 } else if (pid == 0) {
4009 execv(argv[0], (char**) argv);
4010 _exit(EXIT_FAILURE);
4015 if ((r = wait_for_terminate(pid, &status)) < 0)
4018 if (status.si_code == CLD_EXITED) {
4019 if (status.si_status == 0 && (streq(verb, "enable") || streq(verb, "disable")))
4022 return status.si_status == 0 ? 0 : -EINVAL;
4032 log_error("Couldn't find %s.", i->name);
4038 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4043 n_symlinks += strv_length(i->aliases);
4044 n_symlinks += strv_length(i->wanted_by);
4048 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4051 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4054 if ((r = mark_symlink_for_removal(filename)) < 0)
4057 if ((r = remove_marked_symlinks(config_path)) < 0)
4063 static char *get_config_path(void) {
4065 if (arg_user && arg_global)
4066 return strdup(USER_CONFIG_UNIT_PATH);
4071 if (user_config_home(&p) < 0)
4077 return strdup(SYSTEM_CONFIG_UNIT_PATH);
4080 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4084 char *config_path = NULL;
4087 const char *verb = args[0];
4089 dbus_error_init(&error);
4092 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4093 log_error("Failed to determine lookup paths: %s", strerror(-r));
4097 if (!(config_path = get_config_path())) {
4098 log_error("Failed to determine config path");
4103 will_install = hashmap_new(string_hash_func, string_compare_func);
4104 have_installed = hashmap_new(string_hash_func, string_compare_func);
4106 if (!will_install || !have_installed) {
4107 log_error("Failed to allocate unit sets.");
4112 if (!arg_defaults && streq(verb, "disable"))
4113 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4114 log_error("Failed to allocate symlink sets.");
4119 for (j = 1; j < n; j++)
4120 if ((r = install_info_add(args[j])) < 0) {
4121 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4125 while ((i = hashmap_first(will_install))) {
4128 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4130 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4138 /* In test mode and found something */
4144 if (streq(verb, "is-enabled"))
4145 r = r > 0 ? 0 : -ENOENT;
4147 if (n_symlinks <= 0)
4148 log_warning("Unit files contain no applicable installation information. Ignoring.");
4151 /* Don't try to reload anything if the user asked us to not do this */
4153 /* Don't try to reload anything when updating a unit globally */
4155 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4156 (arg_user || sd_booted() > 0) &&
4157 /* Don't try to reload anything if we are running in a chroot environment */
4158 (arg_user || running_in_chroot() <= 0) ) {
4161 if ((q = daemon_reload(bus, args, n)) < 0)
4167 install_info_hashmap_free(will_install);
4168 install_info_hashmap_free(have_installed);
4170 set_free_free(remove_symlinks_to);
4172 lookup_paths_free(&paths);
4179 static int systemctl_help(void) {
4181 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4182 "Send control commands to or query the systemd manager.\n\n"
4183 " -h --help Show this help\n"
4184 " --version Show package version\n"
4185 " -t --type=TYPE List only units of a particular type\n"
4186 " -p --property=NAME Show only properties by this name\n"
4187 " -a --all Show all units/properties, including dead/empty ones\n"
4188 " --full Don't ellipsize unit names on output\n"
4189 " --fail When queueing a new job, fail if conflicting jobs are\n"
4191 " -q --quiet Suppress output\n"
4192 " --no-block Do not wait until operation finished\n"
4193 " --no-pager Do not pipe output into a pager.\n"
4194 " --system Connect to system manager\n"
4195 " --user Connect to user service manager\n"
4196 " --order When generating graph for dot, show only order\n"
4197 " --require When generating graph for dot, show only requirement\n"
4198 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4199 " --global Enable/disable unit files globally\n"
4200 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4202 " --no-ask-password\n"
4203 " Do not ask for system passwords\n"
4204 " --kill-mode=MODE How to send signal\n"
4205 " --kill-who=WHO Who to send signal to\n"
4206 " -s --signal=SIGNAL Which signal to send\n"
4207 " -f --force When enabling unit files, override existing symlinks\n"
4208 " When shutting down, execute action immediately\n"
4209 " --defaults When disabling unit files, remove default symlinks only\n\n"
4211 " list-units List units\n"
4212 " start [NAME...] Start (activate) one or more units\n"
4213 " stop [NAME...] Stop (deactivate) one or more units\n"
4214 " reload [NAME...] Reload one or more units\n"
4215 " restart [NAME...] Start or restart one or more units\n"
4216 " try-restart [NAME...] Restart one or more units if active\n"
4217 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4218 " otherwise start or restart\n"
4219 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4220 " otherwise restart if active\n"
4221 " isolate [NAME] Start one unit and stop all others\n"
4222 " kill [NAME...] Send signal to processes of a unit\n"
4223 " is-active [NAME...] Check whether units are active\n"
4224 " status [NAME...|PID...] Show runtime status of one or more units\n"
4225 " show [NAME...|JOB...] Show properties of one or more\n"
4226 " units/jobs or the manager\n"
4227 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4229 " enable [NAME...] Enable one or more unit files\n"
4230 " disable [NAME...] Disable one or more unit files\n"
4231 " is-enabled [NAME...] Check whether unit files are enabled\n"
4232 " load [NAME...] Load one or more units\n"
4233 " list-jobs List jobs\n"
4234 " cancel [JOB...] Cancel all, one, or more jobs\n"
4235 " monitor Monitor unit/job changes\n"
4236 " dump Dump server status\n"
4237 " dot Dump dependency graph for dot(1)\n"
4238 " snapshot [NAME] Create a snapshot\n"
4239 " delete [NAME...] Remove one or more snapshots\n"
4240 " daemon-reload Reload systemd manager configuration\n"
4241 " daemon-reexec Reexecute systemd manager\n"
4242 " show-environment Dump environment\n"
4243 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4244 " unset-environment [NAME...] Unset one or more environment variables\n"
4245 " default Enter system default mode\n"
4246 " rescue Enter system rescue mode\n"
4247 " emergency Enter system emergency mode\n"
4248 " halt Shut down and halt the system\n"
4249 " poweroff Shut down and power-off the system\n"
4250 " reboot Shut down and reboot the system\n"
4251 " kexec Shut down and reboot the system with kexec\n"
4252 " exit Ask for user instance termination\n",
4253 program_invocation_short_name);
4258 static int halt_help(void) {
4260 printf("%s [OPTIONS...]\n\n"
4261 "%s the system.\n\n"
4262 " --help Show this help\n"
4263 " --halt Halt the machine\n"
4264 " -p --poweroff Switch off the machine\n"
4265 " --reboot Reboot the machine\n"
4266 " -f --force Force immediate halt/power-off/reboot\n"
4267 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4268 " -d --no-wtmp Don't write wtmp record\n"
4269 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4270 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4271 program_invocation_short_name,
4272 arg_action == ACTION_REBOOT ? "Reboot" :
4273 arg_action == ACTION_POWEROFF ? "Power off" :
4279 static int shutdown_help(void) {
4281 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4282 "Shut down the system.\n\n"
4283 " --help Show this help\n"
4284 " -H --halt Halt the machine\n"
4285 " -P --poweroff Power-off the machine\n"
4286 " -r --reboot Reboot the machine\n"
4287 " -h Equivalent to --poweroff, overriden by --halt\n"
4288 " -k Don't halt/power-off/reboot, just send warnings\n"
4289 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4290 " -c Cancel a pending shutdown\n",
4291 program_invocation_short_name);
4296 static int telinit_help(void) {
4298 printf("%s [OPTIONS...] {COMMAND}\n\n"
4299 "Send control commands to the init daemon.\n\n"
4300 " --help Show this help\n"
4301 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4303 " 0 Power-off the machine\n"
4304 " 6 Reboot the machine\n"
4305 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4306 " 1, s, S Enter rescue mode\n"
4307 " q, Q Reload init daemon configuration\n"
4308 " u, U Reexecute init daemon\n",
4309 program_invocation_short_name);
4314 static int runlevel_help(void) {
4316 printf("%s [OPTIONS...]\n\n"
4317 "Prints the previous and current runlevel of the init system.\n\n"
4318 " --help Show this help\n",
4319 program_invocation_short_name);
4324 static int systemctl_parse_argv(int argc, char *argv[]) {
4345 static const struct option options[] = {
4346 { "help", no_argument, NULL, 'h' },
4347 { "version", no_argument, NULL, ARG_VERSION },
4348 { "type", required_argument, NULL, 't' },
4349 { "property", required_argument, NULL, 'p' },
4350 { "all", no_argument, NULL, 'a' },
4351 { "full", no_argument, NULL, ARG_FULL },
4352 { "fail", no_argument, NULL, ARG_FAIL },
4353 { "user", no_argument, NULL, ARG_USER },
4354 { "system", no_argument, NULL, ARG_SYSTEM },
4355 { "global", no_argument, NULL, ARG_GLOBAL },
4356 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4357 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4358 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4359 { "quiet", no_argument, NULL, 'q' },
4360 { "order", no_argument, NULL, ARG_ORDER },
4361 { "require", no_argument, NULL, ARG_REQUIRE },
4362 { "force", no_argument, NULL, 'f' },
4363 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4364 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4365 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4366 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4367 { "signal", required_argument, NULL, 's' },
4368 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4369 { NULL, 0, NULL, 0 }
4377 /* Only when running as systemctl we ask for passwords */
4378 arg_ask_password = true;
4380 while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4389 puts(PACKAGE_STRING);
4391 puts(SYSTEMD_FEATURES);
4401 if (!(l = strv_append(arg_property, optarg)))
4404 strv_free(arg_property);
4407 /* If the user asked for a particular
4408 * property, show it to him, even if it is
4431 arg_no_block = true;
4435 arg_no_pager = true;
4443 arg_dot = DOT_ORDER;
4447 arg_dot = DOT_REQUIRE;
4463 arg_no_reload = true;
4472 arg_defaults = true;
4476 arg_kill_who = optarg;
4480 arg_kill_mode = optarg;
4484 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4485 log_error("Failed to parse signal string %s.", optarg);
4490 case ARG_NO_ASK_PASSWORD:
4491 arg_ask_password = false;
4498 log_error("Unknown option code %c", c);
4506 static int halt_parse_argv(int argc, char *argv[]) {
4515 static const struct option options[] = {
4516 { "help", no_argument, NULL, ARG_HELP },
4517 { "halt", no_argument, NULL, ARG_HALT },
4518 { "poweroff", no_argument, NULL, 'p' },
4519 { "reboot", no_argument, NULL, ARG_REBOOT },
4520 { "force", no_argument, NULL, 'f' },
4521 { "wtmp-only", no_argument, NULL, 'w' },
4522 { "no-wtmp", no_argument, NULL, 'd' },
4523 { "no-sync", no_argument, NULL, 'n' },
4524 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4525 { NULL, 0, NULL, 0 }
4533 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4534 if (runlevel == '0' || runlevel == '6')
4535 arg_immediate = true;
4537 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4545 arg_action = ACTION_HALT;
4549 if (arg_action != ACTION_REBOOT)
4550 arg_action = ACTION_POWEROFF;
4554 arg_action = ACTION_REBOOT;
4558 arg_immediate = true;
4579 /* Compatibility nops */
4586 log_error("Unknown option code %c", c);
4591 if (optind < argc) {
4592 log_error("Too many arguments.");
4599 static int parse_time_spec(const char *t, usec_t *_u) {
4603 if (streq(t, "now"))
4605 else if (t[0] == '+') {
4608 if (safe_atou64(t + 1, &u) < 0)
4611 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4620 hour = strtol(t, &e, 10);
4621 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4624 minute = strtol(e+1, &e, 10);
4625 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4628 n = now(CLOCK_REALTIME);
4629 s = (time_t) (n / USEC_PER_SEC);
4632 assert_se(localtime_r(&s, &tm));
4634 tm.tm_hour = (int) hour;
4635 tm.tm_min = (int) minute;
4638 assert_se(s = mktime(&tm));
4640 *_u = (usec_t) s * USEC_PER_SEC;
4643 *_u += USEC_PER_DAY;
4649 static int shutdown_parse_argv(int argc, char *argv[]) {
4656 static const struct option options[] = {
4657 { "help", no_argument, NULL, ARG_HELP },
4658 { "halt", no_argument, NULL, 'H' },
4659 { "poweroff", no_argument, NULL, 'P' },
4660 { "reboot", no_argument, NULL, 'r' },
4661 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4662 { NULL, 0, NULL, 0 }
4670 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4678 arg_action = ACTION_HALT;
4682 arg_action = ACTION_POWEROFF;
4686 arg_action = ACTION_REBOOT;
4690 if (arg_action != ACTION_HALT)
4691 arg_action = ACTION_POWEROFF;
4704 /* Compatibility nops */
4708 arg_action = ACTION_CANCEL_SHUTDOWN;
4715 log_error("Unknown option code %c", c);
4720 if (argc > optind) {
4721 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4722 log_error("Failed to parse time specification: %s", argv[optind]);
4726 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4728 /* We skip the time argument */
4729 if (argc > optind + 1)
4730 arg_wall = argv + optind + 1;
4737 static int telinit_parse_argv(int argc, char *argv[]) {
4744 static const struct option options[] = {
4745 { "help", no_argument, NULL, ARG_HELP },
4746 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4747 { NULL, 0, NULL, 0 }
4750 static const struct {
4754 { '0', ACTION_POWEROFF },
4755 { '6', ACTION_REBOOT },
4756 { '1', ACTION_RESCUE },
4757 { '2', ACTION_RUNLEVEL2 },
4758 { '3', ACTION_RUNLEVEL3 },
4759 { '4', ACTION_RUNLEVEL4 },
4760 { '5', ACTION_RUNLEVEL5 },
4761 { 's', ACTION_RESCUE },
4762 { 'S', ACTION_RESCUE },
4763 { 'q', ACTION_RELOAD },
4764 { 'Q', ACTION_RELOAD },
4765 { 'u', ACTION_REEXEC },
4766 { 'U', ACTION_REEXEC }
4775 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4790 log_error("Unknown option code %c", c);
4795 if (optind >= argc) {
4800 if (optind + 1 < argc) {
4801 log_error("Too many arguments.");
4805 if (strlen(argv[optind]) != 1) {
4806 log_error("Expected single character argument.");
4810 for (i = 0; i < ELEMENTSOF(table); i++)
4811 if (table[i].from == argv[optind][0])
4814 if (i >= ELEMENTSOF(table)) {
4815 log_error("Unknown command %s.", argv[optind]);
4819 arg_action = table[i].to;
4826 static int runlevel_parse_argv(int argc, char *argv[]) {
4832 static const struct option options[] = {
4833 { "help", no_argument, NULL, ARG_HELP },
4834 { NULL, 0, NULL, 0 }
4842 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4853 log_error("Unknown option code %c", c);
4858 if (optind < argc) {
4859 log_error("Too many arguments.");
4866 static int parse_argv(int argc, char *argv[]) {
4870 if (program_invocation_short_name) {
4872 if (strstr(program_invocation_short_name, "halt")) {
4873 arg_action = ACTION_HALT;
4874 return halt_parse_argv(argc, argv);
4875 } else if (strstr(program_invocation_short_name, "poweroff")) {
4876 arg_action = ACTION_POWEROFF;
4877 return halt_parse_argv(argc, argv);
4878 } else if (strstr(program_invocation_short_name, "reboot")) {
4879 arg_action = ACTION_REBOOT;
4880 return halt_parse_argv(argc, argv);
4881 } else if (strstr(program_invocation_short_name, "shutdown")) {
4882 arg_action = ACTION_POWEROFF;
4883 return shutdown_parse_argv(argc, argv);
4884 } else if (strstr(program_invocation_short_name, "init")) {
4886 if (sd_booted() > 0) {
4887 arg_action = ACTION_INVALID;
4888 return telinit_parse_argv(argc, argv);
4890 /* Hmm, so some other init system is
4891 * running, we need to forward this
4892 * request to it. For now we simply
4893 * guess that it is Upstart. */
4895 execv("/lib/upstart/telinit", argv);
4897 log_error("Couldn't find an alternative telinit implementation to spawn.");
4901 } else if (strstr(program_invocation_short_name, "runlevel")) {
4902 arg_action = ACTION_RUNLEVEL;
4903 return runlevel_parse_argv(argc, argv);
4907 arg_action = ACTION_SYSTEMCTL;
4908 return systemctl_parse_argv(argc, argv);
4911 static int action_to_runlevel(void) {
4913 static const char table[_ACTION_MAX] = {
4914 [ACTION_HALT] = '0',
4915 [ACTION_POWEROFF] = '0',
4916 [ACTION_REBOOT] = '6',
4917 [ACTION_RUNLEVEL2] = '2',
4918 [ACTION_RUNLEVEL3] = '3',
4919 [ACTION_RUNLEVEL4] = '4',
4920 [ACTION_RUNLEVEL5] = '5',
4921 [ACTION_RESCUE] = '1'
4924 assert(arg_action < _ACTION_MAX);
4926 return table[arg_action];
4929 static int talk_upstart(void) {
4930 DBusMessage *m = NULL, *reply = NULL;
4932 int previous, rl, r;
4934 env1_buf[] = "RUNLEVEL=X",
4935 env2_buf[] = "PREVLEVEL=X";
4936 char *env1 = env1_buf, *env2 = env2_buf;
4937 const char *emit = "runlevel";
4938 dbus_bool_t b_false = FALSE;
4939 DBusMessageIter iter, sub;
4940 DBusConnection *bus;
4942 dbus_error_init(&error);
4944 if (!(rl = action_to_runlevel()))
4947 if (utmp_get_runlevel(&previous, NULL) < 0)
4950 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4951 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4956 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4961 if ((r = bus_check_peercred(bus)) < 0) {
4962 log_error("Failed to verify owner of bus.");
4966 if (!(m = dbus_message_new_method_call(
4967 "com.ubuntu.Upstart",
4968 "/com/ubuntu/Upstart",
4969 "com.ubuntu.Upstart0_6",
4972 log_error("Could not allocate message.");
4977 dbus_message_iter_init_append(m, &iter);
4979 env1_buf[sizeof(env1_buf)-2] = rl;
4980 env2_buf[sizeof(env2_buf)-2] = previous;
4982 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4983 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4984 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4985 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4986 !dbus_message_iter_close_container(&iter, &sub) ||
4987 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4988 log_error("Could not append arguments to message.");
4993 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4995 if (error_is_no_service(&error)) {
5000 log_error("Failed to issue method call: %s", bus_error_message(&error));
5009 dbus_message_unref(m);
5012 dbus_message_unref(reply);
5015 dbus_connection_flush(bus);
5016 dbus_connection_close(bus);
5017 dbus_connection_unref(bus);
5020 dbus_error_free(&error);
5025 static int talk_initctl(void) {
5026 struct init_request request;
5030 if (!(rl = action_to_runlevel()))
5034 request.magic = INIT_MAGIC;
5035 request.sleeptime = 0;
5036 request.cmd = INIT_CMD_RUNLVL;
5037 request.runlevel = rl;
5039 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5041 if (errno == ENOENT)
5044 log_error("Failed to open "INIT_FIFO": %m");
5049 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5050 close_nointr_nofail(fd);
5053 log_error("Failed to write to "INIT_FIFO": %m");
5054 return errno ? -errno : -EIO;
5060 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5062 static const struct {
5070 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5072 { "list-units", LESS, 1, list_units },
5073 { "list-jobs", EQUAL, 1, list_jobs },
5074 { "clear-jobs", EQUAL, 1, daemon_reload },
5075 { "load", MORE, 2, load_unit },
5076 { "cancel", MORE, 2, cancel_job },
5077 { "start", MORE, 2, start_unit },
5078 { "stop", MORE, 2, start_unit },
5079 { "reload", MORE, 2, start_unit },
5080 { "restart", MORE, 2, start_unit },
5081 { "try-restart", MORE, 2, start_unit },
5082 { "reload-or-restart", MORE, 2, start_unit },
5083 { "reload-or-try-restart", MORE, 2, start_unit },
5084 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5085 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5086 { "isolate", EQUAL, 2, start_unit },
5087 { "kill", MORE, 2, kill_unit },
5088 { "is-active", MORE, 2, check_unit },
5089 { "check", MORE, 2, check_unit },
5090 { "show", MORE, 1, show },
5091 { "status", MORE, 2, show },
5092 { "monitor", EQUAL, 1, monitor },
5093 { "dump", EQUAL, 1, dump },
5094 { "dot", EQUAL, 1, dot },
5095 { "snapshot", LESS, 2, snapshot },
5096 { "delete", MORE, 2, delete_snapshot },
5097 { "daemon-reload", EQUAL, 1, daemon_reload },
5098 { "daemon-reexec", EQUAL, 1, daemon_reload },
5099 { "show-environment", EQUAL, 1, show_enviroment },
5100 { "set-environment", MORE, 2, set_environment },
5101 { "unset-environment", MORE, 2, set_environment },
5102 { "halt", EQUAL, 1, start_special },
5103 { "poweroff", EQUAL, 1, start_special },
5104 { "reboot", EQUAL, 1, start_special },
5105 { "kexec", EQUAL, 1, start_special },
5106 { "default", EQUAL, 1, start_special },
5107 { "rescue", EQUAL, 1, start_special },
5108 { "emergency", EQUAL, 1, start_special },
5109 { "exit", EQUAL, 1, start_special },
5110 { "reset-failed", MORE, 1, reset_failed },
5111 { "enable", MORE, 2, enable_unit },
5112 { "disable", MORE, 2, enable_unit },
5113 { "is-enabled", MORE, 2, enable_unit }
5123 left = argc - optind;
5126 /* Special rule: no arguments means "list-units" */
5129 if (streq(argv[optind], "help")) {
5134 for (i = 0; i < ELEMENTSOF(verbs); i++)
5135 if (streq(argv[optind], verbs[i].verb))
5138 if (i >= ELEMENTSOF(verbs)) {
5139 log_error("Unknown operation %s", argv[optind]);
5144 switch (verbs[i].argc_cmp) {
5147 if (left != verbs[i].argc) {
5148 log_error("Invalid number of arguments.");
5155 if (left < verbs[i].argc) {
5156 log_error("Too few arguments.");
5163 if (left > verbs[i].argc) {
5164 log_error("Too many arguments.");
5171 assert_not_reached("Unknown comparison operator.");
5174 /* Require a bus connection for all operations but
5176 if (!streq(verbs[i].verb, "enable") &&
5177 !streq(verbs[i].verb, "disable") &&
5179 log_error("Failed to get D-Bus connection: %s", error->message);
5183 return verbs[i].dispatch(bus, argv + optind, left);
5186 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5188 struct msghdr msghdr;
5190 union sockaddr_union sockaddr;
5191 struct shutdownd_command c;
5199 strncpy(c.wall_message, message, sizeof(c.wall_message));
5201 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5205 sockaddr.sa.sa_family = AF_UNIX;
5206 sockaddr.un.sun_path[0] = 0;
5207 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5210 iovec.iov_base = (char*) &c;
5211 iovec.iov_len = sizeof(c);
5214 msghdr.msg_name = &sockaddr;
5215 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5217 msghdr.msg_iov = &iovec;
5218 msghdr.msg_iovlen = 1;
5220 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5221 close_nointr_nofail(fd);
5225 close_nointr_nofail(fd);
5229 static int reload_with_fallback(DBusConnection *bus) {
5232 /* First, try systemd via D-Bus. */
5233 if (daemon_reload(bus, NULL, 0) > 0)
5237 /* Nothing else worked, so let's try signals */
5238 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5240 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5241 log_error("kill() failed: %m");
5248 static int start_with_fallback(DBusConnection *bus) {
5251 /* First, try systemd via D-Bus. */
5252 if (start_unit(bus, NULL, 0) >= 0)
5256 /* Hmm, talking to systemd via D-Bus didn't work. Then
5257 * let's try to talk to Upstart via D-Bus. */
5258 if (talk_upstart() > 0)
5261 /* Nothing else worked, so let's try
5263 if (talk_initctl() > 0)
5266 log_error("Failed to talk to init daemon.");
5270 warn_wall(arg_action);
5274 static int halt_main(DBusConnection *bus) {
5277 if (geteuid() != 0) {
5278 log_error("Must be root.");
5284 char date[FORMAT_TIMESTAMP_MAX];
5286 m = strv_join(arg_wall, " ");
5287 r = send_shutdownd(arg_when,
5288 arg_action == ACTION_HALT ? 'H' :
5289 arg_action == ACTION_POWEROFF ? 'P' :
5296 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5298 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5299 format_timestamp(date, sizeof(date), arg_when));
5304 if (!arg_dry && !arg_immediate)
5305 return start_with_fallback(bus);
5308 if (sd_booted() > 0)
5309 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5310 else if ((r = utmp_put_shutdown(0)) < 0)
5311 log_warning("Failed to write utmp record: %s", strerror(-r));
5320 /* Make sure C-A-D is handled by the kernel from this
5322 reboot(RB_ENABLE_CAD);
5324 switch (arg_action) {
5327 log_info("Halting.");
5328 reboot(RB_HALT_SYSTEM);
5331 case ACTION_POWEROFF:
5332 log_info("Powering off.");
5333 reboot(RB_POWER_OFF);
5337 log_info("Rebooting.");
5338 reboot(RB_AUTOBOOT);
5342 assert_not_reached("Unknown halt action.");
5345 /* We should never reach this. */
5349 static int runlevel_main(void) {
5350 int r, runlevel, previous;
5352 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5353 printf("unknown\n");
5358 previous <= 0 ? 'N' : previous,
5359 runlevel <= 0 ? 'N' : runlevel);
5364 static void pager_open(void) {
5371 if (!on_tty() || arg_no_pager)
5374 if ((pager = getenv("PAGER")))
5375 if (!*pager || streq(pager, "cat"))
5378 /* Determine and cache number of columns before we spawn the
5379 * pager so that we get the value from the actual tty */
5383 log_error("Failed to create pager pipe: %m");
5388 if (pager_pid < 0) {
5389 log_error("Failed to fork pager: %m");
5394 /* In the child start the pager */
5395 if (pager_pid == 0) {
5397 dup2(fd[0], STDIN_FILENO);
5400 setenv("LESS", "FRSX", 0);
5402 prctl(PR_SET_PDEATHSIG, SIGTERM);
5405 execlp(pager, pager, NULL);
5406 execl("/bin/sh", "sh", "-c", pager, NULL);
5408 /* Debian's alternatives command for pagers is
5409 * called 'pager'. Note that we do not call
5410 * sensible-pagers here, since that is just a
5411 * shell script that implements a logic that
5412 * is similar to this one anyway, but is
5413 * Debian-specific. */
5414 execlp("pager", "pager", NULL);
5416 execlp("less", "less", NULL);
5417 execlp("more", "more", NULL);
5420 log_error("Unable to execute pager: %m");
5421 _exit(EXIT_FAILURE);
5424 /* Return in the parent */
5425 if (dup2(fd[1], STDOUT_FILENO) < 0)
5426 log_error("Failed to duplicate pager pipe: %m");
5431 static void pager_close(void) {
5437 /* Inform pager that we are done */
5439 wait_for_terminate(pager_pid, &dummy);
5443 int main(int argc, char*argv[]) {
5444 int r, retval = EXIT_FAILURE;
5445 DBusConnection *bus = NULL;
5448 dbus_error_init(&error);
5450 log_parse_environment();
5453 if ((r = parse_argv(argc, argv)) < 0)
5456 retval = EXIT_SUCCESS;
5460 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5461 * let's shortcut this */
5462 if (arg_action == ACTION_RUNLEVEL) {
5463 r = runlevel_main();
5464 retval = r < 0 ? EXIT_FAILURE : r;
5468 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5470 switch (arg_action) {
5472 case ACTION_SYSTEMCTL:
5473 r = systemctl_main(bus, argc, argv, &error);
5477 case ACTION_POWEROFF:
5482 case ACTION_RUNLEVEL2:
5483 case ACTION_RUNLEVEL3:
5484 case ACTION_RUNLEVEL4:
5485 case ACTION_RUNLEVEL5:
5487 case ACTION_EMERGENCY:
5488 case ACTION_DEFAULT:
5489 r = start_with_fallback(bus);
5494 r = reload_with_fallback(bus);
5497 case ACTION_CANCEL_SHUTDOWN:
5498 r = send_shutdownd(0, 0, false, NULL);
5501 case ACTION_INVALID:
5502 case ACTION_RUNLEVEL:
5504 assert_not_reached("Unknown action");
5507 retval = r < 0 ? EXIT_FAILURE : r;
5512 dbus_connection_flush(bus);
5513 dbus_connection_close(bus);
5514 dbus_connection_unref(bus);
5517 dbus_error_free(&error);
5521 strv_free(arg_property);