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>
36 #include <dbus/dbus.h>
42 #include "utmp-wtmp.h"
46 #include "dbus-common.h"
47 #include "cgroup-show.h"
48 #include "cgroup-util.h"
50 #include "path-lookup.h"
51 #include "conf-parser.h"
52 #include "sd-daemon.h"
53 #include "shutdownd.h"
54 #include "exit-status.h"
55 #include "bus-errors.h"
57 #include "unit-name.h"
59 static const char *arg_type = NULL;
60 static char **arg_property = NULL;
61 static bool arg_all = false;
62 static bool arg_fail = false;
63 static bool arg_session = false;
64 static bool arg_global = false;
65 static bool arg_immediate = false;
66 static bool arg_no_block = false;
67 static bool arg_no_wtmp = false;
68 static bool arg_no_sync = false;
69 static bool arg_no_wall = false;
70 static bool arg_no_reload = false;
71 static bool arg_dry = false;
72 static bool arg_quiet = false;
73 static bool arg_full = false;
74 static bool arg_force = false;
75 static bool arg_defaults = false;
76 static char **arg_wall = NULL;
77 static usec_t arg_when = 0;
94 ACTION_CANCEL_SHUTDOWN,
96 } arg_action = ACTION_SYSTEMCTL;
103 static bool private_bus = false;
105 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
107 static bool on_tty(void) {
110 if (_unlikely_(t < 0))
111 t = isatty(STDOUT_FILENO) > 0;
116 static const char *ansi_highlight(bool b) {
121 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
124 static const char *ansi_highlight_green(bool b) {
129 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
132 static bool error_is_no_service(const DBusError *error) {
135 if (!dbus_error_is_set(error))
138 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
141 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
144 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
147 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
150 if (!dbus_error_is_set(error))
153 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
154 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
155 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
156 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
157 return EXIT_NOPERMISSION;
159 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
160 return EXIT_NOTINSTALLED;
162 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
163 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
164 return EXIT_NOTIMPLEMENTED;
166 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
167 return EXIT_NOTCONFIGURED;
175 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
180 if (dbus_message_iter_get_arg_type(iter) != type)
183 dbus_message_iter_get_basic(iter, data);
185 if (!dbus_message_iter_next(iter) != !next)
191 static void warn_wall(enum action action) {
192 static const char *table[_ACTION_MAX] = {
193 [ACTION_HALT] = "The system is going down for system halt NOW!",
194 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
195 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
196 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
197 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
206 if (!(p = strv_join(arg_wall, " "))) {
207 log_error("Failed to join strings.");
223 utmp_wall(table[action]);
228 const char *description;
229 const char *load_state;
230 const char *active_state;
231 const char *sub_state;
232 const char *following;
233 const char *unit_path;
235 const char *job_type;
236 const char *job_path;
239 static int compare_unit_info(const void *a, const void *b) {
241 const struct unit_info *u = a, *v = b;
243 d1 = strrchr(u->id, '.');
244 d2 = strrchr(v->id, '.');
249 if ((r = strcasecmp(d1, d2)) != 0)
253 return strcasecmp(u->id, v->id);
256 static bool output_show_job(const struct unit_info *u) {
259 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
260 streq(dot+1, arg_type))) &&
261 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
264 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
265 unsigned active_len, sub_len, job_len;
266 const struct unit_info *u;
268 active_len = sizeof("ACTIVE")-1;
269 sub_len = sizeof("SUB")-1;
270 job_len = sizeof("JOB")-1;
272 for (u = unit_infos; u < unit_infos + c; u++) {
273 if (!output_show_job(u))
276 active_len = MAX(active_len, strlen(u->active_state));
277 sub_len = MAX(sub_len, strlen(u->sub_state));
279 job_len = MAX(job_len, strlen(u->job_type));
283 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
284 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
285 if (columns() >= 80+12 || arg_full)
286 printf(" %s\n", "DESCRIPTION");
291 for (u = unit_infos; u < unit_infos + c; u++) {
294 const char *on_loaded, *off_loaded;
295 const char *on_active, *off_active;
297 if (!output_show_job(u))
300 if (!streq(u->load_state, "loaded") &&
301 !streq(u->load_state, "banned")) {
302 on_loaded = ansi_highlight(true);
303 off_loaded = ansi_highlight(false);
305 on_loaded = off_loaded = "";
307 if (streq(u->active_state, "failed")) {
308 on_active = ansi_highlight(true);
309 off_active = ansi_highlight(false);
311 on_active = off_active = "";
313 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
315 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
317 on_loaded, u->load_state, off_loaded,
318 on_active, active_len, u->active_state,
319 sub_len, u->sub_state, off_active,
324 a -= strlen(on_loaded) + strlen(off_loaded);
325 a -= strlen(on_active) + strlen(off_active);
328 printf(" %-*s", job_len, u->job_type);
332 if (a + b + 1 < columns()) {
334 printf(" %-*s", job_len, "");
337 printf(" %s", u->description);
339 printf(" %.*s", columns() - a - b - 1, u->description);
346 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
347 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
348 "SUB = The low-level unit activation state, values depend on unit type.\n"
349 "JOB = Pending job for the unit.\n");
352 printf("\n%u units listed.\n", c);
354 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
358 static int list_units(DBusConnection *bus, char **args, unsigned n) {
359 DBusMessage *m = NULL, *reply = NULL;
362 DBusMessageIter iter, sub, sub2;
363 unsigned c = 0, n_units = 0;
364 struct unit_info *unit_infos = NULL;
366 dbus_error_init(&error);
370 if (!(m = dbus_message_new_method_call(
371 "org.freedesktop.systemd1",
372 "/org/freedesktop/systemd1",
373 "org.freedesktop.systemd1.Manager",
375 log_error("Could not allocate message.");
379 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
380 log_error("Failed to issue method call: %s", bus_error_message(&error));
385 if (!dbus_message_iter_init(reply, &iter) ||
386 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
387 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
388 log_error("Failed to parse reply.");
393 dbus_message_iter_recurse(&iter, &sub);
395 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
398 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
399 log_error("Failed to parse reply.");
407 n_units = MAX(2*c, 16);
408 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
411 log_error("Failed to allocate unit array.");
421 dbus_message_iter_recurse(&sub, &sub2);
423 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
424 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
425 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
426 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
427 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
428 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
429 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
430 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
431 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
432 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
433 log_error("Failed to parse reply.");
438 dbus_message_iter_next(&sub);
442 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
443 output_units_list(unit_infos, c);
449 dbus_message_unref(m);
452 dbus_message_unref(reply);
456 dbus_error_free(&error);
461 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
462 static const char * const colors[] = {
463 "Requires", "[color=\"black\"]",
464 "RequiresOverridable", "[color=\"black\"]",
465 "Requisite", "[color=\"darkblue\"]",
466 "RequisiteOverridable", "[color=\"darkblue\"]",
467 "Wants", "[color=\"darkgrey\"]",
468 "Conflicts", "[color=\"red\"]",
469 "ConflictedBy", "[color=\"red\"]",
470 "After", "[color=\"green\"]"
473 const char *c = NULL;
480 for (i = 0; i < ELEMENTSOF(colors); i += 2)
481 if (streq(colors[i], prop)) {
489 if (arg_dot != DOT_ALL)
490 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
493 switch (dbus_message_iter_get_arg_type(iter)) {
495 case DBUS_TYPE_ARRAY:
497 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
500 dbus_message_iter_recurse(iter, &sub);
502 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
505 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
506 dbus_message_iter_get_basic(&sub, &s);
507 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
509 dbus_message_iter_next(&sub);
519 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
520 DBusMessage *m = NULL, *reply = NULL;
521 const char *interface = "org.freedesktop.systemd1.Unit";
524 DBusMessageIter iter, sub, sub2, sub3;
529 dbus_error_init(&error);
531 if (!(m = dbus_message_new_method_call(
532 "org.freedesktop.systemd1",
534 "org.freedesktop.DBus.Properties",
536 log_error("Could not allocate message.");
541 if (!dbus_message_append_args(m,
542 DBUS_TYPE_STRING, &interface,
543 DBUS_TYPE_INVALID)) {
544 log_error("Could not append arguments to message.");
549 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
550 log_error("Failed to issue method call: %s", bus_error_message(&error));
555 if (!dbus_message_iter_init(reply, &iter) ||
556 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
557 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
558 log_error("Failed to parse reply.");
563 dbus_message_iter_recurse(&iter, &sub);
565 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
568 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
569 log_error("Failed to parse reply.");
574 dbus_message_iter_recurse(&sub, &sub2);
576 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
577 log_error("Failed to parse reply.");
582 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
583 log_error("Failed to parse reply.");
588 dbus_message_iter_recurse(&sub2, &sub3);
590 if (dot_one_property(name, prop, &sub3)) {
591 log_error("Failed to parse reply.");
596 dbus_message_iter_next(&sub);
603 dbus_message_unref(m);
606 dbus_message_unref(reply);
608 dbus_error_free(&error);
613 static int dot(DBusConnection *bus, char **args, unsigned n) {
614 DBusMessage *m = NULL, *reply = NULL;
617 DBusMessageIter iter, sub, sub2;
619 dbus_error_init(&error);
623 if (!(m = dbus_message_new_method_call(
624 "org.freedesktop.systemd1",
625 "/org/freedesktop/systemd1",
626 "org.freedesktop.systemd1.Manager",
628 log_error("Could not allocate message.");
632 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
633 log_error("Failed to issue method call: %s", bus_error_message(&error));
638 if (!dbus_message_iter_init(reply, &iter) ||
639 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
640 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
641 log_error("Failed to parse reply.");
646 printf("digraph systemd {\n");
648 dbus_message_iter_recurse(&iter, &sub);
649 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
650 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
652 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
653 log_error("Failed to parse reply.");
658 dbus_message_iter_recurse(&sub, &sub2);
660 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
661 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
662 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
663 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
664 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
665 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
666 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
667 log_error("Failed to parse reply.");
672 if ((r = dot_one(bus, id, unit_path)) < 0)
675 /* printf("\t\"%s\";\n", id); */
676 dbus_message_iter_next(&sub);
681 log_info(" Color legend: black = Requires\n"
682 " dark blue = Requisite\n"
683 " dark grey = Wants\n"
687 if (isatty(fileno(stdout)))
688 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
689 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
695 dbus_message_unref(m);
698 dbus_message_unref(reply);
700 dbus_error_free(&error);
705 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
706 DBusMessage *m = NULL, *reply = NULL;
709 DBusMessageIter iter, sub, sub2;
712 dbus_error_init(&error);
716 if (!(m = dbus_message_new_method_call(
717 "org.freedesktop.systemd1",
718 "/org/freedesktop/systemd1",
719 "org.freedesktop.systemd1.Manager",
721 log_error("Could not allocate message.");
725 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
726 log_error("Failed to issue method call: %s", bus_error_message(&error));
731 if (!dbus_message_iter_init(reply, &iter) ||
732 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
733 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
734 log_error("Failed to parse reply.");
739 dbus_message_iter_recurse(&iter, &sub);
741 if (isatty(STDOUT_FILENO))
742 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
744 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
745 const char *name, *type, *state, *job_path, *unit_path;
749 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
750 log_error("Failed to parse reply.");
755 dbus_message_iter_recurse(&sub, &sub2);
757 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
758 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
759 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
760 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
761 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
762 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
763 log_error("Failed to parse reply.");
768 e = arg_full ? NULL : ellipsize(name, 25, 33);
769 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
774 dbus_message_iter_next(&sub);
777 if (isatty(STDOUT_FILENO))
778 printf("\n%u jobs listed.\n", k);
784 dbus_message_unref(m);
787 dbus_message_unref(reply);
789 dbus_error_free(&error);
794 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
795 DBusMessage *m = NULL, *reply = NULL;
800 dbus_error_init(&error);
805 for (i = 1; i < n; i++) {
807 if (!(m = dbus_message_new_method_call(
808 "org.freedesktop.systemd1",
809 "/org/freedesktop/systemd1",
810 "org.freedesktop.systemd1.Manager",
812 log_error("Could not allocate message.");
817 if (!dbus_message_append_args(m,
818 DBUS_TYPE_STRING, &args[i],
819 DBUS_TYPE_INVALID)) {
820 log_error("Could not append arguments to message.");
825 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
826 log_error("Failed to issue method call: %s", bus_error_message(&error));
831 dbus_message_unref(m);
832 dbus_message_unref(reply);
841 dbus_message_unref(m);
844 dbus_message_unref(reply);
846 dbus_error_free(&error);
851 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
852 DBusMessage *m = NULL, *reply = NULL;
857 dbus_error_init(&error);
863 return daemon_reload(bus, args, n);
865 for (i = 1; i < n; i++) {
869 if (!(m = dbus_message_new_method_call(
870 "org.freedesktop.systemd1",
871 "/org/freedesktop/systemd1",
872 "org.freedesktop.systemd1.Manager",
874 log_error("Could not allocate message.");
879 if ((r = safe_atou(args[i], &id)) < 0) {
880 log_error("Failed to parse job id: %s", strerror(-r));
884 assert_cc(sizeof(uint32_t) == sizeof(id));
885 if (!dbus_message_append_args(m,
886 DBUS_TYPE_UINT32, &id,
887 DBUS_TYPE_INVALID)) {
888 log_error("Could not append arguments to message.");
893 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
894 log_error("Failed to issue method call: %s", bus_error_message(&error));
899 if (!dbus_message_get_args(reply, &error,
900 DBUS_TYPE_OBJECT_PATH, &path,
901 DBUS_TYPE_INVALID)) {
902 log_error("Failed to parse reply: %s", bus_error_message(&error));
907 dbus_message_unref(m);
908 if (!(m = dbus_message_new_method_call(
909 "org.freedesktop.systemd1",
911 "org.freedesktop.systemd1.Job",
913 log_error("Could not allocate message.");
918 dbus_message_unref(reply);
919 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
920 log_error("Failed to issue method call: %s", bus_error_message(&error));
925 dbus_message_unref(m);
926 dbus_message_unref(reply);
934 dbus_message_unref(m);
937 dbus_message_unref(reply);
939 dbus_error_free(&error);
944 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
945 DBusMessage *m = NULL, *reply = NULL;
946 dbus_bool_t b = FALSE;
947 DBusMessageIter iter, sub;
949 *interface = "org.freedesktop.systemd1.Unit",
950 *property = "NeedDaemonReload",
953 /* We ignore all errors here, since this is used to show a warning only */
955 if (!(m = dbus_message_new_method_call(
956 "org.freedesktop.systemd1",
957 "/org/freedesktop/systemd1",
958 "org.freedesktop.systemd1.Manager",
962 if (!dbus_message_append_args(m,
963 DBUS_TYPE_STRING, &unit,
967 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
970 if (!dbus_message_get_args(reply, NULL,
971 DBUS_TYPE_OBJECT_PATH, &path,
975 dbus_message_unref(m);
976 if (!(m = dbus_message_new_method_call(
977 "org.freedesktop.systemd1",
979 "org.freedesktop.DBus.Properties",
983 if (!dbus_message_append_args(m,
984 DBUS_TYPE_STRING, &interface,
985 DBUS_TYPE_STRING, &property,
986 DBUS_TYPE_INVALID)) {
990 dbus_message_unref(reply);
991 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
994 if (!dbus_message_iter_init(reply, &iter) ||
995 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
998 dbus_message_iter_recurse(&iter, &sub);
1000 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1003 dbus_message_iter_get_basic(&sub, &b);
1007 dbus_message_unref(m);
1010 dbus_message_unref(reply);
1015 typedef struct WaitData {
1020 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1028 dbus_error_init(&error);
1030 log_debug("Got D-Bus request: %s.%s() on %s",
1031 dbus_message_get_interface(message),
1032 dbus_message_get_member(message),
1033 dbus_message_get_path(message));
1035 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1036 log_error("Warning! D-Bus connection terminated.");
1037 dbus_connection_close(connection);
1039 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1042 dbus_bool_t success = true;
1044 if (!dbus_message_get_args(message, &error,
1045 DBUS_TYPE_UINT32, &id,
1046 DBUS_TYPE_OBJECT_PATH, &path,
1047 DBUS_TYPE_BOOLEAN, &success,
1049 log_error("Failed to parse message: %s", bus_error_message(&error));
1053 if ((p = set_remove(d->set, (char*) path)))
1061 dbus_error_free(&error);
1062 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1065 static int enable_wait_for_jobs(DBusConnection *bus) {
1073 dbus_error_init(&error);
1074 dbus_bus_add_match(bus,
1076 "sender='org.freedesktop.systemd1',"
1077 "interface='org.freedesktop.systemd1.Manager',"
1078 "member='JobRemoved',"
1079 "path='/org/freedesktop/systemd1'",
1082 if (dbus_error_is_set(&error)) {
1083 log_error("Failed to add match: %s", bus_error_message(&error));
1084 dbus_error_free(&error);
1088 /* This is slightly dirty, since we don't undo the match registrations. */
1092 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1103 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1104 log_error("Failed to add filter.");
1109 while (!set_isempty(s) &&
1110 dbus_connection_read_write_dispatch(bus, -1))
1113 if (!arg_quiet && d.failed)
1114 log_error("Job failed, see system logs for details.");
1116 r = d.failed ? -EIO : 0;
1119 /* This is slightly dirty, since we don't undo the filter registration. */
1124 static int start_unit_one(
1125 DBusConnection *bus,
1132 DBusMessage *m = NULL, *reply = NULL;
1141 assert(arg_no_block || s);
1143 if (!(m = dbus_message_new_method_call(
1144 "org.freedesktop.systemd1",
1145 "/org/freedesktop/systemd1",
1146 "org.freedesktop.systemd1.Manager",
1148 log_error("Could not allocate message.");
1153 if (!dbus_message_append_args(m,
1154 DBUS_TYPE_STRING, &name,
1155 DBUS_TYPE_STRING, &mode,
1156 DBUS_TYPE_INVALID)) {
1157 log_error("Could not append arguments to message.");
1162 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1164 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1165 /* There's always a fallback possible for
1166 * legacy actions. */
1171 log_error("Failed to issue method call: %s", bus_error_message(error));
1176 if (!dbus_message_get_args(reply, error,
1177 DBUS_TYPE_OBJECT_PATH, &path,
1178 DBUS_TYPE_INVALID)) {
1179 log_error("Failed to parse reply: %s", bus_error_message(error));
1184 if (need_daemon_reload(bus, name))
1185 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1186 arg_session ? "--session" : "--system");
1188 if (!arg_no_block) {
1191 if (!(p = strdup(path))) {
1192 log_error("Failed to duplicate path.");
1197 if ((r = set_put(s, p)) < 0) {
1199 log_error("Failed to add path to set.");
1208 dbus_message_unref(m);
1211 dbus_message_unref(reply);
1216 static enum action verb_to_action(const char *verb) {
1217 if (streq(verb, "halt"))
1219 else if (streq(verb, "poweroff"))
1220 return ACTION_POWEROFF;
1221 else if (streq(verb, "reboot"))
1222 return ACTION_REBOOT;
1223 else if (streq(verb, "rescue"))
1224 return ACTION_RESCUE;
1225 else if (streq(verb, "emergency"))
1226 return ACTION_EMERGENCY;
1227 else if (streq(verb, "default"))
1228 return ACTION_DEFAULT;
1230 return ACTION_INVALID;
1233 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1235 static const char * const table[_ACTION_MAX] = {
1236 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1237 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1238 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1239 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1240 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1241 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1242 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1243 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1244 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1245 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1250 const char *method, *mode, *one_name;
1254 dbus_error_init(&error);
1258 if (arg_action == ACTION_SYSTEMCTL) {
1260 streq(args[0], "stop") ? "StopUnit" :
1261 streq(args[0], "reload") ? "ReloadUnit" :
1262 streq(args[0], "restart") ? "RestartUnit" :
1263 streq(args[0], "try-restart") ||
1264 streq(args[0], "condrestart") ? "TryRestartUnit" :
1265 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1266 streq(args[0], "reload-or-try-restart") ||
1267 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
1271 (streq(args[0], "isolate") ||
1272 streq(args[0], "rescue") ||
1273 streq(args[0], "emergency")) ? "isolate" :
1277 one_name = table[verb_to_action(args[0])];
1280 assert(arg_action < ELEMENTSOF(table));
1281 assert(table[arg_action]);
1283 method = "StartUnit";
1285 mode = (arg_action == ACTION_EMERGENCY ||
1286 arg_action == ACTION_RESCUE ||
1287 arg_action == ACTION_RUNLEVEL2 ||
1288 arg_action == ACTION_RUNLEVEL3 ||
1289 arg_action == ACTION_RUNLEVEL4 ||
1290 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1292 one_name = table[arg_action];
1295 if (!arg_no_block) {
1296 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1297 log_error("Could not watch jobs: %s", strerror(-ret));
1301 if (!(s = set_new(string_hash_func, string_compare_func))) {
1302 log_error("Failed to allocate set.");
1309 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1312 for (i = 1; i < n; i++)
1313 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1314 ret = translate_bus_error_to_exit_status(r, &error);
1315 dbus_error_free(&error);
1320 if ((r = wait_for_jobs(bus, s)) < 0) {
1329 dbus_error_free(&error);
1334 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1340 r = start_unit(bus, args, n);
1343 warn_wall(verb_to_action(args[0]));
1348 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1349 DBusMessage *m = NULL, *reply = NULL;
1351 *interface = "org.freedesktop.systemd1.Unit",
1352 *property = "ActiveState";
1353 int r = 3; /* According to LSB: "program is not running" */
1360 dbus_error_init(&error);
1362 for (i = 1; i < n; i++) {
1363 const char *path = NULL;
1365 DBusMessageIter iter, sub;
1367 if (!(m = dbus_message_new_method_call(
1368 "org.freedesktop.systemd1",
1369 "/org/freedesktop/systemd1",
1370 "org.freedesktop.systemd1.Manager",
1372 log_error("Could not allocate message.");
1377 if (!dbus_message_append_args(m,
1378 DBUS_TYPE_STRING, &args[i],
1379 DBUS_TYPE_INVALID)) {
1380 log_error("Could not append arguments to message.");
1385 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1387 /* Hmm, cannot figure out anything about this unit... */
1391 dbus_error_free(&error);
1395 if (!dbus_message_get_args(reply, &error,
1396 DBUS_TYPE_OBJECT_PATH, &path,
1397 DBUS_TYPE_INVALID)) {
1398 log_error("Failed to parse reply: %s", bus_error_message(&error));
1403 dbus_message_unref(m);
1404 if (!(m = dbus_message_new_method_call(
1405 "org.freedesktop.systemd1",
1407 "org.freedesktop.DBus.Properties",
1409 log_error("Could not allocate message.");
1414 if (!dbus_message_append_args(m,
1415 DBUS_TYPE_STRING, &interface,
1416 DBUS_TYPE_STRING, &property,
1417 DBUS_TYPE_INVALID)) {
1418 log_error("Could not append arguments to message.");
1423 dbus_message_unref(reply);
1424 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1425 log_error("Failed to issue method call: %s", bus_error_message(&error));
1430 if (!dbus_message_iter_init(reply, &iter) ||
1431 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1432 log_error("Failed to parse reply.");
1437 dbus_message_iter_recurse(&iter, &sub);
1439 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1440 log_error("Failed to parse reply.");
1445 dbus_message_iter_get_basic(&sub, &state);
1450 if (streq(state, "active") || streq(state, "reloading"))
1453 dbus_message_unref(m);
1454 dbus_message_unref(reply);
1460 dbus_message_unref(m);
1463 dbus_message_unref(reply);
1465 dbus_error_free(&error);
1470 typedef struct ExecStatusInfo {
1476 usec_t start_timestamp;
1477 usec_t exit_timestamp;
1482 LIST_FIELDS(struct ExecStatusInfo, exec);
1485 static void exec_status_info_free(ExecStatusInfo *i) {
1493 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1494 uint64_t start_timestamp, exit_timestamp;
1495 DBusMessageIter sub2, sub3;
1499 int32_t code, status;
1505 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1508 dbus_message_iter_recurse(sub, &sub2);
1510 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1513 if (!(i->path = strdup(path)))
1516 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1517 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1521 dbus_message_iter_recurse(&sub2, &sub3);
1522 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1523 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1524 dbus_message_iter_next(&sub3);
1529 if (!(i->argv = new0(char*, n+1)))
1533 dbus_message_iter_recurse(&sub2, &sub3);
1534 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1537 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1538 dbus_message_iter_get_basic(&sub3, &s);
1539 dbus_message_iter_next(&sub3);
1541 if (!(i->argv[n++] = strdup(s)))
1545 if (!dbus_message_iter_next(&sub2) ||
1546 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1547 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1548 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1549 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1550 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1551 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1555 i->start_timestamp = (usec_t) start_timestamp;
1556 i->exit_timestamp = (usec_t) exit_timestamp;
1557 i->pid = (pid_t) pid;
1564 typedef struct UnitStatusInfo {
1566 const char *load_state;
1567 const char *active_state;
1568 const char *sub_state;
1570 const char *description;
1573 const char *default_control_group;
1575 usec_t inactive_exit_timestamp;
1576 usec_t active_enter_timestamp;
1577 usec_t active_exit_timestamp;
1578 usec_t inactive_enter_timestamp;
1580 bool need_daemon_reload;
1585 const char *status_text;
1587 #ifdef HAVE_SYSV_COMPAT
1591 usec_t start_timestamp;
1592 usec_t exit_timestamp;
1594 int exit_code, exit_status;
1597 unsigned n_accepted;
1598 unsigned n_connections;
1602 const char *sysfs_path;
1604 /* Mount, Automount */
1610 LIST_HEAD(ExecStatusInfo, exec);
1613 static void print_status_info(UnitStatusInfo *i) {
1615 const char *on, *off, *ss;
1617 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1618 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1622 /* This shows pretty information about a unit. See
1623 * print_property() for a low-level property printer */
1625 printf("%s", strna(i->id));
1627 if (i->description && !streq_ptr(i->id, i->description))
1628 printf(" - %s", i->description);
1632 if (streq_ptr(i->load_state, "failed") ||
1633 streq_ptr(i->load_state, "banned")) {
1634 on = ansi_highlight(true);
1635 off = ansi_highlight(false);
1640 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1642 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1644 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1646 if (streq_ptr(i->active_state, "failed")) {
1647 on = ansi_highlight(true);
1648 off = ansi_highlight(false);
1649 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1650 on = ansi_highlight_green(true);
1651 off = ansi_highlight_green(false);
1656 printf("\t Active: %s%s (%s)%s",
1658 strna(i->active_state),
1662 printf("\t Active: %s%s%s",
1664 strna(i->active_state),
1667 timestamp = (streq_ptr(i->active_state, "active") ||
1668 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1669 (streq_ptr(i->active_state, "inactive") ||
1670 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1671 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1672 i->active_exit_timestamp;
1674 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1675 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1678 printf(" since [%s; %s]\n", s2, s1);
1680 printf(" since [%s]\n", s2);
1685 printf("\t Device: %s\n", i->sysfs_path);
1687 printf("\t Where: %s\n", i->where);
1689 printf("\t What: %s\n", i->what);
1692 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1694 LIST_FOREACH(exec, p, i->exec) {
1697 /* Only show exited processes here */
1701 t = strv_join(p->argv, " ");
1702 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1705 if (p->code == CLD_EXITED) {
1708 printf("status=%i", p->status);
1710 #ifdef HAVE_SYSV_COMPAT
1711 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1713 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1718 printf("signal=%s", signal_to_string(p->status));
1721 if (i->main_pid == p->pid &&
1722 i->start_timestamp == p->start_timestamp &&
1723 i->exit_timestamp == p->start_timestamp)
1724 /* Let's not show this twice */
1727 if (p->pid == i->control_pid)
1731 if (i->main_pid > 0 || i->control_pid > 0) {
1734 if (i->main_pid > 0) {
1735 printf("Main PID: %u", (unsigned) i->main_pid);
1739 get_process_name(i->main_pid, &t);
1744 } else if (i->exit_code > 0) {
1745 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1747 if (i->exit_code == CLD_EXITED) {
1750 printf("status=%i", i->exit_status);
1752 #ifdef HAVE_SYSV_COMPAT
1753 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1755 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
1760 printf("signal=%s", signal_to_string(i->exit_status));
1765 if (i->main_pid > 0 && i->control_pid > 0)
1768 if (i->control_pid > 0) {
1771 printf(" Control: %u", (unsigned) i->control_pid);
1773 get_process_name(i->control_pid, &t);
1784 printf("\t Status: \"%s\"\n", i->status_text);
1786 if (i->default_control_group) {
1789 printf("\t CGroup: %s\n", i->default_control_group);
1791 if ((c = columns()) > 18)
1796 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1799 if (i->need_daemon_reload)
1800 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1801 ansi_highlight(true),
1802 ansi_highlight(false),
1803 arg_session ? "--session" : "--system");
1806 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1808 switch (dbus_message_iter_get_arg_type(iter)) {
1810 case DBUS_TYPE_STRING: {
1813 dbus_message_iter_get_basic(iter, &s);
1816 if (streq(name, "Id"))
1818 else if (streq(name, "LoadState"))
1820 else if (streq(name, "ActiveState"))
1821 i->active_state = s;
1822 else if (streq(name, "SubState"))
1824 else if (streq(name, "Description"))
1826 else if (streq(name, "FragmentPath"))
1828 #ifdef HAVE_SYSV_COMPAT
1829 else if (streq(name, "SysVPath")) {
1834 else if (streq(name, "DefaultControlGroup"))
1835 i->default_control_group = s;
1836 else if (streq(name, "StatusText"))
1838 else if (streq(name, "SysFSPath"))
1840 else if (streq(name, "Where"))
1842 else if (streq(name, "What"))
1849 case DBUS_TYPE_BOOLEAN: {
1852 dbus_message_iter_get_basic(iter, &b);
1854 if (streq(name, "Accept"))
1856 else if (streq(name, "NeedDaemonReload"))
1857 i->need_daemon_reload = b;
1862 case DBUS_TYPE_UINT32: {
1865 dbus_message_iter_get_basic(iter, &u);
1867 if (streq(name, "MainPID")) {
1869 i->main_pid = (pid_t) u;
1872 } else if (streq(name, "ControlPID"))
1873 i->control_pid = (pid_t) u;
1874 else if (streq(name, "ExecMainPID")) {
1876 i->main_pid = (pid_t) u;
1877 } else if (streq(name, "NAccepted"))
1879 else if (streq(name, "NConnections"))
1880 i->n_connections = u;
1885 case DBUS_TYPE_INT32: {
1888 dbus_message_iter_get_basic(iter, &j);
1890 if (streq(name, "ExecMainCode"))
1891 i->exit_code = (int) j;
1892 else if (streq(name, "ExecMainStatus"))
1893 i->exit_status = (int) j;
1898 case DBUS_TYPE_UINT64: {
1901 dbus_message_iter_get_basic(iter, &u);
1903 if (streq(name, "ExecMainStartTimestamp"))
1904 i->start_timestamp = (usec_t) u;
1905 else if (streq(name, "ExecMainExitTimestamp"))
1906 i->exit_timestamp = (usec_t) u;
1907 else if (streq(name, "ActiveEnterTimestamp"))
1908 i->active_enter_timestamp = (usec_t) u;
1909 else if (streq(name, "InactiveEnterTimestamp"))
1910 i->inactive_enter_timestamp = (usec_t) u;
1911 else if (streq(name, "InactiveExitTimestamp"))
1912 i->inactive_exit_timestamp = (usec_t) u;
1913 else if (streq(name, "ActiveExitTimestamp"))
1914 i->active_exit_timestamp = (usec_t) u;
1919 case DBUS_TYPE_ARRAY: {
1921 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1922 startswith(name, "Exec")) {
1923 DBusMessageIter sub;
1925 dbus_message_iter_recurse(iter, &sub);
1926 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1927 ExecStatusInfo *info;
1930 if (!(info = new0(ExecStatusInfo, 1)))
1933 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1938 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1940 dbus_message_iter_next(&sub);
1951 static int print_property(const char *name, DBusMessageIter *iter) {
1955 /* This is a low-level property printer, see
1956 * print_status_info() for the nicer output */
1958 if (arg_property && !strv_find(arg_property, name))
1961 switch (dbus_message_iter_get_arg_type(iter)) {
1963 case DBUS_TYPE_STRING: {
1965 dbus_message_iter_get_basic(iter, &s);
1967 if (arg_all || s[0])
1968 printf("%s=%s\n", name, s);
1973 case DBUS_TYPE_BOOLEAN: {
1975 dbus_message_iter_get_basic(iter, &b);
1976 printf("%s=%s\n", name, yes_no(b));
1981 case DBUS_TYPE_UINT64: {
1983 dbus_message_iter_get_basic(iter, &u);
1985 /* Yes, heuristics! But we can change this check
1986 * should it turn out to not be sufficient */
1988 if (strstr(name, "Timestamp")) {
1989 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1991 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1992 printf("%s=%s\n", name, strempty(t));
1993 } else if (strstr(name, "USec")) {
1994 char timespan[FORMAT_TIMESPAN_MAX];
1996 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1998 printf("%s=%llu\n", name, (unsigned long long) u);
2003 case DBUS_TYPE_UINT32: {
2005 dbus_message_iter_get_basic(iter, &u);
2007 if (strstr(name, "UMask") || strstr(name, "Mode"))
2008 printf("%s=%04o\n", name, u);
2010 printf("%s=%u\n", name, (unsigned) u);
2015 case DBUS_TYPE_INT32: {
2017 dbus_message_iter_get_basic(iter, &i);
2019 printf("%s=%i\n", name, (int) i);
2023 case DBUS_TYPE_DOUBLE: {
2025 dbus_message_iter_get_basic(iter, &d);
2027 printf("%s=%g\n", name, d);
2031 case DBUS_TYPE_STRUCT: {
2032 DBusMessageIter sub;
2033 dbus_message_iter_recurse(iter, &sub);
2035 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2038 dbus_message_iter_get_basic(&sub, &u);
2041 printf("%s=%u\n", name, (unsigned) u);
2043 printf("%s=\n", name);
2046 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2049 dbus_message_iter_get_basic(&sub, &s);
2051 if (arg_all || s[0])
2052 printf("%s=%s\n", name, s);
2060 case DBUS_TYPE_ARRAY:
2062 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2063 DBusMessageIter sub;
2066 dbus_message_iter_recurse(iter, &sub);
2068 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2069 printf("%s=", name);
2071 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2074 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2075 dbus_message_iter_get_basic(&sub, &s);
2076 printf("%s%s", space ? " " : "", s);
2079 dbus_message_iter_next(&sub);
2087 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2088 DBusMessageIter sub;
2090 dbus_message_iter_recurse(iter, &sub);
2092 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2093 printf("%s=", name);
2095 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2098 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2099 dbus_message_iter_get_basic(&sub, &u);
2102 dbus_message_iter_next(&sub);
2110 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2111 DBusMessageIter sub, sub2;
2113 dbus_message_iter_recurse(iter, &sub);
2114 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2115 const char *type, *path;
2117 dbus_message_iter_recurse(&sub, &sub2);
2119 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2120 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2121 printf("%s=%s\n", type, path);
2123 dbus_message_iter_next(&sub);
2128 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2129 DBusMessageIter sub, sub2;
2131 dbus_message_iter_recurse(iter, &sub);
2132 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2134 uint64_t value, next_elapse;
2136 dbus_message_iter_recurse(&sub, &sub2);
2138 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2139 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2140 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2141 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2143 printf("%s={ value=%s ; next_elapse=%s }\n",
2145 format_timespan(timespan1, sizeof(timespan1), value),
2146 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2149 dbus_message_iter_next(&sub);
2154 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2155 DBusMessageIter sub;
2157 dbus_message_iter_recurse(iter, &sub);
2158 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2159 ExecStatusInfo info;
2162 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2163 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2166 t = strv_join(info.argv, " ");
2168 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2172 yes_no(info.ignore),
2173 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2174 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2175 (unsigned) info. pid,
2176 sigchld_code_to_string(info.code),
2178 info.code == CLD_EXITED ? "" : "/",
2179 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2185 strv_free(info.argv);
2187 dbus_message_iter_next(&sub);
2197 printf("%s=[unprintable]\n", name);
2202 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2203 DBusMessage *m = NULL, *reply = NULL;
2204 const char *interface = "";
2207 DBusMessageIter iter, sub, sub2, sub3;
2208 UnitStatusInfo info;
2216 dbus_error_init(&error);
2218 if (!(m = dbus_message_new_method_call(
2219 "org.freedesktop.systemd1",
2221 "org.freedesktop.DBus.Properties",
2223 log_error("Could not allocate message.");
2228 if (!dbus_message_append_args(m,
2229 DBUS_TYPE_STRING, &interface,
2230 DBUS_TYPE_INVALID)) {
2231 log_error("Could not append arguments to message.");
2236 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2237 log_error("Failed to issue method call: %s", bus_error_message(&error));
2242 if (!dbus_message_iter_init(reply, &iter) ||
2243 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2244 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2245 log_error("Failed to parse reply.");
2250 dbus_message_iter_recurse(&iter, &sub);
2257 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2260 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2261 log_error("Failed to parse reply.");
2266 dbus_message_iter_recurse(&sub, &sub2);
2268 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2269 log_error("Failed to parse reply.");
2274 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2275 log_error("Failed to parse reply.");
2280 dbus_message_iter_recurse(&sub2, &sub3);
2282 if (show_properties)
2283 r = print_property(name, &sub3);
2285 r = status_property(name, &sub3, &info);
2288 log_error("Failed to parse reply.");
2293 dbus_message_iter_next(&sub);
2298 if (!show_properties)
2299 print_status_info(&info);
2301 if (!streq_ptr(info.active_state, "active") &&
2302 !streq_ptr(info.active_state, "reloading"))
2303 /* According to LSB: "program not running" */
2306 while ((p = info.exec)) {
2307 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2308 exec_status_info_free(p);
2313 dbus_message_unref(m);
2316 dbus_message_unref(reply);
2318 dbus_error_free(&error);
2323 static int show(DBusConnection *bus, char **args, unsigned n) {
2324 DBusMessage *m = NULL, *reply = NULL;
2328 bool show_properties, new_line = false;
2333 dbus_error_init(&error);
2335 show_properties = !streq(args[0], "status");
2337 if (show_properties && n <= 1) {
2338 /* If not argument is specified inspect the manager
2341 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2345 for (i = 1; i < n; i++) {
2346 const char *path = NULL;
2349 if (safe_atou32(args[i], &id) < 0) {
2351 /* Interpret as unit name */
2353 if (!(m = dbus_message_new_method_call(
2354 "org.freedesktop.systemd1",
2355 "/org/freedesktop/systemd1",
2356 "org.freedesktop.systemd1.Manager",
2358 log_error("Could not allocate message.");
2363 if (!dbus_message_append_args(m,
2364 DBUS_TYPE_STRING, &args[i],
2365 DBUS_TYPE_INVALID)) {
2366 log_error("Could not append arguments to message.");
2371 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2373 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2374 log_error("Failed to issue method call: %s", bus_error_message(&error));
2379 dbus_error_free(&error);
2381 dbus_message_unref(m);
2382 if (!(m = dbus_message_new_method_call(
2383 "org.freedesktop.systemd1",
2384 "/org/freedesktop/systemd1",
2385 "org.freedesktop.systemd1.Manager",
2387 log_error("Could not allocate message.");
2392 if (!dbus_message_append_args(m,
2393 DBUS_TYPE_STRING, &args[i],
2394 DBUS_TYPE_INVALID)) {
2395 log_error("Could not append arguments to message.");
2400 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2401 log_error("Failed to issue method call: %s", bus_error_message(&error));
2403 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2404 ret = 4; /* According to LSB: "program or service status is unknown" */
2411 } else if (show_properties) {
2413 /* Interpret as job id */
2415 if (!(m = dbus_message_new_method_call(
2416 "org.freedesktop.systemd1",
2417 "/org/freedesktop/systemd1",
2418 "org.freedesktop.systemd1.Manager",
2420 log_error("Could not allocate message.");
2425 if (!dbus_message_append_args(m,
2426 DBUS_TYPE_UINT32, &id,
2427 DBUS_TYPE_INVALID)) {
2428 log_error("Could not append arguments to message.");
2433 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2434 log_error("Failed to issue method call: %s", bus_error_message(&error));
2440 /* Interpret as PID */
2442 if (!(m = dbus_message_new_method_call(
2443 "org.freedesktop.systemd1",
2444 "/org/freedesktop/systemd1",
2445 "org.freedesktop.systemd1.Manager",
2447 log_error("Could not allocate message.");
2452 if (!dbus_message_append_args(m,
2453 DBUS_TYPE_UINT32, &id,
2454 DBUS_TYPE_INVALID)) {
2455 log_error("Could not append arguments to message.");
2460 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2461 log_error("Failed to issue method call: %s", bus_error_message(&error));
2467 if (!dbus_message_get_args(reply, &error,
2468 DBUS_TYPE_OBJECT_PATH, &path,
2469 DBUS_TYPE_INVALID)) {
2470 log_error("Failed to parse reply: %s", bus_error_message(&error));
2475 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2478 dbus_message_unref(m);
2479 dbus_message_unref(reply);
2485 dbus_message_unref(m);
2488 dbus_message_unref(reply);
2490 dbus_error_free(&error);
2495 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2497 DBusMessage *m = NULL, *reply = NULL;
2502 dbus_error_init(&error);
2504 log_debug("Got D-Bus request: %s.%s() on %s",
2505 dbus_message_get_interface(message),
2506 dbus_message_get_member(message),
2507 dbus_message_get_path(message));
2509 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2510 log_error("Warning! D-Bus connection terminated.");
2511 dbus_connection_close(connection);
2513 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2514 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2515 const char *id, *path;
2517 if (!dbus_message_get_args(message, &error,
2518 DBUS_TYPE_STRING, &id,
2519 DBUS_TYPE_OBJECT_PATH, &path,
2521 log_error("Failed to parse message: %s", bus_error_message(&error));
2522 else if (streq(dbus_message_get_member(message), "UnitNew"))
2523 printf("Unit %s added.\n", id);
2525 printf("Unit %s removed.\n", id);
2527 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2528 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2532 if (!dbus_message_get_args(message, &error,
2533 DBUS_TYPE_UINT32, &id,
2534 DBUS_TYPE_OBJECT_PATH, &path,
2536 log_error("Failed to parse message: %s", bus_error_message(&error));
2537 else if (streq(dbus_message_get_member(message), "JobNew"))
2538 printf("Job %u added.\n", id);
2540 printf("Job %u removed.\n", id);
2543 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2545 const char *path, *interface, *property = "Id";
2546 DBusMessageIter iter, sub;
2548 path = dbus_message_get_path(message);
2550 if (!dbus_message_get_args(message, &error,
2551 DBUS_TYPE_STRING, &interface,
2552 DBUS_TYPE_INVALID)) {
2553 log_error("Failed to parse message: %s", bus_error_message(&error));
2557 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2558 !streq(interface, "org.freedesktop.systemd1.Unit"))
2561 if (!(m = dbus_message_new_method_call(
2562 "org.freedesktop.systemd1",
2564 "org.freedesktop.DBus.Properties",
2566 log_error("Could not allocate message.");
2570 if (!dbus_message_append_args(m,
2571 DBUS_TYPE_STRING, &interface,
2572 DBUS_TYPE_STRING, &property,
2573 DBUS_TYPE_INVALID)) {
2574 log_error("Could not append arguments to message.");
2578 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2579 log_error("Failed to issue method call: %s", bus_error_message(&error));
2583 if (!dbus_message_iter_init(reply, &iter) ||
2584 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2585 log_error("Failed to parse reply.");
2589 dbus_message_iter_recurse(&iter, &sub);
2591 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2594 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2595 log_error("Failed to parse reply.");
2599 dbus_message_iter_get_basic(&sub, &id);
2600 printf("Unit %s changed.\n", id);
2604 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2605 log_error("Failed to parse reply.");
2609 dbus_message_iter_get_basic(&sub, &id);
2610 printf("Job %u changed.\n", id);
2616 dbus_message_unref(m);
2619 dbus_message_unref(reply);
2621 dbus_error_free(&error);
2622 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2626 dbus_message_unref(m);
2629 dbus_message_unref(reply);
2631 dbus_error_free(&error);
2632 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2635 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2636 DBusMessage *m = NULL, *reply = NULL;
2640 dbus_error_init(&error);
2643 dbus_bus_add_match(bus,
2645 "sender='org.freedesktop.systemd1',"
2646 "interface='org.freedesktop.systemd1.Manager',"
2647 "path='/org/freedesktop/systemd1'",
2650 if (dbus_error_is_set(&error)) {
2651 log_error("Failed to add match: %s", bus_error_message(&error));
2656 dbus_bus_add_match(bus,
2658 "sender='org.freedesktop.systemd1',"
2659 "interface='org.freedesktop.DBus.Properties',"
2660 "member='PropertiesChanged'",
2663 if (dbus_error_is_set(&error)) {
2664 log_error("Failed to add match: %s", bus_error_message(&error));
2670 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2671 log_error("Failed to add filter.");
2676 if (!(m = dbus_message_new_method_call(
2677 "org.freedesktop.systemd1",
2678 "/org/freedesktop/systemd1",
2679 "org.freedesktop.systemd1.Manager",
2681 log_error("Could not allocate message.");
2686 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2687 log_error("Failed to issue method call: %s", bus_error_message(&error));
2692 while (dbus_connection_read_write_dispatch(bus, -1))
2699 /* This is slightly dirty, since we don't undo the filter or the matches. */
2702 dbus_message_unref(m);
2705 dbus_message_unref(reply);
2707 dbus_error_free(&error);
2712 static int dump(DBusConnection *bus, char **args, unsigned n) {
2713 DBusMessage *m = NULL, *reply = NULL;
2718 dbus_error_init(&error);
2720 if (!(m = dbus_message_new_method_call(
2721 "org.freedesktop.systemd1",
2722 "/org/freedesktop/systemd1",
2723 "org.freedesktop.systemd1.Manager",
2725 log_error("Could not allocate message.");
2729 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2730 log_error("Failed to issue method call: %s", bus_error_message(&error));
2735 if (!dbus_message_get_args(reply, &error,
2736 DBUS_TYPE_STRING, &text,
2737 DBUS_TYPE_INVALID)) {
2738 log_error("Failed to parse reply: %s", bus_error_message(&error));
2743 fputs(text, stdout);
2749 dbus_message_unref(m);
2752 dbus_message_unref(reply);
2754 dbus_error_free(&error);
2759 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2760 DBusMessage *m = NULL, *reply = NULL;
2763 const char *name = "", *path, *id;
2764 dbus_bool_t cleanup = FALSE;
2765 DBusMessageIter iter, sub;
2767 *interface = "org.freedesktop.systemd1.Unit",
2770 dbus_error_init(&error);
2772 if (!(m = dbus_message_new_method_call(
2773 "org.freedesktop.systemd1",
2774 "/org/freedesktop/systemd1",
2775 "org.freedesktop.systemd1.Manager",
2776 "CreateSnapshot"))) {
2777 log_error("Could not allocate message.");
2784 if (!dbus_message_append_args(m,
2785 DBUS_TYPE_STRING, &name,
2786 DBUS_TYPE_BOOLEAN, &cleanup,
2787 DBUS_TYPE_INVALID)) {
2788 log_error("Could not append arguments to message.");
2793 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2794 log_error("Failed to issue method call: %s", bus_error_message(&error));
2799 if (!dbus_message_get_args(reply, &error,
2800 DBUS_TYPE_OBJECT_PATH, &path,
2801 DBUS_TYPE_INVALID)) {
2802 log_error("Failed to parse reply: %s", bus_error_message(&error));
2807 dbus_message_unref(m);
2808 if (!(m = dbus_message_new_method_call(
2809 "org.freedesktop.systemd1",
2811 "org.freedesktop.DBus.Properties",
2813 log_error("Could not allocate message.");
2817 if (!dbus_message_append_args(m,
2818 DBUS_TYPE_STRING, &interface,
2819 DBUS_TYPE_STRING, &property,
2820 DBUS_TYPE_INVALID)) {
2821 log_error("Could not append arguments to message.");
2826 dbus_message_unref(reply);
2827 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2828 log_error("Failed to issue method call: %s", bus_error_message(&error));
2833 if (!dbus_message_iter_init(reply, &iter) ||
2834 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2835 log_error("Failed to parse reply.");
2840 dbus_message_iter_recurse(&iter, &sub);
2842 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2843 log_error("Failed to parse reply.");
2848 dbus_message_iter_get_basic(&sub, &id);
2856 dbus_message_unref(m);
2859 dbus_message_unref(reply);
2861 dbus_error_free(&error);
2866 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2867 DBusMessage *m = NULL, *reply = NULL;
2875 dbus_error_init(&error);
2877 for (i = 1; i < n; i++) {
2878 const char *path = NULL;
2880 if (!(m = dbus_message_new_method_call(
2881 "org.freedesktop.systemd1",
2882 "/org/freedesktop/systemd1",
2883 "org.freedesktop.systemd1.Manager",
2885 log_error("Could not allocate message.");
2890 if (!dbus_message_append_args(m,
2891 DBUS_TYPE_STRING, &args[i],
2892 DBUS_TYPE_INVALID)) {
2893 log_error("Could not append arguments to message.");
2898 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2899 log_error("Failed to issue method call: %s", bus_error_message(&error));
2904 if (!dbus_message_get_args(reply, &error,
2905 DBUS_TYPE_OBJECT_PATH, &path,
2906 DBUS_TYPE_INVALID)) {
2907 log_error("Failed to parse reply: %s", bus_error_message(&error));
2912 dbus_message_unref(m);
2913 if (!(m = dbus_message_new_method_call(
2914 "org.freedesktop.systemd1",
2916 "org.freedesktop.systemd1.Snapshot",
2918 log_error("Could not allocate message.");
2923 dbus_message_unref(reply);
2924 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2925 log_error("Failed to issue method call: %s", bus_error_message(&error));
2930 dbus_message_unref(m);
2931 dbus_message_unref(reply);
2939 dbus_message_unref(m);
2942 dbus_message_unref(reply);
2944 dbus_error_free(&error);
2949 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2950 DBusMessage *m = NULL, *reply = NULL;
2955 dbus_error_init(&error);
2957 if (arg_action == ACTION_RELOAD)
2959 else if (arg_action == ACTION_REEXEC)
2960 method = "Reexecute";
2962 assert(arg_action == ACTION_SYSTEMCTL);
2965 streq(args[0], "clear-jobs") ||
2966 streq(args[0], "cancel") ? "ClearJobs" :
2967 streq(args[0], "daemon-reexec") ? "Reexecute" :
2968 streq(args[0], "reset-failed") ? "ResetFailed" :
2969 streq(args[0], "daemon-exit") ? "Exit" :
2973 if (!(m = dbus_message_new_method_call(
2974 "org.freedesktop.systemd1",
2975 "/org/freedesktop/systemd1",
2976 "org.freedesktop.systemd1.Manager",
2978 log_error("Could not allocate message.");
2982 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2984 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2985 /* There's always a fallback possible for
2986 * legacy actions. */
2991 log_error("Failed to issue method call: %s", bus_error_message(&error));
3000 dbus_message_unref(m);
3003 dbus_message_unref(reply);
3005 dbus_error_free(&error);
3010 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3011 DBusMessage *m = NULL, *reply = NULL;
3017 dbus_error_init(&error);
3020 return daemon_reload(bus, args, n);
3022 for (i = 1; i < n; i++) {
3024 if (!(m = dbus_message_new_method_call(
3025 "org.freedesktop.systemd1",
3026 "/org/freedesktop/systemd1",
3027 "org.freedesktop.systemd1.Manager",
3028 "ResetFailedUnit"))) {
3029 log_error("Could not allocate message.");
3034 if (!dbus_message_append_args(m,
3035 DBUS_TYPE_STRING, args + i,
3036 DBUS_TYPE_INVALID)) {
3037 log_error("Could not append arguments to message.");
3042 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3043 log_error("Failed to issue method call: %s", bus_error_message(&error));
3048 dbus_message_unref(m);
3049 dbus_message_unref(reply);
3057 dbus_message_unref(m);
3060 dbus_message_unref(reply);
3062 dbus_error_free(&error);
3067 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3068 DBusMessage *m = NULL, *reply = NULL;
3070 DBusMessageIter iter, sub, sub2;
3073 *interface = "org.freedesktop.systemd1.Manager",
3074 *property = "Environment";
3076 dbus_error_init(&error);
3078 if (!(m = dbus_message_new_method_call(
3079 "org.freedesktop.systemd1",
3080 "/org/freedesktop/systemd1",
3081 "org.freedesktop.DBus.Properties",
3083 log_error("Could not allocate message.");
3087 if (!dbus_message_append_args(m,
3088 DBUS_TYPE_STRING, &interface,
3089 DBUS_TYPE_STRING, &property,
3090 DBUS_TYPE_INVALID)) {
3091 log_error("Could not append arguments to message.");
3096 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3097 log_error("Failed to issue method call: %s", bus_error_message(&error));
3102 if (!dbus_message_iter_init(reply, &iter) ||
3103 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3104 log_error("Failed to parse reply.");
3109 dbus_message_iter_recurse(&iter, &sub);
3111 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3112 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3113 log_error("Failed to parse reply.");
3118 dbus_message_iter_recurse(&sub, &sub2);
3120 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3123 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3124 log_error("Failed to parse reply.");
3129 dbus_message_iter_get_basic(&sub2, &text);
3130 printf("%s\n", text);
3132 dbus_message_iter_next(&sub2);
3139 dbus_message_unref(m);
3142 dbus_message_unref(reply);
3144 dbus_error_free(&error);
3149 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3150 DBusMessage *m = NULL, *reply = NULL;
3154 DBusMessageIter iter, sub;
3157 dbus_error_init(&error);
3159 method = streq(args[0], "set-environment")
3161 : "UnsetEnvironment";
3163 if (!(m = dbus_message_new_method_call(
3164 "org.freedesktop.systemd1",
3165 "/org/freedesktop/systemd1",
3166 "org.freedesktop.systemd1.Manager",
3169 log_error("Could not allocate message.");
3173 dbus_message_iter_init_append(m, &iter);
3175 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3176 log_error("Could not append arguments to message.");
3181 for (i = 1; i < n; i++)
3182 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3183 log_error("Could not append arguments to message.");
3188 if (!dbus_message_iter_close_container(&iter, &sub)) {
3189 log_error("Could not append arguments to message.");
3194 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3195 log_error("Failed to issue method call: %s", bus_error_message(&error));
3204 dbus_message_unref(m);
3207 dbus_message_unref(reply);
3209 dbus_error_free(&error);
3222 static Hashmap *will_install = NULL, *have_installed = NULL;
3223 static Set *remove_symlinks_to = NULL;
3225 static void install_info_free(InstallInfo *i) {
3230 strv_free(i->aliases);
3231 strv_free(i->wanted_by);
3235 static void install_info_hashmap_free(Hashmap *m) {
3238 while ((i = hashmap_steal_first(m)))
3239 install_info_free(i);
3244 static int install_info_add(const char *name) {
3248 assert(will_install);
3250 if (!unit_name_is_valid_no_type(name, true)) {
3251 log_warning("Unit name %s is not a valid unit name.", name);
3255 if (hashmap_get(have_installed, name) ||
3256 hashmap_get(will_install, name))
3259 if (!(i = new0(InstallInfo, 1))) {
3264 if (!(i->name = strdup(name))) {
3269 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3276 install_info_free(i);
3281 static int config_parse_also(
3282 const char *filename,
3284 const char *section,
3298 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3302 if (!(n = strndup(w, l)))
3305 if ((r = install_info_add(n)) < 0) {
3306 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3317 static int mark_symlink_for_removal(const char *p) {
3322 assert(path_is_absolute(p));
3324 if (!remove_symlinks_to)
3327 if (!(n = strdup(p)))
3330 path_kill_slashes(n);
3332 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3334 return r == -EEXIST ? 0 : r;
3340 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3349 if (!(d = fdopendir(fd))) {
3350 close_nointr_nofail(fd);
3356 while ((de = readdir(d))) {
3357 bool is_dir = false, is_link = false;
3359 if (ignore_file(de->d_name))
3362 if (de->d_type == DT_LNK)
3364 else if (de->d_type == DT_DIR)
3366 else if (de->d_type == DT_UNKNOWN) {
3369 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3370 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3377 is_link = S_ISLNK(st.st_mode);
3378 is_dir = S_ISDIR(st.st_mode);
3386 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3387 log_error("Failed to open %s/%s: %m", root, de->d_name);
3394 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3395 log_error("Failed to allocate directory string.");
3396 close_nointr_nofail(nfd);
3401 /* This will close nfd, regardless whether it succeeds or not */
3402 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3408 } else if (is_link) {
3412 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3413 log_error("Failed to allocate symlink string.");
3418 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3419 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3427 if ((c = canonicalize_file_name(dest))) {
3428 /* This might fail if the destination
3429 * is already removed */
3435 path_kill_slashes(dest);
3436 if (set_get(remove_symlinks_to, dest)) {
3439 log_info("rm '%s'", p);
3441 if (unlink(p) < 0) {
3442 log_error("Cannot unlink symlink %s: %m", p);
3447 rmdir_parents(p, config_path);
3448 path_kill_slashes(p);
3450 if (!set_get(remove_symlinks_to, p)) {
3452 if ((r = mark_symlink_for_removal(p)) < 0) {
3471 static int remove_marked_symlinks(const char *config_path) {
3475 assert(config_path);
3477 if (set_size(remove_symlinks_to) <= 0)
3480 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3487 if ((cfd = dup(fd)) < 0) {
3492 /* This takes possession of cfd and closes it */
3493 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3499 close_nointr_nofail(fd);
3504 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3511 if (streq(verb, "enable")) {
3514 mkdir_parents(new_path, 0755);
3516 if (symlink(old_path, new_path) >= 0) {
3519 log_info("ln -s '%s' '%s'", old_path, new_path);
3524 if (errno != EEXIST) {
3525 log_error("Cannot link %s to %s: %m", old_path, new_path);
3529 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3531 if (errno == EINVAL) {
3532 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3536 log_error("readlink() failed: %s", strerror(-r));
3540 if (streq(dest, old_path)) {
3546 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3555 log_info("ln -s '%s' '%s'", old_path, new_path);
3557 if (symlink(old_path, new_path) >= 0)
3560 log_error("Cannot link %s to %s: %m", old_path, new_path);
3563 } else if (streq(verb, "disable")) {
3566 if ((r = mark_symlink_for_removal(old_path)) < 0)
3569 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3570 if (errno == ENOENT)
3573 if (errno == EINVAL) {
3574 log_warning("File %s not a symlink, ignoring.", old_path);
3578 log_error("readlink() failed: %s", strerror(-r));
3582 if (!streq(dest, old_path)) {
3583 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3590 if ((r = mark_symlink_for_removal(new_path)) < 0)
3594 log_info("rm '%s'", new_path);
3596 if (unlink(new_path) >= 0)
3599 log_error("Cannot unlink %s: %m", new_path);
3602 } else if (streq(verb, "is-enabled")) {
3605 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3607 if (errno == ENOENT || errno == EINVAL)
3610 log_error("readlink() failed: %s", strerror(-r));
3614 if (streq(dest, old_path)) {
3622 assert_not_reached("Unknown action.");
3625 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3627 char *alias_path = NULL;
3632 assert(config_path);
3634 STRV_FOREACH(s, i->aliases) {
3637 if (!(alias_path = path_make_absolute(*s, config_path))) {
3638 log_error("Out of memory");
3643 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3646 if (streq(verb, "disable"))
3647 rmdir_parents(alias_path, config_path);
3657 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3659 char *alias_path = NULL;
3664 assert(config_path);
3666 STRV_FOREACH(s, i->wanted_by) {
3667 if (!unit_name_is_valid_no_type(*s, true)) {
3668 log_error("Invalid name %s.", *s);
3676 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3677 log_error("Out of memory");
3682 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3685 if (streq(verb, "disable"))
3686 rmdir_parents(alias_path, config_path);
3697 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3699 const ConfigItem items[] = {
3700 { "Alias", config_parse_strv, &i->aliases, "Install" },
3701 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3702 { "Also", config_parse_also, NULL, "Install" },
3704 { NULL, NULL, NULL, NULL }
3708 char *filename = NULL;
3715 STRV_FOREACH(p, paths->unit_path) {
3718 if (!(filename = path_make_absolute(i->name, *p))) {
3719 log_error("Out of memory");
3723 /* Ensure that we don't follow symlinks */
3724 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3725 if ((f = fdopen(fd, "re")))
3728 if (errno == ELOOP) {
3729 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3734 if (errno != ENOENT) {
3735 log_error("Failed to open %s: %m", filename);
3745 log_error("Couldn't find %s.", i->name);
3751 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3758 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3761 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3764 if ((r = mark_symlink_for_removal(filename)) < 0)
3767 if ((r = remove_marked_symlinks(config_path)) < 0)
3773 static char *get_config_path(void) {
3775 if (arg_session && arg_global)
3776 return strdup(SESSION_CONFIG_UNIT_PATH);
3781 if (session_config_home(&p) < 0)
3787 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3790 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3794 char *config_path = NULL;
3797 const char *verb = args[0];
3799 dbus_error_init(&error);
3802 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3803 log_error("Failed to determine lookup paths: %s", strerror(-r));
3807 if (!(config_path = get_config_path())) {
3808 log_error("Failed to determine config path");
3813 will_install = hashmap_new(string_hash_func, string_compare_func);
3814 have_installed = hashmap_new(string_hash_func, string_compare_func);
3816 if (!will_install || !have_installed) {
3817 log_error("Failed to allocate unit sets.");
3822 if (!arg_defaults && streq(verb, "disable"))
3823 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3824 log_error("Failed to allocate symlink sets.");
3829 for (j = 1; j < n; j++)
3830 if ((r = install_info_add(args[j])) < 0) {
3831 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
3835 while ((i = hashmap_first(will_install))) {
3838 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3840 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3848 /* In test mode and found something */
3854 if (streq(verb, "is-enabled"))
3855 r = r > 0 ? 0 : -ENOENT;
3857 /* Don't try to reload anything if the user asked us to not do this */
3859 /* Don't try to reload anything when updating a unit globally */
3861 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3862 (arg_session || sd_booted() > 0) &&
3863 /* Don't try to reload anything if we are running in a chroot environment */
3864 (arg_session || running_in_chroot() <= 0) ) {
3867 if ((q = daemon_reload(bus, args, n)) < 0)
3872 install_info_hashmap_free(will_install);
3873 install_info_hashmap_free(have_installed);
3875 set_free_free(remove_symlinks_to);
3877 lookup_paths_free(&paths);
3884 static int systemctl_help(void) {
3886 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3887 "Send control commands to or query the systemd manager.\n\n"
3888 " -h --help Show this help\n"
3889 " --version Show package version\n"
3890 " -t --type=TYPE List only units of a particular type\n"
3891 " -p --property=NAME Show only properties by this name\n"
3892 " -a --all Show all units/properties, including dead/empty ones\n"
3893 " --full Don't ellipsize unit names on output\n"
3894 " --fail When queueing a new job, fail if conflicting jobs are\n"
3896 " -q --quiet Suppress output\n"
3897 " --no-block Do not wait until operation finished\n"
3898 " --system Connect to system bus\n"
3899 " --session Connect to session bus\n"
3900 " --order When generating graph for dot, show only order\n"
3901 " --require When generating graph for dot, show only requirement\n"
3902 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3903 " --global Enable/disable unit files globally\n"
3904 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3906 " --force When enabling unit files, override existing symlinks\n"
3907 " --defaults When disabling unit files, remove default symlinks only\n\n"
3909 " list-units List units\n"
3910 " start [NAME...] Start (activate) one or more units\n"
3911 " stop [NAME...] Stop (deactivate) one or more units\n"
3912 " reload [NAME...] Reload one or more units\n"
3913 " restart [NAME...] Start or restart one or more units\n"
3914 " try-restart [NAME...] Restart one or more units if active\n"
3915 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3916 " otherwise start or restart\n"
3917 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3918 " otherwise restart if active\n"
3919 " isolate [NAME] Start one unit and stop all others\n"
3920 " is-active [NAME...] Check whether units are active\n"
3921 " status [NAME...|PID...] Show runtime status of one or more units\n"
3922 " show [NAME...|JOB...] Show properties of one or more\n"
3923 " units/jobs or the manager\n"
3924 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3926 " enable [NAME...] Enable one or more unit files\n"
3927 " disable [NAME...] Disable one or more unit files\n"
3928 " is-enabled [NAME...] Check whether unit files are enabled\n"
3929 " load [NAME...] Load one or more units\n"
3930 " list-jobs List jobs\n"
3931 " cancel [JOB...] Cancel all, one, or more jobs\n"
3932 " monitor Monitor unit/job changes\n"
3933 " dump Dump server status\n"
3934 " dot Dump dependency graph for dot(1)\n"
3935 " snapshot [NAME] Create a snapshot\n"
3936 " delete [NAME...] Remove one or more snapshots\n"
3937 " daemon-reload Reload systemd manager configuration\n"
3938 " daemon-reexec Reexecute systemd manager\n"
3939 " daemon-exit Ask the systemd manager to quit\n"
3940 " show-environment Dump environment\n"
3941 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3942 " unset-environment [NAME...] Unset one or more environment variables\n"
3943 " halt Shut down and halt the system\n"
3944 " poweroff Shut down and power-off the system\n"
3945 " reboot Shut down and reboot the system\n"
3946 " rescue Enter system rescue mode\n"
3947 " emergency Enter system emergency mode\n"
3948 " default Enter system default mode\n",
3949 program_invocation_short_name);
3954 static int halt_help(void) {
3956 printf("%s [OPTIONS...]\n\n"
3957 "%s the system.\n\n"
3958 " --help Show this help\n"
3959 " --halt Halt the machine\n"
3960 " -p --poweroff Switch off the machine\n"
3961 " --reboot Reboot the machine\n"
3962 " -f --force Force immediate halt/power-off/reboot\n"
3963 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3964 " -d --no-wtmp Don't write wtmp record\n"
3965 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3966 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3967 program_invocation_short_name,
3968 arg_action == ACTION_REBOOT ? "Reboot" :
3969 arg_action == ACTION_POWEROFF ? "Power off" :
3975 static int shutdown_help(void) {
3977 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3978 "Shut down the system.\n\n"
3979 " --help Show this help\n"
3980 " -H --halt Halt the machine\n"
3981 " -P --poweroff Power-off the machine\n"
3982 " -r --reboot Reboot the machine\n"
3983 " -h Equivalent to --poweroff, overriden by --halt\n"
3984 " -k Don't halt/power-off/reboot, just send warnings\n"
3985 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3986 " -c Cancel a pending shutdown\n",
3987 program_invocation_short_name);
3992 static int telinit_help(void) {
3994 printf("%s [OPTIONS...] {COMMAND}\n\n"
3995 "Send control commands to the init daemon.\n\n"
3996 " --help Show this help\n"
3997 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3999 " 0 Power-off the machine\n"
4000 " 6 Reboot the machine\n"
4001 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4002 " 1, s, S Enter rescue mode\n"
4003 " q, Q Reload init daemon configuration\n"
4004 " u, U Reexecute init daemon\n",
4005 program_invocation_short_name);
4010 static int runlevel_help(void) {
4012 printf("%s [OPTIONS...]\n\n"
4013 "Prints the previous and current runlevel of the init system.\n\n"
4014 " --help Show this help\n",
4015 program_invocation_short_name);
4020 static int systemctl_parse_argv(int argc, char *argv[]) {
4038 static const struct option options[] = {
4039 { "help", no_argument, NULL, 'h' },
4040 { "version", no_argument, NULL, ARG_VERSION },
4041 { "type", required_argument, NULL, 't' },
4042 { "property", required_argument, NULL, 'p' },
4043 { "all", no_argument, NULL, 'a' },
4044 { "full", no_argument, NULL, ARG_FULL },
4045 { "fail", no_argument, NULL, ARG_FAIL },
4046 { "session", no_argument, NULL, ARG_SESSION },
4047 { "system", no_argument, NULL, ARG_SYSTEM },
4048 { "global", no_argument, NULL, ARG_GLOBAL },
4049 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4050 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4051 { "quiet", no_argument, NULL, 'q' },
4052 { "order", no_argument, NULL, ARG_ORDER },
4053 { "require", no_argument, NULL, ARG_REQUIRE },
4054 { "force", no_argument, NULL, ARG_FORCE },
4055 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4056 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4057 { NULL, 0, NULL, 0 }
4065 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4074 puts(PACKAGE_STRING);
4076 puts(SYSTEMD_FEATURES);
4086 if (!(l = strv_append(arg_property, optarg)))
4089 strv_free(arg_property);
4092 /* If the user asked for a particular
4093 * property, show it to him, even if it is
4112 arg_session = false;
4116 arg_no_block = true;
4124 arg_dot = DOT_ORDER;
4128 arg_dot = DOT_REQUIRE;
4144 arg_no_reload = true;
4153 arg_defaults = true;
4160 log_error("Unknown option code %c", c);
4168 static int halt_parse_argv(int argc, char *argv[]) {
4177 static const struct option options[] = {
4178 { "help", no_argument, NULL, ARG_HELP },
4179 { "halt", no_argument, NULL, ARG_HALT },
4180 { "poweroff", no_argument, NULL, 'p' },
4181 { "reboot", no_argument, NULL, ARG_REBOOT },
4182 { "force", no_argument, NULL, 'f' },
4183 { "wtmp-only", no_argument, NULL, 'w' },
4184 { "no-wtmp", no_argument, NULL, 'd' },
4185 { "no-sync", no_argument, NULL, 'n' },
4186 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4187 { NULL, 0, NULL, 0 }
4195 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4196 if (runlevel == '0' || runlevel == '6')
4197 arg_immediate = true;
4199 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4207 arg_action = ACTION_HALT;
4211 if (arg_action != ACTION_REBOOT)
4212 arg_action = ACTION_POWEROFF;
4216 arg_action = ACTION_REBOOT;
4220 arg_immediate = true;
4241 /* Compatibility nops */
4248 log_error("Unknown option code %c", c);
4253 if (optind < argc) {
4254 log_error("Too many arguments.");
4261 static int parse_time_spec(const char *t, usec_t *_u) {
4265 if (streq(t, "now"))
4267 else if (t[0] == '+') {
4270 if (safe_atou64(t + 1, &u) < 0)
4273 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4282 hour = strtol(t, &e, 10);
4283 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4286 minute = strtol(e+1, &e, 10);
4287 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4290 n = now(CLOCK_REALTIME);
4291 s = (time_t) (n / USEC_PER_SEC);
4294 assert_se(localtime_r(&s, &tm));
4296 tm.tm_hour = (int) hour;
4297 tm.tm_min = (int) minute;
4300 assert_se(s = mktime(&tm));
4302 *_u = (usec_t) s * USEC_PER_SEC;
4305 *_u += USEC_PER_DAY;
4311 static int shutdown_parse_argv(int argc, char *argv[]) {
4318 static const struct option options[] = {
4319 { "help", no_argument, NULL, ARG_HELP },
4320 { "halt", no_argument, NULL, 'H' },
4321 { "poweroff", no_argument, NULL, 'P' },
4322 { "reboot", no_argument, NULL, 'r' },
4323 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4324 { NULL, 0, NULL, 0 }
4332 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4340 arg_action = ACTION_HALT;
4344 arg_action = ACTION_POWEROFF;
4348 arg_action = ACTION_REBOOT;
4352 if (arg_action != ACTION_HALT)
4353 arg_action = ACTION_POWEROFF;
4366 /* Compatibility nops */
4370 arg_action = ACTION_CANCEL_SHUTDOWN;
4377 log_error("Unknown option code %c", c);
4382 if (argc > optind) {
4383 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4384 log_error("Failed to parse time specification: %s", argv[optind]);
4388 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4390 /* We skip the time argument */
4391 if (argc > optind + 1)
4392 arg_wall = argv + optind + 1;
4399 static int telinit_parse_argv(int argc, char *argv[]) {
4406 static const struct option options[] = {
4407 { "help", no_argument, NULL, ARG_HELP },
4408 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4409 { NULL, 0, NULL, 0 }
4412 static const struct {
4416 { '0', ACTION_POWEROFF },
4417 { '6', ACTION_REBOOT },
4418 { '1', ACTION_RESCUE },
4419 { '2', ACTION_RUNLEVEL2 },
4420 { '3', ACTION_RUNLEVEL3 },
4421 { '4', ACTION_RUNLEVEL4 },
4422 { '5', ACTION_RUNLEVEL5 },
4423 { 's', ACTION_RESCUE },
4424 { 'S', ACTION_RESCUE },
4425 { 'q', ACTION_RELOAD },
4426 { 'Q', ACTION_RELOAD },
4427 { 'u', ACTION_REEXEC },
4428 { 'U', ACTION_REEXEC }
4437 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4452 log_error("Unknown option code %c", c);
4457 if (optind >= argc) {
4462 if (optind + 1 < argc) {
4463 log_error("Too many arguments.");
4467 if (strlen(argv[optind]) != 1) {
4468 log_error("Expected single character argument.");
4472 for (i = 0; i < ELEMENTSOF(table); i++)
4473 if (table[i].from == argv[optind][0])
4476 if (i >= ELEMENTSOF(table)) {
4477 log_error("Unknown command %s.", argv[optind]);
4481 arg_action = table[i].to;
4488 static int runlevel_parse_argv(int argc, char *argv[]) {
4494 static const struct option options[] = {
4495 { "help", no_argument, NULL, ARG_HELP },
4496 { NULL, 0, NULL, 0 }
4504 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4515 log_error("Unknown option code %c", c);
4520 if (optind < argc) {
4521 log_error("Too many arguments.");
4528 static int parse_argv(int argc, char *argv[]) {
4532 if (program_invocation_short_name) {
4534 if (strstr(program_invocation_short_name, "halt")) {
4535 arg_action = ACTION_HALT;
4536 return halt_parse_argv(argc, argv);
4537 } else if (strstr(program_invocation_short_name, "poweroff")) {
4538 arg_action = ACTION_POWEROFF;
4539 return halt_parse_argv(argc, argv);
4540 } else if (strstr(program_invocation_short_name, "reboot")) {
4541 arg_action = ACTION_REBOOT;
4542 return halt_parse_argv(argc, argv);
4543 } else if (strstr(program_invocation_short_name, "shutdown")) {
4544 arg_action = ACTION_POWEROFF;
4545 return shutdown_parse_argv(argc, argv);
4546 } else if (strstr(program_invocation_short_name, "init")) {
4548 if (sd_booted() > 0) {
4549 arg_action = ACTION_INVALID;
4550 return telinit_parse_argv(argc, argv);
4552 /* Hmm, so some other init system is
4553 * running, we need to forward this
4554 * request to it. For now we simply
4555 * guess that it is Upstart. */
4557 execv("/lib/upstart/telinit", argv);
4559 log_error("Couldn't find an alternative telinit implementation to spawn.");
4563 } else if (strstr(program_invocation_short_name, "runlevel")) {
4564 arg_action = ACTION_RUNLEVEL;
4565 return runlevel_parse_argv(argc, argv);
4569 arg_action = ACTION_SYSTEMCTL;
4570 return systemctl_parse_argv(argc, argv);
4573 static int action_to_runlevel(void) {
4575 static const char table[_ACTION_MAX] = {
4576 [ACTION_HALT] = '0',
4577 [ACTION_POWEROFF] = '0',
4578 [ACTION_REBOOT] = '6',
4579 [ACTION_RUNLEVEL2] = '2',
4580 [ACTION_RUNLEVEL3] = '3',
4581 [ACTION_RUNLEVEL4] = '4',
4582 [ACTION_RUNLEVEL5] = '5',
4583 [ACTION_RESCUE] = '1'
4586 assert(arg_action < _ACTION_MAX);
4588 return table[arg_action];
4591 static int talk_upstart(void) {
4592 DBusMessage *m = NULL, *reply = NULL;
4594 int previous, rl, r;
4596 env1_buf[] = "RUNLEVEL=X",
4597 env2_buf[] = "PREVLEVEL=X";
4598 char *env1 = env1_buf, *env2 = env2_buf;
4599 const char *emit = "runlevel";
4600 dbus_bool_t b_false = FALSE;
4601 DBusMessageIter iter, sub;
4602 DBusConnection *bus;
4604 dbus_error_init(&error);
4606 if (!(rl = action_to_runlevel()))
4609 if (utmp_get_runlevel(&previous, NULL) < 0)
4612 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4613 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4618 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4623 if ((r = bus_check_peercred(bus)) < 0) {
4624 log_error("Failed to verify owner of bus.");
4628 if (!(m = dbus_message_new_method_call(
4629 "com.ubuntu.Upstart",
4630 "/com/ubuntu/Upstart",
4631 "com.ubuntu.Upstart0_6",
4634 log_error("Could not allocate message.");
4639 dbus_message_iter_init_append(m, &iter);
4641 env1_buf[sizeof(env1_buf)-2] = rl;
4642 env2_buf[sizeof(env2_buf)-2] = previous;
4644 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4645 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4646 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4647 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4648 !dbus_message_iter_close_container(&iter, &sub) ||
4649 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4650 log_error("Could not append arguments to message.");
4655 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4657 if (error_is_no_service(&error)) {
4662 log_error("Failed to issue method call: %s", bus_error_message(&error));
4671 dbus_message_unref(m);
4674 dbus_message_unref(reply);
4677 dbus_connection_flush(bus);
4678 dbus_connection_close(bus);
4679 dbus_connection_unref(bus);
4682 dbus_error_free(&error);
4687 static int talk_initctl(void) {
4688 struct init_request request;
4692 if (!(rl = action_to_runlevel()))
4696 request.magic = INIT_MAGIC;
4697 request.sleeptime = 0;
4698 request.cmd = INIT_CMD_RUNLVL;
4699 request.runlevel = rl;
4701 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4703 if (errno == ENOENT)
4706 log_error("Failed to open "INIT_FIFO": %m");
4711 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4712 close_nointr_nofail(fd);
4715 log_error("Failed to write to "INIT_FIFO": %m");
4716 return errno ? -errno : -EIO;
4722 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4724 static const struct {
4732 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4734 { "list-units", LESS, 1, list_units },
4735 { "list-jobs", EQUAL, 1, list_jobs },
4736 { "clear-jobs", EQUAL, 1, daemon_reload },
4737 { "load", MORE, 2, load_unit },
4738 { "cancel", MORE, 2, cancel_job },
4739 { "start", MORE, 2, start_unit },
4740 { "stop", MORE, 2, start_unit },
4741 { "reload", MORE, 2, start_unit },
4742 { "restart", MORE, 2, start_unit },
4743 { "try-restart", MORE, 2, start_unit },
4744 { "reload-or-restart", MORE, 2, start_unit },
4745 { "reload-or-try-restart", MORE, 2, start_unit },
4746 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4747 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4748 { "isolate", EQUAL, 2, start_unit },
4749 { "is-active", MORE, 2, check_unit },
4750 { "check", MORE, 2, check_unit },
4751 { "show", MORE, 1, show },
4752 { "status", MORE, 2, show },
4753 { "monitor", EQUAL, 1, monitor },
4754 { "dump", EQUAL, 1, dump },
4755 { "dot", EQUAL, 1, dot },
4756 { "snapshot", LESS, 2, snapshot },
4757 { "delete", MORE, 2, delete_snapshot },
4758 { "daemon-reload", EQUAL, 1, daemon_reload },
4759 { "daemon-reexec", EQUAL, 1, daemon_reload },
4760 { "daemon-exit", EQUAL, 1, daemon_reload },
4761 { "show-environment", EQUAL, 1, show_enviroment },
4762 { "set-environment", MORE, 2, set_environment },
4763 { "unset-environment", MORE, 2, set_environment },
4764 { "halt", EQUAL, 1, start_special },
4765 { "poweroff", EQUAL, 1, start_special },
4766 { "reboot", EQUAL, 1, start_special },
4767 { "default", EQUAL, 1, start_special },
4768 { "rescue", EQUAL, 1, start_special },
4769 { "emergency", EQUAL, 1, start_special },
4770 { "reset-failed", MORE, 1, reset_failed },
4771 { "enable", MORE, 2, enable_unit },
4772 { "disable", MORE, 2, enable_unit },
4773 { "is-enabled", MORE, 2, enable_unit }
4783 left = argc - optind;
4786 /* Special rule: no arguments means "list-units" */
4789 if (streq(argv[optind], "help")) {
4794 for (i = 0; i < ELEMENTSOF(verbs); i++)
4795 if (streq(argv[optind], verbs[i].verb))
4798 if (i >= ELEMENTSOF(verbs)) {
4799 log_error("Unknown operation %s", argv[optind]);
4804 switch (verbs[i].argc_cmp) {
4807 if (left != verbs[i].argc) {
4808 log_error("Invalid number of arguments.");
4815 if (left < verbs[i].argc) {
4816 log_error("Too few arguments.");
4823 if (left > verbs[i].argc) {
4824 log_error("Too many arguments.");
4831 assert_not_reached("Unknown comparison operator.");
4834 /* Require a bus connection for all operations but
4836 if (!streq(verbs[i].verb, "enable") &&
4837 !streq(verbs[i].verb, "disable") &&
4839 log_error("Failed to get D-Bus connection: %s", error->message);
4843 return verbs[i].dispatch(bus, argv + optind, left);
4846 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4848 struct msghdr msghdr;
4850 union sockaddr_union sockaddr;
4851 struct shutdownd_command c;
4859 strncpy(c.wall_message, message, sizeof(c.wall_message));
4861 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4865 sockaddr.sa.sa_family = AF_UNIX;
4866 sockaddr.un.sun_path[0] = 0;
4867 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4870 iovec.iov_base = (char*) &c;
4871 iovec.iov_len = sizeof(c);
4874 msghdr.msg_name = &sockaddr;
4875 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4877 msghdr.msg_iov = &iovec;
4878 msghdr.msg_iovlen = 1;
4880 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4881 close_nointr_nofail(fd);
4885 close_nointr_nofail(fd);
4889 static int reload_with_fallback(DBusConnection *bus) {
4892 /* First, try systemd via D-Bus. */
4893 if (daemon_reload(bus, NULL, 0) > 0)
4897 /* Nothing else worked, so let's try signals */
4898 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4900 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4901 log_error("kill() failed: %m");
4908 static int start_with_fallback(DBusConnection *bus) {
4911 /* First, try systemd via D-Bus. */
4912 if (start_unit(bus, NULL, 0) >= 0)
4916 /* Hmm, talking to systemd via D-Bus didn't work. Then
4917 * let's try to talk to Upstart via D-Bus. */
4918 if (talk_upstart() > 0)
4921 /* Nothing else worked, so let's try
4923 if (talk_initctl() > 0)
4926 log_error("Failed to talk to init daemon.");
4930 warn_wall(arg_action);
4934 static int halt_main(DBusConnection *bus) {
4937 if (geteuid() != 0) {
4938 log_error("Must be root.");
4944 char date[FORMAT_TIMESTAMP_MAX];
4946 m = strv_join(arg_wall, " ");
4947 r = send_shutdownd(arg_when,
4948 arg_action == ACTION_HALT ? 'H' :
4949 arg_action == ACTION_POWEROFF ? 'P' :
4956 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4958 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4959 format_timestamp(date, sizeof(date), arg_when));
4964 if (!arg_dry && !arg_immediate)
4965 return start_with_fallback(bus);
4968 if (sd_booted() > 0)
4969 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4970 else if ((r = utmp_put_shutdown(0)) < 0)
4971 log_warning("Failed to write utmp record: %s", strerror(-r));
4980 /* Make sure C-A-D is handled by the kernel from this
4982 reboot(RB_ENABLE_CAD);
4984 switch (arg_action) {
4987 log_info("Halting.");
4988 reboot(RB_HALT_SYSTEM);
4991 case ACTION_POWEROFF:
4992 log_info("Powering off.");
4993 reboot(RB_POWER_OFF);
4997 log_info("Rebooting.");
4998 reboot(RB_AUTOBOOT);
5002 assert_not_reached("Unknown halt action.");
5005 /* We should never reach this. */
5009 static int runlevel_main(void) {
5010 int r, runlevel, previous;
5012 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5013 printf("unknown\n");
5018 previous <= 0 ? 'N' : previous,
5019 runlevel <= 0 ? 'N' : runlevel);
5024 int main(int argc, char*argv[]) {
5025 int r, retval = EXIT_FAILURE;
5026 DBusConnection *bus = NULL;
5029 dbus_error_init(&error);
5031 log_parse_environment();
5034 if ((r = parse_argv(argc, argv)) < 0)
5037 retval = EXIT_SUCCESS;
5041 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5042 * let's shortcut this */
5043 if (arg_action == ACTION_RUNLEVEL) {
5044 r = runlevel_main();
5045 retval = r < 0 ? EXIT_FAILURE : r;
5049 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5051 switch (arg_action) {
5053 case ACTION_SYSTEMCTL:
5054 r = systemctl_main(bus, argc, argv, &error);
5058 case ACTION_POWEROFF:
5063 case ACTION_RUNLEVEL2:
5064 case ACTION_RUNLEVEL3:
5065 case ACTION_RUNLEVEL4:
5066 case ACTION_RUNLEVEL5:
5068 case ACTION_EMERGENCY:
5069 case ACTION_DEFAULT:
5070 r = start_with_fallback(bus);
5075 r = reload_with_fallback(bus);
5078 case ACTION_CANCEL_SHUTDOWN:
5079 r = send_shutdownd(0, 0, false, NULL);
5082 case ACTION_INVALID:
5083 case ACTION_RUNLEVEL:
5085 assert_not_reached("Unknown action");
5088 retval = r < 0 ? EXIT_FAILURE : r;
5093 dbus_connection_flush(bus);
5094 dbus_connection_close(bus);
5095 dbus_connection_unref(bus);
5098 dbus_error_free(&error);
5102 strv_free(arg_property);