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 bool arg_failed = false;
80 static char **arg_wall = NULL;
81 static const char *arg_kill_who = NULL;
82 static const char *arg_kill_mode = NULL;
83 static int arg_signal = SIGTERM;
84 static usec_t arg_when = 0;
103 ACTION_CANCEL_SHUTDOWN,
105 } arg_action = ACTION_SYSTEMCTL;
112 static bool private_bus = false;
114 static pid_t pager_pid = 0;
116 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
117 static void pager_open(void);
119 static bool on_tty(void) {
122 /* Note that this is invoked relatively early, before we start
123 * the pager. That means the value we return reflects whether
124 * we originally were started on a tty, not if we currently
125 * are. But this is intended, since we want colour and so on
126 * when run in our own pager. */
128 if (_unlikely_(t < 0))
129 t = isatty(STDOUT_FILENO) > 0;
134 static void spawn_ask_password_agent(void) {
137 /* We check STDIN here, not STDOUT, since this is about input,
139 if (!isatty(STDIN_FILENO))
142 if (!arg_ask_password)
150 /* Spawns a temporary TTY agent, making sure it goes away when
153 if ((child = fork()) < 0)
158 const char * const args[] = {
159 SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH,
165 bool stdout_is_tty, stderr_is_tty;
167 /* Make sure the agent goes away when the parent dies */
168 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
171 /* Check whether our parent died before we were able
172 * to set the death signal */
173 if (getppid() != parent)
176 /* Don't leak fds to the agent */
177 close_all_fds(NULL, 0);
179 stdout_is_tty = isatty(STDOUT_FILENO);
180 stderr_is_tty = isatty(STDERR_FILENO);
182 if (!stdout_is_tty || !stderr_is_tty) {
183 /* Detach from stdout/stderr. and reopen
184 * /dev/tty for them. This is important to
185 * ensure that when systemctl is started via
186 * popen() or a similar call that expects to
187 * read EOF we actually do generate EOF and
188 * not delay this indefinitely by because we
189 * keep an unused copy of stdin around. */
190 if ((fd = open("/dev/tty", O_WRONLY)) < 0) {
191 log_error("Failed to open /dev/tty: %m");
196 dup2(fd, STDOUT_FILENO);
199 dup2(fd, STDERR_FILENO);
205 execv(args[0], (char **) args);
210 static const char *ansi_highlight(bool b) {
215 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
218 static const char *ansi_highlight_green(bool b) {
223 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
226 static bool error_is_no_service(const DBusError *error) {
229 if (!dbus_error_is_set(error))
232 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
235 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
238 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
241 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
244 if (!dbus_error_is_set(error))
247 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
248 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
249 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
250 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
251 return EXIT_NOPERMISSION;
253 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
254 return EXIT_NOTINSTALLED;
256 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
257 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
258 return EXIT_NOTIMPLEMENTED;
260 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
261 return EXIT_NOTCONFIGURED;
269 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
274 if (dbus_message_iter_get_arg_type(iter) != type)
277 dbus_message_iter_get_basic(iter, data);
279 if (!dbus_message_iter_next(iter) != !next)
285 static void warn_wall(enum action action) {
286 static const char *table[_ACTION_MAX] = {
287 [ACTION_HALT] = "The system is going down for system halt NOW!",
288 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
289 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
290 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
291 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
292 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
301 if (!(p = strv_join(arg_wall, " "))) {
302 log_error("Failed to join strings.");
318 utmp_wall(table[action], NULL);
323 const char *description;
324 const char *load_state;
325 const char *active_state;
326 const char *sub_state;
327 const char *following;
328 const char *unit_path;
330 const char *job_type;
331 const char *job_path;
334 static int compare_unit_info(const void *a, const void *b) {
336 const struct unit_info *u = a, *v = b;
338 d1 = strrchr(u->id, '.');
339 d2 = strrchr(v->id, '.');
344 if ((r = strcasecmp(d1, d2)) != 0)
348 return strcasecmp(u->id, v->id);
351 static bool output_show_unit(const struct unit_info *u) {
355 return streq(u->active_state, "failed");
357 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
358 streq(dot+1, arg_type))) &&
359 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
362 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
363 unsigned active_len, sub_len, job_len, n_shown = 0;
364 const struct unit_info *u;
366 active_len = sizeof("ACTIVE")-1;
367 sub_len = sizeof("SUB")-1;
368 job_len = sizeof("JOB")-1;
370 for (u = unit_infos; u < unit_infos + c; u++) {
371 if (!output_show_unit(u))
374 active_len = MAX(active_len, strlen(u->active_state));
375 sub_len = MAX(sub_len, strlen(u->sub_state));
377 job_len = MAX(job_len, strlen(u->job_type));
381 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
382 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
383 if (columns() >= 80+12 || arg_full)
384 printf(" %s\n", "DESCRIPTION");
389 for (u = unit_infos; u < unit_infos + c; u++) {
392 const char *on_loaded, *off_loaded;
393 const char *on_active, *off_active;
395 if (!output_show_unit(u))
400 if (!streq(u->load_state, "loaded") &&
401 !streq(u->load_state, "banned")) {
402 on_loaded = ansi_highlight(true);
403 off_loaded = ansi_highlight(false);
405 on_loaded = off_loaded = "";
407 if (streq(u->active_state, "failed")) {
408 on_active = ansi_highlight(true);
409 off_active = ansi_highlight(false);
411 on_active = off_active = "";
413 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
415 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
417 on_loaded, u->load_state, off_loaded,
418 on_active, active_len, u->active_state,
419 sub_len, u->sub_state, off_active,
424 a -= strlen(on_loaded) + strlen(off_loaded);
425 a -= strlen(on_active) + strlen(off_active);
428 printf(" %-*s", job_len, u->job_type);
432 if (a + b + 1 < columns()) {
434 printf(" %-*s", job_len, "");
437 printf(" %s", u->description);
439 printf(" %.*s", columns() - a - b - 1, u->description);
446 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
447 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
448 "SUB = The low-level unit activation state, values depend on unit type.\n"
449 "JOB = Pending job for the unit.\n");
452 printf("\n%u units listed.\n", n_shown);
454 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
458 static int list_units(DBusConnection *bus, char **args, unsigned n) {
459 DBusMessage *m = NULL, *reply = NULL;
462 DBusMessageIter iter, sub, sub2;
463 unsigned c = 0, n_units = 0;
464 struct unit_info *unit_infos = NULL;
466 dbus_error_init(&error);
472 if (!(m = dbus_message_new_method_call(
473 "org.freedesktop.systemd1",
474 "/org/freedesktop/systemd1",
475 "org.freedesktop.systemd1.Manager",
477 log_error("Could not allocate message.");
481 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
482 log_error("Failed to issue method call: %s", bus_error_message(&error));
487 if (!dbus_message_iter_init(reply, &iter) ||
488 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
489 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
490 log_error("Failed to parse reply.");
495 dbus_message_iter_recurse(&iter, &sub);
497 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
500 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
501 log_error("Failed to parse reply.");
509 n_units = MAX(2*c, 16);
510 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
513 log_error("Failed to allocate unit array.");
523 dbus_message_iter_recurse(&sub, &sub2);
525 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
526 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
527 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
528 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
529 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
530 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
531 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
532 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
533 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
534 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
535 log_error("Failed to parse reply.");
540 dbus_message_iter_next(&sub);
545 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
546 output_units_list(unit_infos, c);
553 dbus_message_unref(m);
556 dbus_message_unref(reply);
560 dbus_error_free(&error);
565 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
566 static const char * const colors[] = {
567 "Requires", "[color=\"black\"]",
568 "RequiresOverridable", "[color=\"black\"]",
569 "Requisite", "[color=\"darkblue\"]",
570 "RequisiteOverridable", "[color=\"darkblue\"]",
571 "Wants", "[color=\"darkgrey\"]",
572 "Conflicts", "[color=\"red\"]",
573 "ConflictedBy", "[color=\"red\"]",
574 "After", "[color=\"green\"]"
577 const char *c = NULL;
584 for (i = 0; i < ELEMENTSOF(colors); i += 2)
585 if (streq(colors[i], prop)) {
593 if (arg_dot != DOT_ALL)
594 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
597 switch (dbus_message_iter_get_arg_type(iter)) {
599 case DBUS_TYPE_ARRAY:
601 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
604 dbus_message_iter_recurse(iter, &sub);
606 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
609 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
610 dbus_message_iter_get_basic(&sub, &s);
611 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
613 dbus_message_iter_next(&sub);
623 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
624 DBusMessage *m = NULL, *reply = NULL;
625 const char *interface = "org.freedesktop.systemd1.Unit";
628 DBusMessageIter iter, sub, sub2, sub3;
633 dbus_error_init(&error);
635 if (!(m = dbus_message_new_method_call(
636 "org.freedesktop.systemd1",
638 "org.freedesktop.DBus.Properties",
640 log_error("Could not allocate message.");
645 if (!dbus_message_append_args(m,
646 DBUS_TYPE_STRING, &interface,
647 DBUS_TYPE_INVALID)) {
648 log_error("Could not append arguments to message.");
653 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
654 log_error("Failed to issue method call: %s", bus_error_message(&error));
659 if (!dbus_message_iter_init(reply, &iter) ||
660 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
661 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
662 log_error("Failed to parse reply.");
667 dbus_message_iter_recurse(&iter, &sub);
669 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
672 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
673 log_error("Failed to parse reply.");
678 dbus_message_iter_recurse(&sub, &sub2);
680 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
681 log_error("Failed to parse reply.");
686 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
687 log_error("Failed to parse reply.");
692 dbus_message_iter_recurse(&sub2, &sub3);
694 if (dot_one_property(name, prop, &sub3)) {
695 log_error("Failed to parse reply.");
700 dbus_message_iter_next(&sub);
707 dbus_message_unref(m);
710 dbus_message_unref(reply);
712 dbus_error_free(&error);
717 static int dot(DBusConnection *bus, char **args, unsigned n) {
718 DBusMessage *m = NULL, *reply = NULL;
721 DBusMessageIter iter, sub, sub2;
723 dbus_error_init(&error);
727 if (!(m = dbus_message_new_method_call(
728 "org.freedesktop.systemd1",
729 "/org/freedesktop/systemd1",
730 "org.freedesktop.systemd1.Manager",
732 log_error("Could not allocate message.");
736 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
737 log_error("Failed to issue method call: %s", bus_error_message(&error));
742 if (!dbus_message_iter_init(reply, &iter) ||
743 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
744 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
745 log_error("Failed to parse reply.");
750 printf("digraph systemd {\n");
752 dbus_message_iter_recurse(&iter, &sub);
753 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
754 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
756 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
757 log_error("Failed to parse reply.");
762 dbus_message_iter_recurse(&sub, &sub2);
764 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
765 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
766 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
767 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
768 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
769 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
770 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
771 log_error("Failed to parse reply.");
776 if ((r = dot_one(bus, id, unit_path)) < 0)
779 /* printf("\t\"%s\";\n", id); */
780 dbus_message_iter_next(&sub);
785 log_info(" Color legend: black = Requires\n"
786 " dark blue = Requisite\n"
787 " dark grey = Wants\n"
791 if (isatty(fileno(stdout)))
792 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
793 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
799 dbus_message_unref(m);
802 dbus_message_unref(reply);
804 dbus_error_free(&error);
809 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
810 DBusMessage *m = NULL, *reply = NULL;
813 DBusMessageIter iter, sub, sub2;
816 dbus_error_init(&error);
822 if (!(m = dbus_message_new_method_call(
823 "org.freedesktop.systemd1",
824 "/org/freedesktop/systemd1",
825 "org.freedesktop.systemd1.Manager",
827 log_error("Could not allocate message.");
831 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
832 log_error("Failed to issue method call: %s", bus_error_message(&error));
837 if (!dbus_message_iter_init(reply, &iter) ||
838 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
839 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
840 log_error("Failed to parse reply.");
845 dbus_message_iter_recurse(&iter, &sub);
847 if (isatty(STDOUT_FILENO))
848 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
850 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
851 const char *name, *type, *state, *job_path, *unit_path;
855 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
856 log_error("Failed to parse reply.");
861 dbus_message_iter_recurse(&sub, &sub2);
863 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
864 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
865 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
866 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
867 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
868 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
869 log_error("Failed to parse reply.");
874 e = arg_full ? NULL : ellipsize(name, 25, 33);
875 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
880 dbus_message_iter_next(&sub);
883 if (isatty(STDOUT_FILENO))
884 printf("\n%u jobs listed.\n", k);
890 dbus_message_unref(m);
893 dbus_message_unref(reply);
895 dbus_error_free(&error);
900 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
901 DBusMessage *m = NULL, *reply = NULL;
906 dbus_error_init(&error);
911 for (i = 1; i < n; i++) {
913 if (!(m = dbus_message_new_method_call(
914 "org.freedesktop.systemd1",
915 "/org/freedesktop/systemd1",
916 "org.freedesktop.systemd1.Manager",
918 log_error("Could not allocate message.");
923 if (!dbus_message_append_args(m,
924 DBUS_TYPE_STRING, &args[i],
925 DBUS_TYPE_INVALID)) {
926 log_error("Could not append arguments to message.");
931 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
932 log_error("Failed to issue method call: %s", bus_error_message(&error));
937 dbus_message_unref(m);
938 dbus_message_unref(reply);
947 dbus_message_unref(m);
950 dbus_message_unref(reply);
952 dbus_error_free(&error);
957 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
958 DBusMessage *m = NULL, *reply = NULL;
963 dbus_error_init(&error);
969 return daemon_reload(bus, args, n);
971 for (i = 1; i < n; i++) {
975 if (!(m = dbus_message_new_method_call(
976 "org.freedesktop.systemd1",
977 "/org/freedesktop/systemd1",
978 "org.freedesktop.systemd1.Manager",
980 log_error("Could not allocate message.");
985 if ((r = safe_atou(args[i], &id)) < 0) {
986 log_error("Failed to parse job id: %s", strerror(-r));
990 assert_cc(sizeof(uint32_t) == sizeof(id));
991 if (!dbus_message_append_args(m,
992 DBUS_TYPE_UINT32, &id,
993 DBUS_TYPE_INVALID)) {
994 log_error("Could not append arguments to message.");
999 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1000 log_error("Failed to issue method call: %s", bus_error_message(&error));
1005 if (!dbus_message_get_args(reply, &error,
1006 DBUS_TYPE_OBJECT_PATH, &path,
1007 DBUS_TYPE_INVALID)) {
1008 log_error("Failed to parse reply: %s", bus_error_message(&error));
1013 dbus_message_unref(m);
1014 if (!(m = dbus_message_new_method_call(
1015 "org.freedesktop.systemd1",
1017 "org.freedesktop.systemd1.Job",
1019 log_error("Could not allocate message.");
1024 dbus_message_unref(reply);
1025 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1026 log_error("Failed to issue method call: %s", bus_error_message(&error));
1031 dbus_message_unref(m);
1032 dbus_message_unref(reply);
1040 dbus_message_unref(m);
1043 dbus_message_unref(reply);
1045 dbus_error_free(&error);
1050 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1051 DBusMessage *m = NULL, *reply = NULL;
1052 dbus_bool_t b = FALSE;
1053 DBusMessageIter iter, sub;
1055 *interface = "org.freedesktop.systemd1.Unit",
1056 *property = "NeedDaemonReload",
1059 /* We ignore all errors here, since this is used to show a warning only */
1061 if (!(m = dbus_message_new_method_call(
1062 "org.freedesktop.systemd1",
1063 "/org/freedesktop/systemd1",
1064 "org.freedesktop.systemd1.Manager",
1068 if (!dbus_message_append_args(m,
1069 DBUS_TYPE_STRING, &unit,
1073 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1076 if (!dbus_message_get_args(reply, NULL,
1077 DBUS_TYPE_OBJECT_PATH, &path,
1081 dbus_message_unref(m);
1082 if (!(m = dbus_message_new_method_call(
1083 "org.freedesktop.systemd1",
1085 "org.freedesktop.DBus.Properties",
1089 if (!dbus_message_append_args(m,
1090 DBUS_TYPE_STRING, &interface,
1091 DBUS_TYPE_STRING, &property,
1092 DBUS_TYPE_INVALID)) {
1096 dbus_message_unref(reply);
1097 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1100 if (!dbus_message_iter_init(reply, &iter) ||
1101 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1104 dbus_message_iter_recurse(&iter, &sub);
1106 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1109 dbus_message_iter_get_basic(&sub, &b);
1113 dbus_message_unref(m);
1116 dbus_message_unref(reply);
1121 typedef struct WaitData {
1126 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1134 dbus_error_init(&error);
1136 log_debug("Got D-Bus request: %s.%s() on %s",
1137 dbus_message_get_interface(message),
1138 dbus_message_get_member(message),
1139 dbus_message_get_path(message));
1141 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1142 log_error("Warning! D-Bus connection terminated.");
1143 dbus_connection_close(connection);
1145 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1148 dbus_bool_t success = true;
1150 if (!dbus_message_get_args(message, &error,
1151 DBUS_TYPE_UINT32, &id,
1152 DBUS_TYPE_OBJECT_PATH, &path,
1153 DBUS_TYPE_BOOLEAN, &success,
1155 log_error("Failed to parse message: %s", bus_error_message(&error));
1159 if ((p = set_remove(d->set, (char*) path)))
1167 dbus_error_free(&error);
1168 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1171 static int enable_wait_for_jobs(DBusConnection *bus) {
1179 dbus_error_init(&error);
1180 dbus_bus_add_match(bus,
1182 "sender='org.freedesktop.systemd1',"
1183 "interface='org.freedesktop.systemd1.Manager',"
1184 "member='JobRemoved',"
1185 "path='/org/freedesktop/systemd1'",
1188 if (dbus_error_is_set(&error)) {
1189 log_error("Failed to add match: %s", bus_error_message(&error));
1190 dbus_error_free(&error);
1194 /* This is slightly dirty, since we don't undo the match registrations. */
1198 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1209 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1210 log_error("Failed to add filter.");
1215 while (!set_isempty(s) &&
1216 dbus_connection_read_write_dispatch(bus, -1))
1219 if (!arg_quiet && d.failed)
1220 log_error("Job failed. See system logs and 'systemctl status' for details.");
1222 r = d.failed ? -EIO : 0;
1225 /* This is slightly dirty, since we don't undo the filter registration. */
1230 static int start_unit_one(
1231 DBusConnection *bus,
1238 DBusMessage *m = NULL, *reply = NULL;
1247 assert(arg_no_block || s);
1249 if (!(m = dbus_message_new_method_call(
1250 "org.freedesktop.systemd1",
1251 "/org/freedesktop/systemd1",
1252 "org.freedesktop.systemd1.Manager",
1254 log_error("Could not allocate message.");
1259 if (!dbus_message_append_args(m,
1260 DBUS_TYPE_STRING, &name,
1261 DBUS_TYPE_STRING, &mode,
1262 DBUS_TYPE_INVALID)) {
1263 log_error("Could not append arguments to message.");
1268 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1270 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1271 /* There's always a fallback possible for
1272 * legacy actions. */
1277 log_error("Failed to issue method call: %s", bus_error_message(error));
1282 if (!dbus_message_get_args(reply, error,
1283 DBUS_TYPE_OBJECT_PATH, &path,
1284 DBUS_TYPE_INVALID)) {
1285 log_error("Failed to parse reply: %s", bus_error_message(error));
1290 if (need_daemon_reload(bus, name))
1291 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1292 arg_user ? "--user" : "--system");
1294 if (!arg_no_block) {
1297 if (!(p = strdup(path))) {
1298 log_error("Failed to duplicate path.");
1303 if ((r = set_put(s, p)) < 0) {
1305 log_error("Failed to add path to set.");
1314 dbus_message_unref(m);
1317 dbus_message_unref(reply);
1322 static enum action verb_to_action(const char *verb) {
1323 if (streq(verb, "halt"))
1325 else if (streq(verb, "poweroff"))
1326 return ACTION_POWEROFF;
1327 else if (streq(verb, "reboot"))
1328 return ACTION_REBOOT;
1329 else if (streq(verb, "kexec"))
1330 return ACTION_KEXEC;
1331 else if (streq(verb, "rescue"))
1332 return ACTION_RESCUE;
1333 else if (streq(verb, "emergency"))
1334 return ACTION_EMERGENCY;
1335 else if (streq(verb, "default"))
1336 return ACTION_DEFAULT;
1337 else if (streq(verb, "exit"))
1340 return ACTION_INVALID;
1343 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1345 static const char * const table[_ACTION_MAX] = {
1346 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1347 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1348 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1349 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1350 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1351 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1352 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1353 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1354 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1355 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1356 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1357 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1362 const char *method, *mode, *one_name;
1366 dbus_error_init(&error);
1370 spawn_ask_password_agent();
1372 if (arg_action == ACTION_SYSTEMCTL) {
1374 streq(args[0], "stop") ? "StopUnit" :
1375 streq(args[0], "reload") ? "ReloadUnit" :
1376 streq(args[0], "restart") ? "RestartUnit" :
1377 streq(args[0], "try-restart") ||
1378 streq(args[0], "condrestart") ? "TryRestartUnit" :
1379 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1380 streq(args[0], "reload-or-try-restart") ||
1381 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1385 (streq(args[0], "isolate") ||
1386 streq(args[0], "rescue") ||
1387 streq(args[0], "emergency")) ? "isolate" :
1391 one_name = table[verb_to_action(args[0])];
1394 assert(arg_action < ELEMENTSOF(table));
1395 assert(table[arg_action]);
1397 method = "StartUnit";
1399 mode = (arg_action == ACTION_EMERGENCY ||
1400 arg_action == ACTION_RESCUE ||
1401 arg_action == ACTION_RUNLEVEL2 ||
1402 arg_action == ACTION_RUNLEVEL3 ||
1403 arg_action == ACTION_RUNLEVEL4 ||
1404 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1406 one_name = table[arg_action];
1409 if (!arg_no_block) {
1410 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1411 log_error("Could not watch jobs: %s", strerror(-ret));
1415 if (!(s = set_new(string_hash_func, string_compare_func))) {
1416 log_error("Failed to allocate set.");
1423 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1426 for (i = 1; i < n; i++)
1427 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1428 ret = translate_bus_error_to_exit_status(r, &error);
1429 dbus_error_free(&error);
1434 if ((r = wait_for_jobs(bus, s)) < 0) {
1443 dbus_error_free(&error);
1448 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1455 (streq(args[0], "halt") ||
1456 streq(args[0], "poweroff") ||
1457 streq(args[0], "reboot") ||
1458 streq(args[0], "kexec") ||
1459 streq(args[0], "exit")))
1460 return daemon_reload(bus, args, n);
1462 r = start_unit(bus, args, n);
1465 warn_wall(verb_to_action(args[0]));
1470 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1471 DBusMessage *m = NULL, *reply = NULL;
1473 *interface = "org.freedesktop.systemd1.Unit",
1474 *property = "ActiveState";
1475 int r = 3; /* According to LSB: "program is not running" */
1482 dbus_error_init(&error);
1484 for (i = 1; i < n; i++) {
1485 const char *path = NULL;
1487 DBusMessageIter iter, sub;
1489 if (!(m = dbus_message_new_method_call(
1490 "org.freedesktop.systemd1",
1491 "/org/freedesktop/systemd1",
1492 "org.freedesktop.systemd1.Manager",
1494 log_error("Could not allocate message.");
1499 if (!dbus_message_append_args(m,
1500 DBUS_TYPE_STRING, &args[i],
1501 DBUS_TYPE_INVALID)) {
1502 log_error("Could not append arguments to message.");
1507 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1509 /* Hmm, cannot figure out anything about this unit... */
1513 dbus_error_free(&error);
1514 dbus_message_unref(m);
1518 if (!dbus_message_get_args(reply, &error,
1519 DBUS_TYPE_OBJECT_PATH, &path,
1520 DBUS_TYPE_INVALID)) {
1521 log_error("Failed to parse reply: %s", bus_error_message(&error));
1526 dbus_message_unref(m);
1527 if (!(m = dbus_message_new_method_call(
1528 "org.freedesktop.systemd1",
1530 "org.freedesktop.DBus.Properties",
1532 log_error("Could not allocate message.");
1537 if (!dbus_message_append_args(m,
1538 DBUS_TYPE_STRING, &interface,
1539 DBUS_TYPE_STRING, &property,
1540 DBUS_TYPE_INVALID)) {
1541 log_error("Could not append arguments to message.");
1546 dbus_message_unref(reply);
1547 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1548 log_error("Failed to issue method call: %s", bus_error_message(&error));
1553 if (!dbus_message_iter_init(reply, &iter) ||
1554 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1555 log_error("Failed to parse reply.");
1560 dbus_message_iter_recurse(&iter, &sub);
1562 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1563 log_error("Failed to parse reply.");
1568 dbus_message_iter_get_basic(&sub, &state);
1573 if (streq(state, "active") || streq(state, "reloading"))
1576 dbus_message_unref(m);
1577 dbus_message_unref(reply);
1583 dbus_message_unref(m);
1586 dbus_message_unref(reply);
1588 dbus_error_free(&error);
1593 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1594 DBusMessage *m = NULL, *reply = NULL;
1602 dbus_error_init(&error);
1605 arg_kill_who = "all";
1608 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1610 for (i = 1; i < n; i++) {
1612 if (!(m = dbus_message_new_method_call(
1613 "org.freedesktop.systemd1",
1614 "/org/freedesktop/systemd1",
1615 "org.freedesktop.systemd1.Manager",
1617 log_error("Could not allocate message.");
1622 if (!dbus_message_append_args(m,
1623 DBUS_TYPE_STRING, &args[i],
1624 DBUS_TYPE_STRING, &arg_kill_who,
1625 DBUS_TYPE_STRING, &arg_kill_mode,
1626 DBUS_TYPE_INT32, &arg_signal,
1627 DBUS_TYPE_INVALID)) {
1628 log_error("Could not append arguments to message.");
1633 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1634 log_error("Failed to issue method call: %s", bus_error_message(&error));
1635 dbus_error_free(&error);
1639 dbus_message_unref(m);
1642 dbus_message_unref(reply);
1648 dbus_message_unref(m);
1651 dbus_message_unref(reply);
1653 dbus_error_free(&error);
1658 typedef struct ExecStatusInfo {
1666 usec_t start_timestamp;
1667 usec_t exit_timestamp;
1672 LIST_FIELDS(struct ExecStatusInfo, exec);
1675 static void exec_status_info_free(ExecStatusInfo *i) {
1684 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1685 uint64_t start_timestamp, exit_timestamp;
1686 DBusMessageIter sub2, sub3;
1690 int32_t code, status;
1696 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1699 dbus_message_iter_recurse(sub, &sub2);
1701 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1704 if (!(i->path = strdup(path)))
1707 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1708 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1712 dbus_message_iter_recurse(&sub2, &sub3);
1713 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1714 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1715 dbus_message_iter_next(&sub3);
1720 if (!(i->argv = new0(char*, n+1)))
1724 dbus_message_iter_recurse(&sub2, &sub3);
1725 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1728 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1729 dbus_message_iter_get_basic(&sub3, &s);
1730 dbus_message_iter_next(&sub3);
1732 if (!(i->argv[n++] = strdup(s)))
1736 if (!dbus_message_iter_next(&sub2) ||
1737 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1738 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1739 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1740 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1741 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1742 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1746 i->start_timestamp = (usec_t) start_timestamp;
1747 i->exit_timestamp = (usec_t) exit_timestamp;
1748 i->pid = (pid_t) pid;
1755 typedef struct UnitStatusInfo {
1757 const char *load_state;
1758 const char *active_state;
1759 const char *sub_state;
1761 const char *description;
1762 const char *following;
1765 const char *default_control_group;
1767 usec_t inactive_exit_timestamp;
1768 usec_t active_enter_timestamp;
1769 usec_t active_exit_timestamp;
1770 usec_t inactive_enter_timestamp;
1772 bool need_daemon_reload;
1777 const char *status_text;
1779 #ifdef HAVE_SYSV_COMPAT
1783 usec_t start_timestamp;
1784 usec_t exit_timestamp;
1786 int exit_code, exit_status;
1789 unsigned n_accepted;
1790 unsigned n_connections;
1794 const char *sysfs_path;
1796 /* Mount, Automount */
1802 LIST_HEAD(ExecStatusInfo, exec);
1805 static void print_status_info(UnitStatusInfo *i) {
1807 const char *on, *off, *ss;
1809 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1810 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1814 /* This shows pretty information about a unit. See
1815 * print_property() for a low-level property printer */
1817 printf("%s", strna(i->id));
1819 if (i->description && !streq_ptr(i->id, i->description))
1820 printf(" - %s", i->description);
1825 printf("\t Follow: unit currently follows state of %s\n", i->following);
1827 if (streq_ptr(i->load_state, "failed") ||
1828 streq_ptr(i->load_state, "banned")) {
1829 on = ansi_highlight(true);
1830 off = ansi_highlight(false);
1835 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1837 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1839 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1841 if (streq_ptr(i->active_state, "failed")) {
1842 on = ansi_highlight(true);
1843 off = ansi_highlight(false);
1844 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1845 on = ansi_highlight_green(true);
1846 off = ansi_highlight_green(false);
1851 printf("\t Active: %s%s (%s)%s",
1853 strna(i->active_state),
1857 printf("\t Active: %s%s%s",
1859 strna(i->active_state),
1862 timestamp = (streq_ptr(i->active_state, "active") ||
1863 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1864 (streq_ptr(i->active_state, "inactive") ||
1865 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1866 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1867 i->active_exit_timestamp;
1869 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1870 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1873 printf(" since %s; %s\n", s2, s1);
1875 printf(" since %s\n", s2);
1880 printf("\t Device: %s\n", i->sysfs_path);
1882 printf("\t Where: %s\n", i->where);
1884 printf("\t What: %s\n", i->what);
1887 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1889 LIST_FOREACH(exec, p, i->exec) {
1893 /* Only show exited processes here */
1897 t = strv_join(p->argv, " ");
1898 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1901 #ifdef HAVE_SYSV_COMPAT
1903 good = is_clean_exit_lsb(p->code, p->status);
1906 good = is_clean_exit(p->code, p->status);
1909 on = ansi_highlight(true);
1910 off = ansi_highlight(false);
1914 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1916 if (p->code == CLD_EXITED) {
1919 printf("status=%i", p->status);
1921 #ifdef HAVE_SYSV_COMPAT
1922 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1924 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1929 printf("signal=%s", signal_to_string(p->status));
1931 printf(")%s\n", off);
1935 if (i->main_pid == p->pid &&
1936 i->start_timestamp == p->start_timestamp &&
1937 i->exit_timestamp == p->start_timestamp)
1938 /* Let's not show this twice */
1941 if (p->pid == i->control_pid)
1945 if (i->main_pid > 0 || i->control_pid > 0) {
1948 if (i->main_pid > 0) {
1949 printf("Main PID: %u", (unsigned) i->main_pid);
1953 get_process_name(i->main_pid, &t);
1958 } else if (i->exit_code > 0) {
1959 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1961 if (i->exit_code == CLD_EXITED) {
1964 printf("status=%i", i->exit_status);
1966 #ifdef HAVE_SYSV_COMPAT
1967 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1969 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1974 printf("signal=%s", signal_to_string(i->exit_status));
1979 if (i->main_pid > 0 && i->control_pid > 0)
1982 if (i->control_pid > 0) {
1985 printf(" Control: %u", (unsigned) i->control_pid);
1987 get_process_name(i->control_pid, &t);
1998 printf("\t Status: \"%s\"\n", i->status_text);
2000 if (i->default_control_group) {
2003 printf("\t CGroup: %s\n", i->default_control_group);
2005 if ((c = columns()) > 18)
2010 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2013 if (i->need_daemon_reload)
2014 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2015 ansi_highlight(true),
2016 ansi_highlight(false),
2017 arg_user ? "--user" : "--system");
2020 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2022 switch (dbus_message_iter_get_arg_type(iter)) {
2024 case DBUS_TYPE_STRING: {
2027 dbus_message_iter_get_basic(iter, &s);
2030 if (streq(name, "Id"))
2032 else if (streq(name, "LoadState"))
2034 else if (streq(name, "ActiveState"))
2035 i->active_state = s;
2036 else if (streq(name, "SubState"))
2038 else if (streq(name, "Description"))
2040 else if (streq(name, "FragmentPath"))
2042 #ifdef HAVE_SYSV_COMPAT
2043 else if (streq(name, "SysVPath")) {
2048 else if (streq(name, "DefaultControlGroup"))
2049 i->default_control_group = s;
2050 else if (streq(name, "StatusText"))
2052 else if (streq(name, "SysFSPath"))
2054 else if (streq(name, "Where"))
2056 else if (streq(name, "What"))
2058 else if (streq(name, "Following"))
2065 case DBUS_TYPE_BOOLEAN: {
2068 dbus_message_iter_get_basic(iter, &b);
2070 if (streq(name, "Accept"))
2072 else if (streq(name, "NeedDaemonReload"))
2073 i->need_daemon_reload = b;
2078 case DBUS_TYPE_UINT32: {
2081 dbus_message_iter_get_basic(iter, &u);
2083 if (streq(name, "MainPID")) {
2085 i->main_pid = (pid_t) u;
2088 } else if (streq(name, "ControlPID"))
2089 i->control_pid = (pid_t) u;
2090 else if (streq(name, "ExecMainPID")) {
2092 i->main_pid = (pid_t) u;
2093 } else if (streq(name, "NAccepted"))
2095 else if (streq(name, "NConnections"))
2096 i->n_connections = u;
2101 case DBUS_TYPE_INT32: {
2104 dbus_message_iter_get_basic(iter, &j);
2106 if (streq(name, "ExecMainCode"))
2107 i->exit_code = (int) j;
2108 else if (streq(name, "ExecMainStatus"))
2109 i->exit_status = (int) j;
2114 case DBUS_TYPE_UINT64: {
2117 dbus_message_iter_get_basic(iter, &u);
2119 if (streq(name, "ExecMainStartTimestamp"))
2120 i->start_timestamp = (usec_t) u;
2121 else if (streq(name, "ExecMainExitTimestamp"))
2122 i->exit_timestamp = (usec_t) u;
2123 else if (streq(name, "ActiveEnterTimestamp"))
2124 i->active_enter_timestamp = (usec_t) u;
2125 else if (streq(name, "InactiveEnterTimestamp"))
2126 i->inactive_enter_timestamp = (usec_t) u;
2127 else if (streq(name, "InactiveExitTimestamp"))
2128 i->inactive_exit_timestamp = (usec_t) u;
2129 else if (streq(name, "ActiveExitTimestamp"))
2130 i->active_exit_timestamp = (usec_t) u;
2135 case DBUS_TYPE_ARRAY: {
2137 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2138 startswith(name, "Exec")) {
2139 DBusMessageIter sub;
2141 dbus_message_iter_recurse(iter, &sub);
2142 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2143 ExecStatusInfo *info;
2146 if (!(info = new0(ExecStatusInfo, 1)))
2149 if (!(info->name = strdup(name))) {
2154 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2159 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2161 dbus_message_iter_next(&sub);
2172 static int print_property(const char *name, DBusMessageIter *iter) {
2176 /* This is a low-level property printer, see
2177 * print_status_info() for the nicer output */
2179 if (arg_property && !strv_find(arg_property, name))
2182 switch (dbus_message_iter_get_arg_type(iter)) {
2184 case DBUS_TYPE_STRING: {
2186 dbus_message_iter_get_basic(iter, &s);
2188 if (arg_all || s[0])
2189 printf("%s=%s\n", name, s);
2194 case DBUS_TYPE_BOOLEAN: {
2196 dbus_message_iter_get_basic(iter, &b);
2197 printf("%s=%s\n", name, yes_no(b));
2202 case DBUS_TYPE_UINT64: {
2204 dbus_message_iter_get_basic(iter, &u);
2206 /* Yes, heuristics! But we can change this check
2207 * should it turn out to not be sufficient */
2209 if (strstr(name, "Timestamp")) {
2210 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2212 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2213 printf("%s=%s\n", name, strempty(t));
2214 } else if (strstr(name, "USec")) {
2215 char timespan[FORMAT_TIMESPAN_MAX];
2217 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2219 printf("%s=%llu\n", name, (unsigned long long) u);
2224 case DBUS_TYPE_UINT32: {
2226 dbus_message_iter_get_basic(iter, &u);
2228 if (strstr(name, "UMask") || strstr(name, "Mode"))
2229 printf("%s=%04o\n", name, u);
2231 printf("%s=%u\n", name, (unsigned) u);
2236 case DBUS_TYPE_INT32: {
2238 dbus_message_iter_get_basic(iter, &i);
2240 printf("%s=%i\n", name, (int) i);
2244 case DBUS_TYPE_DOUBLE: {
2246 dbus_message_iter_get_basic(iter, &d);
2248 printf("%s=%g\n", name, d);
2252 case DBUS_TYPE_STRUCT: {
2253 DBusMessageIter sub;
2254 dbus_message_iter_recurse(iter, &sub);
2256 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2259 dbus_message_iter_get_basic(&sub, &u);
2262 printf("%s=%u\n", name, (unsigned) u);
2264 printf("%s=\n", name);
2267 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2270 dbus_message_iter_get_basic(&sub, &s);
2272 if (arg_all || s[0])
2273 printf("%s=%s\n", name, s);
2281 case DBUS_TYPE_ARRAY:
2283 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2284 DBusMessageIter sub;
2287 dbus_message_iter_recurse(iter, &sub);
2289 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2290 printf("%s=", name);
2292 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2295 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2296 dbus_message_iter_get_basic(&sub, &s);
2297 printf("%s%s", space ? " " : "", s);
2300 dbus_message_iter_next(&sub);
2308 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2309 DBusMessageIter sub;
2311 dbus_message_iter_recurse(iter, &sub);
2313 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2314 printf("%s=", name);
2316 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2319 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2320 dbus_message_iter_get_basic(&sub, &u);
2323 dbus_message_iter_next(&sub);
2331 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2332 DBusMessageIter sub, sub2;
2334 dbus_message_iter_recurse(iter, &sub);
2335 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2336 const char *type, *path;
2338 dbus_message_iter_recurse(&sub, &sub2);
2340 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2341 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2342 printf("%s=%s\n", type, path);
2344 dbus_message_iter_next(&sub);
2349 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2350 DBusMessageIter sub, sub2;
2352 dbus_message_iter_recurse(iter, &sub);
2353 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2355 uint64_t value, next_elapse;
2357 dbus_message_iter_recurse(&sub, &sub2);
2359 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2360 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2361 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2362 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2364 printf("%s={ value=%s ; next_elapse=%s }\n",
2366 format_timespan(timespan1, sizeof(timespan1), value),
2367 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2370 dbus_message_iter_next(&sub);
2375 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2376 DBusMessageIter sub;
2378 dbus_message_iter_recurse(iter, &sub);
2379 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2380 ExecStatusInfo info;
2383 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2384 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2387 t = strv_join(info.argv, " ");
2389 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2393 yes_no(info.ignore),
2394 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2395 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2396 (unsigned) info. pid,
2397 sigchld_code_to_string(info.code),
2399 info.code == CLD_EXITED ? "" : "/",
2400 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2406 strv_free(info.argv);
2408 dbus_message_iter_next(&sub);
2418 printf("%s=[unprintable]\n", name);
2423 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2424 DBusMessage *m = NULL, *reply = NULL;
2425 const char *interface = "";
2428 DBusMessageIter iter, sub, sub2, sub3;
2429 UnitStatusInfo info;
2437 dbus_error_init(&error);
2439 if (!(m = dbus_message_new_method_call(
2440 "org.freedesktop.systemd1",
2442 "org.freedesktop.DBus.Properties",
2444 log_error("Could not allocate message.");
2449 if (!dbus_message_append_args(m,
2450 DBUS_TYPE_STRING, &interface,
2451 DBUS_TYPE_INVALID)) {
2452 log_error("Could not append arguments to message.");
2457 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2458 log_error("Failed to issue method call: %s", bus_error_message(&error));
2463 if (!dbus_message_iter_init(reply, &iter) ||
2464 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2465 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2466 log_error("Failed to parse reply.");
2471 dbus_message_iter_recurse(&iter, &sub);
2478 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2481 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2482 log_error("Failed to parse reply.");
2487 dbus_message_iter_recurse(&sub, &sub2);
2489 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2490 log_error("Failed to parse reply.");
2495 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2496 log_error("Failed to parse reply.");
2501 dbus_message_iter_recurse(&sub2, &sub3);
2503 if (show_properties)
2504 r = print_property(name, &sub3);
2506 r = status_property(name, &sub3, &info);
2509 log_error("Failed to parse reply.");
2514 dbus_message_iter_next(&sub);
2519 if (!show_properties)
2520 print_status_info(&info);
2522 if (!streq_ptr(info.active_state, "active") &&
2523 !streq_ptr(info.active_state, "reloading") &&
2524 streq(verb, "status"))
2525 /* According to LSB: "program not running" */
2528 while ((p = info.exec)) {
2529 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2530 exec_status_info_free(p);
2535 dbus_message_unref(m);
2538 dbus_message_unref(reply);
2540 dbus_error_free(&error);
2545 static int show(DBusConnection *bus, char **args, unsigned n) {
2546 DBusMessage *m = NULL, *reply = NULL;
2550 bool show_properties, new_line = false;
2555 dbus_error_init(&error);
2557 show_properties = !streq(args[0], "status");
2559 if (show_properties)
2562 if (show_properties && n <= 1) {
2563 /* If not argument is specified inspect the manager
2566 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2570 for (i = 1; i < n; i++) {
2571 const char *path = NULL;
2574 if (safe_atou32(args[i], &id) < 0) {
2576 /* Interpret as unit name */
2578 if (!(m = dbus_message_new_method_call(
2579 "org.freedesktop.systemd1",
2580 "/org/freedesktop/systemd1",
2581 "org.freedesktop.systemd1.Manager",
2583 log_error("Could not allocate message.");
2588 if (!dbus_message_append_args(m,
2589 DBUS_TYPE_STRING, &args[i],
2590 DBUS_TYPE_INVALID)) {
2591 log_error("Could not append arguments to message.");
2596 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2598 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2599 log_error("Failed to issue method call: %s", bus_error_message(&error));
2604 dbus_error_free(&error);
2606 dbus_message_unref(m);
2607 if (!(m = dbus_message_new_method_call(
2608 "org.freedesktop.systemd1",
2609 "/org/freedesktop/systemd1",
2610 "org.freedesktop.systemd1.Manager",
2612 log_error("Could not allocate message.");
2617 if (!dbus_message_append_args(m,
2618 DBUS_TYPE_STRING, &args[i],
2619 DBUS_TYPE_INVALID)) {
2620 log_error("Could not append arguments to message.");
2625 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2626 log_error("Failed to issue method call: %s", bus_error_message(&error));
2628 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2629 ret = 4; /* According to LSB: "program or service status is unknown" */
2636 } else if (show_properties) {
2638 /* Interpret as job id */
2640 if (!(m = dbus_message_new_method_call(
2641 "org.freedesktop.systemd1",
2642 "/org/freedesktop/systemd1",
2643 "org.freedesktop.systemd1.Manager",
2645 log_error("Could not allocate message.");
2650 if (!dbus_message_append_args(m,
2651 DBUS_TYPE_UINT32, &id,
2652 DBUS_TYPE_INVALID)) {
2653 log_error("Could not append arguments to message.");
2658 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2659 log_error("Failed to issue method call: %s", bus_error_message(&error));
2665 /* Interpret as PID */
2667 if (!(m = dbus_message_new_method_call(
2668 "org.freedesktop.systemd1",
2669 "/org/freedesktop/systemd1",
2670 "org.freedesktop.systemd1.Manager",
2672 log_error("Could not allocate message.");
2677 if (!dbus_message_append_args(m,
2678 DBUS_TYPE_UINT32, &id,
2679 DBUS_TYPE_INVALID)) {
2680 log_error("Could not append arguments to message.");
2685 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2686 log_error("Failed to issue method call: %s", bus_error_message(&error));
2692 if (!dbus_message_get_args(reply, &error,
2693 DBUS_TYPE_OBJECT_PATH, &path,
2694 DBUS_TYPE_INVALID)) {
2695 log_error("Failed to parse reply: %s", bus_error_message(&error));
2700 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2703 dbus_message_unref(m);
2704 dbus_message_unref(reply);
2710 dbus_message_unref(m);
2713 dbus_message_unref(reply);
2715 dbus_error_free(&error);
2720 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2722 DBusMessage *m = NULL, *reply = NULL;
2727 dbus_error_init(&error);
2729 log_debug("Got D-Bus request: %s.%s() on %s",
2730 dbus_message_get_interface(message),
2731 dbus_message_get_member(message),
2732 dbus_message_get_path(message));
2734 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2735 log_error("Warning! D-Bus connection terminated.");
2736 dbus_connection_close(connection);
2738 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2739 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2740 const char *id, *path;
2742 if (!dbus_message_get_args(message, &error,
2743 DBUS_TYPE_STRING, &id,
2744 DBUS_TYPE_OBJECT_PATH, &path,
2746 log_error("Failed to parse message: %s", bus_error_message(&error));
2747 else if (streq(dbus_message_get_member(message), "UnitNew"))
2748 printf("Unit %s added.\n", id);
2750 printf("Unit %s removed.\n", id);
2752 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2753 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2757 if (!dbus_message_get_args(message, &error,
2758 DBUS_TYPE_UINT32, &id,
2759 DBUS_TYPE_OBJECT_PATH, &path,
2761 log_error("Failed to parse message: %s", bus_error_message(&error));
2762 else if (streq(dbus_message_get_member(message), "JobNew"))
2763 printf("Job %u added.\n", id);
2765 printf("Job %u removed.\n", id);
2768 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2770 const char *path, *interface, *property = "Id";
2771 DBusMessageIter iter, sub;
2773 path = dbus_message_get_path(message);
2775 if (!dbus_message_get_args(message, &error,
2776 DBUS_TYPE_STRING, &interface,
2777 DBUS_TYPE_INVALID)) {
2778 log_error("Failed to parse message: %s", bus_error_message(&error));
2782 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2783 !streq(interface, "org.freedesktop.systemd1.Unit"))
2786 if (!(m = dbus_message_new_method_call(
2787 "org.freedesktop.systemd1",
2789 "org.freedesktop.DBus.Properties",
2791 log_error("Could not allocate message.");
2795 if (!dbus_message_append_args(m,
2796 DBUS_TYPE_STRING, &interface,
2797 DBUS_TYPE_STRING, &property,
2798 DBUS_TYPE_INVALID)) {
2799 log_error("Could not append arguments to message.");
2803 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2804 log_error("Failed to issue method call: %s", bus_error_message(&error));
2808 if (!dbus_message_iter_init(reply, &iter) ||
2809 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2810 log_error("Failed to parse reply.");
2814 dbus_message_iter_recurse(&iter, &sub);
2816 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2819 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2820 log_error("Failed to parse reply.");
2824 dbus_message_iter_get_basic(&sub, &id);
2825 printf("Unit %s changed.\n", id);
2829 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2830 log_error("Failed to parse reply.");
2834 dbus_message_iter_get_basic(&sub, &id);
2835 printf("Job %u changed.\n", id);
2841 dbus_message_unref(m);
2844 dbus_message_unref(reply);
2846 dbus_error_free(&error);
2847 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2851 dbus_message_unref(m);
2854 dbus_message_unref(reply);
2856 dbus_error_free(&error);
2857 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2860 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2861 DBusMessage *m = NULL, *reply = NULL;
2865 dbus_error_init(&error);
2868 dbus_bus_add_match(bus,
2870 "sender='org.freedesktop.systemd1',"
2871 "interface='org.freedesktop.systemd1.Manager',"
2872 "path='/org/freedesktop/systemd1'",
2875 if (dbus_error_is_set(&error)) {
2876 log_error("Failed to add match: %s", bus_error_message(&error));
2881 dbus_bus_add_match(bus,
2883 "sender='org.freedesktop.systemd1',"
2884 "interface='org.freedesktop.DBus.Properties',"
2885 "member='PropertiesChanged'",
2888 if (dbus_error_is_set(&error)) {
2889 log_error("Failed to add match: %s", bus_error_message(&error));
2895 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2896 log_error("Failed to add filter.");
2901 if (!(m = dbus_message_new_method_call(
2902 "org.freedesktop.systemd1",
2903 "/org/freedesktop/systemd1",
2904 "org.freedesktop.systemd1.Manager",
2906 log_error("Could not allocate message.");
2911 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2912 log_error("Failed to issue method call: %s", bus_error_message(&error));
2917 while (dbus_connection_read_write_dispatch(bus, -1))
2924 /* This is slightly dirty, since we don't undo the filter or the matches. */
2927 dbus_message_unref(m);
2930 dbus_message_unref(reply);
2932 dbus_error_free(&error);
2937 static int dump(DBusConnection *bus, char **args, unsigned n) {
2938 DBusMessage *m = NULL, *reply = NULL;
2943 dbus_error_init(&error);
2947 if (!(m = dbus_message_new_method_call(
2948 "org.freedesktop.systemd1",
2949 "/org/freedesktop/systemd1",
2950 "org.freedesktop.systemd1.Manager",
2952 log_error("Could not allocate message.");
2956 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2957 log_error("Failed to issue method call: %s", bus_error_message(&error));
2962 if (!dbus_message_get_args(reply, &error,
2963 DBUS_TYPE_STRING, &text,
2964 DBUS_TYPE_INVALID)) {
2965 log_error("Failed to parse reply: %s", bus_error_message(&error));
2970 fputs(text, stdout);
2976 dbus_message_unref(m);
2979 dbus_message_unref(reply);
2981 dbus_error_free(&error);
2986 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2987 DBusMessage *m = NULL, *reply = NULL;
2990 const char *name = "", *path, *id;
2991 dbus_bool_t cleanup = FALSE;
2992 DBusMessageIter iter, sub;
2994 *interface = "org.freedesktop.systemd1.Unit",
2997 dbus_error_init(&error);
2999 if (!(m = dbus_message_new_method_call(
3000 "org.freedesktop.systemd1",
3001 "/org/freedesktop/systemd1",
3002 "org.freedesktop.systemd1.Manager",
3003 "CreateSnapshot"))) {
3004 log_error("Could not allocate message.");
3011 if (!dbus_message_append_args(m,
3012 DBUS_TYPE_STRING, &name,
3013 DBUS_TYPE_BOOLEAN, &cleanup,
3014 DBUS_TYPE_INVALID)) {
3015 log_error("Could not append arguments to message.");
3020 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3021 log_error("Failed to issue method call: %s", bus_error_message(&error));
3026 if (!dbus_message_get_args(reply, &error,
3027 DBUS_TYPE_OBJECT_PATH, &path,
3028 DBUS_TYPE_INVALID)) {
3029 log_error("Failed to parse reply: %s", bus_error_message(&error));
3034 dbus_message_unref(m);
3035 if (!(m = dbus_message_new_method_call(
3036 "org.freedesktop.systemd1",
3038 "org.freedesktop.DBus.Properties",
3040 log_error("Could not allocate message.");
3044 if (!dbus_message_append_args(m,
3045 DBUS_TYPE_STRING, &interface,
3046 DBUS_TYPE_STRING, &property,
3047 DBUS_TYPE_INVALID)) {
3048 log_error("Could not append arguments to message.");
3053 dbus_message_unref(reply);
3054 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3055 log_error("Failed to issue method call: %s", bus_error_message(&error));
3060 if (!dbus_message_iter_init(reply, &iter) ||
3061 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3062 log_error("Failed to parse reply.");
3067 dbus_message_iter_recurse(&iter, &sub);
3069 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3070 log_error("Failed to parse reply.");
3075 dbus_message_iter_get_basic(&sub, &id);
3083 dbus_message_unref(m);
3086 dbus_message_unref(reply);
3088 dbus_error_free(&error);
3093 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3094 DBusMessage *m = NULL, *reply = NULL;
3102 dbus_error_init(&error);
3104 for (i = 1; i < n; i++) {
3105 const char *path = NULL;
3107 if (!(m = dbus_message_new_method_call(
3108 "org.freedesktop.systemd1",
3109 "/org/freedesktop/systemd1",
3110 "org.freedesktop.systemd1.Manager",
3112 log_error("Could not allocate message.");
3117 if (!dbus_message_append_args(m,
3118 DBUS_TYPE_STRING, &args[i],
3119 DBUS_TYPE_INVALID)) {
3120 log_error("Could not append arguments to message.");
3125 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3126 log_error("Failed to issue method call: %s", bus_error_message(&error));
3131 if (!dbus_message_get_args(reply, &error,
3132 DBUS_TYPE_OBJECT_PATH, &path,
3133 DBUS_TYPE_INVALID)) {
3134 log_error("Failed to parse reply: %s", bus_error_message(&error));
3139 dbus_message_unref(m);
3140 if (!(m = dbus_message_new_method_call(
3141 "org.freedesktop.systemd1",
3143 "org.freedesktop.systemd1.Snapshot",
3145 log_error("Could not allocate message.");
3150 dbus_message_unref(reply);
3151 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3152 log_error("Failed to issue method call: %s", bus_error_message(&error));
3157 dbus_message_unref(m);
3158 dbus_message_unref(reply);
3166 dbus_message_unref(m);
3169 dbus_message_unref(reply);
3171 dbus_error_free(&error);
3176 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3177 DBusMessage *m = NULL, *reply = NULL;
3182 dbus_error_init(&error);
3184 if (arg_action == ACTION_RELOAD)
3186 else if (arg_action == ACTION_REEXEC)
3187 method = "Reexecute";
3189 assert(arg_action == ACTION_SYSTEMCTL);
3192 streq(args[0], "clear-jobs") ||
3193 streq(args[0], "cancel") ? "ClearJobs" :
3194 streq(args[0], "daemon-reexec") ? "Reexecute" :
3195 streq(args[0], "reset-failed") ? "ResetFailed" :
3196 streq(args[0], "halt") ? "Halt" :
3197 streq(args[0], "poweroff") ? "PowerOff" :
3198 streq(args[0], "reboot") ? "Reboot" :
3199 streq(args[0], "kexec") ? "KExec" :
3200 streq(args[0], "exit") ? "Exit" :
3201 /* "daemon-reload" */ "Reload";
3204 if (!(m = dbus_message_new_method_call(
3205 "org.freedesktop.systemd1",
3206 "/org/freedesktop/systemd1",
3207 "org.freedesktop.systemd1.Manager",
3209 log_error("Could not allocate message.");
3213 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3215 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3216 /* There's always a fallback possible for
3217 * legacy actions. */
3222 log_error("Failed to issue method call: %s", bus_error_message(&error));
3231 dbus_message_unref(m);
3234 dbus_message_unref(reply);
3236 dbus_error_free(&error);
3241 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3242 DBusMessage *m = NULL, *reply = NULL;
3248 dbus_error_init(&error);
3251 return daemon_reload(bus, args, n);
3253 for (i = 1; i < n; i++) {
3255 if (!(m = dbus_message_new_method_call(
3256 "org.freedesktop.systemd1",
3257 "/org/freedesktop/systemd1",
3258 "org.freedesktop.systemd1.Manager",
3259 "ResetFailedUnit"))) {
3260 log_error("Could not allocate message.");
3265 if (!dbus_message_append_args(m,
3266 DBUS_TYPE_STRING, args + i,
3267 DBUS_TYPE_INVALID)) {
3268 log_error("Could not append arguments to message.");
3273 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3274 log_error("Failed to issue method call: %s", bus_error_message(&error));
3279 dbus_message_unref(m);
3280 dbus_message_unref(reply);
3288 dbus_message_unref(m);
3291 dbus_message_unref(reply);
3293 dbus_error_free(&error);
3298 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3299 DBusMessage *m = NULL, *reply = NULL;
3301 DBusMessageIter iter, sub, sub2;
3304 *interface = "org.freedesktop.systemd1.Manager",
3305 *property = "Environment";
3307 dbus_error_init(&error);
3311 if (!(m = dbus_message_new_method_call(
3312 "org.freedesktop.systemd1",
3313 "/org/freedesktop/systemd1",
3314 "org.freedesktop.DBus.Properties",
3316 log_error("Could not allocate message.");
3320 if (!dbus_message_append_args(m,
3321 DBUS_TYPE_STRING, &interface,
3322 DBUS_TYPE_STRING, &property,
3323 DBUS_TYPE_INVALID)) {
3324 log_error("Could not append arguments to message.");
3329 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3330 log_error("Failed to issue method call: %s", bus_error_message(&error));
3335 if (!dbus_message_iter_init(reply, &iter) ||
3336 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3337 log_error("Failed to parse reply.");
3342 dbus_message_iter_recurse(&iter, &sub);
3344 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3345 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3346 log_error("Failed to parse reply.");
3351 dbus_message_iter_recurse(&sub, &sub2);
3353 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3356 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3357 log_error("Failed to parse reply.");
3362 dbus_message_iter_get_basic(&sub2, &text);
3363 printf("%s\n", text);
3365 dbus_message_iter_next(&sub2);
3372 dbus_message_unref(m);
3375 dbus_message_unref(reply);
3377 dbus_error_free(&error);
3382 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3383 DBusMessage *m = NULL, *reply = NULL;
3387 DBusMessageIter iter, sub;
3390 dbus_error_init(&error);
3392 method = streq(args[0], "set-environment")
3394 : "UnsetEnvironment";
3396 if (!(m = dbus_message_new_method_call(
3397 "org.freedesktop.systemd1",
3398 "/org/freedesktop/systemd1",
3399 "org.freedesktop.systemd1.Manager",
3402 log_error("Could not allocate message.");
3406 dbus_message_iter_init_append(m, &iter);
3408 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3409 log_error("Could not append arguments to message.");
3414 for (i = 1; i < n; i++)
3415 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3416 log_error("Could not append arguments to message.");
3421 if (!dbus_message_iter_close_container(&iter, &sub)) {
3422 log_error("Could not append arguments to message.");
3427 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3428 log_error("Failed to issue method call: %s", bus_error_message(&error));
3437 dbus_message_unref(m);
3440 dbus_message_unref(reply);
3442 dbus_error_free(&error);
3455 static Hashmap *will_install = NULL, *have_installed = NULL;
3456 static Set *remove_symlinks_to = NULL;
3457 static unsigned n_symlinks = 0;
3459 static void install_info_free(InstallInfo *i) {
3464 strv_free(i->aliases);
3465 strv_free(i->wanted_by);
3469 static void install_info_hashmap_free(Hashmap *m) {
3472 while ((i = hashmap_steal_first(m)))
3473 install_info_free(i);
3478 static int install_info_add(const char *name) {
3482 assert(will_install);
3484 if (!unit_name_is_valid_no_type(name, true)) {
3485 log_warning("Unit name %s is not a valid unit name.", name);
3489 if (hashmap_get(have_installed, name) ||
3490 hashmap_get(will_install, name))
3493 if (!(i = new0(InstallInfo, 1))) {
3498 if (!(i->name = strdup(name))) {
3503 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3510 install_info_free(i);
3515 static int config_parse_also(
3516 const char *filename,
3518 const char *section,
3532 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3536 if (!(n = strndup(w, l)))
3539 if ((r = install_info_add(n)) < 0) {
3540 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3551 static int mark_symlink_for_removal(const char *p) {
3556 assert(path_is_absolute(p));
3558 if (!remove_symlinks_to)
3561 if (!(n = strdup(p)))
3564 path_kill_slashes(n);
3566 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3568 return r == -EEXIST ? 0 : r;
3574 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3583 if (!(d = fdopendir(fd))) {
3584 close_nointr_nofail(fd);
3590 while ((de = readdir(d))) {
3591 bool is_dir = false, is_link = false;
3593 if (ignore_file(de->d_name))
3596 if (de->d_type == DT_LNK)
3598 else if (de->d_type == DT_DIR)
3600 else if (de->d_type == DT_UNKNOWN) {
3603 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3604 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3611 is_link = S_ISLNK(st.st_mode);
3612 is_dir = S_ISDIR(st.st_mode);
3620 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3621 log_error("Failed to open %s/%s: %m", root, de->d_name);
3628 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3629 log_error("Failed to allocate directory string.");
3630 close_nointr_nofail(nfd);
3635 /* This will close nfd, regardless whether it succeeds or not */
3636 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3642 } else if (is_link) {
3646 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3647 log_error("Failed to allocate symlink string.");
3652 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3653 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3661 if ((c = canonicalize_file_name(dest))) {
3662 /* This might fail if the destination
3663 * is already removed */
3669 path_kill_slashes(dest);
3670 if (set_get(remove_symlinks_to, dest)) {
3673 log_info("rm '%s'", p);
3675 if (unlink(p) < 0) {
3676 log_error("Cannot unlink symlink %s: %m", p);
3681 rmdir_parents(p, config_path);
3682 path_kill_slashes(p);
3684 if (!set_get(remove_symlinks_to, p)) {
3686 if ((r = mark_symlink_for_removal(p)) < 0) {
3705 static int remove_marked_symlinks(const char *config_path) {
3709 assert(config_path);
3711 if (set_size(remove_symlinks_to) <= 0)
3714 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3721 if ((cfd = dup(fd)) < 0) {
3726 /* This takes possession of cfd and closes it */
3727 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3733 close_nointr_nofail(fd);
3738 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3745 if (streq(verb, "enable")) {
3748 mkdir_parents(new_path, 0755);
3750 if (symlink(old_path, new_path) >= 0) {
3753 log_info("ln -s '%s' '%s'", old_path, new_path);
3758 if (errno != EEXIST) {
3759 log_error("Cannot link %s to %s: %m", old_path, new_path);
3763 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3765 if (errno == EINVAL) {
3766 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3770 log_error("readlink() failed: %s", strerror(-r));
3774 if (streq(dest, old_path)) {
3780 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3789 log_info("ln -s '%s' '%s'", old_path, new_path);
3791 if (symlink(old_path, new_path) >= 0)
3794 log_error("Cannot link %s to %s: %m", old_path, new_path);
3797 } else if (streq(verb, "disable")) {
3800 if ((r = mark_symlink_for_removal(old_path)) < 0)
3803 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3804 if (errno == ENOENT)
3807 if (errno == EINVAL) {
3808 log_warning("File %s not a symlink, ignoring.", old_path);
3812 log_error("readlink() failed: %s", strerror(-r));
3816 if (!streq(dest, old_path)) {
3817 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3824 if ((r = mark_symlink_for_removal(new_path)) < 0)
3828 log_info("rm '%s'", new_path);
3830 if (unlink(new_path) >= 0)
3833 log_error("Cannot unlink %s: %m", new_path);
3836 } else if (streq(verb, "is-enabled")) {
3839 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3841 if (errno == ENOENT || errno == EINVAL)
3844 log_error("readlink() failed: %s", strerror(-r));
3848 if (streq(dest, old_path)) {
3856 assert_not_reached("Unknown action.");
3859 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3861 char *alias_path = NULL;
3866 assert(config_path);
3868 STRV_FOREACH(s, i->aliases) {
3871 if (!(alias_path = path_make_absolute(*s, config_path))) {
3872 log_error("Out of memory");
3877 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3880 if (streq(verb, "disable"))
3881 rmdir_parents(alias_path, config_path);
3891 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3893 char *alias_path = NULL;
3898 assert(config_path);
3900 STRV_FOREACH(s, i->wanted_by) {
3901 if (!unit_name_is_valid_no_type(*s, true)) {
3902 log_error("Invalid name %s.", *s);
3910 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3911 log_error("Out of memory");
3916 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3919 if (streq(verb, "disable"))
3920 rmdir_parents(alias_path, config_path);
3931 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3933 const ConfigItem items[] = {
3934 { "Alias", config_parse_strv, &i->aliases, "Install" },
3935 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3936 { "Also", config_parse_also, NULL, "Install" },
3938 { NULL, NULL, NULL, NULL }
3942 char *filename = NULL;
3949 STRV_FOREACH(p, paths->unit_path) {
3952 if (!(filename = path_make_absolute(i->name, *p))) {
3953 log_error("Out of memory");
3957 /* Ensure that we don't follow symlinks */
3958 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3959 if ((f = fdopen(fd, "re")))
3962 if (errno == ELOOP) {
3963 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3968 if (errno != ENOENT) {
3969 log_error("Failed to open %s: %m", filename);
3979 #if defined(TARGET_FEDORA) && defined (HAVE_SYSV_COMPAT)
3981 if (endswith(i->name, ".service")) {
3985 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
3986 log_error("Out of memory");
3990 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
3991 exists = access(sysv, F_OK) >= 0;
3997 const char *argv[] = {
4004 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4006 argv[1] = file_name_from_path(sysv);
4008 streq(verb, "enable") ? "on" :
4009 streq(verb, "disable") ? "off" : NULL;
4011 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
4013 if ((pid = fork()) < 0) {
4014 log_error("Failed to fork: %m");
4017 } else if (pid == 0) {
4018 execv(argv[0], (char**) argv);
4019 _exit(EXIT_FAILURE);
4024 if ((r = wait_for_terminate(pid, &status)) < 0)
4027 if (status.si_code == CLD_EXITED) {
4028 if (status.si_status == 0 && (streq(verb, "enable") || streq(verb, "disable")))
4031 return status.si_status == 0 ? 0 : -EINVAL;
4041 log_error("Couldn't find %s.", i->name);
4047 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4052 n_symlinks += strv_length(i->aliases);
4053 n_symlinks += strv_length(i->wanted_by);
4057 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4060 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4063 if ((r = mark_symlink_for_removal(filename)) < 0)
4066 if ((r = remove_marked_symlinks(config_path)) < 0)
4072 static char *get_config_path(void) {
4074 if (arg_user && arg_global)
4075 return strdup(USER_CONFIG_UNIT_PATH);
4080 if (user_config_home(&p) < 0)
4086 return strdup(SYSTEM_CONFIG_UNIT_PATH);
4089 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4093 char *config_path = NULL;
4096 const char *verb = args[0];
4098 dbus_error_init(&error);
4101 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4102 log_error("Failed to determine lookup paths: %s", strerror(-r));
4106 if (!(config_path = get_config_path())) {
4107 log_error("Failed to determine config path");
4112 will_install = hashmap_new(string_hash_func, string_compare_func);
4113 have_installed = hashmap_new(string_hash_func, string_compare_func);
4115 if (!will_install || !have_installed) {
4116 log_error("Failed to allocate unit sets.");
4121 if (!arg_defaults && streq(verb, "disable"))
4122 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4123 log_error("Failed to allocate symlink sets.");
4128 for (j = 1; j < n; j++)
4129 if ((r = install_info_add(args[j])) < 0) {
4130 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4134 while ((i = hashmap_first(will_install))) {
4137 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4139 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4147 /* In test mode and found something */
4153 if (streq(verb, "is-enabled"))
4154 r = r > 0 ? 0 : -ENOENT;
4156 if (n_symlinks <= 0)
4157 log_warning("Unit files contain no applicable installation information. Ignoring.");
4160 /* Don't try to reload anything if the user asked us to not do this */
4162 /* Don't try to reload anything when updating a unit globally */
4164 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4165 (arg_user || sd_booted() > 0) &&
4166 /* Don't try to reload anything if we are running in a chroot environment */
4167 (arg_user || running_in_chroot() <= 0) ) {
4170 if ((q = daemon_reload(bus, args, n)) < 0)
4176 install_info_hashmap_free(will_install);
4177 install_info_hashmap_free(have_installed);
4179 set_free_free(remove_symlinks_to);
4181 lookup_paths_free(&paths);
4188 static int systemctl_help(void) {
4190 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4191 "Send control commands to or query the systemd manager.\n\n"
4192 " -h --help Show this help\n"
4193 " --version Show package version\n"
4194 " -t --type=TYPE List only units of a particular type\n"
4195 " -p --property=NAME Show only properties by this name\n"
4196 " -a --all Show all units/properties, including dead/empty ones\n"
4197 " --failed Show only failed units\n"
4198 " --full Don't ellipsize unit names on output\n"
4199 " --fail When queueing a new job, fail if conflicting jobs are\n"
4201 " -q --quiet Suppress output\n"
4202 " --no-block Do not wait until operation finished\n"
4203 " --no-pager Do not pipe output into a pager.\n"
4204 " --system Connect to system manager\n"
4205 " --user Connect to user service manager\n"
4206 " --order When generating graph for dot, show only order\n"
4207 " --require When generating graph for dot, show only requirement\n"
4208 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4209 " --global Enable/disable unit files globally\n"
4210 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4212 " --no-ask-password\n"
4213 " Do not ask for system passwords\n"
4214 " --kill-mode=MODE How to send signal\n"
4215 " --kill-who=WHO Who to send signal to\n"
4216 " -s --signal=SIGNAL Which signal to send\n"
4217 " -f --force When enabling unit files, override existing symlinks\n"
4218 " When shutting down, execute action immediately\n"
4219 " --defaults When disabling unit files, remove default symlinks only\n\n"
4221 " list-units List units\n"
4222 " start [NAME...] Start (activate) one or more units\n"
4223 " stop [NAME...] Stop (deactivate) one or more units\n"
4224 " reload [NAME...] Reload one or more units\n"
4225 " restart [NAME...] Start or restart one or more units\n"
4226 " try-restart [NAME...] Restart one or more units if active\n"
4227 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4228 " otherwise start or restart\n"
4229 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4230 " otherwise restart if active\n"
4231 " isolate [NAME] Start one unit and stop all others\n"
4232 " kill [NAME...] Send signal to processes of a unit\n"
4233 " is-active [NAME...] Check whether units are active\n"
4234 " status [NAME...|PID...] Show runtime status of one or more units\n"
4235 " show [NAME...|JOB...] Show properties of one or more\n"
4236 " units/jobs or the manager\n"
4237 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4239 " enable [NAME...] Enable one or more unit files\n"
4240 " disable [NAME...] Disable one or more unit files\n"
4241 " is-enabled [NAME...] Check whether unit files are enabled\n"
4242 " load [NAME...] Load one or more units\n"
4243 " list-jobs List jobs\n"
4244 " cancel [JOB...] Cancel all, one, or more jobs\n"
4245 " monitor Monitor unit/job changes\n"
4246 " dump Dump server status\n"
4247 " dot Dump dependency graph for dot(1)\n"
4248 " snapshot [NAME] Create a snapshot\n"
4249 " delete [NAME...] Remove one or more snapshots\n"
4250 " daemon-reload Reload systemd manager configuration\n"
4251 " daemon-reexec Reexecute systemd manager\n"
4252 " show-environment Dump environment\n"
4253 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4254 " unset-environment [NAME...] Unset one or more environment variables\n"
4255 " default Enter system default mode\n"
4256 " rescue Enter system rescue mode\n"
4257 " emergency Enter system emergency mode\n"
4258 " halt Shut down and halt the system\n"
4259 " poweroff Shut down and power-off the system\n"
4260 " reboot Shut down and reboot the system\n"
4261 " kexec Shut down and reboot the system with kexec\n"
4262 " exit Ask for user instance termination\n",
4263 program_invocation_short_name);
4268 static int halt_help(void) {
4270 printf("%s [OPTIONS...]\n\n"
4271 "%s the system.\n\n"
4272 " --help Show this help\n"
4273 " --halt Halt the machine\n"
4274 " -p --poweroff Switch off the machine\n"
4275 " --reboot Reboot the machine\n"
4276 " -f --force Force immediate halt/power-off/reboot\n"
4277 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4278 " -d --no-wtmp Don't write wtmp record\n"
4279 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4280 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4281 program_invocation_short_name,
4282 arg_action == ACTION_REBOOT ? "Reboot" :
4283 arg_action == ACTION_POWEROFF ? "Power off" :
4289 static int shutdown_help(void) {
4291 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4292 "Shut down the system.\n\n"
4293 " --help Show this help\n"
4294 " -H --halt Halt the machine\n"
4295 " -P --poweroff Power-off the machine\n"
4296 " -r --reboot Reboot the machine\n"
4297 " -h Equivalent to --poweroff, overriden by --halt\n"
4298 " -k Don't halt/power-off/reboot, just send warnings\n"
4299 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4300 " -c Cancel a pending shutdown\n",
4301 program_invocation_short_name);
4306 static int telinit_help(void) {
4308 printf("%s [OPTIONS...] {COMMAND}\n\n"
4309 "Send control commands to the init daemon.\n\n"
4310 " --help Show this help\n"
4311 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4313 " 0 Power-off the machine\n"
4314 " 6 Reboot the machine\n"
4315 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4316 " 1, s, S Enter rescue mode\n"
4317 " q, Q Reload init daemon configuration\n"
4318 " u, U Reexecute init daemon\n",
4319 program_invocation_short_name);
4324 static int runlevel_help(void) {
4326 printf("%s [OPTIONS...]\n\n"
4327 "Prints the previous and current runlevel of the init system.\n\n"
4328 " --help Show this help\n",
4329 program_invocation_short_name);
4334 static int systemctl_parse_argv(int argc, char *argv[]) {
4352 ARG_NO_ASK_PASSWORD,
4356 static const struct option options[] = {
4357 { "help", no_argument, NULL, 'h' },
4358 { "version", no_argument, NULL, ARG_VERSION },
4359 { "type", required_argument, NULL, 't' },
4360 { "property", required_argument, NULL, 'p' },
4361 { "all", no_argument, NULL, 'a' },
4362 { "failed", no_argument, NULL, ARG_FAILED },
4363 { "full", no_argument, NULL, ARG_FULL },
4364 { "fail", no_argument, NULL, ARG_FAIL },
4365 { "user", no_argument, NULL, ARG_USER },
4366 { "system", no_argument, NULL, ARG_SYSTEM },
4367 { "global", no_argument, NULL, ARG_GLOBAL },
4368 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4369 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4370 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4371 { "quiet", no_argument, NULL, 'q' },
4372 { "order", no_argument, NULL, ARG_ORDER },
4373 { "require", no_argument, NULL, ARG_REQUIRE },
4374 { "force", no_argument, NULL, 'f' },
4375 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4376 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4377 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4378 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4379 { "signal", required_argument, NULL, 's' },
4380 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4381 { NULL, 0, NULL, 0 }
4389 /* Only when running as systemctl we ask for passwords */
4390 arg_ask_password = true;
4392 while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4401 puts(PACKAGE_STRING);
4403 puts(SYSTEMD_FEATURES);
4413 if (!(l = strv_append(arg_property, optarg)))
4416 strv_free(arg_property);
4419 /* If the user asked for a particular
4420 * property, show it to him, even if it is
4443 arg_no_block = true;
4447 arg_no_pager = true;
4455 arg_dot = DOT_ORDER;
4459 arg_dot = DOT_REQUIRE;
4479 arg_no_reload = true;
4488 arg_defaults = true;
4492 arg_kill_who = optarg;
4496 arg_kill_mode = optarg;
4500 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4501 log_error("Failed to parse signal string %s.", optarg);
4506 case ARG_NO_ASK_PASSWORD:
4507 arg_ask_password = false;
4514 log_error("Unknown option code %c", c);
4522 static int halt_parse_argv(int argc, char *argv[]) {
4531 static const struct option options[] = {
4532 { "help", no_argument, NULL, ARG_HELP },
4533 { "halt", no_argument, NULL, ARG_HALT },
4534 { "poweroff", no_argument, NULL, 'p' },
4535 { "reboot", no_argument, NULL, ARG_REBOOT },
4536 { "force", no_argument, NULL, 'f' },
4537 { "wtmp-only", no_argument, NULL, 'w' },
4538 { "no-wtmp", no_argument, NULL, 'd' },
4539 { "no-sync", no_argument, NULL, 'n' },
4540 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4541 { NULL, 0, NULL, 0 }
4549 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4550 if (runlevel == '0' || runlevel == '6')
4551 arg_immediate = true;
4553 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4561 arg_action = ACTION_HALT;
4565 if (arg_action != ACTION_REBOOT)
4566 arg_action = ACTION_POWEROFF;
4570 arg_action = ACTION_REBOOT;
4574 arg_immediate = true;
4595 /* Compatibility nops */
4602 log_error("Unknown option code %c", c);
4607 if (optind < argc) {
4608 log_error("Too many arguments.");
4615 static int parse_time_spec(const char *t, usec_t *_u) {
4619 if (streq(t, "now"))
4621 else if (t[0] == '+') {
4624 if (safe_atou64(t + 1, &u) < 0)
4627 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4636 hour = strtol(t, &e, 10);
4637 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4640 minute = strtol(e+1, &e, 10);
4641 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4644 n = now(CLOCK_REALTIME);
4645 s = (time_t) (n / USEC_PER_SEC);
4648 assert_se(localtime_r(&s, &tm));
4650 tm.tm_hour = (int) hour;
4651 tm.tm_min = (int) minute;
4654 assert_se(s = mktime(&tm));
4656 *_u = (usec_t) s * USEC_PER_SEC;
4659 *_u += USEC_PER_DAY;
4665 static int shutdown_parse_argv(int argc, char *argv[]) {
4672 static const struct option options[] = {
4673 { "help", no_argument, NULL, ARG_HELP },
4674 { "halt", no_argument, NULL, 'H' },
4675 { "poweroff", no_argument, NULL, 'P' },
4676 { "reboot", no_argument, NULL, 'r' },
4677 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4678 { NULL, 0, NULL, 0 }
4686 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4694 arg_action = ACTION_HALT;
4698 arg_action = ACTION_POWEROFF;
4702 arg_action = ACTION_REBOOT;
4706 if (arg_action != ACTION_HALT)
4707 arg_action = ACTION_POWEROFF;
4720 /* Compatibility nops */
4724 arg_action = ACTION_CANCEL_SHUTDOWN;
4731 log_error("Unknown option code %c", c);
4736 if (argc > optind) {
4737 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4738 log_error("Failed to parse time specification: %s", argv[optind]);
4742 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4744 /* We skip the time argument */
4745 if (argc > optind + 1)
4746 arg_wall = argv + optind + 1;
4753 static int telinit_parse_argv(int argc, char *argv[]) {
4760 static const struct option options[] = {
4761 { "help", no_argument, NULL, ARG_HELP },
4762 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4763 { NULL, 0, NULL, 0 }
4766 static const struct {
4770 { '0', ACTION_POWEROFF },
4771 { '6', ACTION_REBOOT },
4772 { '1', ACTION_RESCUE },
4773 { '2', ACTION_RUNLEVEL2 },
4774 { '3', ACTION_RUNLEVEL3 },
4775 { '4', ACTION_RUNLEVEL4 },
4776 { '5', ACTION_RUNLEVEL5 },
4777 { 's', ACTION_RESCUE },
4778 { 'S', ACTION_RESCUE },
4779 { 'q', ACTION_RELOAD },
4780 { 'Q', ACTION_RELOAD },
4781 { 'u', ACTION_REEXEC },
4782 { 'U', ACTION_REEXEC }
4791 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4806 log_error("Unknown option code %c", c);
4811 if (optind >= argc) {
4816 if (optind + 1 < argc) {
4817 log_error("Too many arguments.");
4821 if (strlen(argv[optind]) != 1) {
4822 log_error("Expected single character argument.");
4826 for (i = 0; i < ELEMENTSOF(table); i++)
4827 if (table[i].from == argv[optind][0])
4830 if (i >= ELEMENTSOF(table)) {
4831 log_error("Unknown command %s.", argv[optind]);
4835 arg_action = table[i].to;
4842 static int runlevel_parse_argv(int argc, char *argv[]) {
4848 static const struct option options[] = {
4849 { "help", no_argument, NULL, ARG_HELP },
4850 { NULL, 0, NULL, 0 }
4858 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4869 log_error("Unknown option code %c", c);
4874 if (optind < argc) {
4875 log_error("Too many arguments.");
4882 static int parse_argv(int argc, char *argv[]) {
4886 if (program_invocation_short_name) {
4888 if (strstr(program_invocation_short_name, "halt")) {
4889 arg_action = ACTION_HALT;
4890 return halt_parse_argv(argc, argv);
4891 } else if (strstr(program_invocation_short_name, "poweroff")) {
4892 arg_action = ACTION_POWEROFF;
4893 return halt_parse_argv(argc, argv);
4894 } else if (strstr(program_invocation_short_name, "reboot")) {
4895 arg_action = ACTION_REBOOT;
4896 return halt_parse_argv(argc, argv);
4897 } else if (strstr(program_invocation_short_name, "shutdown")) {
4898 arg_action = ACTION_POWEROFF;
4899 return shutdown_parse_argv(argc, argv);
4900 } else if (strstr(program_invocation_short_name, "init")) {
4902 if (sd_booted() > 0) {
4903 arg_action = ACTION_INVALID;
4904 return telinit_parse_argv(argc, argv);
4906 /* Hmm, so some other init system is
4907 * running, we need to forward this
4908 * request to it. For now we simply
4909 * guess that it is Upstart. */
4911 execv("/lib/upstart/telinit", argv);
4913 log_error("Couldn't find an alternative telinit implementation to spawn.");
4917 } else if (strstr(program_invocation_short_name, "runlevel")) {
4918 arg_action = ACTION_RUNLEVEL;
4919 return runlevel_parse_argv(argc, argv);
4923 arg_action = ACTION_SYSTEMCTL;
4924 return systemctl_parse_argv(argc, argv);
4927 static int action_to_runlevel(void) {
4929 static const char table[_ACTION_MAX] = {
4930 [ACTION_HALT] = '0',
4931 [ACTION_POWEROFF] = '0',
4932 [ACTION_REBOOT] = '6',
4933 [ACTION_RUNLEVEL2] = '2',
4934 [ACTION_RUNLEVEL3] = '3',
4935 [ACTION_RUNLEVEL4] = '4',
4936 [ACTION_RUNLEVEL5] = '5',
4937 [ACTION_RESCUE] = '1'
4940 assert(arg_action < _ACTION_MAX);
4942 return table[arg_action];
4945 static int talk_upstart(void) {
4946 DBusMessage *m = NULL, *reply = NULL;
4948 int previous, rl, r;
4950 env1_buf[] = "RUNLEVEL=X",
4951 env2_buf[] = "PREVLEVEL=X";
4952 char *env1 = env1_buf, *env2 = env2_buf;
4953 const char *emit = "runlevel";
4954 dbus_bool_t b_false = FALSE;
4955 DBusMessageIter iter, sub;
4956 DBusConnection *bus;
4958 dbus_error_init(&error);
4960 if (!(rl = action_to_runlevel()))
4963 if (utmp_get_runlevel(&previous, NULL) < 0)
4966 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4967 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4972 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4977 if ((r = bus_check_peercred(bus)) < 0) {
4978 log_error("Failed to verify owner of bus.");
4982 if (!(m = dbus_message_new_method_call(
4983 "com.ubuntu.Upstart",
4984 "/com/ubuntu/Upstart",
4985 "com.ubuntu.Upstart0_6",
4988 log_error("Could not allocate message.");
4993 dbus_message_iter_init_append(m, &iter);
4995 env1_buf[sizeof(env1_buf)-2] = rl;
4996 env2_buf[sizeof(env2_buf)-2] = previous;
4998 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4999 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5000 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5001 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5002 !dbus_message_iter_close_container(&iter, &sub) ||
5003 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5004 log_error("Could not append arguments to message.");
5009 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5011 if (error_is_no_service(&error)) {
5016 log_error("Failed to issue method call: %s", bus_error_message(&error));
5025 dbus_message_unref(m);
5028 dbus_message_unref(reply);
5031 dbus_connection_flush(bus);
5032 dbus_connection_close(bus);
5033 dbus_connection_unref(bus);
5036 dbus_error_free(&error);
5041 static int talk_initctl(void) {
5042 struct init_request request;
5046 if (!(rl = action_to_runlevel()))
5050 request.magic = INIT_MAGIC;
5051 request.sleeptime = 0;
5052 request.cmd = INIT_CMD_RUNLVL;
5053 request.runlevel = rl;
5055 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5057 if (errno == ENOENT)
5060 log_error("Failed to open "INIT_FIFO": %m");
5065 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5066 close_nointr_nofail(fd);
5069 log_error("Failed to write to "INIT_FIFO": %m");
5070 return errno ? -errno : -EIO;
5076 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5078 static const struct {
5086 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5088 { "list-units", LESS, 1, list_units },
5089 { "list-jobs", EQUAL, 1, list_jobs },
5090 { "clear-jobs", EQUAL, 1, daemon_reload },
5091 { "load", MORE, 2, load_unit },
5092 { "cancel", MORE, 2, cancel_job },
5093 { "start", MORE, 2, start_unit },
5094 { "stop", MORE, 2, start_unit },
5095 { "reload", MORE, 2, start_unit },
5096 { "restart", MORE, 2, start_unit },
5097 { "try-restart", MORE, 2, start_unit },
5098 { "reload-or-restart", MORE, 2, start_unit },
5099 { "reload-or-try-restart", MORE, 2, start_unit },
5100 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5101 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5102 { "isolate", EQUAL, 2, start_unit },
5103 { "kill", MORE, 2, kill_unit },
5104 { "is-active", MORE, 2, check_unit },
5105 { "check", MORE, 2, check_unit },
5106 { "show", MORE, 1, show },
5107 { "status", MORE, 2, show },
5108 { "monitor", EQUAL, 1, monitor },
5109 { "dump", EQUAL, 1, dump },
5110 { "dot", EQUAL, 1, dot },
5111 { "snapshot", LESS, 2, snapshot },
5112 { "delete", MORE, 2, delete_snapshot },
5113 { "daemon-reload", EQUAL, 1, daemon_reload },
5114 { "daemon-reexec", EQUAL, 1, daemon_reload },
5115 { "show-environment", EQUAL, 1, show_enviroment },
5116 { "set-environment", MORE, 2, set_environment },
5117 { "unset-environment", MORE, 2, set_environment },
5118 { "halt", EQUAL, 1, start_special },
5119 { "poweroff", EQUAL, 1, start_special },
5120 { "reboot", EQUAL, 1, start_special },
5121 { "kexec", EQUAL, 1, start_special },
5122 { "default", EQUAL, 1, start_special },
5123 { "rescue", EQUAL, 1, start_special },
5124 { "emergency", EQUAL, 1, start_special },
5125 { "exit", EQUAL, 1, start_special },
5126 { "reset-failed", MORE, 1, reset_failed },
5127 { "enable", MORE, 2, enable_unit },
5128 { "disable", MORE, 2, enable_unit },
5129 { "is-enabled", MORE, 2, enable_unit }
5139 left = argc - optind;
5142 /* Special rule: no arguments means "list-units" */
5145 if (streq(argv[optind], "help")) {
5150 for (i = 0; i < ELEMENTSOF(verbs); i++)
5151 if (streq(argv[optind], verbs[i].verb))
5154 if (i >= ELEMENTSOF(verbs)) {
5155 log_error("Unknown operation %s", argv[optind]);
5160 switch (verbs[i].argc_cmp) {
5163 if (left != verbs[i].argc) {
5164 log_error("Invalid number of arguments.");
5171 if (left < verbs[i].argc) {
5172 log_error("Too few arguments.");
5179 if (left > verbs[i].argc) {
5180 log_error("Too many arguments.");
5187 assert_not_reached("Unknown comparison operator.");
5190 /* Require a bus connection for all operations but
5192 if (!streq(verbs[i].verb, "enable") &&
5193 !streq(verbs[i].verb, "disable") &&
5195 log_error("Failed to get D-Bus connection: %s", error->message);
5199 return verbs[i].dispatch(bus, argv + optind, left);
5202 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5204 struct msghdr msghdr;
5206 union sockaddr_union sockaddr;
5207 struct shutdownd_command c;
5215 strncpy(c.wall_message, message, sizeof(c.wall_message));
5217 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5221 sockaddr.sa.sa_family = AF_UNIX;
5222 sockaddr.un.sun_path[0] = 0;
5223 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5226 iovec.iov_base = (char*) &c;
5227 iovec.iov_len = sizeof(c);
5230 msghdr.msg_name = &sockaddr;
5231 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5233 msghdr.msg_iov = &iovec;
5234 msghdr.msg_iovlen = 1;
5236 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5237 close_nointr_nofail(fd);
5241 close_nointr_nofail(fd);
5245 static int reload_with_fallback(DBusConnection *bus) {
5248 /* First, try systemd via D-Bus. */
5249 if (daemon_reload(bus, NULL, 0) > 0)
5253 /* Nothing else worked, so let's try signals */
5254 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5256 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5257 log_error("kill() failed: %m");
5264 static int start_with_fallback(DBusConnection *bus) {
5267 /* First, try systemd via D-Bus. */
5268 if (start_unit(bus, NULL, 0) >= 0)
5272 /* Hmm, talking to systemd via D-Bus didn't work. Then
5273 * let's try to talk to Upstart via D-Bus. */
5274 if (talk_upstart() > 0)
5277 /* Nothing else worked, so let's try
5279 if (talk_initctl() > 0)
5282 log_error("Failed to talk to init daemon.");
5286 warn_wall(arg_action);
5290 static int halt_main(DBusConnection *bus) {
5293 if (geteuid() != 0) {
5294 log_error("Must be root.");
5300 char date[FORMAT_TIMESTAMP_MAX];
5302 m = strv_join(arg_wall, " ");
5303 r = send_shutdownd(arg_when,
5304 arg_action == ACTION_HALT ? 'H' :
5305 arg_action == ACTION_POWEROFF ? 'P' :
5312 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5314 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5315 format_timestamp(date, sizeof(date), arg_when));
5320 if (!arg_dry && !arg_immediate)
5321 return start_with_fallback(bus);
5324 if (sd_booted() > 0)
5325 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5326 else if ((r = utmp_put_shutdown(0)) < 0)
5327 log_warning("Failed to write utmp record: %s", strerror(-r));
5336 /* Make sure C-A-D is handled by the kernel from this
5338 reboot(RB_ENABLE_CAD);
5340 switch (arg_action) {
5343 log_info("Halting.");
5344 reboot(RB_HALT_SYSTEM);
5347 case ACTION_POWEROFF:
5348 log_info("Powering off.");
5349 reboot(RB_POWER_OFF);
5353 log_info("Rebooting.");
5354 reboot(RB_AUTOBOOT);
5358 assert_not_reached("Unknown halt action.");
5361 /* We should never reach this. */
5365 static int runlevel_main(void) {
5366 int r, runlevel, previous;
5368 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5369 printf("unknown\n");
5374 previous <= 0 ? 'N' : previous,
5375 runlevel <= 0 ? 'N' : runlevel);
5380 static void pager_open(void) {
5387 if (!on_tty() || arg_no_pager)
5390 if ((pager = getenv("PAGER")))
5391 if (!*pager || streq(pager, "cat"))
5394 /* Determine and cache number of columns before we spawn the
5395 * pager so that we get the value from the actual tty */
5399 log_error("Failed to create pager pipe: %m");
5404 if (pager_pid < 0) {
5405 log_error("Failed to fork pager: %m");
5410 /* In the child start the pager */
5411 if (pager_pid == 0) {
5413 dup2(fd[0], STDIN_FILENO);
5416 setenv("LESS", "FRSX", 0);
5418 prctl(PR_SET_PDEATHSIG, SIGTERM);
5421 execlp(pager, pager, NULL);
5422 execl("/bin/sh", "sh", "-c", pager, NULL);
5424 /* Debian's alternatives command for pagers is
5425 * called 'pager'. Note that we do not call
5426 * sensible-pagers here, since that is just a
5427 * shell script that implements a logic that
5428 * is similar to this one anyway, but is
5429 * Debian-specific. */
5430 execlp("pager", "pager", NULL);
5432 execlp("less", "less", NULL);
5433 execlp("more", "more", NULL);
5436 log_error("Unable to execute pager: %m");
5437 _exit(EXIT_FAILURE);
5440 /* Return in the parent */
5441 if (dup2(fd[1], STDOUT_FILENO) < 0)
5442 log_error("Failed to duplicate pager pipe: %m");
5447 static void pager_close(void) {
5453 /* Inform pager that we are done */
5455 wait_for_terminate(pager_pid, &dummy);
5459 int main(int argc, char*argv[]) {
5460 int r, retval = EXIT_FAILURE;
5461 DBusConnection *bus = NULL;
5464 dbus_error_init(&error);
5466 log_parse_environment();
5469 if ((r = parse_argv(argc, argv)) < 0)
5472 retval = EXIT_SUCCESS;
5476 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5477 * let's shortcut this */
5478 if (arg_action == ACTION_RUNLEVEL) {
5479 r = runlevel_main();
5480 retval = r < 0 ? EXIT_FAILURE : r;
5484 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5486 switch (arg_action) {
5488 case ACTION_SYSTEMCTL:
5489 r = systemctl_main(bus, argc, argv, &error);
5493 case ACTION_POWEROFF:
5498 case ACTION_RUNLEVEL2:
5499 case ACTION_RUNLEVEL3:
5500 case ACTION_RUNLEVEL4:
5501 case ACTION_RUNLEVEL5:
5503 case ACTION_EMERGENCY:
5504 case ACTION_DEFAULT:
5505 r = start_with_fallback(bus);
5510 r = reload_with_fallback(bus);
5513 case ACTION_CANCEL_SHUTDOWN:
5514 r = send_shutdownd(0, 0, false, NULL);
5517 case ACTION_INVALID:
5518 case ACTION_RUNLEVEL:
5520 assert_not_reached("Unknown action");
5523 retval = r < 0 ? EXIT_FAILURE : r;
5528 dbus_connection_flush(bus);
5529 dbus_connection_close(bus);
5530 dbus_connection_unref(bus);
5533 dbus_error_free(&error);
5537 strv_free(arg_property);