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.");
1252 log_error("Job failed. See system logs and 'systemctl status' for details.");
1255 r = d.result ? -EIO : 0;
1259 /* This is slightly dirty, since we don't undo the filter registration. */
1264 static int start_unit_one(
1265 DBusConnection *bus,
1272 DBusMessage *m = NULL, *reply = NULL;
1281 assert(arg_no_block || s);
1283 if (!(m = dbus_message_new_method_call(
1284 "org.freedesktop.systemd1",
1285 "/org/freedesktop/systemd1",
1286 "org.freedesktop.systemd1.Manager",
1288 log_error("Could not allocate message.");
1293 if (!dbus_message_append_args(m,
1294 DBUS_TYPE_STRING, &name,
1295 DBUS_TYPE_STRING, &mode,
1296 DBUS_TYPE_INVALID)) {
1297 log_error("Could not append arguments to message.");
1302 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1304 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1305 /* There's always a fallback possible for
1306 * legacy actions. */
1311 log_error("Failed to issue method call: %s", bus_error_message(error));
1316 if (!dbus_message_get_args(reply, error,
1317 DBUS_TYPE_OBJECT_PATH, &path,
1318 DBUS_TYPE_INVALID)) {
1319 log_error("Failed to parse reply: %s", bus_error_message(error));
1324 if (need_daemon_reload(bus, name))
1325 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1326 arg_user ? "--user" : "--system");
1328 if (!arg_no_block) {
1331 if (!(p = strdup(path))) {
1332 log_error("Failed to duplicate path.");
1337 if ((r = set_put(s, p)) < 0) {
1339 log_error("Failed to add path to set.");
1348 dbus_message_unref(m);
1351 dbus_message_unref(reply);
1356 static enum action verb_to_action(const char *verb) {
1357 if (streq(verb, "halt"))
1359 else if (streq(verb, "poweroff"))
1360 return ACTION_POWEROFF;
1361 else if (streq(verb, "reboot"))
1362 return ACTION_REBOOT;
1363 else if (streq(verb, "kexec"))
1364 return ACTION_KEXEC;
1365 else if (streq(verb, "rescue"))
1366 return ACTION_RESCUE;
1367 else if (streq(verb, "emergency"))
1368 return ACTION_EMERGENCY;
1369 else if (streq(verb, "default"))
1370 return ACTION_DEFAULT;
1371 else if (streq(verb, "exit"))
1374 return ACTION_INVALID;
1377 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1379 static const char * const table[_ACTION_MAX] = {
1380 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1381 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1382 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1383 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1384 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1385 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1386 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1387 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1388 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1389 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1390 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1391 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1396 const char *method, *mode, *one_name;
1400 dbus_error_init(&error);
1404 spawn_ask_password_agent();
1406 if (arg_action == ACTION_SYSTEMCTL) {
1408 streq(args[0], "stop") ? "StopUnit" :
1409 streq(args[0], "reload") ? "ReloadUnit" :
1410 streq(args[0], "restart") ? "RestartUnit" :
1411 streq(args[0], "try-restart") ||
1412 streq(args[0], "condrestart") ? "TryRestartUnit" :
1413 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1414 streq(args[0], "reload-or-try-restart") ||
1415 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1419 (streq(args[0], "isolate") ||
1420 streq(args[0], "rescue") ||
1421 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1423 one_name = table[verb_to_action(args[0])];
1426 assert(arg_action < ELEMENTSOF(table));
1427 assert(table[arg_action]);
1429 method = "StartUnit";
1431 mode = (arg_action == ACTION_EMERGENCY ||
1432 arg_action == ACTION_RESCUE ||
1433 arg_action == ACTION_RUNLEVEL2 ||
1434 arg_action == ACTION_RUNLEVEL3 ||
1435 arg_action == ACTION_RUNLEVEL4 ||
1436 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1438 one_name = table[arg_action];
1441 if (!arg_no_block) {
1442 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1443 log_error("Could not watch jobs: %s", strerror(-ret));
1447 if (!(s = set_new(string_hash_func, string_compare_func))) {
1448 log_error("Failed to allocate set.");
1455 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1458 for (i = 1; i < n; i++)
1459 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1460 ret = translate_bus_error_to_exit_status(r, &error);
1461 dbus_error_free(&error);
1466 if ((r = wait_for_jobs(bus, s)) < 0) {
1475 dbus_error_free(&error);
1480 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1487 (streq(args[0], "halt") ||
1488 streq(args[0], "poweroff") ||
1489 streq(args[0], "reboot") ||
1490 streq(args[0], "kexec") ||
1491 streq(args[0], "exit")))
1492 return daemon_reload(bus, args, n);
1494 r = start_unit(bus, args, n);
1497 warn_wall(verb_to_action(args[0]));
1502 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1503 DBusMessage *m = NULL, *reply = NULL;
1505 *interface = "org.freedesktop.systemd1.Unit",
1506 *property = "ActiveState";
1507 int r = 3; /* According to LSB: "program is not running" */
1514 dbus_error_init(&error);
1516 for (i = 1; i < n; i++) {
1517 const char *path = NULL;
1519 DBusMessageIter iter, sub;
1521 if (!(m = dbus_message_new_method_call(
1522 "org.freedesktop.systemd1",
1523 "/org/freedesktop/systemd1",
1524 "org.freedesktop.systemd1.Manager",
1526 log_error("Could not allocate message.");
1531 if (!dbus_message_append_args(m,
1532 DBUS_TYPE_STRING, &args[i],
1533 DBUS_TYPE_INVALID)) {
1534 log_error("Could not append arguments to message.");
1539 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1541 /* Hmm, cannot figure out anything about this unit... */
1545 dbus_error_free(&error);
1546 dbus_message_unref(m);
1550 if (!dbus_message_get_args(reply, &error,
1551 DBUS_TYPE_OBJECT_PATH, &path,
1552 DBUS_TYPE_INVALID)) {
1553 log_error("Failed to parse reply: %s", bus_error_message(&error));
1558 dbus_message_unref(m);
1559 if (!(m = dbus_message_new_method_call(
1560 "org.freedesktop.systemd1",
1562 "org.freedesktop.DBus.Properties",
1564 log_error("Could not allocate message.");
1569 if (!dbus_message_append_args(m,
1570 DBUS_TYPE_STRING, &interface,
1571 DBUS_TYPE_STRING, &property,
1572 DBUS_TYPE_INVALID)) {
1573 log_error("Could not append arguments to message.");
1578 dbus_message_unref(reply);
1579 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1580 log_error("Failed to issue method call: %s", bus_error_message(&error));
1585 if (!dbus_message_iter_init(reply, &iter) ||
1586 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1587 log_error("Failed to parse reply.");
1592 dbus_message_iter_recurse(&iter, &sub);
1594 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1595 log_error("Failed to parse reply.");
1600 dbus_message_iter_get_basic(&sub, &state);
1605 if (streq(state, "active") || streq(state, "reloading"))
1608 dbus_message_unref(m);
1609 dbus_message_unref(reply);
1615 dbus_message_unref(m);
1618 dbus_message_unref(reply);
1620 dbus_error_free(&error);
1625 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1626 DBusMessage *m = NULL, *reply = NULL;
1634 dbus_error_init(&error);
1637 arg_kill_who = "all";
1640 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1642 for (i = 1; i < n; i++) {
1644 if (!(m = dbus_message_new_method_call(
1645 "org.freedesktop.systemd1",
1646 "/org/freedesktop/systemd1",
1647 "org.freedesktop.systemd1.Manager",
1649 log_error("Could not allocate message.");
1654 if (!dbus_message_append_args(m,
1655 DBUS_TYPE_STRING, &args[i],
1656 DBUS_TYPE_STRING, &arg_kill_who,
1657 DBUS_TYPE_STRING, &arg_kill_mode,
1658 DBUS_TYPE_INT32, &arg_signal,
1659 DBUS_TYPE_INVALID)) {
1660 log_error("Could not append arguments to message.");
1665 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1666 log_error("Failed to issue method call: %s", bus_error_message(&error));
1667 dbus_error_free(&error);
1671 dbus_message_unref(m);
1674 dbus_message_unref(reply);
1680 dbus_message_unref(m);
1683 dbus_message_unref(reply);
1685 dbus_error_free(&error);
1690 typedef struct ExecStatusInfo {
1698 usec_t start_timestamp;
1699 usec_t exit_timestamp;
1704 LIST_FIELDS(struct ExecStatusInfo, exec);
1707 static void exec_status_info_free(ExecStatusInfo *i) {
1716 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1717 uint64_t start_timestamp, exit_timestamp;
1718 DBusMessageIter sub2, sub3;
1722 int32_t code, status;
1728 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1731 dbus_message_iter_recurse(sub, &sub2);
1733 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1736 if (!(i->path = strdup(path)))
1739 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1740 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1744 dbus_message_iter_recurse(&sub2, &sub3);
1745 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1746 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1747 dbus_message_iter_next(&sub3);
1752 if (!(i->argv = new0(char*, n+1)))
1756 dbus_message_iter_recurse(&sub2, &sub3);
1757 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1760 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1761 dbus_message_iter_get_basic(&sub3, &s);
1762 dbus_message_iter_next(&sub3);
1764 if (!(i->argv[n++] = strdup(s)))
1768 if (!dbus_message_iter_next(&sub2) ||
1769 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1770 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1771 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1772 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1773 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1774 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1778 i->start_timestamp = (usec_t) start_timestamp;
1779 i->exit_timestamp = (usec_t) exit_timestamp;
1780 i->pid = (pid_t) pid;
1787 typedef struct UnitStatusInfo {
1789 const char *load_state;
1790 const char *active_state;
1791 const char *sub_state;
1793 const char *description;
1794 const char *following;
1797 const char *default_control_group;
1799 usec_t inactive_exit_timestamp;
1800 usec_t active_enter_timestamp;
1801 usec_t active_exit_timestamp;
1802 usec_t inactive_enter_timestamp;
1804 bool need_daemon_reload;
1809 const char *status_text;
1811 #ifdef HAVE_SYSV_COMPAT
1815 usec_t start_timestamp;
1816 usec_t exit_timestamp;
1818 int exit_code, exit_status;
1821 unsigned n_accepted;
1822 unsigned n_connections;
1826 const char *sysfs_path;
1828 /* Mount, Automount */
1834 LIST_HEAD(ExecStatusInfo, exec);
1837 static void print_status_info(UnitStatusInfo *i) {
1839 const char *on, *off, *ss;
1841 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1842 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1846 /* This shows pretty information about a unit. See
1847 * print_property() for a low-level property printer */
1849 printf("%s", strna(i->id));
1851 if (i->description && !streq_ptr(i->id, i->description))
1852 printf(" - %s", i->description);
1857 printf("\t Follow: unit currently follows state of %s\n", i->following);
1859 if (streq_ptr(i->load_state, "failed") ||
1860 streq_ptr(i->load_state, "banned")) {
1861 on = ansi_highlight(true);
1862 off = ansi_highlight(false);
1867 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1869 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1871 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1873 if (streq_ptr(i->active_state, "failed")) {
1874 on = ansi_highlight(true);
1875 off = ansi_highlight(false);
1876 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1877 on = ansi_highlight_green(true);
1878 off = ansi_highlight_green(false);
1883 printf("\t Active: %s%s (%s)%s",
1885 strna(i->active_state),
1889 printf("\t Active: %s%s%s",
1891 strna(i->active_state),
1894 timestamp = (streq_ptr(i->active_state, "active") ||
1895 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1896 (streq_ptr(i->active_state, "inactive") ||
1897 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1898 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1899 i->active_exit_timestamp;
1901 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1902 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1905 printf(" since %s; %s\n", s2, s1);
1907 printf(" since %s\n", s2);
1912 printf("\t Device: %s\n", i->sysfs_path);
1914 printf("\t Where: %s\n", i->where);
1916 printf("\t What: %s\n", i->what);
1919 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1921 LIST_FOREACH(exec, p, i->exec) {
1925 /* Only show exited processes here */
1929 t = strv_join(p->argv, " ");
1930 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1933 #ifdef HAVE_SYSV_COMPAT
1935 good = is_clean_exit_lsb(p->code, p->status);
1938 good = is_clean_exit(p->code, p->status);
1941 on = ansi_highlight(true);
1942 off = ansi_highlight(false);
1946 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1948 if (p->code == CLD_EXITED) {
1951 printf("status=%i", p->status);
1953 #ifdef HAVE_SYSV_COMPAT
1954 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1956 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1961 printf("signal=%s", signal_to_string(p->status));
1963 printf(")%s\n", off);
1967 if (i->main_pid == p->pid &&
1968 i->start_timestamp == p->start_timestamp &&
1969 i->exit_timestamp == p->start_timestamp)
1970 /* Let's not show this twice */
1973 if (p->pid == i->control_pid)
1977 if (i->main_pid > 0 || i->control_pid > 0) {
1980 if (i->main_pid > 0) {
1981 printf("Main PID: %u", (unsigned) i->main_pid);
1985 get_process_name(i->main_pid, &t);
1990 } else if (i->exit_code > 0) {
1991 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1993 if (i->exit_code == CLD_EXITED) {
1996 printf("status=%i", i->exit_status);
1998 #ifdef HAVE_SYSV_COMPAT
1999 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2001 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2006 printf("signal=%s", signal_to_string(i->exit_status));
2011 if (i->main_pid > 0 && i->control_pid > 0)
2014 if (i->control_pid > 0) {
2017 printf(" Control: %u", (unsigned) i->control_pid);
2019 get_process_name(i->control_pid, &t);
2030 printf("\t Status: \"%s\"\n", i->status_text);
2032 if (i->default_control_group) {
2035 printf("\t CGroup: %s\n", i->default_control_group);
2037 if ((c = columns()) > 18)
2042 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2045 if (i->need_daemon_reload)
2046 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2047 ansi_highlight(true),
2048 ansi_highlight(false),
2049 arg_user ? "--user" : "--system");
2052 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2054 switch (dbus_message_iter_get_arg_type(iter)) {
2056 case DBUS_TYPE_STRING: {
2059 dbus_message_iter_get_basic(iter, &s);
2062 if (streq(name, "Id"))
2064 else if (streq(name, "LoadState"))
2066 else if (streq(name, "ActiveState"))
2067 i->active_state = s;
2068 else if (streq(name, "SubState"))
2070 else if (streq(name, "Description"))
2072 else if (streq(name, "FragmentPath"))
2074 #ifdef HAVE_SYSV_COMPAT
2075 else if (streq(name, "SysVPath")) {
2080 else if (streq(name, "DefaultControlGroup"))
2081 i->default_control_group = s;
2082 else if (streq(name, "StatusText"))
2084 else if (streq(name, "SysFSPath"))
2086 else if (streq(name, "Where"))
2088 else if (streq(name, "What"))
2090 else if (streq(name, "Following"))
2097 case DBUS_TYPE_BOOLEAN: {
2100 dbus_message_iter_get_basic(iter, &b);
2102 if (streq(name, "Accept"))
2104 else if (streq(name, "NeedDaemonReload"))
2105 i->need_daemon_reload = b;
2110 case DBUS_TYPE_UINT32: {
2113 dbus_message_iter_get_basic(iter, &u);
2115 if (streq(name, "MainPID")) {
2117 i->main_pid = (pid_t) u;
2120 } else if (streq(name, "ControlPID"))
2121 i->control_pid = (pid_t) u;
2122 else if (streq(name, "ExecMainPID")) {
2124 i->main_pid = (pid_t) u;
2125 } else if (streq(name, "NAccepted"))
2127 else if (streq(name, "NConnections"))
2128 i->n_connections = u;
2133 case DBUS_TYPE_INT32: {
2136 dbus_message_iter_get_basic(iter, &j);
2138 if (streq(name, "ExecMainCode"))
2139 i->exit_code = (int) j;
2140 else if (streq(name, "ExecMainStatus"))
2141 i->exit_status = (int) j;
2146 case DBUS_TYPE_UINT64: {
2149 dbus_message_iter_get_basic(iter, &u);
2151 if (streq(name, "ExecMainStartTimestamp"))
2152 i->start_timestamp = (usec_t) u;
2153 else if (streq(name, "ExecMainExitTimestamp"))
2154 i->exit_timestamp = (usec_t) u;
2155 else if (streq(name, "ActiveEnterTimestamp"))
2156 i->active_enter_timestamp = (usec_t) u;
2157 else if (streq(name, "InactiveEnterTimestamp"))
2158 i->inactive_enter_timestamp = (usec_t) u;
2159 else if (streq(name, "InactiveExitTimestamp"))
2160 i->inactive_exit_timestamp = (usec_t) u;
2161 else if (streq(name, "ActiveExitTimestamp"))
2162 i->active_exit_timestamp = (usec_t) u;
2167 case DBUS_TYPE_ARRAY: {
2169 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2170 startswith(name, "Exec")) {
2171 DBusMessageIter sub;
2173 dbus_message_iter_recurse(iter, &sub);
2174 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2175 ExecStatusInfo *info;
2178 if (!(info = new0(ExecStatusInfo, 1)))
2181 if (!(info->name = strdup(name))) {
2186 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2191 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2193 dbus_message_iter_next(&sub);
2204 static int print_property(const char *name, DBusMessageIter *iter) {
2208 /* This is a low-level property printer, see
2209 * print_status_info() for the nicer output */
2211 if (arg_property && !strv_find(arg_property, name))
2214 switch (dbus_message_iter_get_arg_type(iter)) {
2216 case DBUS_TYPE_STRING: {
2218 dbus_message_iter_get_basic(iter, &s);
2220 if (arg_all || s[0])
2221 printf("%s=%s\n", name, s);
2226 case DBUS_TYPE_BOOLEAN: {
2228 dbus_message_iter_get_basic(iter, &b);
2229 printf("%s=%s\n", name, yes_no(b));
2234 case DBUS_TYPE_UINT64: {
2236 dbus_message_iter_get_basic(iter, &u);
2238 /* Yes, heuristics! But we can change this check
2239 * should it turn out to not be sufficient */
2241 if (strstr(name, "Timestamp")) {
2242 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2244 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2245 printf("%s=%s\n", name, strempty(t));
2246 } else if (strstr(name, "USec")) {
2247 char timespan[FORMAT_TIMESPAN_MAX];
2249 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2251 printf("%s=%llu\n", name, (unsigned long long) u);
2256 case DBUS_TYPE_UINT32: {
2258 dbus_message_iter_get_basic(iter, &u);
2260 if (strstr(name, "UMask") || strstr(name, "Mode"))
2261 printf("%s=%04o\n", name, u);
2263 printf("%s=%u\n", name, (unsigned) u);
2268 case DBUS_TYPE_INT32: {
2270 dbus_message_iter_get_basic(iter, &i);
2272 printf("%s=%i\n", name, (int) i);
2276 case DBUS_TYPE_DOUBLE: {
2278 dbus_message_iter_get_basic(iter, &d);
2280 printf("%s=%g\n", name, d);
2284 case DBUS_TYPE_STRUCT: {
2285 DBusMessageIter sub;
2286 dbus_message_iter_recurse(iter, &sub);
2288 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2291 dbus_message_iter_get_basic(&sub, &u);
2294 printf("%s=%u\n", name, (unsigned) u);
2296 printf("%s=\n", name);
2299 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2302 dbus_message_iter_get_basic(&sub, &s);
2304 if (arg_all || s[0])
2305 printf("%s=%s\n", name, s);
2313 case DBUS_TYPE_ARRAY:
2315 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2316 DBusMessageIter sub;
2319 dbus_message_iter_recurse(iter, &sub);
2321 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2322 printf("%s=", name);
2324 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2327 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2328 dbus_message_iter_get_basic(&sub, &s);
2329 printf("%s%s", space ? " " : "", s);
2332 dbus_message_iter_next(&sub);
2340 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2341 DBusMessageIter sub;
2343 dbus_message_iter_recurse(iter, &sub);
2345 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2346 printf("%s=", name);
2348 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2351 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2352 dbus_message_iter_get_basic(&sub, &u);
2355 dbus_message_iter_next(&sub);
2363 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2364 DBusMessageIter sub, sub2;
2366 dbus_message_iter_recurse(iter, &sub);
2367 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2368 const char *type, *path;
2370 dbus_message_iter_recurse(&sub, &sub2);
2372 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2373 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2374 printf("%s=%s\n", type, path);
2376 dbus_message_iter_next(&sub);
2381 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2382 DBusMessageIter sub, sub2;
2384 dbus_message_iter_recurse(iter, &sub);
2385 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2387 uint64_t value, next_elapse;
2389 dbus_message_iter_recurse(&sub, &sub2);
2391 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2392 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2393 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2394 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2396 printf("%s={ value=%s ; next_elapse=%s }\n",
2398 format_timespan(timespan1, sizeof(timespan1), value),
2399 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2402 dbus_message_iter_next(&sub);
2407 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2408 DBusMessageIter sub;
2410 dbus_message_iter_recurse(iter, &sub);
2411 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2412 ExecStatusInfo info;
2415 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2416 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2419 t = strv_join(info.argv, " ");
2421 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2425 yes_no(info.ignore),
2426 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2427 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2428 (unsigned) info. pid,
2429 sigchld_code_to_string(info.code),
2431 info.code == CLD_EXITED ? "" : "/",
2432 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2438 strv_free(info.argv);
2440 dbus_message_iter_next(&sub);
2450 printf("%s=[unprintable]\n", name);
2455 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2456 DBusMessage *m = NULL, *reply = NULL;
2457 const char *interface = "";
2460 DBusMessageIter iter, sub, sub2, sub3;
2461 UnitStatusInfo info;
2469 dbus_error_init(&error);
2471 if (!(m = dbus_message_new_method_call(
2472 "org.freedesktop.systemd1",
2474 "org.freedesktop.DBus.Properties",
2476 log_error("Could not allocate message.");
2481 if (!dbus_message_append_args(m,
2482 DBUS_TYPE_STRING, &interface,
2483 DBUS_TYPE_INVALID)) {
2484 log_error("Could not append arguments to message.");
2489 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2490 log_error("Failed to issue method call: %s", bus_error_message(&error));
2495 if (!dbus_message_iter_init(reply, &iter) ||
2496 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2497 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2498 log_error("Failed to parse reply.");
2503 dbus_message_iter_recurse(&iter, &sub);
2510 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2513 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2514 log_error("Failed to parse reply.");
2519 dbus_message_iter_recurse(&sub, &sub2);
2521 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2522 log_error("Failed to parse reply.");
2527 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2528 log_error("Failed to parse reply.");
2533 dbus_message_iter_recurse(&sub2, &sub3);
2535 if (show_properties)
2536 r = print_property(name, &sub3);
2538 r = status_property(name, &sub3, &info);
2541 log_error("Failed to parse reply.");
2546 dbus_message_iter_next(&sub);
2551 if (!show_properties)
2552 print_status_info(&info);
2554 if (!streq_ptr(info.active_state, "active") &&
2555 !streq_ptr(info.active_state, "reloading") &&
2556 streq(verb, "status"))
2557 /* According to LSB: "program not running" */
2560 while ((p = info.exec)) {
2561 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2562 exec_status_info_free(p);
2567 dbus_message_unref(m);
2570 dbus_message_unref(reply);
2572 dbus_error_free(&error);
2577 static int show(DBusConnection *bus, char **args, unsigned n) {
2578 DBusMessage *m = NULL, *reply = NULL;
2582 bool show_properties, new_line = false;
2587 dbus_error_init(&error);
2589 show_properties = !streq(args[0], "status");
2591 if (show_properties)
2594 if (show_properties && n <= 1) {
2595 /* If not argument is specified inspect the manager
2598 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2602 for (i = 1; i < n; i++) {
2603 const char *path = NULL;
2606 if (safe_atou32(args[i], &id) < 0) {
2608 /* Interpret as unit name */
2610 if (!(m = dbus_message_new_method_call(
2611 "org.freedesktop.systemd1",
2612 "/org/freedesktop/systemd1",
2613 "org.freedesktop.systemd1.Manager",
2615 log_error("Could not allocate message.");
2620 if (!dbus_message_append_args(m,
2621 DBUS_TYPE_STRING, &args[i],
2622 DBUS_TYPE_INVALID)) {
2623 log_error("Could not append arguments to message.");
2628 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2630 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2631 log_error("Failed to issue method call: %s", bus_error_message(&error));
2636 dbus_error_free(&error);
2638 dbus_message_unref(m);
2639 if (!(m = dbus_message_new_method_call(
2640 "org.freedesktop.systemd1",
2641 "/org/freedesktop/systemd1",
2642 "org.freedesktop.systemd1.Manager",
2644 log_error("Could not allocate message.");
2649 if (!dbus_message_append_args(m,
2650 DBUS_TYPE_STRING, &args[i],
2651 DBUS_TYPE_INVALID)) {
2652 log_error("Could not append arguments to message.");
2657 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2658 log_error("Failed to issue method call: %s", bus_error_message(&error));
2660 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2661 ret = 4; /* According to LSB: "program or service status is unknown" */
2668 } else if (show_properties) {
2670 /* Interpret as job id */
2672 if (!(m = dbus_message_new_method_call(
2673 "org.freedesktop.systemd1",
2674 "/org/freedesktop/systemd1",
2675 "org.freedesktop.systemd1.Manager",
2677 log_error("Could not allocate message.");
2682 if (!dbus_message_append_args(m,
2683 DBUS_TYPE_UINT32, &id,
2684 DBUS_TYPE_INVALID)) {
2685 log_error("Could not append arguments to message.");
2690 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2691 log_error("Failed to issue method call: %s", bus_error_message(&error));
2697 /* Interpret as PID */
2699 if (!(m = dbus_message_new_method_call(
2700 "org.freedesktop.systemd1",
2701 "/org/freedesktop/systemd1",
2702 "org.freedesktop.systemd1.Manager",
2704 log_error("Could not allocate message.");
2709 if (!dbus_message_append_args(m,
2710 DBUS_TYPE_UINT32, &id,
2711 DBUS_TYPE_INVALID)) {
2712 log_error("Could not append arguments to message.");
2717 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2718 log_error("Failed to issue method call: %s", bus_error_message(&error));
2724 if (!dbus_message_get_args(reply, &error,
2725 DBUS_TYPE_OBJECT_PATH, &path,
2726 DBUS_TYPE_INVALID)) {
2727 log_error("Failed to parse reply: %s", bus_error_message(&error));
2732 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2735 dbus_message_unref(m);
2736 dbus_message_unref(reply);
2742 dbus_message_unref(m);
2745 dbus_message_unref(reply);
2747 dbus_error_free(&error);
2752 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2754 DBusMessage *m = NULL, *reply = NULL;
2759 dbus_error_init(&error);
2761 log_debug("Got D-Bus request: %s.%s() on %s",
2762 dbus_message_get_interface(message),
2763 dbus_message_get_member(message),
2764 dbus_message_get_path(message));
2766 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2767 log_error("Warning! D-Bus connection terminated.");
2768 dbus_connection_close(connection);
2770 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2771 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2772 const char *id, *path;
2774 if (!dbus_message_get_args(message, &error,
2775 DBUS_TYPE_STRING, &id,
2776 DBUS_TYPE_OBJECT_PATH, &path,
2778 log_error("Failed to parse message: %s", bus_error_message(&error));
2779 else if (streq(dbus_message_get_member(message), "UnitNew"))
2780 printf("Unit %s added.\n", id);
2782 printf("Unit %s removed.\n", id);
2784 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2785 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2787 const char *path, *result;
2789 if (!dbus_message_get_args(message, &error,
2790 DBUS_TYPE_UINT32, &id,
2791 DBUS_TYPE_OBJECT_PATH, &path,
2792 DBUS_TYPE_STRING, &result,
2794 log_error("Failed to parse message: %s", bus_error_message(&error));
2795 else if (streq(dbus_message_get_member(message), "JobNew"))
2796 printf("Job %u added.\n", id);
2798 printf("Job %u removed.\n", id);
2801 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2803 const char *path, *interface, *property = "Id";
2804 DBusMessageIter iter, sub;
2806 path = dbus_message_get_path(message);
2808 if (!dbus_message_get_args(message, &error,
2809 DBUS_TYPE_STRING, &interface,
2810 DBUS_TYPE_INVALID)) {
2811 log_error("Failed to parse message: %s", bus_error_message(&error));
2815 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2816 !streq(interface, "org.freedesktop.systemd1.Unit"))
2819 if (!(m = dbus_message_new_method_call(
2820 "org.freedesktop.systemd1",
2822 "org.freedesktop.DBus.Properties",
2824 log_error("Could not allocate message.");
2828 if (!dbus_message_append_args(m,
2829 DBUS_TYPE_STRING, &interface,
2830 DBUS_TYPE_STRING, &property,
2831 DBUS_TYPE_INVALID)) {
2832 log_error("Could not append arguments to message.");
2836 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2837 log_error("Failed to issue method call: %s", bus_error_message(&error));
2841 if (!dbus_message_iter_init(reply, &iter) ||
2842 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2843 log_error("Failed to parse reply.");
2847 dbus_message_iter_recurse(&iter, &sub);
2849 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2852 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2853 log_error("Failed to parse reply.");
2857 dbus_message_iter_get_basic(&sub, &id);
2858 printf("Unit %s changed.\n", id);
2862 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2863 log_error("Failed to parse reply.");
2867 dbus_message_iter_get_basic(&sub, &id);
2868 printf("Job %u changed.\n", id);
2874 dbus_message_unref(m);
2877 dbus_message_unref(reply);
2879 dbus_error_free(&error);
2880 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2884 dbus_message_unref(m);
2887 dbus_message_unref(reply);
2889 dbus_error_free(&error);
2890 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2893 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2894 DBusMessage *m = NULL, *reply = NULL;
2898 dbus_error_init(&error);
2901 dbus_bus_add_match(bus,
2903 "sender='org.freedesktop.systemd1',"
2904 "interface='org.freedesktop.systemd1.Manager',"
2905 "path='/org/freedesktop/systemd1'",
2908 if (dbus_error_is_set(&error)) {
2909 log_error("Failed to add match: %s", bus_error_message(&error));
2914 dbus_bus_add_match(bus,
2916 "sender='org.freedesktop.systemd1',"
2917 "interface='org.freedesktop.DBus.Properties',"
2918 "member='PropertiesChanged'",
2921 if (dbus_error_is_set(&error)) {
2922 log_error("Failed to add match: %s", bus_error_message(&error));
2928 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2929 log_error("Failed to add filter.");
2934 if (!(m = dbus_message_new_method_call(
2935 "org.freedesktop.systemd1",
2936 "/org/freedesktop/systemd1",
2937 "org.freedesktop.systemd1.Manager",
2939 log_error("Could not allocate message.");
2944 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2945 log_error("Failed to issue method call: %s", bus_error_message(&error));
2950 while (dbus_connection_read_write_dispatch(bus, -1))
2957 /* This is slightly dirty, since we don't undo the filter or the matches. */
2960 dbus_message_unref(m);
2963 dbus_message_unref(reply);
2965 dbus_error_free(&error);
2970 static int dump(DBusConnection *bus, char **args, unsigned n) {
2971 DBusMessage *m = NULL, *reply = NULL;
2976 dbus_error_init(&error);
2980 if (!(m = dbus_message_new_method_call(
2981 "org.freedesktop.systemd1",
2982 "/org/freedesktop/systemd1",
2983 "org.freedesktop.systemd1.Manager",
2985 log_error("Could not allocate message.");
2989 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2990 log_error("Failed to issue method call: %s", bus_error_message(&error));
2995 if (!dbus_message_get_args(reply, &error,
2996 DBUS_TYPE_STRING, &text,
2997 DBUS_TYPE_INVALID)) {
2998 log_error("Failed to parse reply: %s", bus_error_message(&error));
3003 fputs(text, stdout);
3009 dbus_message_unref(m);
3012 dbus_message_unref(reply);
3014 dbus_error_free(&error);
3019 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3020 DBusMessage *m = NULL, *reply = NULL;
3023 const char *name = "", *path, *id;
3024 dbus_bool_t cleanup = FALSE;
3025 DBusMessageIter iter, sub;
3027 *interface = "org.freedesktop.systemd1.Unit",
3030 dbus_error_init(&error);
3032 if (!(m = dbus_message_new_method_call(
3033 "org.freedesktop.systemd1",
3034 "/org/freedesktop/systemd1",
3035 "org.freedesktop.systemd1.Manager",
3036 "CreateSnapshot"))) {
3037 log_error("Could not allocate message.");
3044 if (!dbus_message_append_args(m,
3045 DBUS_TYPE_STRING, &name,
3046 DBUS_TYPE_BOOLEAN, &cleanup,
3047 DBUS_TYPE_INVALID)) {
3048 log_error("Could not append arguments to message.");
3053 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3054 log_error("Failed to issue method call: %s", bus_error_message(&error));
3059 if (!dbus_message_get_args(reply, &error,
3060 DBUS_TYPE_OBJECT_PATH, &path,
3061 DBUS_TYPE_INVALID)) {
3062 log_error("Failed to parse reply: %s", bus_error_message(&error));
3067 dbus_message_unref(m);
3068 if (!(m = dbus_message_new_method_call(
3069 "org.freedesktop.systemd1",
3071 "org.freedesktop.DBus.Properties",
3073 log_error("Could not allocate message.");
3077 if (!dbus_message_append_args(m,
3078 DBUS_TYPE_STRING, &interface,
3079 DBUS_TYPE_STRING, &property,
3080 DBUS_TYPE_INVALID)) {
3081 log_error("Could not append arguments to message.");
3086 dbus_message_unref(reply);
3087 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3088 log_error("Failed to issue method call: %s", bus_error_message(&error));
3093 if (!dbus_message_iter_init(reply, &iter) ||
3094 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3095 log_error("Failed to parse reply.");
3100 dbus_message_iter_recurse(&iter, &sub);
3102 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3103 log_error("Failed to parse reply.");
3108 dbus_message_iter_get_basic(&sub, &id);
3116 dbus_message_unref(m);
3119 dbus_message_unref(reply);
3121 dbus_error_free(&error);
3126 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3127 DBusMessage *m = NULL, *reply = NULL;
3135 dbus_error_init(&error);
3137 for (i = 1; i < n; i++) {
3138 const char *path = NULL;
3140 if (!(m = dbus_message_new_method_call(
3141 "org.freedesktop.systemd1",
3142 "/org/freedesktop/systemd1",
3143 "org.freedesktop.systemd1.Manager",
3145 log_error("Could not allocate message.");
3150 if (!dbus_message_append_args(m,
3151 DBUS_TYPE_STRING, &args[i],
3152 DBUS_TYPE_INVALID)) {
3153 log_error("Could not append arguments to message.");
3158 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3159 log_error("Failed to issue method call: %s", bus_error_message(&error));
3164 if (!dbus_message_get_args(reply, &error,
3165 DBUS_TYPE_OBJECT_PATH, &path,
3166 DBUS_TYPE_INVALID)) {
3167 log_error("Failed to parse reply: %s", bus_error_message(&error));
3172 dbus_message_unref(m);
3173 if (!(m = dbus_message_new_method_call(
3174 "org.freedesktop.systemd1",
3176 "org.freedesktop.systemd1.Snapshot",
3178 log_error("Could not allocate message.");
3183 dbus_message_unref(reply);
3184 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3185 log_error("Failed to issue method call: %s", bus_error_message(&error));
3190 dbus_message_unref(m);
3191 dbus_message_unref(reply);
3199 dbus_message_unref(m);
3202 dbus_message_unref(reply);
3204 dbus_error_free(&error);
3209 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3210 DBusMessage *m = NULL, *reply = NULL;
3215 dbus_error_init(&error);
3217 if (arg_action == ACTION_RELOAD)
3219 else if (arg_action == ACTION_REEXEC)
3220 method = "Reexecute";
3222 assert(arg_action == ACTION_SYSTEMCTL);
3225 streq(args[0], "clear-jobs") ||
3226 streq(args[0], "cancel") ? "ClearJobs" :
3227 streq(args[0], "daemon-reexec") ? "Reexecute" :
3228 streq(args[0], "reset-failed") ? "ResetFailed" :
3229 streq(args[0], "halt") ? "Halt" :
3230 streq(args[0], "poweroff") ? "PowerOff" :
3231 streq(args[0], "reboot") ? "Reboot" :
3232 streq(args[0], "kexec") ? "KExec" :
3233 streq(args[0], "exit") ? "Exit" :
3234 /* "daemon-reload" */ "Reload";
3237 if (!(m = dbus_message_new_method_call(
3238 "org.freedesktop.systemd1",
3239 "/org/freedesktop/systemd1",
3240 "org.freedesktop.systemd1.Manager",
3242 log_error("Could not allocate message.");
3246 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3248 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3249 /* There's always a fallback possible for
3250 * legacy actions. */
3255 log_error("Failed to issue method call: %s", bus_error_message(&error));
3264 dbus_message_unref(m);
3267 dbus_message_unref(reply);
3269 dbus_error_free(&error);
3274 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3275 DBusMessage *m = NULL, *reply = NULL;
3281 dbus_error_init(&error);
3284 return daemon_reload(bus, args, n);
3286 for (i = 1; i < n; i++) {
3288 if (!(m = dbus_message_new_method_call(
3289 "org.freedesktop.systemd1",
3290 "/org/freedesktop/systemd1",
3291 "org.freedesktop.systemd1.Manager",
3292 "ResetFailedUnit"))) {
3293 log_error("Could not allocate message.");
3298 if (!dbus_message_append_args(m,
3299 DBUS_TYPE_STRING, args + i,
3300 DBUS_TYPE_INVALID)) {
3301 log_error("Could not append arguments to message.");
3306 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3307 log_error("Failed to issue method call: %s", bus_error_message(&error));
3312 dbus_message_unref(m);
3313 dbus_message_unref(reply);
3321 dbus_message_unref(m);
3324 dbus_message_unref(reply);
3326 dbus_error_free(&error);
3331 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3332 DBusMessage *m = NULL, *reply = NULL;
3334 DBusMessageIter iter, sub, sub2;
3337 *interface = "org.freedesktop.systemd1.Manager",
3338 *property = "Environment";
3340 dbus_error_init(&error);
3344 if (!(m = dbus_message_new_method_call(
3345 "org.freedesktop.systemd1",
3346 "/org/freedesktop/systemd1",
3347 "org.freedesktop.DBus.Properties",
3349 log_error("Could not allocate message.");
3353 if (!dbus_message_append_args(m,
3354 DBUS_TYPE_STRING, &interface,
3355 DBUS_TYPE_STRING, &property,
3356 DBUS_TYPE_INVALID)) {
3357 log_error("Could not append arguments to message.");
3362 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3363 log_error("Failed to issue method call: %s", bus_error_message(&error));
3368 if (!dbus_message_iter_init(reply, &iter) ||
3369 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3370 log_error("Failed to parse reply.");
3375 dbus_message_iter_recurse(&iter, &sub);
3377 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3378 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3379 log_error("Failed to parse reply.");
3384 dbus_message_iter_recurse(&sub, &sub2);
3386 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3389 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3390 log_error("Failed to parse reply.");
3395 dbus_message_iter_get_basic(&sub2, &text);
3396 printf("%s\n", text);
3398 dbus_message_iter_next(&sub2);
3405 dbus_message_unref(m);
3408 dbus_message_unref(reply);
3410 dbus_error_free(&error);
3415 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3416 DBusMessage *m = NULL, *reply = NULL;
3420 DBusMessageIter iter, sub;
3423 dbus_error_init(&error);
3425 method = streq(args[0], "set-environment")
3427 : "UnsetEnvironment";
3429 if (!(m = dbus_message_new_method_call(
3430 "org.freedesktop.systemd1",
3431 "/org/freedesktop/systemd1",
3432 "org.freedesktop.systemd1.Manager",
3435 log_error("Could not allocate message.");
3439 dbus_message_iter_init_append(m, &iter);
3441 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3442 log_error("Could not append arguments to message.");
3447 for (i = 1; i < n; i++)
3448 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3449 log_error("Could not append arguments to message.");
3454 if (!dbus_message_iter_close_container(&iter, &sub)) {
3455 log_error("Could not append arguments to message.");
3460 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3461 log_error("Failed to issue method call: %s", bus_error_message(&error));
3470 dbus_message_unref(m);
3473 dbus_message_unref(reply);
3475 dbus_error_free(&error);
3488 static Hashmap *will_install = NULL, *have_installed = NULL;
3489 static Set *remove_symlinks_to = NULL;
3490 static unsigned n_symlinks = 0;
3492 static void install_info_free(InstallInfo *i) {
3497 strv_free(i->aliases);
3498 strv_free(i->wanted_by);
3502 static void install_info_hashmap_free(Hashmap *m) {
3505 while ((i = hashmap_steal_first(m)))
3506 install_info_free(i);
3511 static int install_info_add(const char *name) {
3515 assert(will_install);
3517 if (!unit_name_is_valid_no_type(name, true)) {
3518 log_warning("Unit name %s is not a valid unit name.", name);
3522 if (hashmap_get(have_installed, name) ||
3523 hashmap_get(will_install, name))
3526 if (!(i = new0(InstallInfo, 1))) {
3531 if (!(i->name = strdup(name))) {
3536 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3543 install_info_free(i);
3548 static int config_parse_also(
3549 const char *filename,
3551 const char *section,
3565 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3569 if (!(n = strndup(w, l)))
3572 if ((r = install_info_add(n)) < 0) {
3573 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3584 static int mark_symlink_for_removal(const char *p) {
3589 assert(path_is_absolute(p));
3591 if (!remove_symlinks_to)
3594 if (!(n = strdup(p)))
3597 path_kill_slashes(n);
3599 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3601 return r == -EEXIST ? 0 : r;
3607 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3616 if (!(d = fdopendir(fd))) {
3617 close_nointr_nofail(fd);
3623 while ((de = readdir(d))) {
3624 bool is_dir = false, is_link = false;
3626 if (ignore_file(de->d_name))
3629 if (de->d_type == DT_LNK)
3631 else if (de->d_type == DT_DIR)
3633 else if (de->d_type == DT_UNKNOWN) {
3636 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3637 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3644 is_link = S_ISLNK(st.st_mode);
3645 is_dir = S_ISDIR(st.st_mode);
3653 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3654 log_error("Failed to open %s/%s: %m", root, de->d_name);
3661 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3662 log_error("Failed to allocate directory string.");
3663 close_nointr_nofail(nfd);
3668 /* This will close nfd, regardless whether it succeeds or not */
3669 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3675 } else if (is_link) {
3679 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3680 log_error("Failed to allocate symlink string.");
3685 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3686 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3694 if ((c = canonicalize_file_name(dest))) {
3695 /* This might fail if the destination
3696 * is already removed */
3702 path_kill_slashes(dest);
3703 if (set_get(remove_symlinks_to, dest)) {
3706 log_info("rm '%s'", p);
3708 if (unlink(p) < 0) {
3709 log_error("Cannot unlink symlink %s: %m", p);
3714 rmdir_parents(p, config_path);
3715 path_kill_slashes(p);
3717 if (!set_get(remove_symlinks_to, p)) {
3719 if ((r = mark_symlink_for_removal(p)) < 0) {
3738 static int remove_marked_symlinks(const char *config_path) {
3742 assert(config_path);
3744 if (set_size(remove_symlinks_to) <= 0)
3747 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3754 if ((cfd = dup(fd)) < 0) {
3759 /* This takes possession of cfd and closes it */
3760 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3766 close_nointr_nofail(fd);
3771 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3778 if (streq(verb, "enable")) {
3781 mkdir_parents(new_path, 0755);
3783 if (symlink(old_path, new_path) >= 0) {
3786 log_info("ln -s '%s' '%s'", old_path, new_path);
3791 if (errno != EEXIST) {
3792 log_error("Cannot link %s to %s: %m", old_path, new_path);
3796 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3798 if (errno == EINVAL) {
3799 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3803 log_error("readlink() failed: %s", strerror(-r));
3807 if (streq(dest, old_path)) {
3813 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3822 log_info("ln -s '%s' '%s'", old_path, new_path);
3824 if (symlink(old_path, new_path) >= 0)
3827 log_error("Cannot link %s to %s: %m", old_path, new_path);
3830 } else if (streq(verb, "disable")) {
3833 if ((r = mark_symlink_for_removal(old_path)) < 0)
3836 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3837 if (errno == ENOENT)
3840 if (errno == EINVAL) {
3841 log_warning("File %s not a symlink, ignoring.", old_path);
3845 log_error("readlink() failed: %s", strerror(-r));
3849 if (!streq(dest, old_path)) {
3850 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3857 if ((r = mark_symlink_for_removal(new_path)) < 0)
3861 log_info("rm '%s'", new_path);
3863 if (unlink(new_path) >= 0)
3866 log_error("Cannot unlink %s: %m", new_path);
3869 } else if (streq(verb, "is-enabled")) {
3872 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3874 if (errno == ENOENT || errno == EINVAL)
3877 log_error("readlink() failed: %s", strerror(-r));
3881 if (streq(dest, old_path)) {
3889 assert_not_reached("Unknown action.");
3892 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3894 char *alias_path = NULL;
3899 assert(config_path);
3901 STRV_FOREACH(s, i->aliases) {
3904 if (!(alias_path = path_make_absolute(*s, config_path))) {
3905 log_error("Out of memory");
3910 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3913 if (streq(verb, "disable"))
3914 rmdir_parents(alias_path, config_path);
3924 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3926 char *alias_path = NULL;
3931 assert(config_path);
3933 STRV_FOREACH(s, i->wanted_by) {
3934 if (!unit_name_is_valid_no_type(*s, true)) {
3935 log_error("Invalid name %s.", *s);
3943 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3944 log_error("Out of memory");
3949 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3952 if (streq(verb, "disable"))
3953 rmdir_parents(alias_path, config_path);
3964 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3966 const ConfigItem items[] = {
3967 { "Alias", config_parse_strv, &i->aliases, "Install" },
3968 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3969 { "Also", config_parse_also, NULL, "Install" },
3971 { NULL, NULL, NULL, NULL }
3975 char *filename = NULL;
3982 STRV_FOREACH(p, paths->unit_path) {
3985 if (!(filename = path_make_absolute(i->name, *p))) {
3986 log_error("Out of memory");
3990 /* Ensure that we don't follow symlinks */
3991 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3992 if ((f = fdopen(fd, "re")))
3995 if (errno == ELOOP) {
3996 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4001 if (errno != ENOENT) {
4002 log_error("Failed to open %s: %m", filename);
4012 #if defined(TARGET_FEDORA) && defined (HAVE_SYSV_COMPAT)
4014 if (endswith(i->name, ".service")) {
4018 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4019 log_error("Out of memory");
4023 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4024 exists = access(sysv, F_OK) >= 0;
4030 const char *argv[] = {
4037 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4039 argv[1] = file_name_from_path(sysv);
4041 streq(verb, "enable") ? "on" :
4042 streq(verb, "disable") ? "off" : NULL;
4044 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
4046 if ((pid = fork()) < 0) {
4047 log_error("Failed to fork: %m");
4050 } else if (pid == 0) {
4051 execv(argv[0], (char**) argv);
4052 _exit(EXIT_FAILURE);
4057 if ((r = wait_for_terminate(pid, &status)) < 0)
4060 if (status.si_code == CLD_EXITED) {
4061 if (status.si_status == 0 && (streq(verb, "enable") || streq(verb, "disable")))
4064 return status.si_status == 0 ? 0 : -EINVAL;
4074 log_error("Couldn't find %s.", i->name);
4080 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4085 n_symlinks += strv_length(i->aliases);
4086 n_symlinks += strv_length(i->wanted_by);
4090 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4093 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4096 if ((r = mark_symlink_for_removal(filename)) < 0)
4099 if ((r = remove_marked_symlinks(config_path)) < 0)
4105 static char *get_config_path(void) {
4107 if (arg_user && arg_global)
4108 return strdup(USER_CONFIG_UNIT_PATH);
4113 if (user_config_home(&p) < 0)
4119 return strdup(SYSTEM_CONFIG_UNIT_PATH);
4122 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4126 char *config_path = NULL;
4129 const char *verb = args[0];
4131 dbus_error_init(&error);
4134 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4135 log_error("Failed to determine lookup paths: %s", strerror(-r));
4139 if (!(config_path = get_config_path())) {
4140 log_error("Failed to determine config path");
4145 will_install = hashmap_new(string_hash_func, string_compare_func);
4146 have_installed = hashmap_new(string_hash_func, string_compare_func);
4148 if (!will_install || !have_installed) {
4149 log_error("Failed to allocate unit sets.");
4154 if (!arg_defaults && streq(verb, "disable"))
4155 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4156 log_error("Failed to allocate symlink sets.");
4161 for (j = 1; j < n; j++)
4162 if ((r = install_info_add(args[j])) < 0) {
4163 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4167 while ((i = hashmap_first(will_install))) {
4170 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4172 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4180 /* In test mode and found something */
4186 if (streq(verb, "is-enabled"))
4187 r = r > 0 ? 0 : -ENOENT;
4189 if (n_symlinks <= 0)
4190 log_warning("Unit files contain no applicable installation information. Ignoring.");
4193 /* Don't try to reload anything if the user asked us to not do this */
4195 /* Don't try to reload anything when updating a unit globally */
4197 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4198 (arg_user || sd_booted() > 0) &&
4199 /* Don't try to reload anything if we are running in a chroot environment */
4200 (arg_user || running_in_chroot() <= 0) ) {
4203 if ((q = daemon_reload(bus, args, n)) < 0)
4209 install_info_hashmap_free(will_install);
4210 install_info_hashmap_free(have_installed);
4212 set_free_free(remove_symlinks_to);
4214 lookup_paths_free(&paths);
4221 static int systemctl_help(void) {
4223 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4224 "Send control commands to or query the systemd manager.\n\n"
4225 " -h --help Show this help\n"
4226 " --version Show package version\n"
4227 " -t --type=TYPE List only units of a particular type\n"
4228 " -p --property=NAME Show only properties by this name\n"
4229 " -a --all Show all units/properties, including dead/empty ones\n"
4230 " --failed Show only failed units\n"
4231 " --full Don't ellipsize unit names on output\n"
4232 " --fail When queueing a new job, fail if conflicting jobs are\n"
4234 " --ignore-dependencies\n"
4235 " When queueing a new job, ignore all its dependencies\n"
4236 " -q --quiet Suppress output\n"
4237 " --no-block Do not wait until operation finished\n"
4238 " --no-pager Do not pipe output into a pager.\n"
4239 " --system Connect to system manager\n"
4240 " --user Connect to user service manager\n"
4241 " --order When generating graph for dot, show only order\n"
4242 " --require When generating graph for dot, show only requirement\n"
4243 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4244 " --global Enable/disable unit files globally\n"
4245 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4247 " --no-ask-password\n"
4248 " Do not ask for system passwords\n"
4249 " --kill-mode=MODE How to send signal\n"
4250 " --kill-who=WHO Who to send signal to\n"
4251 " -s --signal=SIGNAL Which signal to send\n"
4252 " -f --force When enabling unit files, override existing symlinks\n"
4253 " When shutting down, execute action immediately\n"
4254 " --defaults When disabling unit files, remove default symlinks only\n\n"
4256 " list-units List units\n"
4257 " start [NAME...] Start (activate) one or more units\n"
4258 " stop [NAME...] Stop (deactivate) one or more units\n"
4259 " reload [NAME...] Reload one or more units\n"
4260 " restart [NAME...] Start or restart one or more units\n"
4261 " try-restart [NAME...] Restart one or more units if active\n"
4262 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4263 " otherwise start or restart\n"
4264 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4265 " otherwise restart if active\n"
4266 " isolate [NAME] Start one unit and stop all others\n"
4267 " kill [NAME...] Send signal to processes of a unit\n"
4268 " is-active [NAME...] Check whether units are active\n"
4269 " status [NAME...|PID...] Show runtime status of one or more units\n"
4270 " show [NAME...|JOB...] Show properties of one or more\n"
4271 " units/jobs or the manager\n"
4272 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4274 " enable [NAME...] Enable one or more unit files\n"
4275 " disable [NAME...] Disable one or more unit files\n"
4276 " is-enabled [NAME...] Check whether unit files are enabled\n"
4277 " load [NAME...] Load one or more units\n"
4278 " list-jobs List jobs\n"
4279 " cancel [JOB...] Cancel all, one, or more jobs\n"
4280 " monitor Monitor unit/job changes\n"
4281 " dump Dump server status\n"
4282 " dot Dump dependency graph for dot(1)\n"
4283 " snapshot [NAME] Create a snapshot\n"
4284 " delete [NAME...] Remove one or more snapshots\n"
4285 " daemon-reload Reload systemd manager configuration\n"
4286 " daemon-reexec Reexecute systemd manager\n"
4287 " show-environment Dump environment\n"
4288 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4289 " unset-environment [NAME...] Unset one or more environment variables\n"
4290 " default Enter system default mode\n"
4291 " rescue Enter system rescue mode\n"
4292 " emergency Enter system emergency mode\n"
4293 " halt Shut down and halt the system\n"
4294 " poweroff Shut down and power-off the system\n"
4295 " reboot Shut down and reboot the system\n"
4296 " kexec Shut down and reboot the system with kexec\n"
4297 " exit Ask for user instance termination\n",
4298 program_invocation_short_name);
4303 static int halt_help(void) {
4305 printf("%s [OPTIONS...]\n\n"
4306 "%s the system.\n\n"
4307 " --help Show this help\n"
4308 " --halt Halt the machine\n"
4309 " -p --poweroff Switch off the machine\n"
4310 " --reboot Reboot the machine\n"
4311 " -f --force Force immediate halt/power-off/reboot\n"
4312 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4313 " -d --no-wtmp Don't write wtmp record\n"
4314 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4315 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4316 program_invocation_short_name,
4317 arg_action == ACTION_REBOOT ? "Reboot" :
4318 arg_action == ACTION_POWEROFF ? "Power off" :
4324 static int shutdown_help(void) {
4326 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4327 "Shut down the system.\n\n"
4328 " --help Show this help\n"
4329 " -H --halt Halt the machine\n"
4330 " -P --poweroff Power-off the machine\n"
4331 " -r --reboot Reboot the machine\n"
4332 " -h Equivalent to --poweroff, overriden by --halt\n"
4333 " -k Don't halt/power-off/reboot, just send warnings\n"
4334 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4335 " -c Cancel a pending shutdown\n",
4336 program_invocation_short_name);
4341 static int telinit_help(void) {
4343 printf("%s [OPTIONS...] {COMMAND}\n\n"
4344 "Send control commands to the init daemon.\n\n"
4345 " --help Show this help\n"
4346 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4348 " 0 Power-off the machine\n"
4349 " 6 Reboot the machine\n"
4350 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4351 " 1, s, S Enter rescue mode\n"
4352 " q, Q Reload init daemon configuration\n"
4353 " u, U Reexecute init daemon\n",
4354 program_invocation_short_name);
4359 static int runlevel_help(void) {
4361 printf("%s [OPTIONS...]\n\n"
4362 "Prints the previous and current runlevel of the init system.\n\n"
4363 " --help Show this help\n",
4364 program_invocation_short_name);
4369 static int systemctl_parse_argv(int argc, char *argv[]) {
4373 ARG_IGNORE_DEPENDENCIES,
4388 ARG_NO_ASK_PASSWORD,
4392 static const struct option options[] = {
4393 { "help", no_argument, NULL, 'h' },
4394 { "version", no_argument, NULL, ARG_VERSION },
4395 { "type", required_argument, NULL, 't' },
4396 { "property", required_argument, NULL, 'p' },
4397 { "all", no_argument, NULL, 'a' },
4398 { "failed", no_argument, NULL, ARG_FAILED },
4399 { "full", no_argument, NULL, ARG_FULL },
4400 { "fail", no_argument, NULL, ARG_FAIL },
4401 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4402 { "user", no_argument, NULL, ARG_USER },
4403 { "system", no_argument, NULL, ARG_SYSTEM },
4404 { "global", no_argument, NULL, ARG_GLOBAL },
4405 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4406 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4407 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4408 { "quiet", no_argument, NULL, 'q' },
4409 { "order", no_argument, NULL, ARG_ORDER },
4410 { "require", no_argument, NULL, ARG_REQUIRE },
4411 { "force", no_argument, NULL, 'f' },
4412 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4413 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4414 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4415 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4416 { "signal", required_argument, NULL, 's' },
4417 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4418 { NULL, 0, NULL, 0 }
4426 /* Only when running as systemctl we ask for passwords */
4427 arg_ask_password = true;
4429 while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4438 puts(PACKAGE_STRING);
4440 puts(SYSTEMD_FEATURES);
4450 if (!(l = strv_append(arg_property, optarg)))
4453 strv_free(arg_property);
4456 /* If the user asked for a particular
4457 * property, show it to him, even if it is
4468 arg_job_mode = "fail";
4471 case ARG_IGNORE_DEPENDENCIES:
4472 arg_job_mode = "ignore-dependencies";
4484 arg_no_block = true;
4488 arg_no_pager = true;
4496 arg_dot = DOT_ORDER;
4500 arg_dot = DOT_REQUIRE;
4520 arg_no_reload = true;
4529 arg_defaults = true;
4533 arg_kill_who = optarg;
4537 arg_kill_mode = optarg;
4541 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4542 log_error("Failed to parse signal string %s.", optarg);
4547 case ARG_NO_ASK_PASSWORD:
4548 arg_ask_password = false;
4555 log_error("Unknown option code %c", c);
4563 static int halt_parse_argv(int argc, char *argv[]) {
4572 static const struct option options[] = {
4573 { "help", no_argument, NULL, ARG_HELP },
4574 { "halt", no_argument, NULL, ARG_HALT },
4575 { "poweroff", no_argument, NULL, 'p' },
4576 { "reboot", no_argument, NULL, ARG_REBOOT },
4577 { "force", no_argument, NULL, 'f' },
4578 { "wtmp-only", no_argument, NULL, 'w' },
4579 { "no-wtmp", no_argument, NULL, 'd' },
4580 { "no-sync", no_argument, NULL, 'n' },
4581 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4582 { NULL, 0, NULL, 0 }
4590 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4591 if (runlevel == '0' || runlevel == '6')
4592 arg_immediate = true;
4594 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4602 arg_action = ACTION_HALT;
4606 if (arg_action != ACTION_REBOOT)
4607 arg_action = ACTION_POWEROFF;
4611 arg_action = ACTION_REBOOT;
4615 arg_immediate = true;
4636 /* Compatibility nops */
4643 log_error("Unknown option code %c", c);
4648 if (optind < argc) {
4649 log_error("Too many arguments.");
4656 static int parse_time_spec(const char *t, usec_t *_u) {
4660 if (streq(t, "now"))
4662 else if (t[0] == '+') {
4665 if (safe_atou64(t + 1, &u) < 0)
4668 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4677 hour = strtol(t, &e, 10);
4678 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4681 minute = strtol(e+1, &e, 10);
4682 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4685 n = now(CLOCK_REALTIME);
4686 s = (time_t) (n / USEC_PER_SEC);
4689 assert_se(localtime_r(&s, &tm));
4691 tm.tm_hour = (int) hour;
4692 tm.tm_min = (int) minute;
4695 assert_se(s = mktime(&tm));
4697 *_u = (usec_t) s * USEC_PER_SEC;
4700 *_u += USEC_PER_DAY;
4706 static bool kexec_loaded(void) {
4707 bool loaded = false;
4710 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4718 static int shutdown_parse_argv(int argc, char *argv[]) {
4725 static const struct option options[] = {
4726 { "help", no_argument, NULL, ARG_HELP },
4727 { "halt", no_argument, NULL, 'H' },
4728 { "poweroff", no_argument, NULL, 'P' },
4729 { "reboot", no_argument, NULL, 'r' },
4730 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4731 { NULL, 0, NULL, 0 }
4739 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4747 arg_action = ACTION_HALT;
4751 arg_action = ACTION_POWEROFF;
4756 arg_action = ACTION_KEXEC;
4758 arg_action = ACTION_REBOOT;
4762 if (arg_action != ACTION_HALT)
4763 arg_action = ACTION_POWEROFF;
4776 /* Compatibility nops */
4780 arg_action = ACTION_CANCEL_SHUTDOWN;
4787 log_error("Unknown option code %c", c);
4792 if (argc > optind) {
4793 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4794 log_error("Failed to parse time specification: %s", argv[optind]);
4798 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4800 /* We skip the time argument */
4801 if (argc > optind + 1)
4802 arg_wall = argv + optind + 1;
4809 static int telinit_parse_argv(int argc, char *argv[]) {
4816 static const struct option options[] = {
4817 { "help", no_argument, NULL, ARG_HELP },
4818 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4819 { NULL, 0, NULL, 0 }
4822 static const struct {
4826 { '0', ACTION_POWEROFF },
4827 { '6', ACTION_REBOOT },
4828 { '1', ACTION_RESCUE },
4829 { '2', ACTION_RUNLEVEL2 },
4830 { '3', ACTION_RUNLEVEL3 },
4831 { '4', ACTION_RUNLEVEL4 },
4832 { '5', ACTION_RUNLEVEL5 },
4833 { 's', ACTION_RESCUE },
4834 { 'S', ACTION_RESCUE },
4835 { 'q', ACTION_RELOAD },
4836 { 'Q', ACTION_RELOAD },
4837 { 'u', ACTION_REEXEC },
4838 { 'U', ACTION_REEXEC }
4847 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4862 log_error("Unknown option code %c", c);
4867 if (optind >= argc) {
4872 if (optind + 1 < argc) {
4873 log_error("Too many arguments.");
4877 if (strlen(argv[optind]) != 1) {
4878 log_error("Expected single character argument.");
4882 for (i = 0; i < ELEMENTSOF(table); i++)
4883 if (table[i].from == argv[optind][0])
4886 if (i >= ELEMENTSOF(table)) {
4887 log_error("Unknown command %s.", argv[optind]);
4891 arg_action = table[i].to;
4898 static int runlevel_parse_argv(int argc, char *argv[]) {
4904 static const struct option options[] = {
4905 { "help", no_argument, NULL, ARG_HELP },
4906 { NULL, 0, NULL, 0 }
4914 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4925 log_error("Unknown option code %c", c);
4930 if (optind < argc) {
4931 log_error("Too many arguments.");
4938 static int parse_argv(int argc, char *argv[]) {
4942 if (program_invocation_short_name) {
4944 if (strstr(program_invocation_short_name, "halt")) {
4945 arg_action = ACTION_HALT;
4946 return halt_parse_argv(argc, argv);
4947 } else if (strstr(program_invocation_short_name, "poweroff")) {
4948 arg_action = ACTION_POWEROFF;
4949 return halt_parse_argv(argc, argv);
4950 } else if (strstr(program_invocation_short_name, "reboot")) {
4952 arg_action = ACTION_KEXEC;
4954 arg_action = ACTION_REBOOT;
4955 return halt_parse_argv(argc, argv);
4956 } else if (strstr(program_invocation_short_name, "shutdown")) {
4957 arg_action = ACTION_POWEROFF;
4958 return shutdown_parse_argv(argc, argv);
4959 } else if (strstr(program_invocation_short_name, "init")) {
4961 if (sd_booted() > 0) {
4962 arg_action = ACTION_INVALID;
4963 return telinit_parse_argv(argc, argv);
4965 /* Hmm, so some other init system is
4966 * running, we need to forward this
4967 * request to it. For now we simply
4968 * guess that it is Upstart. */
4970 execv("/lib/upstart/telinit", argv);
4972 log_error("Couldn't find an alternative telinit implementation to spawn.");
4976 } else if (strstr(program_invocation_short_name, "runlevel")) {
4977 arg_action = ACTION_RUNLEVEL;
4978 return runlevel_parse_argv(argc, argv);
4982 arg_action = ACTION_SYSTEMCTL;
4983 return systemctl_parse_argv(argc, argv);
4986 static int action_to_runlevel(void) {
4988 static const char table[_ACTION_MAX] = {
4989 [ACTION_HALT] = '0',
4990 [ACTION_POWEROFF] = '0',
4991 [ACTION_REBOOT] = '6',
4992 [ACTION_RUNLEVEL2] = '2',
4993 [ACTION_RUNLEVEL3] = '3',
4994 [ACTION_RUNLEVEL4] = '4',
4995 [ACTION_RUNLEVEL5] = '5',
4996 [ACTION_RESCUE] = '1'
4999 assert(arg_action < _ACTION_MAX);
5001 return table[arg_action];
5004 static int talk_upstart(void) {
5005 DBusMessage *m = NULL, *reply = NULL;
5007 int previous, rl, r;
5009 env1_buf[] = "RUNLEVEL=X",
5010 env2_buf[] = "PREVLEVEL=X";
5011 char *env1 = env1_buf, *env2 = env2_buf;
5012 const char *emit = "runlevel";
5013 dbus_bool_t b_false = FALSE;
5014 DBusMessageIter iter, sub;
5015 DBusConnection *bus;
5017 dbus_error_init(&error);
5019 if (!(rl = action_to_runlevel()))
5022 if (utmp_get_runlevel(&previous, NULL) < 0)
5025 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5026 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5031 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5036 if ((r = bus_check_peercred(bus)) < 0) {
5037 log_error("Failed to verify owner of bus.");
5041 if (!(m = dbus_message_new_method_call(
5042 "com.ubuntu.Upstart",
5043 "/com/ubuntu/Upstart",
5044 "com.ubuntu.Upstart0_6",
5047 log_error("Could not allocate message.");
5052 dbus_message_iter_init_append(m, &iter);
5054 env1_buf[sizeof(env1_buf)-2] = rl;
5055 env2_buf[sizeof(env2_buf)-2] = previous;
5057 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5058 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5059 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5060 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5061 !dbus_message_iter_close_container(&iter, &sub) ||
5062 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5063 log_error("Could not append arguments to message.");
5068 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5070 if (error_is_no_service(&error)) {
5075 log_error("Failed to issue method call: %s", bus_error_message(&error));
5084 dbus_message_unref(m);
5087 dbus_message_unref(reply);
5090 dbus_connection_flush(bus);
5091 dbus_connection_close(bus);
5092 dbus_connection_unref(bus);
5095 dbus_error_free(&error);
5100 static int talk_initctl(void) {
5101 struct init_request request;
5105 if (!(rl = action_to_runlevel()))
5109 request.magic = INIT_MAGIC;
5110 request.sleeptime = 0;
5111 request.cmd = INIT_CMD_RUNLVL;
5112 request.runlevel = rl;
5114 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5116 if (errno == ENOENT)
5119 log_error("Failed to open "INIT_FIFO": %m");
5124 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5125 close_nointr_nofail(fd);
5128 log_error("Failed to write to "INIT_FIFO": %m");
5129 return errno ? -errno : -EIO;
5135 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5137 static const struct {
5145 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5147 { "list-units", LESS, 1, list_units },
5148 { "list-jobs", EQUAL, 1, list_jobs },
5149 { "clear-jobs", EQUAL, 1, daemon_reload },
5150 { "load", MORE, 2, load_unit },
5151 { "cancel", MORE, 2, cancel_job },
5152 { "start", MORE, 2, start_unit },
5153 { "stop", MORE, 2, start_unit },
5154 { "reload", MORE, 2, start_unit },
5155 { "restart", MORE, 2, start_unit },
5156 { "try-restart", MORE, 2, start_unit },
5157 { "reload-or-restart", MORE, 2, start_unit },
5158 { "reload-or-try-restart", MORE, 2, start_unit },
5159 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5160 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5161 { "isolate", EQUAL, 2, start_unit },
5162 { "kill", MORE, 2, kill_unit },
5163 { "is-active", MORE, 2, check_unit },
5164 { "check", MORE, 2, check_unit },
5165 { "show", MORE, 1, show },
5166 { "status", MORE, 2, show },
5167 { "monitor", EQUAL, 1, monitor },
5168 { "dump", EQUAL, 1, dump },
5169 { "dot", EQUAL, 1, dot },
5170 { "snapshot", LESS, 2, snapshot },
5171 { "delete", MORE, 2, delete_snapshot },
5172 { "daemon-reload", EQUAL, 1, daemon_reload },
5173 { "daemon-reexec", EQUAL, 1, daemon_reload },
5174 { "show-environment", EQUAL, 1, show_enviroment },
5175 { "set-environment", MORE, 2, set_environment },
5176 { "unset-environment", MORE, 2, set_environment },
5177 { "halt", EQUAL, 1, start_special },
5178 { "poweroff", EQUAL, 1, start_special },
5179 { "reboot", EQUAL, 1, start_special },
5180 { "kexec", EQUAL, 1, start_special },
5181 { "default", EQUAL, 1, start_special },
5182 { "rescue", EQUAL, 1, start_special },
5183 { "emergency", EQUAL, 1, start_special },
5184 { "exit", EQUAL, 1, start_special },
5185 { "reset-failed", MORE, 1, reset_failed },
5186 { "enable", MORE, 2, enable_unit },
5187 { "disable", MORE, 2, enable_unit },
5188 { "is-enabled", MORE, 2, enable_unit }
5198 left = argc - optind;
5201 /* Special rule: no arguments means "list-units" */
5204 if (streq(argv[optind], "help")) {
5209 for (i = 0; i < ELEMENTSOF(verbs); i++)
5210 if (streq(argv[optind], verbs[i].verb))
5213 if (i >= ELEMENTSOF(verbs)) {
5214 log_error("Unknown operation %s", argv[optind]);
5219 switch (verbs[i].argc_cmp) {
5222 if (left != verbs[i].argc) {
5223 log_error("Invalid number of arguments.");
5230 if (left < verbs[i].argc) {
5231 log_error("Too few arguments.");
5238 if (left > verbs[i].argc) {
5239 log_error("Too many arguments.");
5246 assert_not_reached("Unknown comparison operator.");
5249 /* Require a bus connection for all operations but
5251 if (!streq(verbs[i].verb, "enable") &&
5252 !streq(verbs[i].verb, "disable") &&
5254 log_error("Failed to get D-Bus connection: %s", error->message);
5258 return verbs[i].dispatch(bus, argv + optind, left);
5261 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5263 struct msghdr msghdr;
5265 union sockaddr_union sockaddr;
5266 struct shutdownd_command c;
5274 strncpy(c.wall_message, message, sizeof(c.wall_message));
5276 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5280 sockaddr.sa.sa_family = AF_UNIX;
5281 sockaddr.un.sun_path[0] = 0;
5282 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5285 iovec.iov_base = (char*) &c;
5286 iovec.iov_len = sizeof(c);
5289 msghdr.msg_name = &sockaddr;
5290 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5292 msghdr.msg_iov = &iovec;
5293 msghdr.msg_iovlen = 1;
5295 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5296 close_nointr_nofail(fd);
5300 close_nointr_nofail(fd);
5304 static int reload_with_fallback(DBusConnection *bus) {
5307 /* First, try systemd via D-Bus. */
5308 if (daemon_reload(bus, NULL, 0) > 0)
5312 /* Nothing else worked, so let's try signals */
5313 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5315 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5316 log_error("kill() failed: %m");
5323 static int start_with_fallback(DBusConnection *bus) {
5326 /* First, try systemd via D-Bus. */
5327 if (start_unit(bus, NULL, 0) >= 0)
5331 /* Hmm, talking to systemd via D-Bus didn't work. Then
5332 * let's try to talk to Upstart via D-Bus. */
5333 if (talk_upstart() > 0)
5336 /* Nothing else worked, so let's try
5338 if (talk_initctl() > 0)
5341 log_error("Failed to talk to init daemon.");
5345 warn_wall(arg_action);
5349 static int halt_main(DBusConnection *bus) {
5352 if (geteuid() != 0) {
5353 log_error("Must be root.");
5359 char date[FORMAT_TIMESTAMP_MAX];
5361 m = strv_join(arg_wall, " ");
5362 r = send_shutdownd(arg_when,
5363 arg_action == ACTION_HALT ? 'H' :
5364 arg_action == ACTION_POWEROFF ? 'P' :
5371 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5373 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5374 format_timestamp(date, sizeof(date), arg_when));
5379 if (!arg_dry && !arg_immediate)
5380 return start_with_fallback(bus);
5383 if (sd_booted() > 0)
5384 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5385 else if ((r = utmp_put_shutdown(0)) < 0)
5386 log_warning("Failed to write utmp record: %s", strerror(-r));
5395 /* Make sure C-A-D is handled by the kernel from this
5397 reboot(RB_ENABLE_CAD);
5399 switch (arg_action) {
5402 log_info("Halting.");
5403 reboot(RB_HALT_SYSTEM);
5406 case ACTION_POWEROFF:
5407 log_info("Powering off.");
5408 reboot(RB_POWER_OFF);
5412 log_info("Rebooting.");
5413 reboot(RB_AUTOBOOT);
5417 assert_not_reached("Unknown halt action.");
5420 /* We should never reach this. */
5424 static int runlevel_main(void) {
5425 int r, runlevel, previous;
5427 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5428 printf("unknown\n");
5433 previous <= 0 ? 'N' : previous,
5434 runlevel <= 0 ? 'N' : runlevel);
5439 static void pager_open(void) {
5446 if (!on_tty() || arg_no_pager)
5449 if ((pager = getenv("PAGER")))
5450 if (!*pager || streq(pager, "cat"))
5453 /* Determine and cache number of columns before we spawn the
5454 * pager so that we get the value from the actual tty */
5458 log_error("Failed to create pager pipe: %m");
5463 if (pager_pid < 0) {
5464 log_error("Failed to fork pager: %m");
5469 /* In the child start the pager */
5470 if (pager_pid == 0) {
5472 dup2(fd[0], STDIN_FILENO);
5475 setenv("LESS", "FRSX", 0);
5477 prctl(PR_SET_PDEATHSIG, SIGTERM);
5480 execlp(pager, pager, NULL);
5481 execl("/bin/sh", "sh", "-c", pager, NULL);
5483 /* Debian's alternatives command for pagers is
5484 * called 'pager'. Note that we do not call
5485 * sensible-pagers here, since that is just a
5486 * shell script that implements a logic that
5487 * is similar to this one anyway, but is
5488 * Debian-specific. */
5489 execlp("pager", "pager", NULL);
5491 execlp("less", "less", NULL);
5492 execlp("more", "more", NULL);
5495 log_error("Unable to execute pager: %m");
5496 _exit(EXIT_FAILURE);
5499 /* Return in the parent */
5500 if (dup2(fd[1], STDOUT_FILENO) < 0)
5501 log_error("Failed to duplicate pager pipe: %m");
5506 static void pager_close(void) {
5512 /* Inform pager that we are done */
5514 wait_for_terminate(pager_pid, &dummy);
5518 int main(int argc, char*argv[]) {
5519 int r, retval = EXIT_FAILURE;
5520 DBusConnection *bus = NULL;
5523 dbus_error_init(&error);
5525 log_parse_environment();
5528 if ((r = parse_argv(argc, argv)) < 0)
5531 retval = EXIT_SUCCESS;
5535 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5536 * let's shortcut this */
5537 if (arg_action == ACTION_RUNLEVEL) {
5538 r = runlevel_main();
5539 retval = r < 0 ? EXIT_FAILURE : r;
5543 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5545 switch (arg_action) {
5547 case ACTION_SYSTEMCTL:
5548 r = systemctl_main(bus, argc, argv, &error);
5552 case ACTION_POWEROFF:
5558 case ACTION_RUNLEVEL2:
5559 case ACTION_RUNLEVEL3:
5560 case ACTION_RUNLEVEL4:
5561 case ACTION_RUNLEVEL5:
5563 case ACTION_EMERGENCY:
5564 case ACTION_DEFAULT:
5565 r = start_with_fallback(bus);
5570 r = reload_with_fallback(bus);
5573 case ACTION_CANCEL_SHUTDOWN:
5574 r = send_shutdownd(0, 0, false, NULL);
5577 case ACTION_INVALID:
5578 case ACTION_RUNLEVEL:
5580 assert_not_reached("Unknown action");
5583 retval = r < 0 ? EXIT_FAILURE : r;
5588 dbus_connection_flush(bus);
5589 dbus_connection_close(bus);
5590 dbus_connection_unref(bus);
5593 dbus_error_free(&error);
5597 strv_free(arg_property);