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 const char *arg_job_mode = "replace";
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")) {
1147 const char *path, *result;
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_STRING, &result,
1154 DBUS_TYPE_INVALID)) {
1157 if ((p = set_remove(d->set, (char*) path)))
1161 d->result = strdup(result);
1166 dbus_error_free(&error);
1168 if (dbus_message_get_args(message, &error,
1169 DBUS_TYPE_UINT32, &id,
1170 DBUS_TYPE_OBJECT_PATH, &path,
1171 DBUS_TYPE_BOOLEAN, &success,
1172 DBUS_TYPE_INVALID)) {
1175 /* Compatibility with older systemd versions <
1176 * 19 during upgrades. This should be dropped
1179 if ((p = set_remove(d->set, (char*) path)))
1183 d->result = strdup("failed");
1189 log_error("Failed to parse message: %s", bus_error_message(&error));
1193 dbus_error_free(&error);
1194 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1197 static int enable_wait_for_jobs(DBusConnection *bus) {
1205 dbus_error_init(&error);
1206 dbus_bus_add_match(bus,
1208 "sender='org.freedesktop.systemd1',"
1209 "interface='org.freedesktop.systemd1.Manager',"
1210 "member='JobRemoved',"
1211 "path='/org/freedesktop/systemd1'",
1214 if (dbus_error_is_set(&error)) {
1215 log_error("Failed to add match: %s", bus_error_message(&error));
1216 dbus_error_free(&error);
1220 /* This is slightly dirty, since we don't undo the match registrations. */
1224 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1234 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1235 log_error("Failed to add filter.");
1240 while (!set_isempty(s) &&
1241 dbus_connection_read_write_dispatch(bus, -1))
1244 if (!arg_quiet && d.result) {
1245 if (streq(d.result, "timeout"))
1246 log_error("Job timed out.");
1247 else if (streq(d.result, "canceled"))
1248 log_error("Job canceled.");
1249 else if (streq(d.result, "dependency"))
1250 log_error("A dependency job failed. See system logs for details.");
1251 else if (!streq(d.result, "done"))
1252 log_error("Job failed. See system logs and 'systemctl status' for details.");
1255 if (streq_ptr(d.result, "timeout"))
1257 else if (streq_ptr(d.result, "canceled"))
1259 else if (!streq_ptr(d.result, "done"))
1267 /* This is slightly dirty, since we don't undo the filter registration. */
1272 static int start_unit_one(
1273 DBusConnection *bus,
1280 DBusMessage *m = NULL, *reply = NULL;
1289 assert(arg_no_block || s);
1291 if (!(m = dbus_message_new_method_call(
1292 "org.freedesktop.systemd1",
1293 "/org/freedesktop/systemd1",
1294 "org.freedesktop.systemd1.Manager",
1296 log_error("Could not allocate message.");
1301 if (!dbus_message_append_args(m,
1302 DBUS_TYPE_STRING, &name,
1303 DBUS_TYPE_STRING, &mode,
1304 DBUS_TYPE_INVALID)) {
1305 log_error("Could not append arguments to message.");
1310 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1312 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1313 /* There's always a fallback possible for
1314 * legacy actions. */
1319 log_error("Failed to issue method call: %s", bus_error_message(error));
1324 if (!dbus_message_get_args(reply, error,
1325 DBUS_TYPE_OBJECT_PATH, &path,
1326 DBUS_TYPE_INVALID)) {
1327 log_error("Failed to parse reply: %s", bus_error_message(error));
1332 if (need_daemon_reload(bus, name))
1333 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1334 arg_user ? "--user" : "--system");
1336 if (!arg_no_block) {
1339 if (!(p = strdup(path))) {
1340 log_error("Failed to duplicate path.");
1345 if ((r = set_put(s, p)) < 0) {
1347 log_error("Failed to add path to set.");
1356 dbus_message_unref(m);
1359 dbus_message_unref(reply);
1364 static enum action verb_to_action(const char *verb) {
1365 if (streq(verb, "halt"))
1367 else if (streq(verb, "poweroff"))
1368 return ACTION_POWEROFF;
1369 else if (streq(verb, "reboot"))
1370 return ACTION_REBOOT;
1371 else if (streq(verb, "kexec"))
1372 return ACTION_KEXEC;
1373 else if (streq(verb, "rescue"))
1374 return ACTION_RESCUE;
1375 else if (streq(verb, "emergency"))
1376 return ACTION_EMERGENCY;
1377 else if (streq(verb, "default"))
1378 return ACTION_DEFAULT;
1379 else if (streq(verb, "exit"))
1382 return ACTION_INVALID;
1385 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1387 static const char * const table[_ACTION_MAX] = {
1388 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1389 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1390 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1391 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1392 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1393 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1394 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1395 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1396 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1397 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1398 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1399 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1404 const char *method, *mode, *one_name;
1408 dbus_error_init(&error);
1412 spawn_ask_password_agent();
1414 if (arg_action == ACTION_SYSTEMCTL) {
1416 streq(args[0], "stop") ? "StopUnit" :
1417 streq(args[0], "reload") ? "ReloadUnit" :
1418 streq(args[0], "restart") ? "RestartUnit" :
1419 streq(args[0], "try-restart") ||
1420 streq(args[0], "condrestart") ? "TryRestartUnit" :
1421 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1422 streq(args[0], "reload-or-try-restart") ||
1423 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1427 (streq(args[0], "isolate") ||
1428 streq(args[0], "rescue") ||
1429 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1431 one_name = table[verb_to_action(args[0])];
1434 assert(arg_action < ELEMENTSOF(table));
1435 assert(table[arg_action]);
1437 method = "StartUnit";
1439 mode = (arg_action == ACTION_EMERGENCY ||
1440 arg_action == ACTION_RESCUE ||
1441 arg_action == ACTION_RUNLEVEL2 ||
1442 arg_action == ACTION_RUNLEVEL3 ||
1443 arg_action == ACTION_RUNLEVEL4 ||
1444 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1446 one_name = table[arg_action];
1449 if (!arg_no_block) {
1450 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1451 log_error("Could not watch jobs: %s", strerror(-ret));
1455 if (!(s = set_new(string_hash_func, string_compare_func))) {
1456 log_error("Failed to allocate set.");
1463 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1466 for (i = 1; i < n; i++)
1467 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1468 ret = translate_bus_error_to_exit_status(r, &error);
1469 dbus_error_free(&error);
1474 if ((r = wait_for_jobs(bus, s)) < 0) {
1483 dbus_error_free(&error);
1488 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1495 (streq(args[0], "halt") ||
1496 streq(args[0], "poweroff") ||
1497 streq(args[0], "reboot") ||
1498 streq(args[0], "kexec") ||
1499 streq(args[0], "exit")))
1500 return daemon_reload(bus, args, n);
1502 r = start_unit(bus, args, n);
1505 warn_wall(verb_to_action(args[0]));
1510 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1511 DBusMessage *m = NULL, *reply = NULL;
1513 *interface = "org.freedesktop.systemd1.Unit",
1514 *property = "ActiveState";
1515 int r = 3; /* According to LSB: "program is not running" */
1522 dbus_error_init(&error);
1524 for (i = 1; i < n; i++) {
1525 const char *path = NULL;
1527 DBusMessageIter iter, sub;
1529 if (!(m = dbus_message_new_method_call(
1530 "org.freedesktop.systemd1",
1531 "/org/freedesktop/systemd1",
1532 "org.freedesktop.systemd1.Manager",
1534 log_error("Could not allocate message.");
1539 if (!dbus_message_append_args(m,
1540 DBUS_TYPE_STRING, &args[i],
1541 DBUS_TYPE_INVALID)) {
1542 log_error("Could not append arguments to message.");
1547 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1549 /* Hmm, cannot figure out anything about this unit... */
1553 dbus_error_free(&error);
1554 dbus_message_unref(m);
1558 if (!dbus_message_get_args(reply, &error,
1559 DBUS_TYPE_OBJECT_PATH, &path,
1560 DBUS_TYPE_INVALID)) {
1561 log_error("Failed to parse reply: %s", bus_error_message(&error));
1566 dbus_message_unref(m);
1567 if (!(m = dbus_message_new_method_call(
1568 "org.freedesktop.systemd1",
1570 "org.freedesktop.DBus.Properties",
1572 log_error("Could not allocate message.");
1577 if (!dbus_message_append_args(m,
1578 DBUS_TYPE_STRING, &interface,
1579 DBUS_TYPE_STRING, &property,
1580 DBUS_TYPE_INVALID)) {
1581 log_error("Could not append arguments to message.");
1586 dbus_message_unref(reply);
1587 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1588 log_error("Failed to issue method call: %s", bus_error_message(&error));
1593 if (!dbus_message_iter_init(reply, &iter) ||
1594 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1595 log_error("Failed to parse reply.");
1600 dbus_message_iter_recurse(&iter, &sub);
1602 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1603 log_error("Failed to parse reply.");
1608 dbus_message_iter_get_basic(&sub, &state);
1613 if (streq(state, "active") || streq(state, "reloading"))
1616 dbus_message_unref(m);
1617 dbus_message_unref(reply);
1623 dbus_message_unref(m);
1626 dbus_message_unref(reply);
1628 dbus_error_free(&error);
1633 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1634 DBusMessage *m = NULL, *reply = NULL;
1642 dbus_error_init(&error);
1645 arg_kill_who = "all";
1648 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1650 for (i = 1; i < n; i++) {
1652 if (!(m = dbus_message_new_method_call(
1653 "org.freedesktop.systemd1",
1654 "/org/freedesktop/systemd1",
1655 "org.freedesktop.systemd1.Manager",
1657 log_error("Could not allocate message.");
1662 if (!dbus_message_append_args(m,
1663 DBUS_TYPE_STRING, &args[i],
1664 DBUS_TYPE_STRING, &arg_kill_who,
1665 DBUS_TYPE_STRING, &arg_kill_mode,
1666 DBUS_TYPE_INT32, &arg_signal,
1667 DBUS_TYPE_INVALID)) {
1668 log_error("Could not append arguments to message.");
1673 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1674 log_error("Failed to issue method call: %s", bus_error_message(&error));
1675 dbus_error_free(&error);
1679 dbus_message_unref(m);
1682 dbus_message_unref(reply);
1688 dbus_message_unref(m);
1691 dbus_message_unref(reply);
1693 dbus_error_free(&error);
1698 typedef struct ExecStatusInfo {
1706 usec_t start_timestamp;
1707 usec_t exit_timestamp;
1712 LIST_FIELDS(struct ExecStatusInfo, exec);
1715 static void exec_status_info_free(ExecStatusInfo *i) {
1724 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1725 uint64_t start_timestamp, exit_timestamp;
1726 DBusMessageIter sub2, sub3;
1730 int32_t code, status;
1736 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1739 dbus_message_iter_recurse(sub, &sub2);
1741 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1744 if (!(i->path = strdup(path)))
1747 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1748 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1752 dbus_message_iter_recurse(&sub2, &sub3);
1753 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1754 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1755 dbus_message_iter_next(&sub3);
1760 if (!(i->argv = new0(char*, n+1)))
1764 dbus_message_iter_recurse(&sub2, &sub3);
1765 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1768 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1769 dbus_message_iter_get_basic(&sub3, &s);
1770 dbus_message_iter_next(&sub3);
1772 if (!(i->argv[n++] = strdup(s)))
1776 if (!dbus_message_iter_next(&sub2) ||
1777 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1778 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1779 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1780 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1781 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1782 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1786 i->start_timestamp = (usec_t) start_timestamp;
1787 i->exit_timestamp = (usec_t) exit_timestamp;
1788 i->pid = (pid_t) pid;
1795 typedef struct UnitStatusInfo {
1797 const char *load_state;
1798 const char *active_state;
1799 const char *sub_state;
1801 const char *description;
1802 const char *following;
1805 const char *default_control_group;
1807 usec_t inactive_exit_timestamp;
1808 usec_t active_enter_timestamp;
1809 usec_t active_exit_timestamp;
1810 usec_t inactive_enter_timestamp;
1812 bool need_daemon_reload;
1817 const char *status_text;
1819 #ifdef HAVE_SYSV_COMPAT
1823 usec_t start_timestamp;
1824 usec_t exit_timestamp;
1826 int exit_code, exit_status;
1829 unsigned n_accepted;
1830 unsigned n_connections;
1834 const char *sysfs_path;
1836 /* Mount, Automount */
1842 LIST_HEAD(ExecStatusInfo, exec);
1845 static void print_status_info(UnitStatusInfo *i) {
1847 const char *on, *off, *ss;
1849 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1850 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1854 /* This shows pretty information about a unit. See
1855 * print_property() for a low-level property printer */
1857 printf("%s", strna(i->id));
1859 if (i->description && !streq_ptr(i->id, i->description))
1860 printf(" - %s", i->description);
1865 printf("\t Follow: unit currently follows state of %s\n", i->following);
1867 if (streq_ptr(i->load_state, "failed") ||
1868 streq_ptr(i->load_state, "banned")) {
1869 on = ansi_highlight(true);
1870 off = ansi_highlight(false);
1875 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1877 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1879 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1881 if (streq_ptr(i->active_state, "failed")) {
1882 on = ansi_highlight(true);
1883 off = ansi_highlight(false);
1884 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1885 on = ansi_highlight_green(true);
1886 off = ansi_highlight_green(false);
1891 printf("\t Active: %s%s (%s)%s",
1893 strna(i->active_state),
1897 printf("\t Active: %s%s%s",
1899 strna(i->active_state),
1902 timestamp = (streq_ptr(i->active_state, "active") ||
1903 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1904 (streq_ptr(i->active_state, "inactive") ||
1905 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1906 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1907 i->active_exit_timestamp;
1909 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1910 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1913 printf(" since %s; %s\n", s2, s1);
1915 printf(" since %s\n", s2);
1920 printf("\t Device: %s\n", i->sysfs_path);
1922 printf("\t Where: %s\n", i->where);
1924 printf("\t What: %s\n", i->what);
1927 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1929 LIST_FOREACH(exec, p, i->exec) {
1933 /* Only show exited processes here */
1937 t = strv_join(p->argv, " ");
1938 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1941 #ifdef HAVE_SYSV_COMPAT
1943 good = is_clean_exit_lsb(p->code, p->status);
1946 good = is_clean_exit(p->code, p->status);
1949 on = ansi_highlight(true);
1950 off = ansi_highlight(false);
1954 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1956 if (p->code == CLD_EXITED) {
1959 printf("status=%i", p->status);
1961 #ifdef HAVE_SYSV_COMPAT
1962 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1964 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1969 printf("signal=%s", signal_to_string(p->status));
1971 printf(")%s\n", off);
1975 if (i->main_pid == p->pid &&
1976 i->start_timestamp == p->start_timestamp &&
1977 i->exit_timestamp == p->start_timestamp)
1978 /* Let's not show this twice */
1981 if (p->pid == i->control_pid)
1985 if (i->main_pid > 0 || i->control_pid > 0) {
1988 if (i->main_pid > 0) {
1989 printf("Main PID: %u", (unsigned) i->main_pid);
1993 get_process_name(i->main_pid, &t);
1998 } else if (i->exit_code > 0) {
1999 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2001 if (i->exit_code == CLD_EXITED) {
2004 printf("status=%i", i->exit_status);
2006 #ifdef HAVE_SYSV_COMPAT
2007 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2009 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2014 printf("signal=%s", signal_to_string(i->exit_status));
2019 if (i->main_pid > 0 && i->control_pid > 0)
2022 if (i->control_pid > 0) {
2025 printf(" Control: %u", (unsigned) i->control_pid);
2027 get_process_name(i->control_pid, &t);
2038 printf("\t Status: \"%s\"\n", i->status_text);
2040 if (i->default_control_group) {
2043 printf("\t CGroup: %s\n", i->default_control_group);
2045 if ((c = columns()) > 18)
2050 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2053 if (i->need_daemon_reload)
2054 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2055 ansi_highlight(true),
2056 ansi_highlight(false),
2057 arg_user ? "--user" : "--system");
2060 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2062 switch (dbus_message_iter_get_arg_type(iter)) {
2064 case DBUS_TYPE_STRING: {
2067 dbus_message_iter_get_basic(iter, &s);
2070 if (streq(name, "Id"))
2072 else if (streq(name, "LoadState"))
2074 else if (streq(name, "ActiveState"))
2075 i->active_state = s;
2076 else if (streq(name, "SubState"))
2078 else if (streq(name, "Description"))
2080 else if (streq(name, "FragmentPath"))
2082 #ifdef HAVE_SYSV_COMPAT
2083 else if (streq(name, "SysVPath")) {
2088 else if (streq(name, "DefaultControlGroup"))
2089 i->default_control_group = s;
2090 else if (streq(name, "StatusText"))
2092 else if (streq(name, "SysFSPath"))
2094 else if (streq(name, "Where"))
2096 else if (streq(name, "What"))
2098 else if (streq(name, "Following"))
2105 case DBUS_TYPE_BOOLEAN: {
2108 dbus_message_iter_get_basic(iter, &b);
2110 if (streq(name, "Accept"))
2112 else if (streq(name, "NeedDaemonReload"))
2113 i->need_daemon_reload = b;
2118 case DBUS_TYPE_UINT32: {
2121 dbus_message_iter_get_basic(iter, &u);
2123 if (streq(name, "MainPID")) {
2125 i->main_pid = (pid_t) u;
2128 } else if (streq(name, "ControlPID"))
2129 i->control_pid = (pid_t) u;
2130 else if (streq(name, "ExecMainPID")) {
2132 i->main_pid = (pid_t) u;
2133 } else if (streq(name, "NAccepted"))
2135 else if (streq(name, "NConnections"))
2136 i->n_connections = u;
2141 case DBUS_TYPE_INT32: {
2144 dbus_message_iter_get_basic(iter, &j);
2146 if (streq(name, "ExecMainCode"))
2147 i->exit_code = (int) j;
2148 else if (streq(name, "ExecMainStatus"))
2149 i->exit_status = (int) j;
2154 case DBUS_TYPE_UINT64: {
2157 dbus_message_iter_get_basic(iter, &u);
2159 if (streq(name, "ExecMainStartTimestamp"))
2160 i->start_timestamp = (usec_t) u;
2161 else if (streq(name, "ExecMainExitTimestamp"))
2162 i->exit_timestamp = (usec_t) u;
2163 else if (streq(name, "ActiveEnterTimestamp"))
2164 i->active_enter_timestamp = (usec_t) u;
2165 else if (streq(name, "InactiveEnterTimestamp"))
2166 i->inactive_enter_timestamp = (usec_t) u;
2167 else if (streq(name, "InactiveExitTimestamp"))
2168 i->inactive_exit_timestamp = (usec_t) u;
2169 else if (streq(name, "ActiveExitTimestamp"))
2170 i->active_exit_timestamp = (usec_t) u;
2175 case DBUS_TYPE_ARRAY: {
2177 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2178 startswith(name, "Exec")) {
2179 DBusMessageIter sub;
2181 dbus_message_iter_recurse(iter, &sub);
2182 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2183 ExecStatusInfo *info;
2186 if (!(info = new0(ExecStatusInfo, 1)))
2189 if (!(info->name = strdup(name))) {
2194 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2199 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2201 dbus_message_iter_next(&sub);
2212 static int print_property(const char *name, DBusMessageIter *iter) {
2216 /* This is a low-level property printer, see
2217 * print_status_info() for the nicer output */
2219 if (arg_property && !strv_find(arg_property, name))
2222 switch (dbus_message_iter_get_arg_type(iter)) {
2224 case DBUS_TYPE_STRING: {
2226 dbus_message_iter_get_basic(iter, &s);
2228 if (arg_all || s[0])
2229 printf("%s=%s\n", name, s);
2234 case DBUS_TYPE_BOOLEAN: {
2236 dbus_message_iter_get_basic(iter, &b);
2237 printf("%s=%s\n", name, yes_no(b));
2242 case DBUS_TYPE_UINT64: {
2244 dbus_message_iter_get_basic(iter, &u);
2246 /* Yes, heuristics! But we can change this check
2247 * should it turn out to not be sufficient */
2249 if (strstr(name, "Timestamp")) {
2250 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2252 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2253 printf("%s=%s\n", name, strempty(t));
2254 } else if (strstr(name, "USec")) {
2255 char timespan[FORMAT_TIMESPAN_MAX];
2257 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2259 printf("%s=%llu\n", name, (unsigned long long) u);
2264 case DBUS_TYPE_UINT32: {
2266 dbus_message_iter_get_basic(iter, &u);
2268 if (strstr(name, "UMask") || strstr(name, "Mode"))
2269 printf("%s=%04o\n", name, u);
2271 printf("%s=%u\n", name, (unsigned) u);
2276 case DBUS_TYPE_INT32: {
2278 dbus_message_iter_get_basic(iter, &i);
2280 printf("%s=%i\n", name, (int) i);
2284 case DBUS_TYPE_DOUBLE: {
2286 dbus_message_iter_get_basic(iter, &d);
2288 printf("%s=%g\n", name, d);
2292 case DBUS_TYPE_STRUCT: {
2293 DBusMessageIter sub;
2294 dbus_message_iter_recurse(iter, &sub);
2296 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2299 dbus_message_iter_get_basic(&sub, &u);
2302 printf("%s=%u\n", name, (unsigned) u);
2304 printf("%s=\n", name);
2307 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2310 dbus_message_iter_get_basic(&sub, &s);
2312 if (arg_all || s[0])
2313 printf("%s=%s\n", name, s);
2321 case DBUS_TYPE_ARRAY:
2323 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2324 DBusMessageIter sub;
2327 dbus_message_iter_recurse(iter, &sub);
2329 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2330 printf("%s=", name);
2332 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2335 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2336 dbus_message_iter_get_basic(&sub, &s);
2337 printf("%s%s", space ? " " : "", s);
2340 dbus_message_iter_next(&sub);
2348 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2349 DBusMessageIter sub;
2351 dbus_message_iter_recurse(iter, &sub);
2353 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2354 printf("%s=", name);
2356 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2359 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2360 dbus_message_iter_get_basic(&sub, &u);
2363 dbus_message_iter_next(&sub);
2371 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2372 DBusMessageIter sub, sub2;
2374 dbus_message_iter_recurse(iter, &sub);
2375 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2376 const char *type, *path;
2378 dbus_message_iter_recurse(&sub, &sub2);
2380 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2381 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2382 printf("%s=%s\n", type, path);
2384 dbus_message_iter_next(&sub);
2389 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2390 DBusMessageIter sub, sub2;
2392 dbus_message_iter_recurse(iter, &sub);
2393 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2395 uint64_t value, next_elapse;
2397 dbus_message_iter_recurse(&sub, &sub2);
2399 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2400 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2401 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2402 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2404 printf("%s={ value=%s ; next_elapse=%s }\n",
2406 format_timespan(timespan1, sizeof(timespan1), value),
2407 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2410 dbus_message_iter_next(&sub);
2415 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2416 DBusMessageIter sub;
2418 dbus_message_iter_recurse(iter, &sub);
2419 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2420 ExecStatusInfo info;
2423 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2424 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2427 t = strv_join(info.argv, " ");
2429 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2433 yes_no(info.ignore),
2434 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2435 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2436 (unsigned) info. pid,
2437 sigchld_code_to_string(info.code),
2439 info.code == CLD_EXITED ? "" : "/",
2440 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2446 strv_free(info.argv);
2448 dbus_message_iter_next(&sub);
2458 printf("%s=[unprintable]\n", name);
2463 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2464 DBusMessage *m = NULL, *reply = NULL;
2465 const char *interface = "";
2468 DBusMessageIter iter, sub, sub2, sub3;
2469 UnitStatusInfo info;
2477 dbus_error_init(&error);
2479 if (!(m = dbus_message_new_method_call(
2480 "org.freedesktop.systemd1",
2482 "org.freedesktop.DBus.Properties",
2484 log_error("Could not allocate message.");
2489 if (!dbus_message_append_args(m,
2490 DBUS_TYPE_STRING, &interface,
2491 DBUS_TYPE_INVALID)) {
2492 log_error("Could not append arguments to message.");
2497 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2498 log_error("Failed to issue method call: %s", bus_error_message(&error));
2503 if (!dbus_message_iter_init(reply, &iter) ||
2504 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2505 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2506 log_error("Failed to parse reply.");
2511 dbus_message_iter_recurse(&iter, &sub);
2518 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2521 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2522 log_error("Failed to parse reply.");
2527 dbus_message_iter_recurse(&sub, &sub2);
2529 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2530 log_error("Failed to parse reply.");
2535 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2536 log_error("Failed to parse reply.");
2541 dbus_message_iter_recurse(&sub2, &sub3);
2543 if (show_properties)
2544 r = print_property(name, &sub3);
2546 r = status_property(name, &sub3, &info);
2549 log_error("Failed to parse reply.");
2554 dbus_message_iter_next(&sub);
2559 if (!show_properties)
2560 print_status_info(&info);
2562 if (!streq_ptr(info.active_state, "active") &&
2563 !streq_ptr(info.active_state, "reloading") &&
2564 streq(verb, "status"))
2565 /* According to LSB: "program not running" */
2568 while ((p = info.exec)) {
2569 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2570 exec_status_info_free(p);
2575 dbus_message_unref(m);
2578 dbus_message_unref(reply);
2580 dbus_error_free(&error);
2585 static int show(DBusConnection *bus, char **args, unsigned n) {
2586 DBusMessage *m = NULL, *reply = NULL;
2590 bool show_properties, new_line = false;
2595 dbus_error_init(&error);
2597 show_properties = !streq(args[0], "status");
2599 if (show_properties)
2602 if (show_properties && n <= 1) {
2603 /* If not argument is specified inspect the manager
2606 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2610 for (i = 1; i < n; i++) {
2611 const char *path = NULL;
2614 if (safe_atou32(args[i], &id) < 0) {
2616 /* Interpret as unit name */
2618 if (!(m = dbus_message_new_method_call(
2619 "org.freedesktop.systemd1",
2620 "/org/freedesktop/systemd1",
2621 "org.freedesktop.systemd1.Manager",
2623 log_error("Could not allocate message.");
2628 if (!dbus_message_append_args(m,
2629 DBUS_TYPE_STRING, &args[i],
2630 DBUS_TYPE_INVALID)) {
2631 log_error("Could not append arguments to message.");
2636 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2638 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2639 log_error("Failed to issue method call: %s", bus_error_message(&error));
2644 dbus_error_free(&error);
2646 dbus_message_unref(m);
2647 if (!(m = dbus_message_new_method_call(
2648 "org.freedesktop.systemd1",
2649 "/org/freedesktop/systemd1",
2650 "org.freedesktop.systemd1.Manager",
2652 log_error("Could not allocate message.");
2657 if (!dbus_message_append_args(m,
2658 DBUS_TYPE_STRING, &args[i],
2659 DBUS_TYPE_INVALID)) {
2660 log_error("Could not append arguments to message.");
2665 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2666 log_error("Failed to issue method call: %s", bus_error_message(&error));
2668 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2669 ret = 4; /* According to LSB: "program or service status is unknown" */
2676 } else if (show_properties) {
2678 /* Interpret as job id */
2680 if (!(m = dbus_message_new_method_call(
2681 "org.freedesktop.systemd1",
2682 "/org/freedesktop/systemd1",
2683 "org.freedesktop.systemd1.Manager",
2685 log_error("Could not allocate message.");
2690 if (!dbus_message_append_args(m,
2691 DBUS_TYPE_UINT32, &id,
2692 DBUS_TYPE_INVALID)) {
2693 log_error("Could not append arguments to message.");
2698 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2699 log_error("Failed to issue method call: %s", bus_error_message(&error));
2705 /* Interpret as PID */
2707 if (!(m = dbus_message_new_method_call(
2708 "org.freedesktop.systemd1",
2709 "/org/freedesktop/systemd1",
2710 "org.freedesktop.systemd1.Manager",
2712 log_error("Could not allocate message.");
2717 if (!dbus_message_append_args(m,
2718 DBUS_TYPE_UINT32, &id,
2719 DBUS_TYPE_INVALID)) {
2720 log_error("Could not append arguments to message.");
2725 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2726 log_error("Failed to issue method call: %s", bus_error_message(&error));
2732 if (!dbus_message_get_args(reply, &error,
2733 DBUS_TYPE_OBJECT_PATH, &path,
2734 DBUS_TYPE_INVALID)) {
2735 log_error("Failed to parse reply: %s", bus_error_message(&error));
2740 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2743 dbus_message_unref(m);
2744 dbus_message_unref(reply);
2750 dbus_message_unref(m);
2753 dbus_message_unref(reply);
2755 dbus_error_free(&error);
2760 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2762 DBusMessage *m = NULL, *reply = NULL;
2767 dbus_error_init(&error);
2769 log_debug("Got D-Bus request: %s.%s() on %s",
2770 dbus_message_get_interface(message),
2771 dbus_message_get_member(message),
2772 dbus_message_get_path(message));
2774 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2775 log_error("Warning! D-Bus connection terminated.");
2776 dbus_connection_close(connection);
2778 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2779 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2780 const char *id, *path;
2782 if (!dbus_message_get_args(message, &error,
2783 DBUS_TYPE_STRING, &id,
2784 DBUS_TYPE_OBJECT_PATH, &path,
2786 log_error("Failed to parse message: %s", bus_error_message(&error));
2787 else if (streq(dbus_message_get_member(message), "UnitNew"))
2788 printf("Unit %s added.\n", id);
2790 printf("Unit %s removed.\n", id);
2792 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2793 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2795 const char *path, *result;
2797 if (!dbus_message_get_args(message, &error,
2798 DBUS_TYPE_UINT32, &id,
2799 DBUS_TYPE_OBJECT_PATH, &path,
2800 DBUS_TYPE_STRING, &result,
2802 log_error("Failed to parse message: %s", bus_error_message(&error));
2803 else if (streq(dbus_message_get_member(message), "JobNew"))
2804 printf("Job %u added.\n", id);
2806 printf("Job %u removed.\n", id);
2809 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2811 const char *path, *interface, *property = "Id";
2812 DBusMessageIter iter, sub;
2814 path = dbus_message_get_path(message);
2816 if (!dbus_message_get_args(message, &error,
2817 DBUS_TYPE_STRING, &interface,
2818 DBUS_TYPE_INVALID)) {
2819 log_error("Failed to parse message: %s", bus_error_message(&error));
2823 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2824 !streq(interface, "org.freedesktop.systemd1.Unit"))
2827 if (!(m = dbus_message_new_method_call(
2828 "org.freedesktop.systemd1",
2830 "org.freedesktop.DBus.Properties",
2832 log_error("Could not allocate message.");
2836 if (!dbus_message_append_args(m,
2837 DBUS_TYPE_STRING, &interface,
2838 DBUS_TYPE_STRING, &property,
2839 DBUS_TYPE_INVALID)) {
2840 log_error("Could not append arguments to message.");
2844 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2845 log_error("Failed to issue method call: %s", bus_error_message(&error));
2849 if (!dbus_message_iter_init(reply, &iter) ||
2850 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2851 log_error("Failed to parse reply.");
2855 dbus_message_iter_recurse(&iter, &sub);
2857 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2860 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2861 log_error("Failed to parse reply.");
2865 dbus_message_iter_get_basic(&sub, &id);
2866 printf("Unit %s changed.\n", id);
2870 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2871 log_error("Failed to parse reply.");
2875 dbus_message_iter_get_basic(&sub, &id);
2876 printf("Job %u changed.\n", id);
2882 dbus_message_unref(m);
2885 dbus_message_unref(reply);
2887 dbus_error_free(&error);
2888 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2892 dbus_message_unref(m);
2895 dbus_message_unref(reply);
2897 dbus_error_free(&error);
2898 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2901 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2902 DBusMessage *m = NULL, *reply = NULL;
2906 dbus_error_init(&error);
2909 dbus_bus_add_match(bus,
2911 "sender='org.freedesktop.systemd1',"
2912 "interface='org.freedesktop.systemd1.Manager',"
2913 "path='/org/freedesktop/systemd1'",
2916 if (dbus_error_is_set(&error)) {
2917 log_error("Failed to add match: %s", bus_error_message(&error));
2922 dbus_bus_add_match(bus,
2924 "sender='org.freedesktop.systemd1',"
2925 "interface='org.freedesktop.DBus.Properties',"
2926 "member='PropertiesChanged'",
2929 if (dbus_error_is_set(&error)) {
2930 log_error("Failed to add match: %s", bus_error_message(&error));
2936 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2937 log_error("Failed to add filter.");
2942 if (!(m = dbus_message_new_method_call(
2943 "org.freedesktop.systemd1",
2944 "/org/freedesktop/systemd1",
2945 "org.freedesktop.systemd1.Manager",
2947 log_error("Could not allocate message.");
2952 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2953 log_error("Failed to issue method call: %s", bus_error_message(&error));
2958 while (dbus_connection_read_write_dispatch(bus, -1))
2965 /* This is slightly dirty, since we don't undo the filter or the matches. */
2968 dbus_message_unref(m);
2971 dbus_message_unref(reply);
2973 dbus_error_free(&error);
2978 static int dump(DBusConnection *bus, char **args, unsigned n) {
2979 DBusMessage *m = NULL, *reply = NULL;
2984 dbus_error_init(&error);
2988 if (!(m = dbus_message_new_method_call(
2989 "org.freedesktop.systemd1",
2990 "/org/freedesktop/systemd1",
2991 "org.freedesktop.systemd1.Manager",
2993 log_error("Could not allocate message.");
2997 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2998 log_error("Failed to issue method call: %s", bus_error_message(&error));
3003 if (!dbus_message_get_args(reply, &error,
3004 DBUS_TYPE_STRING, &text,
3005 DBUS_TYPE_INVALID)) {
3006 log_error("Failed to parse reply: %s", bus_error_message(&error));
3011 fputs(text, stdout);
3017 dbus_message_unref(m);
3020 dbus_message_unref(reply);
3022 dbus_error_free(&error);
3027 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3028 DBusMessage *m = NULL, *reply = NULL;
3031 const char *name = "", *path, *id;
3032 dbus_bool_t cleanup = FALSE;
3033 DBusMessageIter iter, sub;
3035 *interface = "org.freedesktop.systemd1.Unit",
3038 dbus_error_init(&error);
3040 if (!(m = dbus_message_new_method_call(
3041 "org.freedesktop.systemd1",
3042 "/org/freedesktop/systemd1",
3043 "org.freedesktop.systemd1.Manager",
3044 "CreateSnapshot"))) {
3045 log_error("Could not allocate message.");
3052 if (!dbus_message_append_args(m,
3053 DBUS_TYPE_STRING, &name,
3054 DBUS_TYPE_BOOLEAN, &cleanup,
3055 DBUS_TYPE_INVALID)) {
3056 log_error("Could not append arguments to message.");
3061 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3062 log_error("Failed to issue method call: %s", bus_error_message(&error));
3067 if (!dbus_message_get_args(reply, &error,
3068 DBUS_TYPE_OBJECT_PATH, &path,
3069 DBUS_TYPE_INVALID)) {
3070 log_error("Failed to parse reply: %s", bus_error_message(&error));
3075 dbus_message_unref(m);
3076 if (!(m = dbus_message_new_method_call(
3077 "org.freedesktop.systemd1",
3079 "org.freedesktop.DBus.Properties",
3081 log_error("Could not allocate message.");
3085 if (!dbus_message_append_args(m,
3086 DBUS_TYPE_STRING, &interface,
3087 DBUS_TYPE_STRING, &property,
3088 DBUS_TYPE_INVALID)) {
3089 log_error("Could not append arguments to message.");
3094 dbus_message_unref(reply);
3095 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3096 log_error("Failed to issue method call: %s", bus_error_message(&error));
3101 if (!dbus_message_iter_init(reply, &iter) ||
3102 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3103 log_error("Failed to parse reply.");
3108 dbus_message_iter_recurse(&iter, &sub);
3110 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3111 log_error("Failed to parse reply.");
3116 dbus_message_iter_get_basic(&sub, &id);
3124 dbus_message_unref(m);
3127 dbus_message_unref(reply);
3129 dbus_error_free(&error);
3134 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3135 DBusMessage *m = NULL, *reply = NULL;
3143 dbus_error_init(&error);
3145 for (i = 1; i < n; i++) {
3146 const char *path = NULL;
3148 if (!(m = dbus_message_new_method_call(
3149 "org.freedesktop.systemd1",
3150 "/org/freedesktop/systemd1",
3151 "org.freedesktop.systemd1.Manager",
3153 log_error("Could not allocate message.");
3158 if (!dbus_message_append_args(m,
3159 DBUS_TYPE_STRING, &args[i],
3160 DBUS_TYPE_INVALID)) {
3161 log_error("Could not append arguments to message.");
3166 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3167 log_error("Failed to issue method call: %s", bus_error_message(&error));
3172 if (!dbus_message_get_args(reply, &error,
3173 DBUS_TYPE_OBJECT_PATH, &path,
3174 DBUS_TYPE_INVALID)) {
3175 log_error("Failed to parse reply: %s", bus_error_message(&error));
3180 dbus_message_unref(m);
3181 if (!(m = dbus_message_new_method_call(
3182 "org.freedesktop.systemd1",
3184 "org.freedesktop.systemd1.Snapshot",
3186 log_error("Could not allocate message.");
3191 dbus_message_unref(reply);
3192 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3193 log_error("Failed to issue method call: %s", bus_error_message(&error));
3198 dbus_message_unref(m);
3199 dbus_message_unref(reply);
3207 dbus_message_unref(m);
3210 dbus_message_unref(reply);
3212 dbus_error_free(&error);
3217 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3218 DBusMessage *m = NULL, *reply = NULL;
3223 dbus_error_init(&error);
3225 if (arg_action == ACTION_RELOAD)
3227 else if (arg_action == ACTION_REEXEC)
3228 method = "Reexecute";
3230 assert(arg_action == ACTION_SYSTEMCTL);
3233 streq(args[0], "clear-jobs") ||
3234 streq(args[0], "cancel") ? "ClearJobs" :
3235 streq(args[0], "daemon-reexec") ? "Reexecute" :
3236 streq(args[0], "reset-failed") ? "ResetFailed" :
3237 streq(args[0], "halt") ? "Halt" :
3238 streq(args[0], "poweroff") ? "PowerOff" :
3239 streq(args[0], "reboot") ? "Reboot" :
3240 streq(args[0], "kexec") ? "KExec" :
3241 streq(args[0], "exit") ? "Exit" :
3242 /* "daemon-reload" */ "Reload";
3245 if (!(m = dbus_message_new_method_call(
3246 "org.freedesktop.systemd1",
3247 "/org/freedesktop/systemd1",
3248 "org.freedesktop.systemd1.Manager",
3250 log_error("Could not allocate message.");
3254 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3256 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3257 /* There's always a fallback possible for
3258 * legacy actions. */
3263 log_error("Failed to issue method call: %s", bus_error_message(&error));
3272 dbus_message_unref(m);
3275 dbus_message_unref(reply);
3277 dbus_error_free(&error);
3282 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3283 DBusMessage *m = NULL, *reply = NULL;
3289 dbus_error_init(&error);
3292 return daemon_reload(bus, args, n);
3294 for (i = 1; i < n; i++) {
3296 if (!(m = dbus_message_new_method_call(
3297 "org.freedesktop.systemd1",
3298 "/org/freedesktop/systemd1",
3299 "org.freedesktop.systemd1.Manager",
3300 "ResetFailedUnit"))) {
3301 log_error("Could not allocate message.");
3306 if (!dbus_message_append_args(m,
3307 DBUS_TYPE_STRING, args + i,
3308 DBUS_TYPE_INVALID)) {
3309 log_error("Could not append arguments to message.");
3314 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3315 log_error("Failed to issue method call: %s", bus_error_message(&error));
3320 dbus_message_unref(m);
3321 dbus_message_unref(reply);
3329 dbus_message_unref(m);
3332 dbus_message_unref(reply);
3334 dbus_error_free(&error);
3339 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3340 DBusMessage *m = NULL, *reply = NULL;
3342 DBusMessageIter iter, sub, sub2;
3345 *interface = "org.freedesktop.systemd1.Manager",
3346 *property = "Environment";
3348 dbus_error_init(&error);
3352 if (!(m = dbus_message_new_method_call(
3353 "org.freedesktop.systemd1",
3354 "/org/freedesktop/systemd1",
3355 "org.freedesktop.DBus.Properties",
3357 log_error("Could not allocate message.");
3361 if (!dbus_message_append_args(m,
3362 DBUS_TYPE_STRING, &interface,
3363 DBUS_TYPE_STRING, &property,
3364 DBUS_TYPE_INVALID)) {
3365 log_error("Could not append arguments to message.");
3370 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3371 log_error("Failed to issue method call: %s", bus_error_message(&error));
3376 if (!dbus_message_iter_init(reply, &iter) ||
3377 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3378 log_error("Failed to parse reply.");
3383 dbus_message_iter_recurse(&iter, &sub);
3385 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3386 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3387 log_error("Failed to parse reply.");
3392 dbus_message_iter_recurse(&sub, &sub2);
3394 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3397 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3398 log_error("Failed to parse reply.");
3403 dbus_message_iter_get_basic(&sub2, &text);
3404 printf("%s\n", text);
3406 dbus_message_iter_next(&sub2);
3413 dbus_message_unref(m);
3416 dbus_message_unref(reply);
3418 dbus_error_free(&error);
3423 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3424 DBusMessage *m = NULL, *reply = NULL;
3428 DBusMessageIter iter, sub;
3431 dbus_error_init(&error);
3433 method = streq(args[0], "set-environment")
3435 : "UnsetEnvironment";
3437 if (!(m = dbus_message_new_method_call(
3438 "org.freedesktop.systemd1",
3439 "/org/freedesktop/systemd1",
3440 "org.freedesktop.systemd1.Manager",
3443 log_error("Could not allocate message.");
3447 dbus_message_iter_init_append(m, &iter);
3449 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3450 log_error("Could not append arguments to message.");
3455 for (i = 1; i < n; i++)
3456 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3457 log_error("Could not append arguments to message.");
3462 if (!dbus_message_iter_close_container(&iter, &sub)) {
3463 log_error("Could not append arguments to message.");
3468 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3469 log_error("Failed to issue method call: %s", bus_error_message(&error));
3478 dbus_message_unref(m);
3481 dbus_message_unref(reply);
3483 dbus_error_free(&error);
3496 static Hashmap *will_install = NULL, *have_installed = NULL;
3497 static Set *remove_symlinks_to = NULL;
3498 static unsigned n_symlinks = 0;
3500 static void install_info_free(InstallInfo *i) {
3505 strv_free(i->aliases);
3506 strv_free(i->wanted_by);
3510 static void install_info_hashmap_free(Hashmap *m) {
3513 while ((i = hashmap_steal_first(m)))
3514 install_info_free(i);
3519 static int install_info_add(const char *name) {
3523 assert(will_install);
3525 if (!unit_name_is_valid_no_type(name, true)) {
3526 log_warning("Unit name %s is not a valid unit name.", name);
3530 if (hashmap_get(have_installed, name) ||
3531 hashmap_get(will_install, name))
3534 if (!(i = new0(InstallInfo, 1))) {
3539 if (!(i->name = strdup(name))) {
3544 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3551 install_info_free(i);
3556 static int config_parse_also(
3557 const char *filename,
3559 const char *section,
3573 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3577 if (!(n = strndup(w, l)))
3580 if ((r = install_info_add(n)) < 0) {
3581 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3592 static int mark_symlink_for_removal(const char *p) {
3597 assert(path_is_absolute(p));
3599 if (!remove_symlinks_to)
3602 if (!(n = strdup(p)))
3605 path_kill_slashes(n);
3607 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3609 return r == -EEXIST ? 0 : r;
3615 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3624 if (!(d = fdopendir(fd))) {
3625 close_nointr_nofail(fd);
3631 while ((de = readdir(d))) {
3632 bool is_dir = false, is_link = false;
3634 if (ignore_file(de->d_name))
3637 if (de->d_type == DT_LNK)
3639 else if (de->d_type == DT_DIR)
3641 else if (de->d_type == DT_UNKNOWN) {
3644 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3645 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3652 is_link = S_ISLNK(st.st_mode);
3653 is_dir = S_ISDIR(st.st_mode);
3661 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3662 log_error("Failed to open %s/%s: %m", root, de->d_name);
3669 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3670 log_error("Failed to allocate directory string.");
3671 close_nointr_nofail(nfd);
3676 /* This will close nfd, regardless whether it succeeds or not */
3677 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3683 } else if (is_link) {
3687 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3688 log_error("Failed to allocate symlink string.");
3693 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3694 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3702 if ((c = canonicalize_file_name(dest))) {
3703 /* This might fail if the destination
3704 * is already removed */
3710 path_kill_slashes(dest);
3711 if (set_get(remove_symlinks_to, dest)) {
3714 log_info("rm '%s'", p);
3716 if (unlink(p) < 0) {
3717 log_error("Cannot unlink symlink %s: %m", p);
3722 rmdir_parents(p, config_path);
3723 path_kill_slashes(p);
3725 if (!set_get(remove_symlinks_to, p)) {
3727 if ((r = mark_symlink_for_removal(p)) < 0) {
3746 static int remove_marked_symlinks(const char *config_path) {
3750 assert(config_path);
3752 if (set_size(remove_symlinks_to) <= 0)
3755 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3762 if ((cfd = dup(fd)) < 0) {
3767 /* This takes possession of cfd and closes it */
3768 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3774 close_nointr_nofail(fd);
3779 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3786 if (streq(verb, "enable")) {
3789 mkdir_parents(new_path, 0755);
3791 if (symlink(old_path, new_path) >= 0) {
3794 log_info("ln -s '%s' '%s'", old_path, new_path);
3799 if (errno != EEXIST) {
3800 log_error("Cannot link %s to %s: %m", old_path, new_path);
3804 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3806 if (errno == EINVAL) {
3807 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3811 log_error("readlink() failed: %s", strerror(-r));
3815 if (streq(dest, old_path)) {
3821 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3830 log_info("ln -s '%s' '%s'", old_path, new_path);
3832 if (symlink(old_path, new_path) >= 0)
3835 log_error("Cannot link %s to %s: %m", old_path, new_path);
3838 } else if (streq(verb, "disable")) {
3841 if ((r = mark_symlink_for_removal(old_path)) < 0)
3844 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3845 if (errno == ENOENT)
3848 if (errno == EINVAL) {
3849 log_warning("File %s not a symlink, ignoring.", old_path);
3853 log_error("readlink() failed: %s", strerror(-r));
3857 if (!streq(dest, old_path)) {
3858 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3865 if ((r = mark_symlink_for_removal(new_path)) < 0)
3869 log_info("rm '%s'", new_path);
3871 if (unlink(new_path) >= 0)
3874 log_error("Cannot unlink %s: %m", new_path);
3877 } else if (streq(verb, "is-enabled")) {
3880 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3882 if (errno == ENOENT || errno == EINVAL)
3885 log_error("readlink() failed: %s", strerror(-r));
3889 if (streq(dest, old_path)) {
3897 assert_not_reached("Unknown action.");
3900 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3902 char *alias_path = NULL;
3907 assert(config_path);
3909 STRV_FOREACH(s, i->aliases) {
3912 if (!(alias_path = path_make_absolute(*s, config_path))) {
3913 log_error("Out of memory");
3918 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3921 if (streq(verb, "disable"))
3922 rmdir_parents(alias_path, config_path);
3932 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3934 char *alias_path = NULL;
3939 assert(config_path);
3941 STRV_FOREACH(s, i->wanted_by) {
3942 if (!unit_name_is_valid_no_type(*s, true)) {
3943 log_error("Invalid name %s.", *s);
3951 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3952 log_error("Out of memory");
3957 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3960 if (streq(verb, "disable"))
3961 rmdir_parents(alias_path, config_path);
3972 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3974 const ConfigItem items[] = {
3975 { "Alias", config_parse_strv, &i->aliases, "Install" },
3976 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3977 { "Also", config_parse_also, NULL, "Install" },
3979 { NULL, NULL, NULL, NULL }
3983 char *filename = NULL;
3990 STRV_FOREACH(p, paths->unit_path) {
3993 if (!(filename = path_make_absolute(i->name, *p))) {
3994 log_error("Out of memory");
3998 /* Ensure that we don't follow symlinks */
3999 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
4000 if ((f = fdopen(fd, "re")))
4003 if (errno == ELOOP) {
4004 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4009 if (errno != ENOENT) {
4010 log_error("Failed to open %s: %m", filename);
4020 #if defined(TARGET_FEDORA) && defined (HAVE_SYSV_COMPAT)
4022 if (endswith(i->name, ".service")) {
4026 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4027 log_error("Out of memory");
4031 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4032 exists = access(sysv, F_OK) >= 0;
4038 const char *argv[] = {
4045 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4047 argv[1] = file_name_from_path(sysv);
4049 streq(verb, "enable") ? "on" :
4050 streq(verb, "disable") ? "off" : NULL;
4052 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
4054 if ((pid = fork()) < 0) {
4055 log_error("Failed to fork: %m");
4058 } else if (pid == 0) {
4059 execv(argv[0], (char**) argv);
4060 _exit(EXIT_FAILURE);
4065 if ((r = wait_for_terminate(pid, &status)) < 0)
4068 if (status.si_code == CLD_EXITED) {
4069 if (status.si_status == 0 && (streq(verb, "enable") || streq(verb, "disable")))
4072 return status.si_status == 0 ? 0 : -EINVAL;
4082 log_error("Couldn't find %s.", i->name);
4088 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4093 n_symlinks += strv_length(i->aliases);
4094 n_symlinks += strv_length(i->wanted_by);
4098 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4101 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4104 if ((r = mark_symlink_for_removal(filename)) < 0)
4107 if ((r = remove_marked_symlinks(config_path)) < 0)
4113 static char *get_config_path(void) {
4115 if (arg_user && arg_global)
4116 return strdup(USER_CONFIG_UNIT_PATH);
4121 if (user_config_home(&p) < 0)
4127 return strdup(SYSTEM_CONFIG_UNIT_PATH);
4130 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4134 char *config_path = NULL;
4137 const char *verb = args[0];
4139 dbus_error_init(&error);
4142 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4143 log_error("Failed to determine lookup paths: %s", strerror(-r));
4147 if (!(config_path = get_config_path())) {
4148 log_error("Failed to determine config path");
4153 will_install = hashmap_new(string_hash_func, string_compare_func);
4154 have_installed = hashmap_new(string_hash_func, string_compare_func);
4156 if (!will_install || !have_installed) {
4157 log_error("Failed to allocate unit sets.");
4162 if (!arg_defaults && streq(verb, "disable"))
4163 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4164 log_error("Failed to allocate symlink sets.");
4169 for (j = 1; j < n; j++)
4170 if ((r = install_info_add(args[j])) < 0) {
4171 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4175 while ((i = hashmap_first(will_install))) {
4178 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4180 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4188 /* In test mode and found something */
4194 if (streq(verb, "is-enabled"))
4195 r = r > 0 ? 0 : -ENOENT;
4197 if (n_symlinks <= 0)
4198 log_warning("Unit files contain no applicable installation information. Ignoring.");
4201 /* Don't try to reload anything if the user asked us to not do this */
4203 /* Don't try to reload anything when updating a unit globally */
4205 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4206 (arg_user || sd_booted() > 0) &&
4207 /* Don't try to reload anything if we are running in a chroot environment */
4208 (arg_user || running_in_chroot() <= 0) ) {
4211 if ((q = daemon_reload(bus, args, n)) < 0)
4217 install_info_hashmap_free(will_install);
4218 install_info_hashmap_free(have_installed);
4220 set_free_free(remove_symlinks_to);
4222 lookup_paths_free(&paths);
4229 static int systemctl_help(void) {
4231 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4232 "Send control commands to or query the systemd manager.\n\n"
4233 " -h --help Show this help\n"
4234 " --version Show package version\n"
4235 " -t --type=TYPE List only units of a particular type\n"
4236 " -p --property=NAME Show only properties by this name\n"
4237 " -a --all Show all units/properties, including dead/empty ones\n"
4238 " --failed Show only failed units\n"
4239 " --full Don't ellipsize unit names on output\n"
4240 " --fail When queueing a new job, fail if conflicting jobs are\n"
4242 " --ignore-dependencies\n"
4243 " When queueing a new job, ignore all its dependencies\n"
4244 " -q --quiet Suppress output\n"
4245 " --no-block Do not wait until operation finished\n"
4246 " --no-pager Do not pipe output into a pager.\n"
4247 " --system Connect to system manager\n"
4248 " --user Connect to user service manager\n"
4249 " --order When generating graph for dot, show only order\n"
4250 " --require When generating graph for dot, show only requirement\n"
4251 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4252 " --global Enable/disable unit files globally\n"
4253 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4255 " --no-ask-password\n"
4256 " Do not ask for system passwords\n"
4257 " --kill-mode=MODE How to send signal\n"
4258 " --kill-who=WHO Who to send signal to\n"
4259 " -s --signal=SIGNAL Which signal to send\n"
4260 " -f --force When enabling unit files, override existing symlinks\n"
4261 " When shutting down, execute action immediately\n"
4262 " --defaults When disabling unit files, remove default symlinks only\n\n"
4264 " list-units List units\n"
4265 " start [NAME...] Start (activate) one or more units\n"
4266 " stop [NAME...] Stop (deactivate) one or more units\n"
4267 " reload [NAME...] Reload one or more units\n"
4268 " restart [NAME...] Start or restart one or more units\n"
4269 " try-restart [NAME...] Restart one or more units if active\n"
4270 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4271 " otherwise start or restart\n"
4272 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4273 " otherwise restart if active\n"
4274 " isolate [NAME] Start one unit and stop all others\n"
4275 " kill [NAME...] Send signal to processes of a unit\n"
4276 " is-active [NAME...] Check whether units are active\n"
4277 " status [NAME...|PID...] Show runtime status of one or more units\n"
4278 " show [NAME...|JOB...] Show properties of one or more\n"
4279 " units/jobs or the manager\n"
4280 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4282 " enable [NAME...] Enable one or more unit files\n"
4283 " disable [NAME...] Disable one or more unit files\n"
4284 " is-enabled [NAME...] Check whether unit files are enabled\n"
4285 " load [NAME...] Load one or more units\n"
4286 " list-jobs List jobs\n"
4287 " cancel [JOB...] Cancel all, one, or more jobs\n"
4288 " monitor Monitor unit/job changes\n"
4289 " dump Dump server status\n"
4290 " dot Dump dependency graph for dot(1)\n"
4291 " snapshot [NAME] Create a snapshot\n"
4292 " delete [NAME...] Remove one or more snapshots\n"
4293 " daemon-reload Reload systemd manager configuration\n"
4294 " daemon-reexec Reexecute systemd manager\n"
4295 " show-environment Dump environment\n"
4296 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4297 " unset-environment [NAME...] Unset one or more environment variables\n"
4298 " default Enter system default mode\n"
4299 " rescue Enter system rescue mode\n"
4300 " emergency Enter system emergency mode\n"
4301 " halt Shut down and halt the system\n"
4302 " poweroff Shut down and power-off the system\n"
4303 " reboot Shut down and reboot the system\n"
4304 " kexec Shut down and reboot the system with kexec\n"
4305 " exit Ask for user instance termination\n",
4306 program_invocation_short_name);
4311 static int halt_help(void) {
4313 printf("%s [OPTIONS...]\n\n"
4314 "%s the system.\n\n"
4315 " --help Show this help\n"
4316 " --halt Halt the machine\n"
4317 " -p --poweroff Switch off the machine\n"
4318 " --reboot Reboot the machine\n"
4319 " -f --force Force immediate halt/power-off/reboot\n"
4320 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4321 " -d --no-wtmp Don't write wtmp record\n"
4322 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4323 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4324 program_invocation_short_name,
4325 arg_action == ACTION_REBOOT ? "Reboot" :
4326 arg_action == ACTION_POWEROFF ? "Power off" :
4332 static int shutdown_help(void) {
4334 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4335 "Shut down the system.\n\n"
4336 " --help Show this help\n"
4337 " -H --halt Halt the machine\n"
4338 " -P --poweroff Power-off the machine\n"
4339 " -r --reboot Reboot the machine\n"
4340 " -h Equivalent to --poweroff, overriden by --halt\n"
4341 " -k Don't halt/power-off/reboot, just send warnings\n"
4342 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4343 " -c Cancel a pending shutdown\n",
4344 program_invocation_short_name);
4349 static int telinit_help(void) {
4351 printf("%s [OPTIONS...] {COMMAND}\n\n"
4352 "Send control commands to the init daemon.\n\n"
4353 " --help Show this help\n"
4354 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4356 " 0 Power-off the machine\n"
4357 " 6 Reboot the machine\n"
4358 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4359 " 1, s, S Enter rescue mode\n"
4360 " q, Q Reload init daemon configuration\n"
4361 " u, U Reexecute init daemon\n",
4362 program_invocation_short_name);
4367 static int runlevel_help(void) {
4369 printf("%s [OPTIONS...]\n\n"
4370 "Prints the previous and current runlevel of the init system.\n\n"
4371 " --help Show this help\n",
4372 program_invocation_short_name);
4377 static int systemctl_parse_argv(int argc, char *argv[]) {
4381 ARG_IGNORE_DEPENDENCIES,
4396 ARG_NO_ASK_PASSWORD,
4400 static const struct option options[] = {
4401 { "help", no_argument, NULL, 'h' },
4402 { "version", no_argument, NULL, ARG_VERSION },
4403 { "type", required_argument, NULL, 't' },
4404 { "property", required_argument, NULL, 'p' },
4405 { "all", no_argument, NULL, 'a' },
4406 { "failed", no_argument, NULL, ARG_FAILED },
4407 { "full", no_argument, NULL, ARG_FULL },
4408 { "fail", no_argument, NULL, ARG_FAIL },
4409 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4410 { "user", no_argument, NULL, ARG_USER },
4411 { "system", no_argument, NULL, ARG_SYSTEM },
4412 { "global", no_argument, NULL, ARG_GLOBAL },
4413 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4414 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4415 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4416 { "quiet", no_argument, NULL, 'q' },
4417 { "order", no_argument, NULL, ARG_ORDER },
4418 { "require", no_argument, NULL, ARG_REQUIRE },
4419 { "force", no_argument, NULL, 'f' },
4420 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4421 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4422 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4423 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4424 { "signal", required_argument, NULL, 's' },
4425 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4426 { NULL, 0, NULL, 0 }
4434 /* Only when running as systemctl we ask for passwords */
4435 arg_ask_password = true;
4437 while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4446 puts(PACKAGE_STRING);
4448 puts(SYSTEMD_FEATURES);
4458 if (!(l = strv_append(arg_property, optarg)))
4461 strv_free(arg_property);
4464 /* If the user asked for a particular
4465 * property, show it to him, even if it is
4476 arg_job_mode = "fail";
4479 case ARG_IGNORE_DEPENDENCIES:
4480 arg_job_mode = "ignore-dependencies";
4492 arg_no_block = true;
4496 arg_no_pager = true;
4504 arg_dot = DOT_ORDER;
4508 arg_dot = DOT_REQUIRE;
4528 arg_no_reload = true;
4537 arg_defaults = true;
4541 arg_kill_who = optarg;
4545 arg_kill_mode = optarg;
4549 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4550 log_error("Failed to parse signal string %s.", optarg);
4555 case ARG_NO_ASK_PASSWORD:
4556 arg_ask_password = false;
4563 log_error("Unknown option code %c", c);
4571 static int halt_parse_argv(int argc, char *argv[]) {
4580 static const struct option options[] = {
4581 { "help", no_argument, NULL, ARG_HELP },
4582 { "halt", no_argument, NULL, ARG_HALT },
4583 { "poweroff", no_argument, NULL, 'p' },
4584 { "reboot", no_argument, NULL, ARG_REBOOT },
4585 { "force", no_argument, NULL, 'f' },
4586 { "wtmp-only", no_argument, NULL, 'w' },
4587 { "no-wtmp", no_argument, NULL, 'd' },
4588 { "no-sync", no_argument, NULL, 'n' },
4589 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4590 { NULL, 0, NULL, 0 }
4598 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4599 if (runlevel == '0' || runlevel == '6')
4600 arg_immediate = true;
4602 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4610 arg_action = ACTION_HALT;
4614 if (arg_action != ACTION_REBOOT)
4615 arg_action = ACTION_POWEROFF;
4619 arg_action = ACTION_REBOOT;
4623 arg_immediate = true;
4644 /* Compatibility nops */
4651 log_error("Unknown option code %c", c);
4656 if (optind < argc) {
4657 log_error("Too many arguments.");
4664 static int parse_time_spec(const char *t, usec_t *_u) {
4668 if (streq(t, "now"))
4670 else if (t[0] == '+') {
4673 if (safe_atou64(t + 1, &u) < 0)
4676 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4685 hour = strtol(t, &e, 10);
4686 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4689 minute = strtol(e+1, &e, 10);
4690 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4693 n = now(CLOCK_REALTIME);
4694 s = (time_t) (n / USEC_PER_SEC);
4697 assert_se(localtime_r(&s, &tm));
4699 tm.tm_hour = (int) hour;
4700 tm.tm_min = (int) minute;
4703 assert_se(s = mktime(&tm));
4705 *_u = (usec_t) s * USEC_PER_SEC;
4708 *_u += USEC_PER_DAY;
4714 static bool kexec_loaded(void) {
4715 bool loaded = false;
4718 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4726 static int shutdown_parse_argv(int argc, char *argv[]) {
4733 static const struct option options[] = {
4734 { "help", no_argument, NULL, ARG_HELP },
4735 { "halt", no_argument, NULL, 'H' },
4736 { "poweroff", no_argument, NULL, 'P' },
4737 { "reboot", no_argument, NULL, 'r' },
4738 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4739 { NULL, 0, NULL, 0 }
4747 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4755 arg_action = ACTION_HALT;
4759 arg_action = ACTION_POWEROFF;
4764 arg_action = ACTION_KEXEC;
4766 arg_action = ACTION_REBOOT;
4770 if (arg_action != ACTION_HALT)
4771 arg_action = ACTION_POWEROFF;
4784 /* Compatibility nops */
4788 arg_action = ACTION_CANCEL_SHUTDOWN;
4795 log_error("Unknown option code %c", c);
4800 if (argc > optind) {
4801 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4802 log_error("Failed to parse time specification: %s", argv[optind]);
4806 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4808 /* We skip the time argument */
4809 if (argc > optind + 1)
4810 arg_wall = argv + optind + 1;
4817 static int telinit_parse_argv(int argc, char *argv[]) {
4824 static const struct option options[] = {
4825 { "help", no_argument, NULL, ARG_HELP },
4826 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4827 { NULL, 0, NULL, 0 }
4830 static const struct {
4834 { '0', ACTION_POWEROFF },
4835 { '6', ACTION_REBOOT },
4836 { '1', ACTION_RESCUE },
4837 { '2', ACTION_RUNLEVEL2 },
4838 { '3', ACTION_RUNLEVEL3 },
4839 { '4', ACTION_RUNLEVEL4 },
4840 { '5', ACTION_RUNLEVEL5 },
4841 { 's', ACTION_RESCUE },
4842 { 'S', ACTION_RESCUE },
4843 { 'q', ACTION_RELOAD },
4844 { 'Q', ACTION_RELOAD },
4845 { 'u', ACTION_REEXEC },
4846 { 'U', ACTION_REEXEC }
4855 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4870 log_error("Unknown option code %c", c);
4875 if (optind >= argc) {
4880 if (optind + 1 < argc) {
4881 log_error("Too many arguments.");
4885 if (strlen(argv[optind]) != 1) {
4886 log_error("Expected single character argument.");
4890 for (i = 0; i < ELEMENTSOF(table); i++)
4891 if (table[i].from == argv[optind][0])
4894 if (i >= ELEMENTSOF(table)) {
4895 log_error("Unknown command %s.", argv[optind]);
4899 arg_action = table[i].to;
4906 static int runlevel_parse_argv(int argc, char *argv[]) {
4912 static const struct option options[] = {
4913 { "help", no_argument, NULL, ARG_HELP },
4914 { NULL, 0, NULL, 0 }
4922 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4933 log_error("Unknown option code %c", c);
4938 if (optind < argc) {
4939 log_error("Too many arguments.");
4946 static int parse_argv(int argc, char *argv[]) {
4950 if (program_invocation_short_name) {
4952 if (strstr(program_invocation_short_name, "halt")) {
4953 arg_action = ACTION_HALT;
4954 return halt_parse_argv(argc, argv);
4955 } else if (strstr(program_invocation_short_name, "poweroff")) {
4956 arg_action = ACTION_POWEROFF;
4957 return halt_parse_argv(argc, argv);
4958 } else if (strstr(program_invocation_short_name, "reboot")) {
4960 arg_action = ACTION_KEXEC;
4962 arg_action = ACTION_REBOOT;
4963 return halt_parse_argv(argc, argv);
4964 } else if (strstr(program_invocation_short_name, "shutdown")) {
4965 arg_action = ACTION_POWEROFF;
4966 return shutdown_parse_argv(argc, argv);
4967 } else if (strstr(program_invocation_short_name, "init")) {
4969 if (sd_booted() > 0) {
4970 arg_action = ACTION_INVALID;
4971 return telinit_parse_argv(argc, argv);
4973 /* Hmm, so some other init system is
4974 * running, we need to forward this
4975 * request to it. For now we simply
4976 * guess that it is Upstart. */
4978 execv("/lib/upstart/telinit", argv);
4980 log_error("Couldn't find an alternative telinit implementation to spawn.");
4984 } else if (strstr(program_invocation_short_name, "runlevel")) {
4985 arg_action = ACTION_RUNLEVEL;
4986 return runlevel_parse_argv(argc, argv);
4990 arg_action = ACTION_SYSTEMCTL;
4991 return systemctl_parse_argv(argc, argv);
4994 static int action_to_runlevel(void) {
4996 static const char table[_ACTION_MAX] = {
4997 [ACTION_HALT] = '0',
4998 [ACTION_POWEROFF] = '0',
4999 [ACTION_REBOOT] = '6',
5000 [ACTION_RUNLEVEL2] = '2',
5001 [ACTION_RUNLEVEL3] = '3',
5002 [ACTION_RUNLEVEL4] = '4',
5003 [ACTION_RUNLEVEL5] = '5',
5004 [ACTION_RESCUE] = '1'
5007 assert(arg_action < _ACTION_MAX);
5009 return table[arg_action];
5012 static int talk_upstart(void) {
5013 DBusMessage *m = NULL, *reply = NULL;
5015 int previous, rl, r;
5017 env1_buf[] = "RUNLEVEL=X",
5018 env2_buf[] = "PREVLEVEL=X";
5019 char *env1 = env1_buf, *env2 = env2_buf;
5020 const char *emit = "runlevel";
5021 dbus_bool_t b_false = FALSE;
5022 DBusMessageIter iter, sub;
5023 DBusConnection *bus;
5025 dbus_error_init(&error);
5027 if (!(rl = action_to_runlevel()))
5030 if (utmp_get_runlevel(&previous, NULL) < 0)
5033 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5034 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5039 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5044 if ((r = bus_check_peercred(bus)) < 0) {
5045 log_error("Failed to verify owner of bus.");
5049 if (!(m = dbus_message_new_method_call(
5050 "com.ubuntu.Upstart",
5051 "/com/ubuntu/Upstart",
5052 "com.ubuntu.Upstart0_6",
5055 log_error("Could not allocate message.");
5060 dbus_message_iter_init_append(m, &iter);
5062 env1_buf[sizeof(env1_buf)-2] = rl;
5063 env2_buf[sizeof(env2_buf)-2] = previous;
5065 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5066 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5067 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5068 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5069 !dbus_message_iter_close_container(&iter, &sub) ||
5070 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5071 log_error("Could not append arguments to message.");
5076 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5078 if (error_is_no_service(&error)) {
5083 log_error("Failed to issue method call: %s", bus_error_message(&error));
5092 dbus_message_unref(m);
5095 dbus_message_unref(reply);
5098 dbus_connection_flush(bus);
5099 dbus_connection_close(bus);
5100 dbus_connection_unref(bus);
5103 dbus_error_free(&error);
5108 static int talk_initctl(void) {
5109 struct init_request request;
5113 if (!(rl = action_to_runlevel()))
5117 request.magic = INIT_MAGIC;
5118 request.sleeptime = 0;
5119 request.cmd = INIT_CMD_RUNLVL;
5120 request.runlevel = rl;
5122 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5124 if (errno == ENOENT)
5127 log_error("Failed to open "INIT_FIFO": %m");
5132 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5133 close_nointr_nofail(fd);
5136 log_error("Failed to write to "INIT_FIFO": %m");
5137 return errno ? -errno : -EIO;
5143 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5145 static const struct {
5153 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5155 { "list-units", LESS, 1, list_units },
5156 { "list-jobs", EQUAL, 1, list_jobs },
5157 { "clear-jobs", EQUAL, 1, daemon_reload },
5158 { "load", MORE, 2, load_unit },
5159 { "cancel", MORE, 2, cancel_job },
5160 { "start", MORE, 2, start_unit },
5161 { "stop", MORE, 2, start_unit },
5162 { "reload", MORE, 2, start_unit },
5163 { "restart", MORE, 2, start_unit },
5164 { "try-restart", MORE, 2, start_unit },
5165 { "reload-or-restart", MORE, 2, start_unit },
5166 { "reload-or-try-restart", MORE, 2, start_unit },
5167 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5168 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5169 { "isolate", EQUAL, 2, start_unit },
5170 { "kill", MORE, 2, kill_unit },
5171 { "is-active", MORE, 2, check_unit },
5172 { "check", MORE, 2, check_unit },
5173 { "show", MORE, 1, show },
5174 { "status", MORE, 2, show },
5175 { "monitor", EQUAL, 1, monitor },
5176 { "dump", EQUAL, 1, dump },
5177 { "dot", EQUAL, 1, dot },
5178 { "snapshot", LESS, 2, snapshot },
5179 { "delete", MORE, 2, delete_snapshot },
5180 { "daemon-reload", EQUAL, 1, daemon_reload },
5181 { "daemon-reexec", EQUAL, 1, daemon_reload },
5182 { "show-environment", EQUAL, 1, show_enviroment },
5183 { "set-environment", MORE, 2, set_environment },
5184 { "unset-environment", MORE, 2, set_environment },
5185 { "halt", EQUAL, 1, start_special },
5186 { "poweroff", EQUAL, 1, start_special },
5187 { "reboot", EQUAL, 1, start_special },
5188 { "kexec", EQUAL, 1, start_special },
5189 { "default", EQUAL, 1, start_special },
5190 { "rescue", EQUAL, 1, start_special },
5191 { "emergency", EQUAL, 1, start_special },
5192 { "exit", EQUAL, 1, start_special },
5193 { "reset-failed", MORE, 1, reset_failed },
5194 { "enable", MORE, 2, enable_unit },
5195 { "disable", MORE, 2, enable_unit },
5196 { "is-enabled", MORE, 2, enable_unit }
5206 left = argc - optind;
5209 /* Special rule: no arguments means "list-units" */
5212 if (streq(argv[optind], "help")) {
5217 for (i = 0; i < ELEMENTSOF(verbs); i++)
5218 if (streq(argv[optind], verbs[i].verb))
5221 if (i >= ELEMENTSOF(verbs)) {
5222 log_error("Unknown operation %s", argv[optind]);
5227 switch (verbs[i].argc_cmp) {
5230 if (left != verbs[i].argc) {
5231 log_error("Invalid number of arguments.");
5238 if (left < verbs[i].argc) {
5239 log_error("Too few arguments.");
5246 if (left > verbs[i].argc) {
5247 log_error("Too many arguments.");
5254 assert_not_reached("Unknown comparison operator.");
5257 /* Require a bus connection for all operations but
5259 if (!streq(verbs[i].verb, "enable") &&
5260 !streq(verbs[i].verb, "disable") &&
5262 log_error("Failed to get D-Bus connection: %s", error->message);
5266 return verbs[i].dispatch(bus, argv + optind, left);
5269 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5271 struct msghdr msghdr;
5273 union sockaddr_union sockaddr;
5274 struct shutdownd_command c;
5282 strncpy(c.wall_message, message, sizeof(c.wall_message));
5284 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5288 sockaddr.sa.sa_family = AF_UNIX;
5289 sockaddr.un.sun_path[0] = 0;
5290 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5293 iovec.iov_base = (char*) &c;
5294 iovec.iov_len = sizeof(c);
5297 msghdr.msg_name = &sockaddr;
5298 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5300 msghdr.msg_iov = &iovec;
5301 msghdr.msg_iovlen = 1;
5303 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5304 close_nointr_nofail(fd);
5308 close_nointr_nofail(fd);
5312 static int reload_with_fallback(DBusConnection *bus) {
5315 /* First, try systemd via D-Bus. */
5316 if (daemon_reload(bus, NULL, 0) > 0)
5320 /* Nothing else worked, so let's try signals */
5321 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5323 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5324 log_error("kill() failed: %m");
5331 static int start_with_fallback(DBusConnection *bus) {
5334 /* First, try systemd via D-Bus. */
5335 if (start_unit(bus, NULL, 0) >= 0)
5339 /* Hmm, talking to systemd via D-Bus didn't work. Then
5340 * let's try to talk to Upstart via D-Bus. */
5341 if (talk_upstart() > 0)
5344 /* Nothing else worked, so let's try
5346 if (talk_initctl() > 0)
5349 log_error("Failed to talk to init daemon.");
5353 warn_wall(arg_action);
5357 static int halt_main(DBusConnection *bus) {
5360 if (geteuid() != 0) {
5361 log_error("Must be root.");
5367 char date[FORMAT_TIMESTAMP_MAX];
5369 m = strv_join(arg_wall, " ");
5370 r = send_shutdownd(arg_when,
5371 arg_action == ACTION_HALT ? 'H' :
5372 arg_action == ACTION_POWEROFF ? 'P' :
5379 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5381 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5382 format_timestamp(date, sizeof(date), arg_when));
5387 if (!arg_dry && !arg_immediate)
5388 return start_with_fallback(bus);
5391 if (sd_booted() > 0)
5392 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5393 else if ((r = utmp_put_shutdown(0)) < 0)
5394 log_warning("Failed to write utmp record: %s", strerror(-r));
5403 /* Make sure C-A-D is handled by the kernel from this
5405 reboot(RB_ENABLE_CAD);
5407 switch (arg_action) {
5410 log_info("Halting.");
5411 reboot(RB_HALT_SYSTEM);
5414 case ACTION_POWEROFF:
5415 log_info("Powering off.");
5416 reboot(RB_POWER_OFF);
5420 log_info("Rebooting.");
5421 reboot(RB_AUTOBOOT);
5425 assert_not_reached("Unknown halt action.");
5428 /* We should never reach this. */
5432 static int runlevel_main(void) {
5433 int r, runlevel, previous;
5435 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5436 printf("unknown\n");
5441 previous <= 0 ? 'N' : previous,
5442 runlevel <= 0 ? 'N' : runlevel);
5447 static void pager_open(void) {
5454 if (!on_tty() || arg_no_pager)
5457 if ((pager = getenv("PAGER")))
5458 if (!*pager || streq(pager, "cat"))
5461 /* Determine and cache number of columns before we spawn the
5462 * pager so that we get the value from the actual tty */
5466 log_error("Failed to create pager pipe: %m");
5471 if (pager_pid < 0) {
5472 log_error("Failed to fork pager: %m");
5477 /* In the child start the pager */
5478 if (pager_pid == 0) {
5480 dup2(fd[0], STDIN_FILENO);
5483 setenv("LESS", "FRSX", 0);
5485 prctl(PR_SET_PDEATHSIG, SIGTERM);
5488 execlp(pager, pager, NULL);
5489 execl("/bin/sh", "sh", "-c", pager, NULL);
5491 /* Debian's alternatives command for pagers is
5492 * called 'pager'. Note that we do not call
5493 * sensible-pagers here, since that is just a
5494 * shell script that implements a logic that
5495 * is similar to this one anyway, but is
5496 * Debian-specific. */
5497 execlp("pager", "pager", NULL);
5499 execlp("less", "less", NULL);
5500 execlp("more", "more", NULL);
5503 log_error("Unable to execute pager: %m");
5504 _exit(EXIT_FAILURE);
5507 /* Return in the parent */
5508 if (dup2(fd[1], STDOUT_FILENO) < 0)
5509 log_error("Failed to duplicate pager pipe: %m");
5514 static void pager_close(void) {
5520 /* Inform pager that we are done */
5522 wait_for_terminate(pager_pid, &dummy);
5526 int main(int argc, char*argv[]) {
5527 int r, retval = EXIT_FAILURE;
5528 DBusConnection *bus = NULL;
5531 dbus_error_init(&error);
5533 log_parse_environment();
5536 if ((r = parse_argv(argc, argv)) < 0)
5539 retval = EXIT_SUCCESS;
5543 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5544 * let's shortcut this */
5545 if (arg_action == ACTION_RUNLEVEL) {
5546 r = runlevel_main();
5547 retval = r < 0 ? EXIT_FAILURE : r;
5551 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5553 switch (arg_action) {
5555 case ACTION_SYSTEMCTL:
5556 r = systemctl_main(bus, argc, argv, &error);
5560 case ACTION_POWEROFF:
5566 case ACTION_RUNLEVEL2:
5567 case ACTION_RUNLEVEL3:
5568 case ACTION_RUNLEVEL4:
5569 case ACTION_RUNLEVEL5:
5571 case ACTION_EMERGENCY:
5572 case ACTION_DEFAULT:
5573 r = start_with_fallback(bus);
5578 r = reload_with_fallback(bus);
5581 case ACTION_CANCEL_SHUTDOWN:
5582 r = send_shutdownd(0, 0, false, NULL);
5585 case ACTION_INVALID:
5586 case ACTION_RUNLEVEL:
5588 assert_not_reached("Unknown action");
5591 retval = r < 0 ? EXIT_FAILURE : r;
5596 dbus_connection_flush(bus);
5597 dbus_connection_close(bus);
5598 dbus_connection_unref(bus);
5601 dbus_error_free(&error);
5605 strv_free(arg_property);