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")) {
1148 dbus_bool_t success = true;
1150 if (!dbus_message_get_args(message, &error,
1151 DBUS_TYPE_UINT32, &id,
1152 DBUS_TYPE_OBJECT_PATH, &path,
1153 DBUS_TYPE_BOOLEAN, &success,
1155 log_error("Failed to parse message: %s", bus_error_message(&error));
1159 if ((p = set_remove(d->set, (char*) path)))
1167 dbus_error_free(&error);
1168 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1171 static int enable_wait_for_jobs(DBusConnection *bus) {
1179 dbus_error_init(&error);
1180 dbus_bus_add_match(bus,
1182 "sender='org.freedesktop.systemd1',"
1183 "interface='org.freedesktop.systemd1.Manager',"
1184 "member='JobRemoved',"
1185 "path='/org/freedesktop/systemd1'",
1188 if (dbus_error_is_set(&error)) {
1189 log_error("Failed to add match: %s", bus_error_message(&error));
1190 dbus_error_free(&error);
1194 /* This is slightly dirty, since we don't undo the match registrations. */
1198 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1209 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1210 log_error("Failed to add filter.");
1215 while (!set_isempty(s) &&
1216 dbus_connection_read_write_dispatch(bus, -1))
1219 if (!arg_quiet && d.failed)
1220 log_error("Job failed. See system logs and 'systemctl status' for details.");
1222 r = d.failed ? -EIO : 0;
1225 /* This is slightly dirty, since we don't undo the filter registration. */
1230 static int start_unit_one(
1231 DBusConnection *bus,
1238 DBusMessage *m = NULL, *reply = NULL;
1247 assert(arg_no_block || s);
1249 if (!(m = dbus_message_new_method_call(
1250 "org.freedesktop.systemd1",
1251 "/org/freedesktop/systemd1",
1252 "org.freedesktop.systemd1.Manager",
1254 log_error("Could not allocate message.");
1259 if (!dbus_message_append_args(m,
1260 DBUS_TYPE_STRING, &name,
1261 DBUS_TYPE_STRING, &mode,
1262 DBUS_TYPE_INVALID)) {
1263 log_error("Could not append arguments to message.");
1268 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1270 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1271 /* There's always a fallback possible for
1272 * legacy actions. */
1277 log_error("Failed to issue method call: %s", bus_error_message(error));
1282 if (!dbus_message_get_args(reply, error,
1283 DBUS_TYPE_OBJECT_PATH, &path,
1284 DBUS_TYPE_INVALID)) {
1285 log_error("Failed to parse reply: %s", bus_error_message(error));
1290 if (need_daemon_reload(bus, name))
1291 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1292 arg_user ? "--user" : "--system");
1294 if (!arg_no_block) {
1297 if (!(p = strdup(path))) {
1298 log_error("Failed to duplicate path.");
1303 if ((r = set_put(s, p)) < 0) {
1305 log_error("Failed to add path to set.");
1314 dbus_message_unref(m);
1317 dbus_message_unref(reply);
1322 static enum action verb_to_action(const char *verb) {
1323 if (streq(verb, "halt"))
1325 else if (streq(verb, "poweroff"))
1326 return ACTION_POWEROFF;
1327 else if (streq(verb, "reboot"))
1328 return ACTION_REBOOT;
1329 else if (streq(verb, "kexec"))
1330 return ACTION_KEXEC;
1331 else if (streq(verb, "rescue"))
1332 return ACTION_RESCUE;
1333 else if (streq(verb, "emergency"))
1334 return ACTION_EMERGENCY;
1335 else if (streq(verb, "default"))
1336 return ACTION_DEFAULT;
1337 else if (streq(verb, "exit"))
1340 return ACTION_INVALID;
1343 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1345 static const char * const table[_ACTION_MAX] = {
1346 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1347 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1348 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1349 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1350 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1351 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1352 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1353 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1354 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1355 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1356 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1357 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1362 const char *method, *mode, *one_name;
1366 dbus_error_init(&error);
1370 spawn_ask_password_agent();
1372 if (arg_action == ACTION_SYSTEMCTL) {
1374 streq(args[0], "stop") ? "StopUnit" :
1375 streq(args[0], "reload") ? "ReloadUnit" :
1376 streq(args[0], "restart") ? "RestartUnit" :
1377 streq(args[0], "try-restart") ||
1378 streq(args[0], "condrestart") ? "TryRestartUnit" :
1379 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1380 streq(args[0], "reload-or-try-restart") ||
1381 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1385 (streq(args[0], "isolate") ||
1386 streq(args[0], "rescue") ||
1387 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1389 one_name = table[verb_to_action(args[0])];
1392 assert(arg_action < ELEMENTSOF(table));
1393 assert(table[arg_action]);
1395 method = "StartUnit";
1397 mode = (arg_action == ACTION_EMERGENCY ||
1398 arg_action == ACTION_RESCUE ||
1399 arg_action == ACTION_RUNLEVEL2 ||
1400 arg_action == ACTION_RUNLEVEL3 ||
1401 arg_action == ACTION_RUNLEVEL4 ||
1402 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1404 one_name = table[arg_action];
1407 if (!arg_no_block) {
1408 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1409 log_error("Could not watch jobs: %s", strerror(-ret));
1413 if (!(s = set_new(string_hash_func, string_compare_func))) {
1414 log_error("Failed to allocate set.");
1421 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1424 for (i = 1; i < n; i++)
1425 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1426 ret = translate_bus_error_to_exit_status(r, &error);
1427 dbus_error_free(&error);
1432 if ((r = wait_for_jobs(bus, s)) < 0) {
1441 dbus_error_free(&error);
1446 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1453 (streq(args[0], "halt") ||
1454 streq(args[0], "poweroff") ||
1455 streq(args[0], "reboot") ||
1456 streq(args[0], "kexec") ||
1457 streq(args[0], "exit")))
1458 return daemon_reload(bus, args, n);
1460 r = start_unit(bus, args, n);
1463 warn_wall(verb_to_action(args[0]));
1468 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1469 DBusMessage *m = NULL, *reply = NULL;
1471 *interface = "org.freedesktop.systemd1.Unit",
1472 *property = "ActiveState";
1473 int r = 3; /* According to LSB: "program is not running" */
1480 dbus_error_init(&error);
1482 for (i = 1; i < n; i++) {
1483 const char *path = NULL;
1485 DBusMessageIter iter, sub;
1487 if (!(m = dbus_message_new_method_call(
1488 "org.freedesktop.systemd1",
1489 "/org/freedesktop/systemd1",
1490 "org.freedesktop.systemd1.Manager",
1492 log_error("Could not allocate message.");
1497 if (!dbus_message_append_args(m,
1498 DBUS_TYPE_STRING, &args[i],
1499 DBUS_TYPE_INVALID)) {
1500 log_error("Could not append arguments to message.");
1505 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1507 /* Hmm, cannot figure out anything about this unit... */
1511 dbus_error_free(&error);
1512 dbus_message_unref(m);
1516 if (!dbus_message_get_args(reply, &error,
1517 DBUS_TYPE_OBJECT_PATH, &path,
1518 DBUS_TYPE_INVALID)) {
1519 log_error("Failed to parse reply: %s", bus_error_message(&error));
1524 dbus_message_unref(m);
1525 if (!(m = dbus_message_new_method_call(
1526 "org.freedesktop.systemd1",
1528 "org.freedesktop.DBus.Properties",
1530 log_error("Could not allocate message.");
1535 if (!dbus_message_append_args(m,
1536 DBUS_TYPE_STRING, &interface,
1537 DBUS_TYPE_STRING, &property,
1538 DBUS_TYPE_INVALID)) {
1539 log_error("Could not append arguments to message.");
1544 dbus_message_unref(reply);
1545 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1546 log_error("Failed to issue method call: %s", bus_error_message(&error));
1551 if (!dbus_message_iter_init(reply, &iter) ||
1552 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1553 log_error("Failed to parse reply.");
1558 dbus_message_iter_recurse(&iter, &sub);
1560 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1561 log_error("Failed to parse reply.");
1566 dbus_message_iter_get_basic(&sub, &state);
1571 if (streq(state, "active") || streq(state, "reloading"))
1574 dbus_message_unref(m);
1575 dbus_message_unref(reply);
1581 dbus_message_unref(m);
1584 dbus_message_unref(reply);
1586 dbus_error_free(&error);
1591 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1592 DBusMessage *m = NULL, *reply = NULL;
1600 dbus_error_init(&error);
1603 arg_kill_who = "all";
1606 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1608 for (i = 1; i < n; i++) {
1610 if (!(m = dbus_message_new_method_call(
1611 "org.freedesktop.systemd1",
1612 "/org/freedesktop/systemd1",
1613 "org.freedesktop.systemd1.Manager",
1615 log_error("Could not allocate message.");
1620 if (!dbus_message_append_args(m,
1621 DBUS_TYPE_STRING, &args[i],
1622 DBUS_TYPE_STRING, &arg_kill_who,
1623 DBUS_TYPE_STRING, &arg_kill_mode,
1624 DBUS_TYPE_INT32, &arg_signal,
1625 DBUS_TYPE_INVALID)) {
1626 log_error("Could not append arguments to message.");
1631 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1632 log_error("Failed to issue method call: %s", bus_error_message(&error));
1633 dbus_error_free(&error);
1637 dbus_message_unref(m);
1640 dbus_message_unref(reply);
1646 dbus_message_unref(m);
1649 dbus_message_unref(reply);
1651 dbus_error_free(&error);
1656 typedef struct ExecStatusInfo {
1664 usec_t start_timestamp;
1665 usec_t exit_timestamp;
1670 LIST_FIELDS(struct ExecStatusInfo, exec);
1673 static void exec_status_info_free(ExecStatusInfo *i) {
1682 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1683 uint64_t start_timestamp, exit_timestamp;
1684 DBusMessageIter sub2, sub3;
1688 int32_t code, status;
1694 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1697 dbus_message_iter_recurse(sub, &sub2);
1699 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1702 if (!(i->path = strdup(path)))
1705 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1706 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1710 dbus_message_iter_recurse(&sub2, &sub3);
1711 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1712 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1713 dbus_message_iter_next(&sub3);
1718 if (!(i->argv = new0(char*, n+1)))
1722 dbus_message_iter_recurse(&sub2, &sub3);
1723 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1726 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1727 dbus_message_iter_get_basic(&sub3, &s);
1728 dbus_message_iter_next(&sub3);
1730 if (!(i->argv[n++] = strdup(s)))
1734 if (!dbus_message_iter_next(&sub2) ||
1735 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1736 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1737 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1738 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1739 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1740 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1744 i->start_timestamp = (usec_t) start_timestamp;
1745 i->exit_timestamp = (usec_t) exit_timestamp;
1746 i->pid = (pid_t) pid;
1753 typedef struct UnitStatusInfo {
1755 const char *load_state;
1756 const char *active_state;
1757 const char *sub_state;
1759 const char *description;
1760 const char *following;
1763 const char *default_control_group;
1765 usec_t inactive_exit_timestamp;
1766 usec_t active_enter_timestamp;
1767 usec_t active_exit_timestamp;
1768 usec_t inactive_enter_timestamp;
1770 bool need_daemon_reload;
1775 const char *status_text;
1777 #ifdef HAVE_SYSV_COMPAT
1781 usec_t start_timestamp;
1782 usec_t exit_timestamp;
1784 int exit_code, exit_status;
1787 unsigned n_accepted;
1788 unsigned n_connections;
1792 const char *sysfs_path;
1794 /* Mount, Automount */
1800 LIST_HEAD(ExecStatusInfo, exec);
1803 static void print_status_info(UnitStatusInfo *i) {
1805 const char *on, *off, *ss;
1807 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1808 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1812 /* This shows pretty information about a unit. See
1813 * print_property() for a low-level property printer */
1815 printf("%s", strna(i->id));
1817 if (i->description && !streq_ptr(i->id, i->description))
1818 printf(" - %s", i->description);
1823 printf("\t Follow: unit currently follows state of %s\n", i->following);
1825 if (streq_ptr(i->load_state, "failed") ||
1826 streq_ptr(i->load_state, "banned")) {
1827 on = ansi_highlight(true);
1828 off = ansi_highlight(false);
1833 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1835 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1837 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1839 if (streq_ptr(i->active_state, "failed")) {
1840 on = ansi_highlight(true);
1841 off = ansi_highlight(false);
1842 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1843 on = ansi_highlight_green(true);
1844 off = ansi_highlight_green(false);
1849 printf("\t Active: %s%s (%s)%s",
1851 strna(i->active_state),
1855 printf("\t Active: %s%s%s",
1857 strna(i->active_state),
1860 timestamp = (streq_ptr(i->active_state, "active") ||
1861 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1862 (streq_ptr(i->active_state, "inactive") ||
1863 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1864 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1865 i->active_exit_timestamp;
1867 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1868 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1871 printf(" since %s; %s\n", s2, s1);
1873 printf(" since %s\n", s2);
1878 printf("\t Device: %s\n", i->sysfs_path);
1880 printf("\t Where: %s\n", i->where);
1882 printf("\t What: %s\n", i->what);
1885 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1887 LIST_FOREACH(exec, p, i->exec) {
1891 /* Only show exited processes here */
1895 t = strv_join(p->argv, " ");
1896 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1899 #ifdef HAVE_SYSV_COMPAT
1901 good = is_clean_exit_lsb(p->code, p->status);
1904 good = is_clean_exit(p->code, p->status);
1907 on = ansi_highlight(true);
1908 off = ansi_highlight(false);
1912 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1914 if (p->code == CLD_EXITED) {
1917 printf("status=%i", p->status);
1919 #ifdef HAVE_SYSV_COMPAT
1920 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1922 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1927 printf("signal=%s", signal_to_string(p->status));
1929 printf(")%s\n", off);
1933 if (i->main_pid == p->pid &&
1934 i->start_timestamp == p->start_timestamp &&
1935 i->exit_timestamp == p->start_timestamp)
1936 /* Let's not show this twice */
1939 if (p->pid == i->control_pid)
1943 if (i->main_pid > 0 || i->control_pid > 0) {
1946 if (i->main_pid > 0) {
1947 printf("Main PID: %u", (unsigned) i->main_pid);
1951 get_process_name(i->main_pid, &t);
1956 } else if (i->exit_code > 0) {
1957 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1959 if (i->exit_code == CLD_EXITED) {
1962 printf("status=%i", i->exit_status);
1964 #ifdef HAVE_SYSV_COMPAT
1965 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1967 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1972 printf("signal=%s", signal_to_string(i->exit_status));
1977 if (i->main_pid > 0 && i->control_pid > 0)
1980 if (i->control_pid > 0) {
1983 printf(" Control: %u", (unsigned) i->control_pid);
1985 get_process_name(i->control_pid, &t);
1996 printf("\t Status: \"%s\"\n", i->status_text);
1998 if (i->default_control_group) {
2001 printf("\t CGroup: %s\n", i->default_control_group);
2003 if ((c = columns()) > 18)
2008 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2011 if (i->need_daemon_reload)
2012 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2013 ansi_highlight(true),
2014 ansi_highlight(false),
2015 arg_user ? "--user" : "--system");
2018 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2020 switch (dbus_message_iter_get_arg_type(iter)) {
2022 case DBUS_TYPE_STRING: {
2025 dbus_message_iter_get_basic(iter, &s);
2028 if (streq(name, "Id"))
2030 else if (streq(name, "LoadState"))
2032 else if (streq(name, "ActiveState"))
2033 i->active_state = s;
2034 else if (streq(name, "SubState"))
2036 else if (streq(name, "Description"))
2038 else if (streq(name, "FragmentPath"))
2040 #ifdef HAVE_SYSV_COMPAT
2041 else if (streq(name, "SysVPath")) {
2046 else if (streq(name, "DefaultControlGroup"))
2047 i->default_control_group = s;
2048 else if (streq(name, "StatusText"))
2050 else if (streq(name, "SysFSPath"))
2052 else if (streq(name, "Where"))
2054 else if (streq(name, "What"))
2056 else if (streq(name, "Following"))
2063 case DBUS_TYPE_BOOLEAN: {
2066 dbus_message_iter_get_basic(iter, &b);
2068 if (streq(name, "Accept"))
2070 else if (streq(name, "NeedDaemonReload"))
2071 i->need_daemon_reload = b;
2076 case DBUS_TYPE_UINT32: {
2079 dbus_message_iter_get_basic(iter, &u);
2081 if (streq(name, "MainPID")) {
2083 i->main_pid = (pid_t) u;
2086 } else if (streq(name, "ControlPID"))
2087 i->control_pid = (pid_t) u;
2088 else if (streq(name, "ExecMainPID")) {
2090 i->main_pid = (pid_t) u;
2091 } else if (streq(name, "NAccepted"))
2093 else if (streq(name, "NConnections"))
2094 i->n_connections = u;
2099 case DBUS_TYPE_INT32: {
2102 dbus_message_iter_get_basic(iter, &j);
2104 if (streq(name, "ExecMainCode"))
2105 i->exit_code = (int) j;
2106 else if (streq(name, "ExecMainStatus"))
2107 i->exit_status = (int) j;
2112 case DBUS_TYPE_UINT64: {
2115 dbus_message_iter_get_basic(iter, &u);
2117 if (streq(name, "ExecMainStartTimestamp"))
2118 i->start_timestamp = (usec_t) u;
2119 else if (streq(name, "ExecMainExitTimestamp"))
2120 i->exit_timestamp = (usec_t) u;
2121 else if (streq(name, "ActiveEnterTimestamp"))
2122 i->active_enter_timestamp = (usec_t) u;
2123 else if (streq(name, "InactiveEnterTimestamp"))
2124 i->inactive_enter_timestamp = (usec_t) u;
2125 else if (streq(name, "InactiveExitTimestamp"))
2126 i->inactive_exit_timestamp = (usec_t) u;
2127 else if (streq(name, "ActiveExitTimestamp"))
2128 i->active_exit_timestamp = (usec_t) u;
2133 case DBUS_TYPE_ARRAY: {
2135 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2136 startswith(name, "Exec")) {
2137 DBusMessageIter sub;
2139 dbus_message_iter_recurse(iter, &sub);
2140 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2141 ExecStatusInfo *info;
2144 if (!(info = new0(ExecStatusInfo, 1)))
2147 if (!(info->name = strdup(name))) {
2152 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2157 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2159 dbus_message_iter_next(&sub);
2170 static int print_property(const char *name, DBusMessageIter *iter) {
2174 /* This is a low-level property printer, see
2175 * print_status_info() for the nicer output */
2177 if (arg_property && !strv_find(arg_property, name))
2180 switch (dbus_message_iter_get_arg_type(iter)) {
2182 case DBUS_TYPE_STRING: {
2184 dbus_message_iter_get_basic(iter, &s);
2186 if (arg_all || s[0])
2187 printf("%s=%s\n", name, s);
2192 case DBUS_TYPE_BOOLEAN: {
2194 dbus_message_iter_get_basic(iter, &b);
2195 printf("%s=%s\n", name, yes_no(b));
2200 case DBUS_TYPE_UINT64: {
2202 dbus_message_iter_get_basic(iter, &u);
2204 /* Yes, heuristics! But we can change this check
2205 * should it turn out to not be sufficient */
2207 if (strstr(name, "Timestamp")) {
2208 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2210 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2211 printf("%s=%s\n", name, strempty(t));
2212 } else if (strstr(name, "USec")) {
2213 char timespan[FORMAT_TIMESPAN_MAX];
2215 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2217 printf("%s=%llu\n", name, (unsigned long long) u);
2222 case DBUS_TYPE_UINT32: {
2224 dbus_message_iter_get_basic(iter, &u);
2226 if (strstr(name, "UMask") || strstr(name, "Mode"))
2227 printf("%s=%04o\n", name, u);
2229 printf("%s=%u\n", name, (unsigned) u);
2234 case DBUS_TYPE_INT32: {
2236 dbus_message_iter_get_basic(iter, &i);
2238 printf("%s=%i\n", name, (int) i);
2242 case DBUS_TYPE_DOUBLE: {
2244 dbus_message_iter_get_basic(iter, &d);
2246 printf("%s=%g\n", name, d);
2250 case DBUS_TYPE_STRUCT: {
2251 DBusMessageIter sub;
2252 dbus_message_iter_recurse(iter, &sub);
2254 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2257 dbus_message_iter_get_basic(&sub, &u);
2260 printf("%s=%u\n", name, (unsigned) u);
2262 printf("%s=\n", name);
2265 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2268 dbus_message_iter_get_basic(&sub, &s);
2270 if (arg_all || s[0])
2271 printf("%s=%s\n", name, s);
2279 case DBUS_TYPE_ARRAY:
2281 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2282 DBusMessageIter sub;
2285 dbus_message_iter_recurse(iter, &sub);
2287 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2288 printf("%s=", name);
2290 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2293 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2294 dbus_message_iter_get_basic(&sub, &s);
2295 printf("%s%s", space ? " " : "", s);
2298 dbus_message_iter_next(&sub);
2306 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2307 DBusMessageIter sub;
2309 dbus_message_iter_recurse(iter, &sub);
2311 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2312 printf("%s=", name);
2314 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2317 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2318 dbus_message_iter_get_basic(&sub, &u);
2321 dbus_message_iter_next(&sub);
2329 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2330 DBusMessageIter sub, sub2;
2332 dbus_message_iter_recurse(iter, &sub);
2333 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2334 const char *type, *path;
2336 dbus_message_iter_recurse(&sub, &sub2);
2338 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2339 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2340 printf("%s=%s\n", type, path);
2342 dbus_message_iter_next(&sub);
2347 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2348 DBusMessageIter sub, sub2;
2350 dbus_message_iter_recurse(iter, &sub);
2351 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2353 uint64_t value, next_elapse;
2355 dbus_message_iter_recurse(&sub, &sub2);
2357 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2358 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2359 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2360 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2362 printf("%s={ value=%s ; next_elapse=%s }\n",
2364 format_timespan(timespan1, sizeof(timespan1), value),
2365 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2368 dbus_message_iter_next(&sub);
2373 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2374 DBusMessageIter sub;
2376 dbus_message_iter_recurse(iter, &sub);
2377 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2378 ExecStatusInfo info;
2381 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2382 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2385 t = strv_join(info.argv, " ");
2387 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2391 yes_no(info.ignore),
2392 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2393 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2394 (unsigned) info. pid,
2395 sigchld_code_to_string(info.code),
2397 info.code == CLD_EXITED ? "" : "/",
2398 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2404 strv_free(info.argv);
2406 dbus_message_iter_next(&sub);
2416 printf("%s=[unprintable]\n", name);
2421 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2422 DBusMessage *m = NULL, *reply = NULL;
2423 const char *interface = "";
2426 DBusMessageIter iter, sub, sub2, sub3;
2427 UnitStatusInfo info;
2435 dbus_error_init(&error);
2437 if (!(m = dbus_message_new_method_call(
2438 "org.freedesktop.systemd1",
2440 "org.freedesktop.DBus.Properties",
2442 log_error("Could not allocate message.");
2447 if (!dbus_message_append_args(m,
2448 DBUS_TYPE_STRING, &interface,
2449 DBUS_TYPE_INVALID)) {
2450 log_error("Could not append arguments to message.");
2455 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2456 log_error("Failed to issue method call: %s", bus_error_message(&error));
2461 if (!dbus_message_iter_init(reply, &iter) ||
2462 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2463 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2464 log_error("Failed to parse reply.");
2469 dbus_message_iter_recurse(&iter, &sub);
2476 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2479 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2480 log_error("Failed to parse reply.");
2485 dbus_message_iter_recurse(&sub, &sub2);
2487 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2488 log_error("Failed to parse reply.");
2493 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2494 log_error("Failed to parse reply.");
2499 dbus_message_iter_recurse(&sub2, &sub3);
2501 if (show_properties)
2502 r = print_property(name, &sub3);
2504 r = status_property(name, &sub3, &info);
2507 log_error("Failed to parse reply.");
2512 dbus_message_iter_next(&sub);
2517 if (!show_properties)
2518 print_status_info(&info);
2520 if (!streq_ptr(info.active_state, "active") &&
2521 !streq_ptr(info.active_state, "reloading") &&
2522 streq(verb, "status"))
2523 /* According to LSB: "program not running" */
2526 while ((p = info.exec)) {
2527 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2528 exec_status_info_free(p);
2533 dbus_message_unref(m);
2536 dbus_message_unref(reply);
2538 dbus_error_free(&error);
2543 static int show(DBusConnection *bus, char **args, unsigned n) {
2544 DBusMessage *m = NULL, *reply = NULL;
2548 bool show_properties, new_line = false;
2553 dbus_error_init(&error);
2555 show_properties = !streq(args[0], "status");
2557 if (show_properties)
2560 if (show_properties && n <= 1) {
2561 /* If not argument is specified inspect the manager
2564 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2568 for (i = 1; i < n; i++) {
2569 const char *path = NULL;
2572 if (safe_atou32(args[i], &id) < 0) {
2574 /* Interpret as unit name */
2576 if (!(m = dbus_message_new_method_call(
2577 "org.freedesktop.systemd1",
2578 "/org/freedesktop/systemd1",
2579 "org.freedesktop.systemd1.Manager",
2581 log_error("Could not allocate message.");
2586 if (!dbus_message_append_args(m,
2587 DBUS_TYPE_STRING, &args[i],
2588 DBUS_TYPE_INVALID)) {
2589 log_error("Could not append arguments to message.");
2594 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2596 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2597 log_error("Failed to issue method call: %s", bus_error_message(&error));
2602 dbus_error_free(&error);
2604 dbus_message_unref(m);
2605 if (!(m = dbus_message_new_method_call(
2606 "org.freedesktop.systemd1",
2607 "/org/freedesktop/systemd1",
2608 "org.freedesktop.systemd1.Manager",
2610 log_error("Could not allocate message.");
2615 if (!dbus_message_append_args(m,
2616 DBUS_TYPE_STRING, &args[i],
2617 DBUS_TYPE_INVALID)) {
2618 log_error("Could not append arguments to message.");
2623 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2624 log_error("Failed to issue method call: %s", bus_error_message(&error));
2626 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2627 ret = 4; /* According to LSB: "program or service status is unknown" */
2634 } else if (show_properties) {
2636 /* Interpret as job id */
2638 if (!(m = dbus_message_new_method_call(
2639 "org.freedesktop.systemd1",
2640 "/org/freedesktop/systemd1",
2641 "org.freedesktop.systemd1.Manager",
2643 log_error("Could not allocate message.");
2648 if (!dbus_message_append_args(m,
2649 DBUS_TYPE_UINT32, &id,
2650 DBUS_TYPE_INVALID)) {
2651 log_error("Could not append arguments to message.");
2656 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2657 log_error("Failed to issue method call: %s", bus_error_message(&error));
2663 /* Interpret as PID */
2665 if (!(m = dbus_message_new_method_call(
2666 "org.freedesktop.systemd1",
2667 "/org/freedesktop/systemd1",
2668 "org.freedesktop.systemd1.Manager",
2670 log_error("Could not allocate message.");
2675 if (!dbus_message_append_args(m,
2676 DBUS_TYPE_UINT32, &id,
2677 DBUS_TYPE_INVALID)) {
2678 log_error("Could not append arguments to message.");
2683 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2684 log_error("Failed to issue method call: %s", bus_error_message(&error));
2690 if (!dbus_message_get_args(reply, &error,
2691 DBUS_TYPE_OBJECT_PATH, &path,
2692 DBUS_TYPE_INVALID)) {
2693 log_error("Failed to parse reply: %s", bus_error_message(&error));
2698 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2701 dbus_message_unref(m);
2702 dbus_message_unref(reply);
2708 dbus_message_unref(m);
2711 dbus_message_unref(reply);
2713 dbus_error_free(&error);
2718 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2720 DBusMessage *m = NULL, *reply = NULL;
2725 dbus_error_init(&error);
2727 log_debug("Got D-Bus request: %s.%s() on %s",
2728 dbus_message_get_interface(message),
2729 dbus_message_get_member(message),
2730 dbus_message_get_path(message));
2732 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2733 log_error("Warning! D-Bus connection terminated.");
2734 dbus_connection_close(connection);
2736 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2737 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2738 const char *id, *path;
2740 if (!dbus_message_get_args(message, &error,
2741 DBUS_TYPE_STRING, &id,
2742 DBUS_TYPE_OBJECT_PATH, &path,
2744 log_error("Failed to parse message: %s", bus_error_message(&error));
2745 else if (streq(dbus_message_get_member(message), "UnitNew"))
2746 printf("Unit %s added.\n", id);
2748 printf("Unit %s removed.\n", id);
2750 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2751 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2755 if (!dbus_message_get_args(message, &error,
2756 DBUS_TYPE_UINT32, &id,
2757 DBUS_TYPE_OBJECT_PATH, &path,
2759 log_error("Failed to parse message: %s", bus_error_message(&error));
2760 else if (streq(dbus_message_get_member(message), "JobNew"))
2761 printf("Job %u added.\n", id);
2763 printf("Job %u removed.\n", id);
2766 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2768 const char *path, *interface, *property = "Id";
2769 DBusMessageIter iter, sub;
2771 path = dbus_message_get_path(message);
2773 if (!dbus_message_get_args(message, &error,
2774 DBUS_TYPE_STRING, &interface,
2775 DBUS_TYPE_INVALID)) {
2776 log_error("Failed to parse message: %s", bus_error_message(&error));
2780 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2781 !streq(interface, "org.freedesktop.systemd1.Unit"))
2784 if (!(m = dbus_message_new_method_call(
2785 "org.freedesktop.systemd1",
2787 "org.freedesktop.DBus.Properties",
2789 log_error("Could not allocate message.");
2793 if (!dbus_message_append_args(m,
2794 DBUS_TYPE_STRING, &interface,
2795 DBUS_TYPE_STRING, &property,
2796 DBUS_TYPE_INVALID)) {
2797 log_error("Could not append arguments to message.");
2801 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2802 log_error("Failed to issue method call: %s", bus_error_message(&error));
2806 if (!dbus_message_iter_init(reply, &iter) ||
2807 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2808 log_error("Failed to parse reply.");
2812 dbus_message_iter_recurse(&iter, &sub);
2814 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2817 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2818 log_error("Failed to parse reply.");
2822 dbus_message_iter_get_basic(&sub, &id);
2823 printf("Unit %s changed.\n", id);
2827 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2828 log_error("Failed to parse reply.");
2832 dbus_message_iter_get_basic(&sub, &id);
2833 printf("Job %u changed.\n", id);
2839 dbus_message_unref(m);
2842 dbus_message_unref(reply);
2844 dbus_error_free(&error);
2845 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2849 dbus_message_unref(m);
2852 dbus_message_unref(reply);
2854 dbus_error_free(&error);
2855 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2858 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2859 DBusMessage *m = NULL, *reply = NULL;
2863 dbus_error_init(&error);
2866 dbus_bus_add_match(bus,
2868 "sender='org.freedesktop.systemd1',"
2869 "interface='org.freedesktop.systemd1.Manager',"
2870 "path='/org/freedesktop/systemd1'",
2873 if (dbus_error_is_set(&error)) {
2874 log_error("Failed to add match: %s", bus_error_message(&error));
2879 dbus_bus_add_match(bus,
2881 "sender='org.freedesktop.systemd1',"
2882 "interface='org.freedesktop.DBus.Properties',"
2883 "member='PropertiesChanged'",
2886 if (dbus_error_is_set(&error)) {
2887 log_error("Failed to add match: %s", bus_error_message(&error));
2893 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2894 log_error("Failed to add filter.");
2899 if (!(m = dbus_message_new_method_call(
2900 "org.freedesktop.systemd1",
2901 "/org/freedesktop/systemd1",
2902 "org.freedesktop.systemd1.Manager",
2904 log_error("Could not allocate message.");
2909 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2910 log_error("Failed to issue method call: %s", bus_error_message(&error));
2915 while (dbus_connection_read_write_dispatch(bus, -1))
2922 /* This is slightly dirty, since we don't undo the filter or the matches. */
2925 dbus_message_unref(m);
2928 dbus_message_unref(reply);
2930 dbus_error_free(&error);
2935 static int dump(DBusConnection *bus, char **args, unsigned n) {
2936 DBusMessage *m = NULL, *reply = NULL;
2941 dbus_error_init(&error);
2945 if (!(m = dbus_message_new_method_call(
2946 "org.freedesktop.systemd1",
2947 "/org/freedesktop/systemd1",
2948 "org.freedesktop.systemd1.Manager",
2950 log_error("Could not allocate message.");
2954 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2955 log_error("Failed to issue method call: %s", bus_error_message(&error));
2960 if (!dbus_message_get_args(reply, &error,
2961 DBUS_TYPE_STRING, &text,
2962 DBUS_TYPE_INVALID)) {
2963 log_error("Failed to parse reply: %s", bus_error_message(&error));
2968 fputs(text, stdout);
2974 dbus_message_unref(m);
2977 dbus_message_unref(reply);
2979 dbus_error_free(&error);
2984 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2985 DBusMessage *m = NULL, *reply = NULL;
2988 const char *name = "", *path, *id;
2989 dbus_bool_t cleanup = FALSE;
2990 DBusMessageIter iter, sub;
2992 *interface = "org.freedesktop.systemd1.Unit",
2995 dbus_error_init(&error);
2997 if (!(m = dbus_message_new_method_call(
2998 "org.freedesktop.systemd1",
2999 "/org/freedesktop/systemd1",
3000 "org.freedesktop.systemd1.Manager",
3001 "CreateSnapshot"))) {
3002 log_error("Could not allocate message.");
3009 if (!dbus_message_append_args(m,
3010 DBUS_TYPE_STRING, &name,
3011 DBUS_TYPE_BOOLEAN, &cleanup,
3012 DBUS_TYPE_INVALID)) {
3013 log_error("Could not append arguments to message.");
3018 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3019 log_error("Failed to issue method call: %s", bus_error_message(&error));
3024 if (!dbus_message_get_args(reply, &error,
3025 DBUS_TYPE_OBJECT_PATH, &path,
3026 DBUS_TYPE_INVALID)) {
3027 log_error("Failed to parse reply: %s", bus_error_message(&error));
3032 dbus_message_unref(m);
3033 if (!(m = dbus_message_new_method_call(
3034 "org.freedesktop.systemd1",
3036 "org.freedesktop.DBus.Properties",
3038 log_error("Could not allocate message.");
3042 if (!dbus_message_append_args(m,
3043 DBUS_TYPE_STRING, &interface,
3044 DBUS_TYPE_STRING, &property,
3045 DBUS_TYPE_INVALID)) {
3046 log_error("Could not append arguments to message.");
3051 dbus_message_unref(reply);
3052 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3053 log_error("Failed to issue method call: %s", bus_error_message(&error));
3058 if (!dbus_message_iter_init(reply, &iter) ||
3059 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3060 log_error("Failed to parse reply.");
3065 dbus_message_iter_recurse(&iter, &sub);
3067 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3068 log_error("Failed to parse reply.");
3073 dbus_message_iter_get_basic(&sub, &id);
3081 dbus_message_unref(m);
3084 dbus_message_unref(reply);
3086 dbus_error_free(&error);
3091 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3092 DBusMessage *m = NULL, *reply = NULL;
3100 dbus_error_init(&error);
3102 for (i = 1; i < n; i++) {
3103 const char *path = NULL;
3105 if (!(m = dbus_message_new_method_call(
3106 "org.freedesktop.systemd1",
3107 "/org/freedesktop/systemd1",
3108 "org.freedesktop.systemd1.Manager",
3110 log_error("Could not allocate message.");
3115 if (!dbus_message_append_args(m,
3116 DBUS_TYPE_STRING, &args[i],
3117 DBUS_TYPE_INVALID)) {
3118 log_error("Could not append arguments to message.");
3123 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3124 log_error("Failed to issue method call: %s", bus_error_message(&error));
3129 if (!dbus_message_get_args(reply, &error,
3130 DBUS_TYPE_OBJECT_PATH, &path,
3131 DBUS_TYPE_INVALID)) {
3132 log_error("Failed to parse reply: %s", bus_error_message(&error));
3137 dbus_message_unref(m);
3138 if (!(m = dbus_message_new_method_call(
3139 "org.freedesktop.systemd1",
3141 "org.freedesktop.systemd1.Snapshot",
3143 log_error("Could not allocate message.");
3148 dbus_message_unref(reply);
3149 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3150 log_error("Failed to issue method call: %s", bus_error_message(&error));
3155 dbus_message_unref(m);
3156 dbus_message_unref(reply);
3164 dbus_message_unref(m);
3167 dbus_message_unref(reply);
3169 dbus_error_free(&error);
3174 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3175 DBusMessage *m = NULL, *reply = NULL;
3180 dbus_error_init(&error);
3182 if (arg_action == ACTION_RELOAD)
3184 else if (arg_action == ACTION_REEXEC)
3185 method = "Reexecute";
3187 assert(arg_action == ACTION_SYSTEMCTL);
3190 streq(args[0], "clear-jobs") ||
3191 streq(args[0], "cancel") ? "ClearJobs" :
3192 streq(args[0], "daemon-reexec") ? "Reexecute" :
3193 streq(args[0], "reset-failed") ? "ResetFailed" :
3194 streq(args[0], "halt") ? "Halt" :
3195 streq(args[0], "poweroff") ? "PowerOff" :
3196 streq(args[0], "reboot") ? "Reboot" :
3197 streq(args[0], "kexec") ? "KExec" :
3198 streq(args[0], "exit") ? "Exit" :
3199 /* "daemon-reload" */ "Reload";
3202 if (!(m = dbus_message_new_method_call(
3203 "org.freedesktop.systemd1",
3204 "/org/freedesktop/systemd1",
3205 "org.freedesktop.systemd1.Manager",
3207 log_error("Could not allocate message.");
3211 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3213 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3214 /* There's always a fallback possible for
3215 * legacy actions. */
3220 log_error("Failed to issue method call: %s", bus_error_message(&error));
3229 dbus_message_unref(m);
3232 dbus_message_unref(reply);
3234 dbus_error_free(&error);
3239 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3240 DBusMessage *m = NULL, *reply = NULL;
3246 dbus_error_init(&error);
3249 return daemon_reload(bus, args, n);
3251 for (i = 1; i < n; i++) {
3253 if (!(m = dbus_message_new_method_call(
3254 "org.freedesktop.systemd1",
3255 "/org/freedesktop/systemd1",
3256 "org.freedesktop.systemd1.Manager",
3257 "ResetFailedUnit"))) {
3258 log_error("Could not allocate message.");
3263 if (!dbus_message_append_args(m,
3264 DBUS_TYPE_STRING, args + i,
3265 DBUS_TYPE_INVALID)) {
3266 log_error("Could not append arguments to message.");
3271 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3272 log_error("Failed to issue method call: %s", bus_error_message(&error));
3277 dbus_message_unref(m);
3278 dbus_message_unref(reply);
3286 dbus_message_unref(m);
3289 dbus_message_unref(reply);
3291 dbus_error_free(&error);
3296 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3297 DBusMessage *m = NULL, *reply = NULL;
3299 DBusMessageIter iter, sub, sub2;
3302 *interface = "org.freedesktop.systemd1.Manager",
3303 *property = "Environment";
3305 dbus_error_init(&error);
3309 if (!(m = dbus_message_new_method_call(
3310 "org.freedesktop.systemd1",
3311 "/org/freedesktop/systemd1",
3312 "org.freedesktop.DBus.Properties",
3314 log_error("Could not allocate message.");
3318 if (!dbus_message_append_args(m,
3319 DBUS_TYPE_STRING, &interface,
3320 DBUS_TYPE_STRING, &property,
3321 DBUS_TYPE_INVALID)) {
3322 log_error("Could not append arguments to message.");
3327 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3328 log_error("Failed to issue method call: %s", bus_error_message(&error));
3333 if (!dbus_message_iter_init(reply, &iter) ||
3334 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3335 log_error("Failed to parse reply.");
3340 dbus_message_iter_recurse(&iter, &sub);
3342 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3343 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3344 log_error("Failed to parse reply.");
3349 dbus_message_iter_recurse(&sub, &sub2);
3351 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3354 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3355 log_error("Failed to parse reply.");
3360 dbus_message_iter_get_basic(&sub2, &text);
3361 printf("%s\n", text);
3363 dbus_message_iter_next(&sub2);
3370 dbus_message_unref(m);
3373 dbus_message_unref(reply);
3375 dbus_error_free(&error);
3380 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3381 DBusMessage *m = NULL, *reply = NULL;
3385 DBusMessageIter iter, sub;
3388 dbus_error_init(&error);
3390 method = streq(args[0], "set-environment")
3392 : "UnsetEnvironment";
3394 if (!(m = dbus_message_new_method_call(
3395 "org.freedesktop.systemd1",
3396 "/org/freedesktop/systemd1",
3397 "org.freedesktop.systemd1.Manager",
3400 log_error("Could not allocate message.");
3404 dbus_message_iter_init_append(m, &iter);
3406 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3407 log_error("Could not append arguments to message.");
3412 for (i = 1; i < n; i++)
3413 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3414 log_error("Could not append arguments to message.");
3419 if (!dbus_message_iter_close_container(&iter, &sub)) {
3420 log_error("Could not append arguments to message.");
3425 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3426 log_error("Failed to issue method call: %s", bus_error_message(&error));
3435 dbus_message_unref(m);
3438 dbus_message_unref(reply);
3440 dbus_error_free(&error);
3453 static Hashmap *will_install = NULL, *have_installed = NULL;
3454 static Set *remove_symlinks_to = NULL;
3455 static unsigned n_symlinks = 0;
3457 static void install_info_free(InstallInfo *i) {
3462 strv_free(i->aliases);
3463 strv_free(i->wanted_by);
3467 static void install_info_hashmap_free(Hashmap *m) {
3470 while ((i = hashmap_steal_first(m)))
3471 install_info_free(i);
3476 static int install_info_add(const char *name) {
3480 assert(will_install);
3482 if (!unit_name_is_valid_no_type(name, true)) {
3483 log_warning("Unit name %s is not a valid unit name.", name);
3487 if (hashmap_get(have_installed, name) ||
3488 hashmap_get(will_install, name))
3491 if (!(i = new0(InstallInfo, 1))) {
3496 if (!(i->name = strdup(name))) {
3501 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3508 install_info_free(i);
3513 static int config_parse_also(
3514 const char *filename,
3516 const char *section,
3530 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3534 if (!(n = strndup(w, l)))
3537 if ((r = install_info_add(n)) < 0) {
3538 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3549 static int mark_symlink_for_removal(const char *p) {
3554 assert(path_is_absolute(p));
3556 if (!remove_symlinks_to)
3559 if (!(n = strdup(p)))
3562 path_kill_slashes(n);
3564 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3566 return r == -EEXIST ? 0 : r;
3572 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3581 if (!(d = fdopendir(fd))) {
3582 close_nointr_nofail(fd);
3588 while ((de = readdir(d))) {
3589 bool is_dir = false, is_link = false;
3591 if (ignore_file(de->d_name))
3594 if (de->d_type == DT_LNK)
3596 else if (de->d_type == DT_DIR)
3598 else if (de->d_type == DT_UNKNOWN) {
3601 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3602 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3609 is_link = S_ISLNK(st.st_mode);
3610 is_dir = S_ISDIR(st.st_mode);
3618 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3619 log_error("Failed to open %s/%s: %m", root, de->d_name);
3626 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3627 log_error("Failed to allocate directory string.");
3628 close_nointr_nofail(nfd);
3633 /* This will close nfd, regardless whether it succeeds or not */
3634 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3640 } else if (is_link) {
3644 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3645 log_error("Failed to allocate symlink string.");
3650 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3651 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3659 if ((c = canonicalize_file_name(dest))) {
3660 /* This might fail if the destination
3661 * is already removed */
3667 path_kill_slashes(dest);
3668 if (set_get(remove_symlinks_to, dest)) {
3671 log_info("rm '%s'", p);
3673 if (unlink(p) < 0) {
3674 log_error("Cannot unlink symlink %s: %m", p);
3679 rmdir_parents(p, config_path);
3680 path_kill_slashes(p);
3682 if (!set_get(remove_symlinks_to, p)) {
3684 if ((r = mark_symlink_for_removal(p)) < 0) {
3703 static int remove_marked_symlinks(const char *config_path) {
3707 assert(config_path);
3709 if (set_size(remove_symlinks_to) <= 0)
3712 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3719 if ((cfd = dup(fd)) < 0) {
3724 /* This takes possession of cfd and closes it */
3725 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3731 close_nointr_nofail(fd);
3736 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3743 if (streq(verb, "enable")) {
3746 mkdir_parents(new_path, 0755);
3748 if (symlink(old_path, new_path) >= 0) {
3751 log_info("ln -s '%s' '%s'", old_path, new_path);
3756 if (errno != EEXIST) {
3757 log_error("Cannot link %s to %s: %m", old_path, new_path);
3761 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3763 if (errno == EINVAL) {
3764 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3768 log_error("readlink() failed: %s", strerror(-r));
3772 if (streq(dest, old_path)) {
3778 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3787 log_info("ln -s '%s' '%s'", old_path, new_path);
3789 if (symlink(old_path, new_path) >= 0)
3792 log_error("Cannot link %s to %s: %m", old_path, new_path);
3795 } else if (streq(verb, "disable")) {
3798 if ((r = mark_symlink_for_removal(old_path)) < 0)
3801 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3802 if (errno == ENOENT)
3805 if (errno == EINVAL) {
3806 log_warning("File %s not a symlink, ignoring.", old_path);
3810 log_error("readlink() failed: %s", strerror(-r));
3814 if (!streq(dest, old_path)) {
3815 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3822 if ((r = mark_symlink_for_removal(new_path)) < 0)
3826 log_info("rm '%s'", new_path);
3828 if (unlink(new_path) >= 0)
3831 log_error("Cannot unlink %s: %m", new_path);
3834 } else if (streq(verb, "is-enabled")) {
3837 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3839 if (errno == ENOENT || errno == EINVAL)
3842 log_error("readlink() failed: %s", strerror(-r));
3846 if (streq(dest, old_path)) {
3854 assert_not_reached("Unknown action.");
3857 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3859 char *alias_path = NULL;
3864 assert(config_path);
3866 STRV_FOREACH(s, i->aliases) {
3869 if (!(alias_path = path_make_absolute(*s, config_path))) {
3870 log_error("Out of memory");
3875 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3878 if (streq(verb, "disable"))
3879 rmdir_parents(alias_path, config_path);
3889 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3891 char *alias_path = NULL;
3896 assert(config_path);
3898 STRV_FOREACH(s, i->wanted_by) {
3899 if (!unit_name_is_valid_no_type(*s, true)) {
3900 log_error("Invalid name %s.", *s);
3908 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3909 log_error("Out of memory");
3914 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3917 if (streq(verb, "disable"))
3918 rmdir_parents(alias_path, config_path);
3929 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3931 const ConfigItem items[] = {
3932 { "Alias", config_parse_strv, &i->aliases, "Install" },
3933 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3934 { "Also", config_parse_also, NULL, "Install" },
3936 { NULL, NULL, NULL, NULL }
3940 char *filename = NULL;
3947 STRV_FOREACH(p, paths->unit_path) {
3950 if (!(filename = path_make_absolute(i->name, *p))) {
3951 log_error("Out of memory");
3955 /* Ensure that we don't follow symlinks */
3956 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3957 if ((f = fdopen(fd, "re")))
3960 if (errno == ELOOP) {
3961 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3966 if (errno != ENOENT) {
3967 log_error("Failed to open %s: %m", filename);
3977 #if defined(TARGET_FEDORA) && defined (HAVE_SYSV_COMPAT)
3979 if (endswith(i->name, ".service")) {
3983 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
3984 log_error("Out of memory");
3988 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
3989 exists = access(sysv, F_OK) >= 0;
3995 const char *argv[] = {
4002 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4004 argv[1] = file_name_from_path(sysv);
4006 streq(verb, "enable") ? "on" :
4007 streq(verb, "disable") ? "off" : NULL;
4009 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
4011 if ((pid = fork()) < 0) {
4012 log_error("Failed to fork: %m");
4015 } else if (pid == 0) {
4016 execv(argv[0], (char**) argv);
4017 _exit(EXIT_FAILURE);
4022 if ((r = wait_for_terminate(pid, &status)) < 0)
4025 if (status.si_code == CLD_EXITED) {
4026 if (status.si_status == 0 && (streq(verb, "enable") || streq(verb, "disable")))
4029 return status.si_status == 0 ? 0 : -EINVAL;
4039 log_error("Couldn't find %s.", i->name);
4045 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4050 n_symlinks += strv_length(i->aliases);
4051 n_symlinks += strv_length(i->wanted_by);
4055 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4058 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4061 if ((r = mark_symlink_for_removal(filename)) < 0)
4064 if ((r = remove_marked_symlinks(config_path)) < 0)
4070 static char *get_config_path(void) {
4072 if (arg_user && arg_global)
4073 return strdup(USER_CONFIG_UNIT_PATH);
4078 if (user_config_home(&p) < 0)
4084 return strdup(SYSTEM_CONFIG_UNIT_PATH);
4087 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4091 char *config_path = NULL;
4094 const char *verb = args[0];
4096 dbus_error_init(&error);
4099 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4100 log_error("Failed to determine lookup paths: %s", strerror(-r));
4104 if (!(config_path = get_config_path())) {
4105 log_error("Failed to determine config path");
4110 will_install = hashmap_new(string_hash_func, string_compare_func);
4111 have_installed = hashmap_new(string_hash_func, string_compare_func);
4113 if (!will_install || !have_installed) {
4114 log_error("Failed to allocate unit sets.");
4119 if (!arg_defaults && streq(verb, "disable"))
4120 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4121 log_error("Failed to allocate symlink sets.");
4126 for (j = 1; j < n; j++)
4127 if ((r = install_info_add(args[j])) < 0) {
4128 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4132 while ((i = hashmap_first(will_install))) {
4135 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4137 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4145 /* In test mode and found something */
4151 if (streq(verb, "is-enabled"))
4152 r = r > 0 ? 0 : -ENOENT;
4154 if (n_symlinks <= 0)
4155 log_warning("Unit files contain no applicable installation information. Ignoring.");
4158 /* Don't try to reload anything if the user asked us to not do this */
4160 /* Don't try to reload anything when updating a unit globally */
4162 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4163 (arg_user || sd_booted() > 0) &&
4164 /* Don't try to reload anything if we are running in a chroot environment */
4165 (arg_user || running_in_chroot() <= 0) ) {
4168 if ((q = daemon_reload(bus, args, n)) < 0)
4174 install_info_hashmap_free(will_install);
4175 install_info_hashmap_free(have_installed);
4177 set_free_free(remove_symlinks_to);
4179 lookup_paths_free(&paths);
4186 static int systemctl_help(void) {
4188 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4189 "Send control commands to or query the systemd manager.\n\n"
4190 " -h --help Show this help\n"
4191 " --version Show package version\n"
4192 " -t --type=TYPE List only units of a particular type\n"
4193 " -p --property=NAME Show only properties by this name\n"
4194 " -a --all Show all units/properties, including dead/empty ones\n"
4195 " --failed Show only failed units\n"
4196 " --full Don't ellipsize unit names on output\n"
4197 " --fail When queueing a new job, fail if conflicting jobs are\n"
4199 " --ignore-dependencies\n"
4200 " When queueing a new job, ignore all its dependencies\n"
4201 " -q --quiet Suppress output\n"
4202 " --no-block Do not wait until operation finished\n"
4203 " --no-pager Do not pipe output into a pager.\n"
4204 " --system Connect to system manager\n"
4205 " --user Connect to user service manager\n"
4206 " --order When generating graph for dot, show only order\n"
4207 " --require When generating graph for dot, show only requirement\n"
4208 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4209 " --global Enable/disable unit files globally\n"
4210 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4212 " --no-ask-password\n"
4213 " Do not ask for system passwords\n"
4214 " --kill-mode=MODE How to send signal\n"
4215 " --kill-who=WHO Who to send signal to\n"
4216 " -s --signal=SIGNAL Which signal to send\n"
4217 " -f --force When enabling unit files, override existing symlinks\n"
4218 " When shutting down, execute action immediately\n"
4219 " --defaults When disabling unit files, remove default symlinks only\n\n"
4221 " list-units List units\n"
4222 " start [NAME...] Start (activate) one or more units\n"
4223 " stop [NAME...] Stop (deactivate) one or more units\n"
4224 " reload [NAME...] Reload one or more units\n"
4225 " restart [NAME...] Start or restart one or more units\n"
4226 " try-restart [NAME...] Restart one or more units if active\n"
4227 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4228 " otherwise start or restart\n"
4229 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4230 " otherwise restart if active\n"
4231 " isolate [NAME] Start one unit and stop all others\n"
4232 " kill [NAME...] Send signal to processes of a unit\n"
4233 " is-active [NAME...] Check whether units are active\n"
4234 " status [NAME...|PID...] Show runtime status of one or more units\n"
4235 " show [NAME...|JOB...] Show properties of one or more\n"
4236 " units/jobs or the manager\n"
4237 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4239 " enable [NAME...] Enable one or more unit files\n"
4240 " disable [NAME...] Disable one or more unit files\n"
4241 " is-enabled [NAME...] Check whether unit files are enabled\n"
4242 " load [NAME...] Load one or more units\n"
4243 " list-jobs List jobs\n"
4244 " cancel [JOB...] Cancel all, one, or more jobs\n"
4245 " monitor Monitor unit/job changes\n"
4246 " dump Dump server status\n"
4247 " dot Dump dependency graph for dot(1)\n"
4248 " snapshot [NAME] Create a snapshot\n"
4249 " delete [NAME...] Remove one or more snapshots\n"
4250 " daemon-reload Reload systemd manager configuration\n"
4251 " daemon-reexec Reexecute systemd manager\n"
4252 " show-environment Dump environment\n"
4253 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
4254 " unset-environment [NAME...] Unset one or more environment variables\n"
4255 " default Enter system default mode\n"
4256 " rescue Enter system rescue mode\n"
4257 " emergency Enter system emergency mode\n"
4258 " halt Shut down and halt the system\n"
4259 " poweroff Shut down and power-off the system\n"
4260 " reboot Shut down and reboot the system\n"
4261 " kexec Shut down and reboot the system with kexec\n"
4262 " exit Ask for user instance termination\n",
4263 program_invocation_short_name);
4268 static int halt_help(void) {
4270 printf("%s [OPTIONS...]\n\n"
4271 "%s the system.\n\n"
4272 " --help Show this help\n"
4273 " --halt Halt the machine\n"
4274 " -p --poweroff Switch off the machine\n"
4275 " --reboot Reboot the machine\n"
4276 " -f --force Force immediate halt/power-off/reboot\n"
4277 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4278 " -d --no-wtmp Don't write wtmp record\n"
4279 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4280 " --no-wall Don't send wall message before halt/power-off/reboot\n",
4281 program_invocation_short_name,
4282 arg_action == ACTION_REBOOT ? "Reboot" :
4283 arg_action == ACTION_POWEROFF ? "Power off" :
4289 static int shutdown_help(void) {
4291 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4292 "Shut down the system.\n\n"
4293 " --help Show this help\n"
4294 " -H --halt Halt the machine\n"
4295 " -P --poweroff Power-off the machine\n"
4296 " -r --reboot Reboot the machine\n"
4297 " -h Equivalent to --poweroff, overriden by --halt\n"
4298 " -k Don't halt/power-off/reboot, just send warnings\n"
4299 " --no-wall Don't send wall message before halt/power-off/reboot\n"
4300 " -c Cancel a pending shutdown\n",
4301 program_invocation_short_name);
4306 static int telinit_help(void) {
4308 printf("%s [OPTIONS...] {COMMAND}\n\n"
4309 "Send control commands to the init daemon.\n\n"
4310 " --help Show this help\n"
4311 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
4313 " 0 Power-off the machine\n"
4314 " 6 Reboot the machine\n"
4315 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4316 " 1, s, S Enter rescue mode\n"
4317 " q, Q Reload init daemon configuration\n"
4318 " u, U Reexecute init daemon\n",
4319 program_invocation_short_name);
4324 static int runlevel_help(void) {
4326 printf("%s [OPTIONS...]\n\n"
4327 "Prints the previous and current runlevel of the init system.\n\n"
4328 " --help Show this help\n",
4329 program_invocation_short_name);
4334 static int systemctl_parse_argv(int argc, char *argv[]) {
4338 ARG_IGNORE_DEPENDENCIES,
4353 ARG_NO_ASK_PASSWORD,
4357 static const struct option options[] = {
4358 { "help", no_argument, NULL, 'h' },
4359 { "version", no_argument, NULL, ARG_VERSION },
4360 { "type", required_argument, NULL, 't' },
4361 { "property", required_argument, NULL, 'p' },
4362 { "all", no_argument, NULL, 'a' },
4363 { "failed", no_argument, NULL, ARG_FAILED },
4364 { "full", no_argument, NULL, ARG_FULL },
4365 { "fail", no_argument, NULL, ARG_FAIL },
4366 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4367 { "user", no_argument, NULL, ARG_USER },
4368 { "system", no_argument, NULL, ARG_SYSTEM },
4369 { "global", no_argument, NULL, ARG_GLOBAL },
4370 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4371 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4372 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4373 { "quiet", no_argument, NULL, 'q' },
4374 { "order", no_argument, NULL, ARG_ORDER },
4375 { "require", no_argument, NULL, ARG_REQUIRE },
4376 { "force", no_argument, NULL, 'f' },
4377 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4378 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4379 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4380 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4381 { "signal", required_argument, NULL, 's' },
4382 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4383 { NULL, 0, NULL, 0 }
4391 /* Only when running as systemctl we ask for passwords */
4392 arg_ask_password = true;
4394 while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4403 puts(PACKAGE_STRING);
4405 puts(SYSTEMD_FEATURES);
4415 if (!(l = strv_append(arg_property, optarg)))
4418 strv_free(arg_property);
4421 /* If the user asked for a particular
4422 * property, show it to him, even if it is
4433 arg_job_mode = "fail";
4436 case ARG_IGNORE_DEPENDENCIES:
4437 arg_job_mode = "ignore-dependencies";
4449 arg_no_block = true;
4453 arg_no_pager = true;
4461 arg_dot = DOT_ORDER;
4465 arg_dot = DOT_REQUIRE;
4485 arg_no_reload = true;
4494 arg_defaults = true;
4498 arg_kill_who = optarg;
4502 arg_kill_mode = optarg;
4506 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4507 log_error("Failed to parse signal string %s.", optarg);
4512 case ARG_NO_ASK_PASSWORD:
4513 arg_ask_password = false;
4520 log_error("Unknown option code %c", c);
4528 static int halt_parse_argv(int argc, char *argv[]) {
4537 static const struct option options[] = {
4538 { "help", no_argument, NULL, ARG_HELP },
4539 { "halt", no_argument, NULL, ARG_HALT },
4540 { "poweroff", no_argument, NULL, 'p' },
4541 { "reboot", no_argument, NULL, ARG_REBOOT },
4542 { "force", no_argument, NULL, 'f' },
4543 { "wtmp-only", no_argument, NULL, 'w' },
4544 { "no-wtmp", no_argument, NULL, 'd' },
4545 { "no-sync", no_argument, NULL, 'n' },
4546 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4547 { NULL, 0, NULL, 0 }
4555 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4556 if (runlevel == '0' || runlevel == '6')
4557 arg_immediate = true;
4559 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4567 arg_action = ACTION_HALT;
4571 if (arg_action != ACTION_REBOOT)
4572 arg_action = ACTION_POWEROFF;
4576 arg_action = ACTION_REBOOT;
4580 arg_immediate = true;
4601 /* Compatibility nops */
4608 log_error("Unknown option code %c", c);
4613 if (optind < argc) {
4614 log_error("Too many arguments.");
4621 static int parse_time_spec(const char *t, usec_t *_u) {
4625 if (streq(t, "now"))
4627 else if (t[0] == '+') {
4630 if (safe_atou64(t + 1, &u) < 0)
4633 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4642 hour = strtol(t, &e, 10);
4643 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4646 minute = strtol(e+1, &e, 10);
4647 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4650 n = now(CLOCK_REALTIME);
4651 s = (time_t) (n / USEC_PER_SEC);
4654 assert_se(localtime_r(&s, &tm));
4656 tm.tm_hour = (int) hour;
4657 tm.tm_min = (int) minute;
4660 assert_se(s = mktime(&tm));
4662 *_u = (usec_t) s * USEC_PER_SEC;
4665 *_u += USEC_PER_DAY;
4671 static int shutdown_parse_argv(int argc, char *argv[]) {
4678 static const struct option options[] = {
4679 { "help", no_argument, NULL, ARG_HELP },
4680 { "halt", no_argument, NULL, 'H' },
4681 { "poweroff", no_argument, NULL, 'P' },
4682 { "reboot", no_argument, NULL, 'r' },
4683 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4684 { NULL, 0, NULL, 0 }
4692 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4700 arg_action = ACTION_HALT;
4704 arg_action = ACTION_POWEROFF;
4708 arg_action = ACTION_REBOOT;
4712 if (arg_action != ACTION_HALT)
4713 arg_action = ACTION_POWEROFF;
4726 /* Compatibility nops */
4730 arg_action = ACTION_CANCEL_SHUTDOWN;
4737 log_error("Unknown option code %c", c);
4742 if (argc > optind) {
4743 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4744 log_error("Failed to parse time specification: %s", argv[optind]);
4748 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4750 /* We skip the time argument */
4751 if (argc > optind + 1)
4752 arg_wall = argv + optind + 1;
4759 static int telinit_parse_argv(int argc, char *argv[]) {
4766 static const struct option options[] = {
4767 { "help", no_argument, NULL, ARG_HELP },
4768 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4769 { NULL, 0, NULL, 0 }
4772 static const struct {
4776 { '0', ACTION_POWEROFF },
4777 { '6', ACTION_REBOOT },
4778 { '1', ACTION_RESCUE },
4779 { '2', ACTION_RUNLEVEL2 },
4780 { '3', ACTION_RUNLEVEL3 },
4781 { '4', ACTION_RUNLEVEL4 },
4782 { '5', ACTION_RUNLEVEL5 },
4783 { 's', ACTION_RESCUE },
4784 { 'S', ACTION_RESCUE },
4785 { 'q', ACTION_RELOAD },
4786 { 'Q', ACTION_RELOAD },
4787 { 'u', ACTION_REEXEC },
4788 { 'U', ACTION_REEXEC }
4797 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4812 log_error("Unknown option code %c", c);
4817 if (optind >= argc) {
4822 if (optind + 1 < argc) {
4823 log_error("Too many arguments.");
4827 if (strlen(argv[optind]) != 1) {
4828 log_error("Expected single character argument.");
4832 for (i = 0; i < ELEMENTSOF(table); i++)
4833 if (table[i].from == argv[optind][0])
4836 if (i >= ELEMENTSOF(table)) {
4837 log_error("Unknown command %s.", argv[optind]);
4841 arg_action = table[i].to;
4848 static int runlevel_parse_argv(int argc, char *argv[]) {
4854 static const struct option options[] = {
4855 { "help", no_argument, NULL, ARG_HELP },
4856 { NULL, 0, NULL, 0 }
4864 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4875 log_error("Unknown option code %c", c);
4880 if (optind < argc) {
4881 log_error("Too many arguments.");
4888 static int parse_argv(int argc, char *argv[]) {
4892 if (program_invocation_short_name) {
4894 if (strstr(program_invocation_short_name, "halt")) {
4895 arg_action = ACTION_HALT;
4896 return halt_parse_argv(argc, argv);
4897 } else if (strstr(program_invocation_short_name, "poweroff")) {
4898 arg_action = ACTION_POWEROFF;
4899 return halt_parse_argv(argc, argv);
4900 } else if (strstr(program_invocation_short_name, "reboot")) {
4901 arg_action = ACTION_REBOOT;
4902 return halt_parse_argv(argc, argv);
4903 } else if (strstr(program_invocation_short_name, "shutdown")) {
4904 arg_action = ACTION_POWEROFF;
4905 return shutdown_parse_argv(argc, argv);
4906 } else if (strstr(program_invocation_short_name, "init")) {
4908 if (sd_booted() > 0) {
4909 arg_action = ACTION_INVALID;
4910 return telinit_parse_argv(argc, argv);
4912 /* Hmm, so some other init system is
4913 * running, we need to forward this
4914 * request to it. For now we simply
4915 * guess that it is Upstart. */
4917 execv("/lib/upstart/telinit", argv);
4919 log_error("Couldn't find an alternative telinit implementation to spawn.");
4923 } else if (strstr(program_invocation_short_name, "runlevel")) {
4924 arg_action = ACTION_RUNLEVEL;
4925 return runlevel_parse_argv(argc, argv);
4929 arg_action = ACTION_SYSTEMCTL;
4930 return systemctl_parse_argv(argc, argv);
4933 static int action_to_runlevel(void) {
4935 static const char table[_ACTION_MAX] = {
4936 [ACTION_HALT] = '0',
4937 [ACTION_POWEROFF] = '0',
4938 [ACTION_REBOOT] = '6',
4939 [ACTION_RUNLEVEL2] = '2',
4940 [ACTION_RUNLEVEL3] = '3',
4941 [ACTION_RUNLEVEL4] = '4',
4942 [ACTION_RUNLEVEL5] = '5',
4943 [ACTION_RESCUE] = '1'
4946 assert(arg_action < _ACTION_MAX);
4948 return table[arg_action];
4951 static int talk_upstart(void) {
4952 DBusMessage *m = NULL, *reply = NULL;
4954 int previous, rl, r;
4956 env1_buf[] = "RUNLEVEL=X",
4957 env2_buf[] = "PREVLEVEL=X";
4958 char *env1 = env1_buf, *env2 = env2_buf;
4959 const char *emit = "runlevel";
4960 dbus_bool_t b_false = FALSE;
4961 DBusMessageIter iter, sub;
4962 DBusConnection *bus;
4964 dbus_error_init(&error);
4966 if (!(rl = action_to_runlevel()))
4969 if (utmp_get_runlevel(&previous, NULL) < 0)
4972 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4973 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4978 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4983 if ((r = bus_check_peercred(bus)) < 0) {
4984 log_error("Failed to verify owner of bus.");
4988 if (!(m = dbus_message_new_method_call(
4989 "com.ubuntu.Upstart",
4990 "/com/ubuntu/Upstart",
4991 "com.ubuntu.Upstart0_6",
4994 log_error("Could not allocate message.");
4999 dbus_message_iter_init_append(m, &iter);
5001 env1_buf[sizeof(env1_buf)-2] = rl;
5002 env2_buf[sizeof(env2_buf)-2] = previous;
5004 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5005 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5006 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5007 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5008 !dbus_message_iter_close_container(&iter, &sub) ||
5009 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5010 log_error("Could not append arguments to message.");
5015 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5017 if (error_is_no_service(&error)) {
5022 log_error("Failed to issue method call: %s", bus_error_message(&error));
5031 dbus_message_unref(m);
5034 dbus_message_unref(reply);
5037 dbus_connection_flush(bus);
5038 dbus_connection_close(bus);
5039 dbus_connection_unref(bus);
5042 dbus_error_free(&error);
5047 static int talk_initctl(void) {
5048 struct init_request request;
5052 if (!(rl = action_to_runlevel()))
5056 request.magic = INIT_MAGIC;
5057 request.sleeptime = 0;
5058 request.cmd = INIT_CMD_RUNLVL;
5059 request.runlevel = rl;
5061 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5063 if (errno == ENOENT)
5066 log_error("Failed to open "INIT_FIFO": %m");
5071 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5072 close_nointr_nofail(fd);
5075 log_error("Failed to write to "INIT_FIFO": %m");
5076 return errno ? -errno : -EIO;
5082 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5084 static const struct {
5092 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5094 { "list-units", LESS, 1, list_units },
5095 { "list-jobs", EQUAL, 1, list_jobs },
5096 { "clear-jobs", EQUAL, 1, daemon_reload },
5097 { "load", MORE, 2, load_unit },
5098 { "cancel", MORE, 2, cancel_job },
5099 { "start", MORE, 2, start_unit },
5100 { "stop", MORE, 2, start_unit },
5101 { "reload", MORE, 2, start_unit },
5102 { "restart", MORE, 2, start_unit },
5103 { "try-restart", MORE, 2, start_unit },
5104 { "reload-or-restart", MORE, 2, start_unit },
5105 { "reload-or-try-restart", MORE, 2, start_unit },
5106 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
5107 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5108 { "isolate", EQUAL, 2, start_unit },
5109 { "kill", MORE, 2, kill_unit },
5110 { "is-active", MORE, 2, check_unit },
5111 { "check", MORE, 2, check_unit },
5112 { "show", MORE, 1, show },
5113 { "status", MORE, 2, show },
5114 { "monitor", EQUAL, 1, monitor },
5115 { "dump", EQUAL, 1, dump },
5116 { "dot", EQUAL, 1, dot },
5117 { "snapshot", LESS, 2, snapshot },
5118 { "delete", MORE, 2, delete_snapshot },
5119 { "daemon-reload", EQUAL, 1, daemon_reload },
5120 { "daemon-reexec", EQUAL, 1, daemon_reload },
5121 { "show-environment", EQUAL, 1, show_enviroment },
5122 { "set-environment", MORE, 2, set_environment },
5123 { "unset-environment", MORE, 2, set_environment },
5124 { "halt", EQUAL, 1, start_special },
5125 { "poweroff", EQUAL, 1, start_special },
5126 { "reboot", EQUAL, 1, start_special },
5127 { "kexec", EQUAL, 1, start_special },
5128 { "default", EQUAL, 1, start_special },
5129 { "rescue", EQUAL, 1, start_special },
5130 { "emergency", EQUAL, 1, start_special },
5131 { "exit", EQUAL, 1, start_special },
5132 { "reset-failed", MORE, 1, reset_failed },
5133 { "enable", MORE, 2, enable_unit },
5134 { "disable", MORE, 2, enable_unit },
5135 { "is-enabled", MORE, 2, enable_unit }
5145 left = argc - optind;
5148 /* Special rule: no arguments means "list-units" */
5151 if (streq(argv[optind], "help")) {
5156 for (i = 0; i < ELEMENTSOF(verbs); i++)
5157 if (streq(argv[optind], verbs[i].verb))
5160 if (i >= ELEMENTSOF(verbs)) {
5161 log_error("Unknown operation %s", argv[optind]);
5166 switch (verbs[i].argc_cmp) {
5169 if (left != verbs[i].argc) {
5170 log_error("Invalid number of arguments.");
5177 if (left < verbs[i].argc) {
5178 log_error("Too few arguments.");
5185 if (left > verbs[i].argc) {
5186 log_error("Too many arguments.");
5193 assert_not_reached("Unknown comparison operator.");
5196 /* Require a bus connection for all operations but
5198 if (!streq(verbs[i].verb, "enable") &&
5199 !streq(verbs[i].verb, "disable") &&
5201 log_error("Failed to get D-Bus connection: %s", error->message);
5205 return verbs[i].dispatch(bus, argv + optind, left);
5208 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5210 struct msghdr msghdr;
5212 union sockaddr_union sockaddr;
5213 struct shutdownd_command c;
5221 strncpy(c.wall_message, message, sizeof(c.wall_message));
5223 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5227 sockaddr.sa.sa_family = AF_UNIX;
5228 sockaddr.un.sun_path[0] = 0;
5229 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5232 iovec.iov_base = (char*) &c;
5233 iovec.iov_len = sizeof(c);
5236 msghdr.msg_name = &sockaddr;
5237 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5239 msghdr.msg_iov = &iovec;
5240 msghdr.msg_iovlen = 1;
5242 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5243 close_nointr_nofail(fd);
5247 close_nointr_nofail(fd);
5251 static int reload_with_fallback(DBusConnection *bus) {
5254 /* First, try systemd via D-Bus. */
5255 if (daemon_reload(bus, NULL, 0) > 0)
5259 /* Nothing else worked, so let's try signals */
5260 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5262 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5263 log_error("kill() failed: %m");
5270 static int start_with_fallback(DBusConnection *bus) {
5273 /* First, try systemd via D-Bus. */
5274 if (start_unit(bus, NULL, 0) >= 0)
5278 /* Hmm, talking to systemd via D-Bus didn't work. Then
5279 * let's try to talk to Upstart via D-Bus. */
5280 if (talk_upstart() > 0)
5283 /* Nothing else worked, so let's try
5285 if (talk_initctl() > 0)
5288 log_error("Failed to talk to init daemon.");
5292 warn_wall(arg_action);
5296 static int halt_main(DBusConnection *bus) {
5299 if (geteuid() != 0) {
5300 log_error("Must be root.");
5306 char date[FORMAT_TIMESTAMP_MAX];
5308 m = strv_join(arg_wall, " ");
5309 r = send_shutdownd(arg_when,
5310 arg_action == ACTION_HALT ? 'H' :
5311 arg_action == ACTION_POWEROFF ? 'P' :
5318 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5320 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5321 format_timestamp(date, sizeof(date), arg_when));
5326 if (!arg_dry && !arg_immediate)
5327 return start_with_fallback(bus);
5330 if (sd_booted() > 0)
5331 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5332 else if ((r = utmp_put_shutdown(0)) < 0)
5333 log_warning("Failed to write utmp record: %s", strerror(-r));
5342 /* Make sure C-A-D is handled by the kernel from this
5344 reboot(RB_ENABLE_CAD);
5346 switch (arg_action) {
5349 log_info("Halting.");
5350 reboot(RB_HALT_SYSTEM);
5353 case ACTION_POWEROFF:
5354 log_info("Powering off.");
5355 reboot(RB_POWER_OFF);
5359 log_info("Rebooting.");
5360 reboot(RB_AUTOBOOT);
5364 assert_not_reached("Unknown halt action.");
5367 /* We should never reach this. */
5371 static int runlevel_main(void) {
5372 int r, runlevel, previous;
5374 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5375 printf("unknown\n");
5380 previous <= 0 ? 'N' : previous,
5381 runlevel <= 0 ? 'N' : runlevel);
5386 static void pager_open(void) {
5393 if (!on_tty() || arg_no_pager)
5396 if ((pager = getenv("PAGER")))
5397 if (!*pager || streq(pager, "cat"))
5400 /* Determine and cache number of columns before we spawn the
5401 * pager so that we get the value from the actual tty */
5405 log_error("Failed to create pager pipe: %m");
5410 if (pager_pid < 0) {
5411 log_error("Failed to fork pager: %m");
5416 /* In the child start the pager */
5417 if (pager_pid == 0) {
5419 dup2(fd[0], STDIN_FILENO);
5422 setenv("LESS", "FRSX", 0);
5424 prctl(PR_SET_PDEATHSIG, SIGTERM);
5427 execlp(pager, pager, NULL);
5428 execl("/bin/sh", "sh", "-c", pager, NULL);
5430 /* Debian's alternatives command for pagers is
5431 * called 'pager'. Note that we do not call
5432 * sensible-pagers here, since that is just a
5433 * shell script that implements a logic that
5434 * is similar to this one anyway, but is
5435 * Debian-specific. */
5436 execlp("pager", "pager", NULL);
5438 execlp("less", "less", NULL);
5439 execlp("more", "more", NULL);
5442 log_error("Unable to execute pager: %m");
5443 _exit(EXIT_FAILURE);
5446 /* Return in the parent */
5447 if (dup2(fd[1], STDOUT_FILENO) < 0)
5448 log_error("Failed to duplicate pager pipe: %m");
5453 static void pager_close(void) {
5459 /* Inform pager that we are done */
5461 wait_for_terminate(pager_pid, &dummy);
5465 int main(int argc, char*argv[]) {
5466 int r, retval = EXIT_FAILURE;
5467 DBusConnection *bus = NULL;
5470 dbus_error_init(&error);
5472 log_parse_environment();
5475 if ((r = parse_argv(argc, argv)) < 0)
5478 retval = EXIT_SUCCESS;
5482 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5483 * let's shortcut this */
5484 if (arg_action == ACTION_RUNLEVEL) {
5485 r = runlevel_main();
5486 retval = r < 0 ? EXIT_FAILURE : r;
5490 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5492 switch (arg_action) {
5494 case ACTION_SYSTEMCTL:
5495 r = systemctl_main(bus, argc, argv, &error);
5499 case ACTION_POWEROFF:
5504 case ACTION_RUNLEVEL2:
5505 case ACTION_RUNLEVEL3:
5506 case ACTION_RUNLEVEL4:
5507 case ACTION_RUNLEVEL5:
5509 case ACTION_EMERGENCY:
5510 case ACTION_DEFAULT:
5511 r = start_with_fallback(bus);
5516 r = reload_with_fallback(bus);
5519 case ACTION_CANCEL_SHUTDOWN:
5520 r = send_shutdownd(0, 0, false, NULL);
5523 case ACTION_INVALID:
5524 case ACTION_RUNLEVEL:
5526 assert_not_reached("Unknown action");
5529 retval = r < 0 ? EXIT_FAILURE : r;
5534 dbus_connection_flush(bus);
5535 dbus_connection_close(bus);
5536 dbus_connection_unref(bus);
5539 dbus_error_free(&error);
5543 strv_free(arg_property);