1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/reboot.h>
28 #include <sys/ioctl.h>
32 #include <sys/socket.h>
35 #include <dbus/dbus.h>
41 #include "utmp-wtmp.h"
45 #include "dbus-common.h"
46 #include "cgroup-show.h"
47 #include "cgroup-util.h"
49 #include "path-lookup.h"
50 #include "conf-parser.h"
51 #include "sd-daemon.h"
52 #include "shutdownd.h"
53 #include "exit-status.h"
54 #include "bus-errors.h"
56 static const char *arg_type = NULL;
57 static char **arg_property = NULL;
58 static bool arg_all = false;
59 static bool arg_fail = false;
60 static bool arg_session = false;
61 static bool arg_global = false;
62 static bool arg_immediate = false;
63 static bool arg_no_block = false;
64 static bool arg_no_wtmp = false;
65 static bool arg_no_sync = false;
66 static bool arg_no_wall = false;
67 static bool arg_no_reload = false;
68 static bool arg_dry = false;
69 static bool arg_quiet = false;
70 static bool arg_full = false;
71 static bool arg_force = false;
72 static bool arg_defaults = false;
73 static char **arg_wall = NULL;
74 static usec_t arg_when = 0;
91 ACTION_CANCEL_SHUTDOWN,
93 } arg_action = ACTION_SYSTEMCTL;
100 static bool private_bus = false;
102 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
104 static bool on_tty(void) {
107 if (_unlikely_(t < 0))
108 t = isatty(STDOUT_FILENO) > 0;
113 static const char *ansi_highlight(bool b) {
118 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
121 static const char *ansi_highlight_green(bool b) {
126 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
129 static bool error_is_no_service(const DBusError *error) {
132 if (!dbus_error_is_set(error))
135 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
138 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
141 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
144 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
147 if (!dbus_error_is_set(error))
150 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
151 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
152 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
153 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
154 return EXIT_NOPERMISSION;
156 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
157 return EXIT_NOTINSTALLED;
159 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
160 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
161 return EXIT_NOTIMPLEMENTED;
163 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
164 return EXIT_NOTCONFIGURED;
172 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
177 if (dbus_message_iter_get_arg_type(iter) != type)
180 dbus_message_iter_get_basic(iter, data);
182 if (!dbus_message_iter_next(iter) != !next)
188 static void warn_wall(enum action action) {
189 static const char *table[_ACTION_MAX] = {
190 [ACTION_HALT] = "The system is going down for system halt NOW!",
191 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
192 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
193 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
194 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
203 if (!(p = strv_join(arg_wall, " "))) {
204 log_error("Failed to join strings.");
220 utmp_wall(table[action]);
225 const char *description;
226 const char *load_state;
227 const char *active_state;
228 const char *sub_state;
229 const char *following;
230 const char *unit_path;
232 const char *job_type;
233 const char *job_path;
236 static int compare_unit_info(const void *a, const void *b) {
238 const struct unit_info *u = a, *v = b;
240 d1 = strrchr(u->id, '.');
241 d2 = strrchr(v->id, '.');
246 if ((r = strcasecmp(d1, d2)) != 0)
250 return strcasecmp(u->id, v->id);
253 static int list_units(DBusConnection *bus, char **args, unsigned n) {
254 DBusMessage *m = NULL, *reply = NULL;
257 DBusMessageIter iter, sub, sub2;
258 unsigned c = 0, k, n_units = 0;
259 struct unit_info *unit_infos = NULL;
261 dbus_error_init(&error);
265 if (!(m = dbus_message_new_method_call(
266 "org.freedesktop.systemd1",
267 "/org/freedesktop/systemd1",
268 "org.freedesktop.systemd1.Manager",
270 log_error("Could not allocate message.");
274 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
275 log_error("Failed to issue method call: %s", bus_error_message(&error));
280 if (!dbus_message_iter_init(reply, &iter) ||
281 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
282 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
283 log_error("Failed to parse reply.");
288 dbus_message_iter_recurse(&iter, &sub);
290 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
293 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
294 log_error("Failed to parse reply.");
302 n_units = MAX(2*c, 16);
303 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
306 log_error("Failed to allocate unit array.");
316 dbus_message_iter_recurse(&sub, &sub2);
318 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
319 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
320 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
321 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
322 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
323 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
324 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
325 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
326 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
327 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
328 log_error("Failed to parse reply.");
333 dbus_message_iter_next(&sub);
337 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
339 if (isatty(STDOUT_FILENO)) {
340 if (columns() >= 80+12 || arg_full)
341 printf("%-25s %-6s %-12s %-18s %-15s %s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB", "DESCRIPTION");
343 printf("%-25s %-6s %-12s %-18s %-15s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB");
346 for (k = 0; k < c; k++) {
348 struct unit_info *u = unit_infos+k;
350 if ((!arg_type || ((dot = strrchr(u->id, '.')) &&
351 streq(dot+1, arg_type))) &&
352 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0)) {
355 const char *on_loaded, *off_loaded;
356 const char *on_active, *off_active;
358 if (!streq(u->load_state, "loaded")) {
359 on_loaded = ansi_highlight(true);
360 off_loaded = ansi_highlight(false);
362 on_loaded = off_loaded = "";
364 if (streq(u->active_state, "failed")) {
365 on_active = ansi_highlight(true);
366 off_active = ansi_highlight(false);
368 on_active = off_active = "";
370 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
372 printf("%-25s %s%-6s%s %s%-12s %-18s%s%n",
374 on_loaded, u->load_state, off_loaded,
375 on_active, u->active_state, u->sub_state, off_active,
380 a -= strlen(on_loaded) + strlen(off_loaded);
381 a -= strlen(on_active) + strlen(off_active);
384 printf(" %-15s%n", u->job_type, &b);
388 if (a + b + 1 < columns()) {
393 printf(" %s", u->description);
395 printf(" %.*s", columns() - a - b - 1, u->description);
402 if (isatty(STDOUT_FILENO)) {
404 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
405 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
406 "SUB = The low-level unit activation state, values depend on unit type.\n"
407 "JOB = Pending job for the unit.\n");
410 printf("\n%u units listed.\n", c);
412 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
419 dbus_message_unref(m);
422 dbus_message_unref(reply);
426 dbus_error_free(&error);
431 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
432 static const char * const colors[] = {
433 "Requires", "[color=\"black\"]",
434 "RequiresOverridable", "[color=\"black\"]",
435 "Requisite", "[color=\"darkblue\"]",
436 "RequisiteOverridable", "[color=\"darkblue\"]",
437 "Wants", "[color=\"darkgrey\"]",
438 "Conflicts", "[color=\"red\"]",
439 "ConflictedBy", "[color=\"red\"]",
440 "After", "[color=\"green\"]"
443 const char *c = NULL;
450 for (i = 0; i < ELEMENTSOF(colors); i += 2)
451 if (streq(colors[i], prop)) {
459 if (arg_dot != DOT_ALL)
460 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
463 switch (dbus_message_iter_get_arg_type(iter)) {
465 case DBUS_TYPE_ARRAY:
467 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
470 dbus_message_iter_recurse(iter, &sub);
472 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
475 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
476 dbus_message_iter_get_basic(&sub, &s);
477 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
479 dbus_message_iter_next(&sub);
489 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
490 DBusMessage *m = NULL, *reply = NULL;
491 const char *interface = "org.freedesktop.systemd1.Unit";
494 DBusMessageIter iter, sub, sub2, sub3;
499 dbus_error_init(&error);
501 if (!(m = dbus_message_new_method_call(
502 "org.freedesktop.systemd1",
504 "org.freedesktop.DBus.Properties",
506 log_error("Could not allocate message.");
511 if (!dbus_message_append_args(m,
512 DBUS_TYPE_STRING, &interface,
513 DBUS_TYPE_INVALID)) {
514 log_error("Could not append arguments to message.");
519 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
520 log_error("Failed to issue method call: %s", bus_error_message(&error));
525 if (!dbus_message_iter_init(reply, &iter) ||
526 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
527 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
528 log_error("Failed to parse reply.");
533 dbus_message_iter_recurse(&iter, &sub);
535 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
538 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
539 log_error("Failed to parse reply.");
544 dbus_message_iter_recurse(&sub, &sub2);
546 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
547 log_error("Failed to parse reply.");
552 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
553 log_error("Failed to parse reply.");
558 dbus_message_iter_recurse(&sub2, &sub3);
560 if (dot_one_property(name, prop, &sub3)) {
561 log_error("Failed to parse reply.");
566 dbus_message_iter_next(&sub);
573 dbus_message_unref(m);
576 dbus_message_unref(reply);
578 dbus_error_free(&error);
583 static int dot(DBusConnection *bus, char **args, unsigned n) {
584 DBusMessage *m = NULL, *reply = NULL;
587 DBusMessageIter iter, sub, sub2;
589 dbus_error_init(&error);
593 if (!(m = dbus_message_new_method_call(
594 "org.freedesktop.systemd1",
595 "/org/freedesktop/systemd1",
596 "org.freedesktop.systemd1.Manager",
598 log_error("Could not allocate message.");
602 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
603 log_error("Failed to issue method call: %s", bus_error_message(&error));
608 if (!dbus_message_iter_init(reply, &iter) ||
609 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
610 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
611 log_error("Failed to parse reply.");
616 printf("digraph systemd {\n");
618 dbus_message_iter_recurse(&iter, &sub);
619 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
620 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
622 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
623 log_error("Failed to parse reply.");
628 dbus_message_iter_recurse(&sub, &sub2);
630 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
631 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
632 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
633 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
634 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
635 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
636 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
637 log_error("Failed to parse reply.");
642 if ((r = dot_one(bus, id, unit_path)) < 0)
645 /* printf("\t\"%s\";\n", id); */
646 dbus_message_iter_next(&sub);
651 log_info(" Color legend: black = Requires\n"
652 " dark blue = Requisite\n"
653 " dark grey = Wants\n"
657 if (isatty(fileno(stdout)))
658 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
659 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
665 dbus_message_unref(m);
668 dbus_message_unref(reply);
670 dbus_error_free(&error);
675 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
676 DBusMessage *m = NULL, *reply = NULL;
679 DBusMessageIter iter, sub, sub2;
682 dbus_error_init(&error);
686 if (!(m = dbus_message_new_method_call(
687 "org.freedesktop.systemd1",
688 "/org/freedesktop/systemd1",
689 "org.freedesktop.systemd1.Manager",
691 log_error("Could not allocate message.");
695 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
696 log_error("Failed to issue method call: %s", bus_error_message(&error));
701 if (!dbus_message_iter_init(reply, &iter) ||
702 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
703 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
704 log_error("Failed to parse reply.");
709 dbus_message_iter_recurse(&iter, &sub);
711 if (isatty(STDOUT_FILENO))
712 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
714 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
715 const char *name, *type, *state, *job_path, *unit_path;
719 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
720 log_error("Failed to parse reply.");
725 dbus_message_iter_recurse(&sub, &sub2);
727 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
728 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
729 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
730 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
731 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
732 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
733 log_error("Failed to parse reply.");
738 e = arg_full ? NULL : ellipsize(name, 25, 33);
739 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
744 dbus_message_iter_next(&sub);
747 if (isatty(STDOUT_FILENO))
748 printf("\n%u jobs listed.\n", k);
754 dbus_message_unref(m);
757 dbus_message_unref(reply);
759 dbus_error_free(&error);
764 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
765 DBusMessage *m = NULL, *reply = NULL;
770 dbus_error_init(&error);
775 for (i = 1; i < n; i++) {
777 if (!(m = dbus_message_new_method_call(
778 "org.freedesktop.systemd1",
779 "/org/freedesktop/systemd1",
780 "org.freedesktop.systemd1.Manager",
782 log_error("Could not allocate message.");
787 if (!dbus_message_append_args(m,
788 DBUS_TYPE_STRING, &args[i],
789 DBUS_TYPE_INVALID)) {
790 log_error("Could not append arguments to message.");
795 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
796 log_error("Failed to issue method call: %s", bus_error_message(&error));
801 dbus_message_unref(m);
802 dbus_message_unref(reply);
811 dbus_message_unref(m);
814 dbus_message_unref(reply);
816 dbus_error_free(&error);
821 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
822 DBusMessage *m = NULL, *reply = NULL;
827 dbus_error_init(&error);
833 return daemon_reload(bus, args, n);
835 for (i = 1; i < n; i++) {
839 if (!(m = dbus_message_new_method_call(
840 "org.freedesktop.systemd1",
841 "/org/freedesktop/systemd1",
842 "org.freedesktop.systemd1.Manager",
844 log_error("Could not allocate message.");
849 if ((r = safe_atou(args[i], &id)) < 0) {
850 log_error("Failed to parse job id: %s", strerror(-r));
854 assert_cc(sizeof(uint32_t) == sizeof(id));
855 if (!dbus_message_append_args(m,
856 DBUS_TYPE_UINT32, &id,
857 DBUS_TYPE_INVALID)) {
858 log_error("Could not append arguments to message.");
863 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
864 log_error("Failed to issue method call: %s", bus_error_message(&error));
869 if (!dbus_message_get_args(reply, &error,
870 DBUS_TYPE_OBJECT_PATH, &path,
871 DBUS_TYPE_INVALID)) {
872 log_error("Failed to parse reply: %s", bus_error_message(&error));
877 dbus_message_unref(m);
878 if (!(m = dbus_message_new_method_call(
879 "org.freedesktop.systemd1",
881 "org.freedesktop.systemd1.Job",
883 log_error("Could not allocate message.");
888 dbus_message_unref(reply);
889 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
890 log_error("Failed to issue method call: %s", bus_error_message(&error));
895 dbus_message_unref(m);
896 dbus_message_unref(reply);
904 dbus_message_unref(m);
907 dbus_message_unref(reply);
909 dbus_error_free(&error);
914 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
915 DBusMessage *m = NULL, *reply = NULL;
916 dbus_bool_t b = FALSE;
917 DBusMessageIter iter, sub;
919 *interface = "org.freedesktop.systemd1.Unit",
920 *property = "NeedDaemonReload",
923 /* We ignore all errors here, since this is used to show a warning only */
925 if (!(m = dbus_message_new_method_call(
926 "org.freedesktop.systemd1",
927 "/org/freedesktop/systemd1",
928 "org.freedesktop.systemd1.Manager",
932 if (!dbus_message_append_args(m,
933 DBUS_TYPE_STRING, &unit,
937 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
940 if (!dbus_message_get_args(reply, NULL,
941 DBUS_TYPE_OBJECT_PATH, &path,
945 dbus_message_unref(m);
946 if (!(m = dbus_message_new_method_call(
947 "org.freedesktop.systemd1",
949 "org.freedesktop.DBus.Properties",
953 if (!dbus_message_append_args(m,
954 DBUS_TYPE_STRING, &interface,
955 DBUS_TYPE_STRING, &property,
956 DBUS_TYPE_INVALID)) {
960 dbus_message_unref(reply);
961 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
964 if (!dbus_message_iter_init(reply, &iter) ||
965 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
968 dbus_message_iter_recurse(&iter, &sub);
970 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
973 dbus_message_iter_get_basic(&sub, &b);
977 dbus_message_unref(m);
980 dbus_message_unref(reply);
985 typedef struct WaitData {
990 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
998 dbus_error_init(&error);
1000 log_debug("Got D-Bus request: %s.%s() on %s",
1001 dbus_message_get_interface(message),
1002 dbus_message_get_member(message),
1003 dbus_message_get_path(message));
1005 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1006 log_error("Warning! D-Bus connection terminated.");
1007 dbus_connection_close(connection);
1009 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1012 dbus_bool_t success = true;
1014 if (!dbus_message_get_args(message, &error,
1015 DBUS_TYPE_UINT32, &id,
1016 DBUS_TYPE_OBJECT_PATH, &path,
1017 DBUS_TYPE_BOOLEAN, &success,
1019 log_error("Failed to parse message: %s", bus_error_message(&error));
1023 if ((p = set_remove(d->set, (char*) path)))
1031 dbus_error_free(&error);
1032 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1035 static int enable_wait_for_jobs(DBusConnection *bus) {
1043 dbus_error_init(&error);
1044 dbus_bus_add_match(bus,
1046 "sender='org.freedesktop.systemd1',"
1047 "interface='org.freedesktop.systemd1.Manager',"
1048 "member='JobRemoved',"
1049 "path='/org/freedesktop/systemd1'",
1052 if (dbus_error_is_set(&error)) {
1053 log_error("Failed to add match: %s", bus_error_message(&error));
1054 dbus_error_free(&error);
1058 /* This is slightly dirty, since we don't undo the match registrations. */
1062 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1073 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1074 log_error("Failed to add filter.");
1079 while (!set_isempty(s) &&
1080 dbus_connection_read_write_dispatch(bus, -1))
1083 if (!arg_quiet && d.failed)
1084 log_error("Job failed, see system logs for details.");
1086 r = d.failed ? -EIO : 0;
1089 /* This is slightly dirty, since we don't undo the filter registration. */
1094 static int start_unit_one(
1095 DBusConnection *bus,
1102 DBusMessage *m = NULL, *reply = NULL;
1111 assert(arg_no_block || s);
1113 if (!(m = dbus_message_new_method_call(
1114 "org.freedesktop.systemd1",
1115 "/org/freedesktop/systemd1",
1116 "org.freedesktop.systemd1.Manager",
1118 log_error("Could not allocate message.");
1123 if (!dbus_message_append_args(m,
1124 DBUS_TYPE_STRING, &name,
1125 DBUS_TYPE_STRING, &mode,
1126 DBUS_TYPE_INVALID)) {
1127 log_error("Could not append arguments to message.");
1132 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1134 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1135 /* There's always a fallback possible for
1136 * legacy actions. */
1141 log_error("Failed to issue method call: %s", bus_error_message(error));
1146 if (!dbus_message_get_args(reply, error,
1147 DBUS_TYPE_OBJECT_PATH, &path,
1148 DBUS_TYPE_INVALID)) {
1149 log_error("Failed to parse reply: %s", bus_error_message(error));
1154 if (need_daemon_reload(bus, name))
1155 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1156 arg_session ? "--session" : "--system");
1158 if (!arg_no_block) {
1161 if (!(p = strdup(path))) {
1162 log_error("Failed to duplicate path.");
1167 if ((r = set_put(s, p)) < 0) {
1169 log_error("Failed to add path to set.");
1178 dbus_message_unref(m);
1181 dbus_message_unref(reply);
1186 static enum action verb_to_action(const char *verb) {
1187 if (streq(verb, "halt"))
1189 else if (streq(verb, "poweroff"))
1190 return ACTION_POWEROFF;
1191 else if (streq(verb, "reboot"))
1192 return ACTION_REBOOT;
1193 else if (streq(verb, "rescue"))
1194 return ACTION_RESCUE;
1195 else if (streq(verb, "emergency"))
1196 return ACTION_EMERGENCY;
1197 else if (streq(verb, "default"))
1198 return ACTION_DEFAULT;
1200 return ACTION_INVALID;
1203 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1205 static const char * const table[_ACTION_MAX] = {
1206 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1207 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1208 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1209 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1210 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1211 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1212 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1213 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1214 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1215 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1220 const char *method, *mode, *one_name;
1224 dbus_error_init(&error);
1228 if (arg_action == ACTION_SYSTEMCTL) {
1230 streq(args[0], "stop") ? "StopUnit" :
1231 streq(args[0], "reload") ? "ReloadUnit" :
1232 streq(args[0], "restart") ? "RestartUnit" :
1233 streq(args[0], "try-restart") ? "TryRestartUnit" :
1234 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1235 streq(args[0], "reload-or-try-restart") ||
1236 streq(args[0], "force-reload") ||
1237 streq(args[0], "condrestart") ? "ReloadOrTryRestartUnit" :
1241 (streq(args[0], "isolate") ||
1242 streq(args[0], "rescue") ||
1243 streq(args[0], "emergency")) ? "isolate" :
1247 one_name = table[verb_to_action(args[0])];
1250 assert(arg_action < ELEMENTSOF(table));
1251 assert(table[arg_action]);
1253 method = "StartUnit";
1255 mode = (arg_action == ACTION_EMERGENCY ||
1256 arg_action == ACTION_RESCUE) ? "isolate" : "replace";
1258 one_name = table[arg_action];
1261 if (!arg_no_block) {
1262 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1263 log_error("Could not watch jobs: %s", strerror(-ret));
1267 if (!(s = set_new(string_hash_func, string_compare_func))) {
1268 log_error("Failed to allocate set.");
1275 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1278 for (i = 1; i < n; i++)
1279 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1280 ret = translate_bus_error_to_exit_status(r, &error);
1281 dbus_error_free(&error);
1286 if ((r = wait_for_jobs(bus, s)) < 0) {
1295 dbus_error_free(&error);
1300 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1306 r = start_unit(bus, args, n);
1309 warn_wall(verb_to_action(args[0]));
1314 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1315 DBusMessage *m = NULL, *reply = NULL;
1317 *interface = "org.freedesktop.systemd1.Unit",
1318 *property = "ActiveState";
1319 int r = 3; /* According to LSB: "program is not running" */
1326 dbus_error_init(&error);
1328 for (i = 1; i < n; i++) {
1329 const char *path = NULL;
1331 DBusMessageIter iter, sub;
1333 if (!(m = dbus_message_new_method_call(
1334 "org.freedesktop.systemd1",
1335 "/org/freedesktop/systemd1",
1336 "org.freedesktop.systemd1.Manager",
1338 log_error("Could not allocate message.");
1343 if (!dbus_message_append_args(m,
1344 DBUS_TYPE_STRING, &args[i],
1345 DBUS_TYPE_INVALID)) {
1346 log_error("Could not append arguments to message.");
1351 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1353 /* Hmm, cannot figure out anything about this unit... */
1357 dbus_error_free(&error);
1361 if (!dbus_message_get_args(reply, &error,
1362 DBUS_TYPE_OBJECT_PATH, &path,
1363 DBUS_TYPE_INVALID)) {
1364 log_error("Failed to parse reply: %s", bus_error_message(&error));
1369 dbus_message_unref(m);
1370 if (!(m = dbus_message_new_method_call(
1371 "org.freedesktop.systemd1",
1373 "org.freedesktop.DBus.Properties",
1375 log_error("Could not allocate message.");
1380 if (!dbus_message_append_args(m,
1381 DBUS_TYPE_STRING, &interface,
1382 DBUS_TYPE_STRING, &property,
1383 DBUS_TYPE_INVALID)) {
1384 log_error("Could not append arguments to message.");
1389 dbus_message_unref(reply);
1390 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1391 log_error("Failed to issue method call: %s", bus_error_message(&error));
1396 if (!dbus_message_iter_init(reply, &iter) ||
1397 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1398 log_error("Failed to parse reply.");
1403 dbus_message_iter_recurse(&iter, &sub);
1405 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1406 log_error("Failed to parse reply.");
1411 dbus_message_iter_get_basic(&sub, &state);
1416 if (streq(state, "active") || streq(state, "reloading"))
1419 dbus_message_unref(m);
1420 dbus_message_unref(reply);
1426 dbus_message_unref(m);
1429 dbus_message_unref(reply);
1431 dbus_error_free(&error);
1436 typedef struct ExecStatusInfo {
1442 usec_t start_timestamp;
1443 usec_t exit_timestamp;
1448 LIST_FIELDS(struct ExecStatusInfo, exec);
1451 static void exec_status_info_free(ExecStatusInfo *i) {
1459 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1460 uint64_t start_timestamp, exit_timestamp;
1461 DBusMessageIter sub2, sub3;
1465 int32_t code, status;
1471 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1474 dbus_message_iter_recurse(sub, &sub2);
1476 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1479 if (!(i->path = strdup(path)))
1482 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1483 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1487 dbus_message_iter_recurse(&sub2, &sub3);
1488 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1489 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1490 dbus_message_iter_next(&sub3);
1495 if (!(i->argv = new0(char*, n+1)))
1499 dbus_message_iter_recurse(&sub2, &sub3);
1500 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1503 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1504 dbus_message_iter_get_basic(&sub3, &s);
1505 dbus_message_iter_next(&sub3);
1507 if (!(i->argv[n++] = strdup(s)))
1511 if (!dbus_message_iter_next(&sub2) ||
1512 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1513 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1514 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1515 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1516 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1517 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1521 i->start_timestamp = (usec_t) start_timestamp;
1522 i->exit_timestamp = (usec_t) exit_timestamp;
1523 i->pid = (pid_t) pid;
1530 typedef struct UnitStatusInfo {
1532 const char *load_state;
1533 const char *active_state;
1534 const char *sub_state;
1536 const char *description;
1539 const char *default_control_group;
1541 usec_t inactive_exit_timestamp;
1542 usec_t active_enter_timestamp;
1543 usec_t active_exit_timestamp;
1544 usec_t inactive_enter_timestamp;
1546 bool need_daemon_reload;
1551 const char *status_text;
1555 usec_t start_timestamp;
1556 usec_t exit_timestamp;
1558 int exit_code, exit_status;
1561 unsigned n_accepted;
1562 unsigned n_connections;
1566 const char *sysfs_path;
1568 /* Mount, Automount */
1574 LIST_HEAD(ExecStatusInfo, exec);
1577 static void print_status_info(UnitStatusInfo *i) {
1579 const char *on, *off, *ss;
1581 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1582 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1586 /* This shows pretty information about a unit. See
1587 * print_property() for a low-level property printer */
1589 printf("%s", strna(i->id));
1591 if (i->description && !streq_ptr(i->id, i->description))
1592 printf(" - %s", i->description);
1596 if (streq_ptr(i->load_state, "failed")) {
1597 on = ansi_highlight(true);
1598 off = ansi_highlight(false);
1603 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1605 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1607 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1609 if (streq_ptr(i->active_state, "failed")) {
1610 on = ansi_highlight(true);
1611 off = ansi_highlight(false);
1612 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1613 on = ansi_highlight_green(true);
1614 off = ansi_highlight_green(false);
1619 printf("\t Active: %s%s (%s)%s",
1621 strna(i->active_state),
1625 printf("\t Active: %s%s%s",
1627 strna(i->active_state),
1630 timestamp = (streq_ptr(i->active_state, "active") ||
1631 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1632 (streq_ptr(i->active_state, "inactive") ||
1633 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1634 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1635 i->active_exit_timestamp;
1637 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1638 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1641 printf(" since [%s; %s]\n", s2, s1);
1643 printf(" since [%s]\n", s2);
1648 printf("\t Device: %s\n", i->sysfs_path);
1650 printf("\t Where: %s\n", i->where);
1652 printf("\t What: %s\n", i->what);
1655 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1657 LIST_FOREACH(exec, p, i->exec) {
1660 /* Only show exited processes here */
1664 t = strv_join(p->argv, " ");
1665 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1668 if (p->code == CLD_EXITED) {
1671 printf("status=%i", p->status);
1673 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1677 printf("signal=%s", signal_to_string(p->status));
1680 if (i->main_pid == p->pid &&
1681 i->start_timestamp == p->start_timestamp &&
1682 i->exit_timestamp == p->start_timestamp)
1683 /* Let's not show this twice */
1686 if (p->pid == i->control_pid)
1690 if (i->main_pid > 0 || i->control_pid > 0) {
1693 if (i->main_pid > 0) {
1694 printf("Main PID: %u", (unsigned) i->main_pid);
1698 get_process_name(i->main_pid, &t);
1703 } else if (i->exit_code > 0) {
1704 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1706 if (i->exit_code == CLD_EXITED) {
1709 printf("status=%i", i->exit_status);
1711 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1715 printf("signal=%s", signal_to_string(i->exit_status));
1720 if (i->main_pid > 0 && i->control_pid > 0)
1723 if (i->control_pid > 0) {
1726 printf(" Control: %u", (unsigned) i->control_pid);
1728 get_process_name(i->control_pid, &t);
1739 printf("\t Status: \"%s\"\n", i->status_text);
1741 if (i->default_control_group) {
1744 printf("\t CGroup: %s\n", i->default_control_group);
1746 if ((c = columns()) > 18)
1751 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1754 if (i->need_daemon_reload)
1755 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1756 ansi_highlight(true),
1757 ansi_highlight(false),
1758 arg_session ? "--session" : "--system");
1761 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1763 switch (dbus_message_iter_get_arg_type(iter)) {
1765 case DBUS_TYPE_STRING: {
1768 dbus_message_iter_get_basic(iter, &s);
1771 if (streq(name, "Id"))
1773 else if (streq(name, "LoadState"))
1775 else if (streq(name, "ActiveState"))
1776 i->active_state = s;
1777 else if (streq(name, "SubState"))
1779 else if (streq(name, "Description"))
1781 else if (streq(name, "FragmentPath"))
1783 else if (streq(name, "SysVPath")) {
1786 } else if (streq(name, "DefaultControlGroup"))
1787 i->default_control_group = s;
1788 else if (streq(name, "StatusText"))
1790 else if (streq(name, "SysFSPath"))
1792 else if (streq(name, "Where"))
1794 else if (streq(name, "What"))
1801 case DBUS_TYPE_BOOLEAN: {
1804 dbus_message_iter_get_basic(iter, &b);
1806 if (streq(name, "Accept"))
1808 else if (streq(name, "NeedDaemonReload"))
1809 i->need_daemon_reload = b;
1814 case DBUS_TYPE_UINT32: {
1817 dbus_message_iter_get_basic(iter, &u);
1819 if (streq(name, "MainPID")) {
1821 i->main_pid = (pid_t) u;
1824 } else if (streq(name, "ControlPID"))
1825 i->control_pid = (pid_t) u;
1826 else if (streq(name, "ExecMainPID")) {
1828 i->main_pid = (pid_t) u;
1829 } else if (streq(name, "NAccepted"))
1831 else if (streq(name, "NConnections"))
1832 i->n_connections = u;
1837 case DBUS_TYPE_INT32: {
1840 dbus_message_iter_get_basic(iter, &j);
1842 if (streq(name, "ExecMainCode"))
1843 i->exit_code = (int) j;
1844 else if (streq(name, "ExecMainStatus"))
1845 i->exit_status = (int) j;
1850 case DBUS_TYPE_UINT64: {
1853 dbus_message_iter_get_basic(iter, &u);
1855 if (streq(name, "ExecMainStartTimestamp"))
1856 i->start_timestamp = (usec_t) u;
1857 else if (streq(name, "ExecMainExitTimestamp"))
1858 i->exit_timestamp = (usec_t) u;
1859 else if (streq(name, "ActiveEnterTimestamp"))
1860 i->active_enter_timestamp = (usec_t) u;
1861 else if (streq(name, "InactiveEnterTimestamp"))
1862 i->inactive_enter_timestamp = (usec_t) u;
1863 else if (streq(name, "InactiveExitTimestamp"))
1864 i->inactive_exit_timestamp = (usec_t) u;
1865 else if (streq(name, "ActiveExitTimestamp"))
1866 i->active_exit_timestamp = (usec_t) u;
1871 case DBUS_TYPE_ARRAY: {
1873 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1874 startswith(name, "Exec")) {
1875 DBusMessageIter sub;
1877 dbus_message_iter_recurse(iter, &sub);
1878 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1879 ExecStatusInfo *info;
1882 if (!(info = new0(ExecStatusInfo, 1)))
1885 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1890 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1892 dbus_message_iter_next(&sub);
1903 static int print_property(const char *name, DBusMessageIter *iter) {
1907 /* This is a low-level property printer, see
1908 * print_status_info() for the nicer output */
1910 if (arg_property && !strv_find(arg_property, name))
1913 switch (dbus_message_iter_get_arg_type(iter)) {
1915 case DBUS_TYPE_STRING: {
1917 dbus_message_iter_get_basic(iter, &s);
1919 if (arg_all || s[0])
1920 printf("%s=%s\n", name, s);
1925 case DBUS_TYPE_BOOLEAN: {
1927 dbus_message_iter_get_basic(iter, &b);
1928 printf("%s=%s\n", name, yes_no(b));
1933 case DBUS_TYPE_UINT64: {
1935 dbus_message_iter_get_basic(iter, &u);
1937 /* Yes, heuristics! But we can change this check
1938 * should it turn out to not be sufficient */
1940 if (strstr(name, "Timestamp")) {
1941 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1943 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1944 printf("%s=%s\n", name, strempty(t));
1945 } else if (strstr(name, "USec")) {
1946 char timespan[FORMAT_TIMESPAN_MAX];
1948 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1950 printf("%s=%llu\n", name, (unsigned long long) u);
1955 case DBUS_TYPE_UINT32: {
1957 dbus_message_iter_get_basic(iter, &u);
1959 if (strstr(name, "UMask") || strstr(name, "Mode"))
1960 printf("%s=%04o\n", name, u);
1962 printf("%s=%u\n", name, (unsigned) u);
1967 case DBUS_TYPE_INT32: {
1969 dbus_message_iter_get_basic(iter, &i);
1971 printf("%s=%i\n", name, (int) i);
1975 case DBUS_TYPE_STRUCT: {
1976 DBusMessageIter sub;
1977 dbus_message_iter_recurse(iter, &sub);
1979 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1982 dbus_message_iter_get_basic(&sub, &u);
1985 printf("%s=%u\n", name, (unsigned) u);
1987 printf("%s=\n", name);
1990 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1993 dbus_message_iter_get_basic(&sub, &s);
1995 if (arg_all || s[0])
1996 printf("%s=%s\n", name, s);
2004 case DBUS_TYPE_ARRAY:
2006 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2007 DBusMessageIter sub;
2010 dbus_message_iter_recurse(iter, &sub);
2012 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2013 printf("%s=", name);
2015 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2018 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2019 dbus_message_iter_get_basic(&sub, &s);
2020 printf("%s%s", space ? " " : "", s);
2023 dbus_message_iter_next(&sub);
2031 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2032 DBusMessageIter sub;
2034 dbus_message_iter_recurse(iter, &sub);
2036 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2037 printf("%s=", name);
2039 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2042 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2043 dbus_message_iter_get_basic(&sub, &u);
2046 dbus_message_iter_next(&sub);
2054 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2055 DBusMessageIter sub, sub2;
2057 dbus_message_iter_recurse(iter, &sub);
2058 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2059 const char *type, *path;
2061 dbus_message_iter_recurse(&sub, &sub2);
2063 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2064 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2065 printf("%s=%s\n", type, path);
2067 dbus_message_iter_next(&sub);
2072 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2073 DBusMessageIter sub, sub2;
2075 dbus_message_iter_recurse(iter, &sub);
2076 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2078 uint64_t value, next_elapse;
2080 dbus_message_iter_recurse(&sub, &sub2);
2082 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2083 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2084 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2085 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2087 printf("%s={ value=%s ; next_elapse=%s }\n",
2089 format_timespan(timespan1, sizeof(timespan1), value),
2090 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2093 dbus_message_iter_next(&sub);
2098 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2099 DBusMessageIter sub;
2101 dbus_message_iter_recurse(iter, &sub);
2102 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2103 ExecStatusInfo info;
2106 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2107 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2110 t = strv_join(info.argv, " ");
2112 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2116 yes_no(info.ignore),
2117 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2118 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2119 (unsigned) info. pid,
2120 sigchld_code_to_string(info.code),
2122 info.code == CLD_EXITED ? "" : "/",
2123 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2129 strv_free(info.argv);
2131 dbus_message_iter_next(&sub);
2141 printf("%s=[unprintable]\n", name);
2146 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2147 DBusMessage *m = NULL, *reply = NULL;
2148 const char *interface = "";
2151 DBusMessageIter iter, sub, sub2, sub3;
2152 UnitStatusInfo info;
2160 dbus_error_init(&error);
2162 if (!(m = dbus_message_new_method_call(
2163 "org.freedesktop.systemd1",
2165 "org.freedesktop.DBus.Properties",
2167 log_error("Could not allocate message.");
2172 if (!dbus_message_append_args(m,
2173 DBUS_TYPE_STRING, &interface,
2174 DBUS_TYPE_INVALID)) {
2175 log_error("Could not append arguments to message.");
2180 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2181 log_error("Failed to issue method call: %s", bus_error_message(&error));
2186 if (!dbus_message_iter_init(reply, &iter) ||
2187 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2188 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2189 log_error("Failed to parse reply.");
2194 dbus_message_iter_recurse(&iter, &sub);
2201 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2204 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2205 log_error("Failed to parse reply.");
2210 dbus_message_iter_recurse(&sub, &sub2);
2212 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2213 log_error("Failed to parse reply.");
2218 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2219 log_error("Failed to parse reply.");
2224 dbus_message_iter_recurse(&sub2, &sub3);
2226 if (show_properties)
2227 r = print_property(name, &sub3);
2229 r = status_property(name, &sub3, &info);
2232 log_error("Failed to parse reply.");
2237 dbus_message_iter_next(&sub);
2242 if (!show_properties)
2243 print_status_info(&info);
2245 if (!streq_ptr(info.active_state, "active") &&
2246 !streq_ptr(info.active_state, "reloading"))
2247 /* According to LSB: "program not running" */
2250 while ((p = info.exec)) {
2251 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2252 exec_status_info_free(p);
2257 dbus_message_unref(m);
2260 dbus_message_unref(reply);
2262 dbus_error_free(&error);
2267 static int show(DBusConnection *bus, char **args, unsigned n) {
2268 DBusMessage *m = NULL, *reply = NULL;
2272 bool show_properties, new_line = false;
2277 dbus_error_init(&error);
2279 show_properties = !streq(args[0], "status");
2281 if (show_properties && n <= 1) {
2282 /* If not argument is specified inspect the manager
2285 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2289 for (i = 1; i < n; i++) {
2290 const char *path = NULL;
2293 if (safe_atou32(args[i], &id) < 0) {
2295 /* Interpret as unit name */
2297 if (!(m = dbus_message_new_method_call(
2298 "org.freedesktop.systemd1",
2299 "/org/freedesktop/systemd1",
2300 "org.freedesktop.systemd1.Manager",
2302 log_error("Could not allocate message.");
2307 if (!dbus_message_append_args(m,
2308 DBUS_TYPE_STRING, &args[i],
2309 DBUS_TYPE_INVALID)) {
2310 log_error("Could not append arguments to message.");
2315 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2317 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2318 log_error("Failed to issue method call: %s", bus_error_message(&error));
2323 dbus_error_free(&error);
2325 dbus_message_unref(m);
2326 if (!(m = dbus_message_new_method_call(
2327 "org.freedesktop.systemd1",
2328 "/org/freedesktop/systemd1",
2329 "org.freedesktop.systemd1.Manager",
2331 log_error("Could not allocate message.");
2336 if (!dbus_message_append_args(m,
2337 DBUS_TYPE_STRING, &args[i],
2338 DBUS_TYPE_INVALID)) {
2339 log_error("Could not append arguments to message.");
2344 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2345 log_error("Failed to issue method call: %s", bus_error_message(&error));
2347 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2348 ret = 4; /* According to LSB: "program or service status is unknown" */
2355 } else if (show_properties) {
2357 /* Interpret as job id */
2359 if (!(m = dbus_message_new_method_call(
2360 "org.freedesktop.systemd1",
2361 "/org/freedesktop/systemd1",
2362 "org.freedesktop.systemd1.Manager",
2364 log_error("Could not allocate message.");
2369 if (!dbus_message_append_args(m,
2370 DBUS_TYPE_UINT32, &id,
2371 DBUS_TYPE_INVALID)) {
2372 log_error("Could not append arguments to message.");
2377 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2378 log_error("Failed to issue method call: %s", bus_error_message(&error));
2384 /* Interpret as PID */
2386 if (!(m = dbus_message_new_method_call(
2387 "org.freedesktop.systemd1",
2388 "/org/freedesktop/systemd1",
2389 "org.freedesktop.systemd1.Manager",
2391 log_error("Could not allocate message.");
2396 if (!dbus_message_append_args(m,
2397 DBUS_TYPE_UINT32, &id,
2398 DBUS_TYPE_INVALID)) {
2399 log_error("Could not append arguments to message.");
2404 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2405 log_error("Failed to issue method call: %s", bus_error_message(&error));
2411 if (!dbus_message_get_args(reply, &error,
2412 DBUS_TYPE_OBJECT_PATH, &path,
2413 DBUS_TYPE_INVALID)) {
2414 log_error("Failed to parse reply: %s", bus_error_message(&error));
2419 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2422 dbus_message_unref(m);
2423 dbus_message_unref(reply);
2429 dbus_message_unref(m);
2432 dbus_message_unref(reply);
2434 dbus_error_free(&error);
2439 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2441 DBusMessage *m = NULL, *reply = NULL;
2446 dbus_error_init(&error);
2448 log_debug("Got D-Bus request: %s.%s() on %s",
2449 dbus_message_get_interface(message),
2450 dbus_message_get_member(message),
2451 dbus_message_get_path(message));
2453 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2454 log_error("Warning! D-Bus connection terminated.");
2455 dbus_connection_close(connection);
2457 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2458 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2459 const char *id, *path;
2461 if (!dbus_message_get_args(message, &error,
2462 DBUS_TYPE_STRING, &id,
2463 DBUS_TYPE_OBJECT_PATH, &path,
2465 log_error("Failed to parse message: %s", bus_error_message(&error));
2466 else if (streq(dbus_message_get_member(message), "UnitNew"))
2467 printf("Unit %s added.\n", id);
2469 printf("Unit %s removed.\n", id);
2471 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2472 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2476 if (!dbus_message_get_args(message, &error,
2477 DBUS_TYPE_UINT32, &id,
2478 DBUS_TYPE_OBJECT_PATH, &path,
2480 log_error("Failed to parse message: %s", bus_error_message(&error));
2481 else if (streq(dbus_message_get_member(message), "JobNew"))
2482 printf("Job %u added.\n", id);
2484 printf("Job %u removed.\n", id);
2487 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2489 const char *path, *interface, *property = "Id";
2490 DBusMessageIter iter, sub;
2492 path = dbus_message_get_path(message);
2494 if (!dbus_message_get_args(message, &error,
2495 DBUS_TYPE_STRING, &interface,
2496 DBUS_TYPE_INVALID)) {
2497 log_error("Failed to parse message: %s", bus_error_message(&error));
2501 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2502 !streq(interface, "org.freedesktop.systemd1.Unit"))
2505 if (!(m = dbus_message_new_method_call(
2506 "org.freedesktop.systemd1",
2508 "org.freedesktop.DBus.Properties",
2510 log_error("Could not allocate message.");
2514 if (!dbus_message_append_args(m,
2515 DBUS_TYPE_STRING, &interface,
2516 DBUS_TYPE_STRING, &property,
2517 DBUS_TYPE_INVALID)) {
2518 log_error("Could not append arguments to message.");
2522 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2523 log_error("Failed to issue method call: %s", bus_error_message(&error));
2527 if (!dbus_message_iter_init(reply, &iter) ||
2528 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2529 log_error("Failed to parse reply.");
2533 dbus_message_iter_recurse(&iter, &sub);
2535 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2538 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2539 log_error("Failed to parse reply.");
2543 dbus_message_iter_get_basic(&sub, &id);
2544 printf("Unit %s changed.\n", id);
2548 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2549 log_error("Failed to parse reply.");
2553 dbus_message_iter_get_basic(&sub, &id);
2554 printf("Job %u changed.\n", id);
2560 dbus_message_unref(m);
2563 dbus_message_unref(reply);
2565 dbus_error_free(&error);
2566 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2570 dbus_message_unref(m);
2573 dbus_message_unref(reply);
2575 dbus_error_free(&error);
2576 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2579 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2580 DBusMessage *m = NULL, *reply = NULL;
2584 dbus_error_init(&error);
2587 dbus_bus_add_match(bus,
2589 "sender='org.freedesktop.systemd1',"
2590 "interface='org.freedesktop.systemd1.Manager',"
2591 "path='/org/freedesktop/systemd1'",
2594 if (dbus_error_is_set(&error)) {
2595 log_error("Failed to add match: %s", bus_error_message(&error));
2600 dbus_bus_add_match(bus,
2602 "sender='org.freedesktop.systemd1',"
2603 "interface='org.freedesktop.DBus.Properties',"
2604 "member='PropertiesChanged'",
2607 if (dbus_error_is_set(&error)) {
2608 log_error("Failed to add match: %s", bus_error_message(&error));
2614 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2615 log_error("Failed to add filter.");
2620 if (!(m = dbus_message_new_method_call(
2621 "org.freedesktop.systemd1",
2622 "/org/freedesktop/systemd1",
2623 "org.freedesktop.systemd1.Manager",
2625 log_error("Could not allocate message.");
2630 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2631 log_error("Failed to issue method call: %s", bus_error_message(&error));
2636 while (dbus_connection_read_write_dispatch(bus, -1))
2643 /* This is slightly dirty, since we don't undo the filter or the matches. */
2646 dbus_message_unref(m);
2649 dbus_message_unref(reply);
2651 dbus_error_free(&error);
2656 static int dump(DBusConnection *bus, char **args, unsigned n) {
2657 DBusMessage *m = NULL, *reply = NULL;
2662 dbus_error_init(&error);
2664 if (!(m = dbus_message_new_method_call(
2665 "org.freedesktop.systemd1",
2666 "/org/freedesktop/systemd1",
2667 "org.freedesktop.systemd1.Manager",
2669 log_error("Could not allocate message.");
2673 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2674 log_error("Failed to issue method call: %s", bus_error_message(&error));
2679 if (!dbus_message_get_args(reply, &error,
2680 DBUS_TYPE_STRING, &text,
2681 DBUS_TYPE_INVALID)) {
2682 log_error("Failed to parse reply: %s", bus_error_message(&error));
2687 fputs(text, stdout);
2693 dbus_message_unref(m);
2696 dbus_message_unref(reply);
2698 dbus_error_free(&error);
2703 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2704 DBusMessage *m = NULL, *reply = NULL;
2707 const char *name = "", *path, *id;
2708 dbus_bool_t cleanup = FALSE;
2709 DBusMessageIter iter, sub;
2711 *interface = "org.freedesktop.systemd1.Unit",
2714 dbus_error_init(&error);
2716 if (!(m = dbus_message_new_method_call(
2717 "org.freedesktop.systemd1",
2718 "/org/freedesktop/systemd1",
2719 "org.freedesktop.systemd1.Manager",
2720 "CreateSnapshot"))) {
2721 log_error("Could not allocate message.");
2728 if (!dbus_message_append_args(m,
2729 DBUS_TYPE_STRING, &name,
2730 DBUS_TYPE_BOOLEAN, &cleanup,
2731 DBUS_TYPE_INVALID)) {
2732 log_error("Could not append arguments to message.");
2737 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2738 log_error("Failed to issue method call: %s", bus_error_message(&error));
2743 if (!dbus_message_get_args(reply, &error,
2744 DBUS_TYPE_OBJECT_PATH, &path,
2745 DBUS_TYPE_INVALID)) {
2746 log_error("Failed to parse reply: %s", bus_error_message(&error));
2751 dbus_message_unref(m);
2752 if (!(m = dbus_message_new_method_call(
2753 "org.freedesktop.systemd1",
2755 "org.freedesktop.DBus.Properties",
2757 log_error("Could not allocate message.");
2761 if (!dbus_message_append_args(m,
2762 DBUS_TYPE_STRING, &interface,
2763 DBUS_TYPE_STRING, &property,
2764 DBUS_TYPE_INVALID)) {
2765 log_error("Could not append arguments to message.");
2770 dbus_message_unref(reply);
2771 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2772 log_error("Failed to issue method call: %s", bus_error_message(&error));
2777 if (!dbus_message_iter_init(reply, &iter) ||
2778 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2779 log_error("Failed to parse reply.");
2784 dbus_message_iter_recurse(&iter, &sub);
2786 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2787 log_error("Failed to parse reply.");
2792 dbus_message_iter_get_basic(&sub, &id);
2800 dbus_message_unref(m);
2803 dbus_message_unref(reply);
2805 dbus_error_free(&error);
2810 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2811 DBusMessage *m = NULL, *reply = NULL;
2819 dbus_error_init(&error);
2821 for (i = 1; i < n; i++) {
2822 const char *path = NULL;
2824 if (!(m = dbus_message_new_method_call(
2825 "org.freedesktop.systemd1",
2826 "/org/freedesktop/systemd1",
2827 "org.freedesktop.systemd1.Manager",
2829 log_error("Could not allocate message.");
2834 if (!dbus_message_append_args(m,
2835 DBUS_TYPE_STRING, &args[i],
2836 DBUS_TYPE_INVALID)) {
2837 log_error("Could not append arguments to message.");
2842 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2843 log_error("Failed to issue method call: %s", bus_error_message(&error));
2848 if (!dbus_message_get_args(reply, &error,
2849 DBUS_TYPE_OBJECT_PATH, &path,
2850 DBUS_TYPE_INVALID)) {
2851 log_error("Failed to parse reply: %s", bus_error_message(&error));
2856 dbus_message_unref(m);
2857 if (!(m = dbus_message_new_method_call(
2858 "org.freedesktop.systemd1",
2860 "org.freedesktop.systemd1.Snapshot",
2862 log_error("Could not allocate message.");
2867 dbus_message_unref(reply);
2868 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2869 log_error("Failed to issue method call: %s", bus_error_message(&error));
2874 dbus_message_unref(m);
2875 dbus_message_unref(reply);
2883 dbus_message_unref(m);
2886 dbus_message_unref(reply);
2888 dbus_error_free(&error);
2893 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2894 DBusMessage *m = NULL, *reply = NULL;
2899 dbus_error_init(&error);
2901 if (arg_action == ACTION_RELOAD)
2903 else if (arg_action == ACTION_REEXEC)
2904 method = "Reexecute";
2906 assert(arg_action == ACTION_SYSTEMCTL);
2909 streq(args[0], "clear-jobs") ||
2910 streq(args[0], "cancel") ? "ClearJobs" :
2911 streq(args[0], "daemon-reexec") ? "Reexecute" :
2912 streq(args[0], "reset-failed") ? "ResetFailed" :
2913 streq(args[0], "daemon-exit") ? "Exit" :
2917 if (!(m = dbus_message_new_method_call(
2918 "org.freedesktop.systemd1",
2919 "/org/freedesktop/systemd1",
2920 "org.freedesktop.systemd1.Manager",
2922 log_error("Could not allocate message.");
2926 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2928 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2929 /* There's always a fallback possible for
2930 * legacy actions. */
2935 log_error("Failed to issue method call: %s", bus_error_message(&error));
2944 dbus_message_unref(m);
2947 dbus_message_unref(reply);
2949 dbus_error_free(&error);
2954 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
2955 DBusMessage *m = NULL, *reply = NULL;
2961 dbus_error_init(&error);
2964 return daemon_reload(bus, args, n);
2966 for (i = 1; i < n; i++) {
2968 if (!(m = dbus_message_new_method_call(
2969 "org.freedesktop.systemd1",
2970 "/org/freedesktop/systemd1",
2971 "org.freedesktop.systemd1.Manager",
2972 "ResetFailedUnit"))) {
2973 log_error("Could not allocate message.");
2978 if (!dbus_message_append_args(m,
2979 DBUS_TYPE_STRING, args + i,
2980 DBUS_TYPE_INVALID)) {
2981 log_error("Could not append arguments to message.");
2986 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2987 log_error("Failed to issue method call: %s", bus_error_message(&error));
2992 dbus_message_unref(m);
2993 dbus_message_unref(reply);
3001 dbus_message_unref(m);
3004 dbus_message_unref(reply);
3006 dbus_error_free(&error);
3011 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3012 DBusMessage *m = NULL, *reply = NULL;
3014 DBusMessageIter iter, sub, sub2;
3017 *interface = "org.freedesktop.systemd1.Manager",
3018 *property = "Environment";
3020 dbus_error_init(&error);
3022 if (!(m = dbus_message_new_method_call(
3023 "org.freedesktop.systemd1",
3024 "/org/freedesktop/systemd1",
3025 "org.freedesktop.DBus.Properties",
3027 log_error("Could not allocate message.");
3031 if (!dbus_message_append_args(m,
3032 DBUS_TYPE_STRING, &interface,
3033 DBUS_TYPE_STRING, &property,
3034 DBUS_TYPE_INVALID)) {
3035 log_error("Could not append arguments to message.");
3040 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3041 log_error("Failed to issue method call: %s", bus_error_message(&error));
3046 if (!dbus_message_iter_init(reply, &iter) ||
3047 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3048 log_error("Failed to parse reply.");
3053 dbus_message_iter_recurse(&iter, &sub);
3055 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3056 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3057 log_error("Failed to parse reply.");
3062 dbus_message_iter_recurse(&sub, &sub2);
3064 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3067 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3068 log_error("Failed to parse reply.");
3073 dbus_message_iter_get_basic(&sub2, &text);
3074 printf("%s\n", text);
3076 dbus_message_iter_next(&sub2);
3083 dbus_message_unref(m);
3086 dbus_message_unref(reply);
3088 dbus_error_free(&error);
3093 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3094 DBusMessage *m = NULL, *reply = NULL;
3098 DBusMessageIter iter, sub;
3101 dbus_error_init(&error);
3103 method = streq(args[0], "set-environment")
3105 : "UnsetEnvironment";
3107 if (!(m = dbus_message_new_method_call(
3108 "org.freedesktop.systemd1",
3109 "/org/freedesktop/systemd1",
3110 "org.freedesktop.systemd1.Manager",
3113 log_error("Could not allocate message.");
3117 dbus_message_iter_init_append(m, &iter);
3119 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3120 log_error("Could not append arguments to message.");
3125 for (i = 1; i < n; i++)
3126 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3127 log_error("Could not append arguments to message.");
3132 if (!dbus_message_iter_close_container(&iter, &sub)) {
3133 log_error("Could not append arguments to message.");
3138 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3139 log_error("Failed to issue method call: %s", bus_error_message(&error));
3148 dbus_message_unref(m);
3151 dbus_message_unref(reply);
3153 dbus_error_free(&error);
3166 static Hashmap *will_install = NULL, *have_installed = NULL;
3167 static Set *remove_symlinks_to = NULL;
3169 static void install_info_free(InstallInfo *i) {
3174 strv_free(i->aliases);
3175 strv_free(i->wanted_by);
3179 static void install_info_hashmap_free(Hashmap *m) {
3182 while ((i = hashmap_steal_first(m)))
3183 install_info_free(i);
3188 static bool unit_name_valid(const char *name) {
3190 /* This is a minimal version of unit_name_valid() from
3196 if (ignore_file(name))
3202 static int install_info_add(const char *name) {
3206 assert(will_install);
3208 if (!unit_name_valid(name))
3211 if (hashmap_get(have_installed, name) ||
3212 hashmap_get(will_install, name))
3215 if (!(i = new0(InstallInfo, 1))) {
3220 if (!(i->name = strdup(name))) {
3225 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3232 install_info_free(i);
3237 static int config_parse_also(
3238 const char *filename,
3240 const char *section,
3254 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3258 if (!(n = strndup(w, l)))
3261 r = install_info_add(n);
3271 static int mark_symlink_for_removal(const char *p) {
3276 assert(path_is_absolute(p));
3278 if (!remove_symlinks_to)
3281 if (!(n = strdup(p)))
3284 path_kill_slashes(n);
3286 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3288 return r == -EEXIST ? 0 : r;
3294 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3303 if (!(d = fdopendir(fd))) {
3304 close_nointr_nofail(fd);
3310 while ((de = readdir(d))) {
3311 bool is_dir = false, is_link = false;
3313 if (ignore_file(de->d_name))
3316 if (de->d_type == DT_LNK)
3318 else if (de->d_type == DT_DIR)
3320 else if (de->d_type == DT_UNKNOWN) {
3323 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3324 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3331 is_link = S_ISLNK(st.st_mode);
3332 is_dir = S_ISDIR(st.st_mode);
3340 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3341 log_error("Failed to open %s/%s: %m", root, de->d_name);
3348 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3349 log_error("Failed to allocate directory string.");
3350 close_nointr_nofail(nfd);
3355 /* This will close nfd, regardless whether it succeeds or not */
3356 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3362 } else if (is_link) {
3366 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3367 log_error("Failed to allocate symlink string.");
3372 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3373 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3381 if ((c = canonicalize_file_name(dest))) {
3382 /* This might fail if the destination
3383 * is already removed */
3389 path_kill_slashes(dest);
3390 if (set_get(remove_symlinks_to, dest)) {
3393 log_info("rm '%s'", p);
3395 if (unlink(p) < 0) {
3396 log_error("Cannot unlink symlink %s: %m", p);
3401 rmdir_parents(p, config_path);
3402 path_kill_slashes(p);
3404 if (!set_get(remove_symlinks_to, p)) {
3406 if ((r = mark_symlink_for_removal(p)) < 0) {
3425 static int remove_marked_symlinks(const char *config_path) {
3429 assert(config_path);
3431 if (set_size(remove_symlinks_to) <= 0)
3434 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3441 if ((cfd = dup(fd)) < 0) {
3446 /* This takes possession of cfd and closes it */
3447 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3453 close_nointr_nofail(fd);
3458 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3465 if (streq(verb, "enable")) {
3468 mkdir_parents(new_path, 0755);
3470 if (symlink(old_path, new_path) >= 0) {
3473 log_info("ln -s '%s' '%s'", old_path, new_path);
3478 if (errno != EEXIST) {
3479 log_error("Cannot link %s to %s: %m", old_path, new_path);
3483 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3485 if (errno == EINVAL) {
3486 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3490 log_error("readlink() failed: %s", strerror(-r));
3494 if (streq(dest, old_path)) {
3500 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3509 log_info("ln -s '%s' '%s'", old_path, new_path);
3511 if (symlink(old_path, new_path) >= 0)
3514 log_error("Cannot link %s to %s: %m", old_path, new_path);
3517 } else if (streq(verb, "disable")) {
3520 if ((r = mark_symlink_for_removal(old_path)) < 0)
3523 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3524 if (errno == ENOENT)
3527 if (errno == EINVAL) {
3528 log_warning("File %s not a symlink, ignoring.", old_path);
3532 log_error("readlink() failed: %s", strerror(-r));
3536 if (!streq(dest, old_path)) {
3537 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3544 if ((r = mark_symlink_for_removal(new_path)) < 0)
3548 log_info("rm '%s'", new_path);
3550 if (unlink(new_path) >= 0)
3553 log_error("Cannot unlink %s: %m", new_path);
3556 } else if (streq(verb, "is-enabled")) {
3559 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3561 if (errno == ENOENT || errno == EINVAL)
3564 log_error("readlink() failed: %s", strerror(-r));
3568 if (streq(dest, old_path)) {
3576 assert_not_reached("Unknown action.");
3579 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3581 char *alias_path = NULL;
3586 assert(config_path);
3588 STRV_FOREACH(s, i->aliases) {
3590 if (!unit_name_valid(*s)) {
3591 log_error("Invalid name %s.", *s);
3597 if (!(alias_path = path_make_absolute(*s, config_path))) {
3598 log_error("Out of memory");
3603 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3606 if (streq(verb, "disable"))
3607 rmdir_parents(alias_path, config_path);
3618 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3620 char *alias_path = NULL;
3625 assert(config_path);
3627 STRV_FOREACH(s, i->wanted_by) {
3628 if (!unit_name_valid(*s)) {
3629 log_error("Invalid name %s.", *s);
3637 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
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);
3658 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3660 const ConfigItem items[] = {
3661 { "Alias", config_parse_strv, &i->aliases, "Install" },
3662 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3663 { "Also", config_parse_also, NULL, "Install" },
3665 { NULL, NULL, NULL, NULL }
3669 char *filename = NULL;
3676 STRV_FOREACH(p, paths->unit_path) {
3679 if (!(filename = path_make_absolute(i->name, *p))) {
3680 log_error("Out of memory");
3684 /* Ensure that we don't follow symlinks */
3685 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3686 if ((f = fdopen(fd, "re")))
3689 if (errno == ELOOP) {
3690 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3695 if (errno != ENOENT) {
3696 log_error("Failed to open %s: %m", filename);
3706 log_error("Couldn't find %s.", i->name);
3712 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3719 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3722 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3725 if ((r = mark_symlink_for_removal(filename)) < 0)
3728 if ((r = remove_marked_symlinks(config_path)) < 0)
3734 static char *get_config_path(void) {
3736 if (arg_session && arg_global)
3737 return strdup(SESSION_CONFIG_UNIT_PATH);
3742 if (session_config_home(&p) < 0)
3748 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3751 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3755 char *config_path = NULL;
3758 const char *verb = args[0];
3760 dbus_error_init(&error);
3763 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3764 log_error("Failed to determine lookup paths: %s", strerror(-r));
3768 if (!(config_path = get_config_path())) {
3769 log_error("Failed to determine config path");
3774 will_install = hashmap_new(string_hash_func, string_compare_func);
3775 have_installed = hashmap_new(string_hash_func, string_compare_func);
3777 if (!will_install || !have_installed) {
3778 log_error("Failed to allocate unit sets.");
3783 if (!arg_defaults && streq(verb, "disable"))
3784 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3785 log_error("Failed to allocate symlink sets.");
3790 for (j = 1; j < n; j++)
3791 if ((r = install_info_add(args[j])) < 0)
3794 while ((i = hashmap_first(will_install))) {
3797 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3799 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3807 /* In test mode and found something */
3813 if (streq(verb, "is-enabled"))
3814 r = r > 0 ? 0 : -ENOENT;
3816 /* Don't try to reload anything if the user asked us to not do this */
3818 /* Don't try to reload anything when updating a unit globally */
3820 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3821 (arg_session || sd_booted() > 0) &&
3822 /* Don't try to reload anything if we are running in a chroot environment */
3823 (arg_session || running_in_chroot() <= 0) ) {
3826 if ((q = daemon_reload(bus, args, n)) < 0)
3831 install_info_hashmap_free(will_install);
3832 install_info_hashmap_free(have_installed);
3834 set_free_free(remove_symlinks_to);
3836 lookup_paths_free(&paths);
3843 static int systemctl_help(void) {
3845 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3846 "Send control commands to or query the systemd manager.\n\n"
3847 " -h --help Show this help\n"
3848 " -t --type=TYPE List only units of a particular type\n"
3849 " -p --property=NAME Show only properties by this name\n"
3850 " -a --all Show all units/properties, including dead/empty ones\n"
3851 " --full Don't ellipsize unit names on output\n"
3852 " --fail When queueing a new job, fail if conflicting jobs are\n"
3854 " -q --quiet Suppress output\n"
3855 " --no-block Do not wait until operation finished\n"
3856 " --system Connect to system bus\n"
3857 " --session Connect to session bus\n"
3858 " --order When generating graph for dot, show only order\n"
3859 " --require When generating graph for dot, show only requirement\n"
3860 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3861 " --global Enable/disable unit files globally\n"
3862 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3864 " --force When enabling unit files, override existing symlinks\n"
3865 " --defaults When disabling unit files, remove default symlinks only\n\n"
3867 " list-units List units\n"
3868 " start [NAME...] Start (activate) one or more units\n"
3869 " stop [NAME...] Stop (deactivate) one or more units\n"
3870 " reload [NAME...] Reload one or more units\n"
3871 " restart [NAME...] Start or restart one or more units\n"
3872 " try-restart [NAME...] Restart one or more units if active\n"
3873 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3874 " otherwise start or restart\n"
3875 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3876 " otherwise restart if active\n"
3877 " isolate [NAME] Start one unit and stop all others\n"
3878 " is-active [NAME...] Check whether units are active\n"
3879 " status [NAME...|PID...] Show runtime status of one or more units\n"
3880 " show [NAME...|JOB...] Show properties of one or more\n"
3881 " units/jobs or the manager\n"
3882 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3884 " enable [NAME...] Enable one or more unit files\n"
3885 " disable [NAME...] Disable one or more unit files\n"
3886 " is-enabled [NAME...] Check whether unit files are enabled\n"
3887 " load [NAME...] Load one or more units\n"
3888 " list-jobs List jobs\n"
3889 " cancel [JOB...] Cancel all, one, or more jobs\n"
3890 " monitor Monitor unit/job changes\n"
3891 " dump Dump server status\n"
3892 " dot Dump dependency graph for dot(1)\n"
3893 " snapshot [NAME] Create a snapshot\n"
3894 " delete [NAME...] Remove one or more snapshots\n"
3895 " daemon-reload Reload systemd manager configuration\n"
3896 " daemon-reexec Reexecute systemd manager\n"
3897 " daemon-exit Ask the systemd manager to quit\n"
3898 " show-environment Dump environment\n"
3899 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3900 " unset-environment [NAME...] Unset one or more environment variables\n"
3901 " halt Shut down and halt the system\n"
3902 " poweroff Shut down and power-off the system\n"
3903 " reboot Shut down and reboot the system\n"
3904 " rescue Enter system rescue mode\n"
3905 " emergency Enter system emergency mode\n"
3906 " default Enter system default mode\n",
3907 program_invocation_short_name);
3912 static int halt_help(void) {
3914 printf("%s [OPTIONS...]\n\n"
3915 "%s the system.\n\n"
3916 " --help Show this help\n"
3917 " --halt Halt the machine\n"
3918 " -p --poweroff Switch off the machine\n"
3919 " --reboot Reboot the machine\n"
3920 " -f --force Force immediate halt/power-off/reboot\n"
3921 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3922 " -d --no-wtmp Don't write wtmp record\n"
3923 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3924 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3925 program_invocation_short_name,
3926 arg_action == ACTION_REBOOT ? "Reboot" :
3927 arg_action == ACTION_POWEROFF ? "Power off" :
3933 static int shutdown_help(void) {
3935 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3936 "Shut down the system.\n\n"
3937 " --help Show this help\n"
3938 " -H --halt Halt the machine\n"
3939 " -P --poweroff Power-off the machine\n"
3940 " -r --reboot Reboot the machine\n"
3941 " -h Equivalent to --poweroff, overriden by --halt\n"
3942 " -k Don't halt/power-off/reboot, just send warnings\n"
3943 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3944 " -c Cancel a pending shutdown\n",
3945 program_invocation_short_name);
3950 static int telinit_help(void) {
3952 printf("%s [OPTIONS...] {COMMAND}\n\n"
3953 "Send control commands to the init daemon.\n\n"
3954 " --help Show this help\n"
3955 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3957 " 0 Power-off the machine\n"
3958 " 6 Reboot the machine\n"
3959 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3960 " 1, s, S Enter rescue mode\n"
3961 " q, Q Reload init daemon configuration\n"
3962 " u, U Reexecute init daemon\n",
3963 program_invocation_short_name);
3968 static int runlevel_help(void) {
3970 printf("%s [OPTIONS...]\n\n"
3971 "Prints the previous and current runlevel of the init system.\n\n"
3972 " --help Show this help\n",
3973 program_invocation_short_name);
3978 static int systemctl_parse_argv(int argc, char *argv[]) {
3995 static const struct option options[] = {
3996 { "help", no_argument, NULL, 'h' },
3997 { "type", required_argument, NULL, 't' },
3998 { "property", required_argument, NULL, 'p' },
3999 { "all", no_argument, NULL, 'a' },
4000 { "full", no_argument, NULL, ARG_FULL },
4001 { "fail", no_argument, NULL, ARG_FAIL },
4002 { "session", no_argument, NULL, ARG_SESSION },
4003 { "system", no_argument, NULL, ARG_SYSTEM },
4004 { "global", no_argument, NULL, ARG_GLOBAL },
4005 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4006 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4007 { "quiet", no_argument, NULL, 'q' },
4008 { "order", no_argument, NULL, ARG_ORDER },
4009 { "require", no_argument, NULL, ARG_REQUIRE },
4010 { "force", no_argument, NULL, ARG_FORCE },
4011 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4012 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4013 { NULL, 0, NULL, 0 }
4021 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4036 if (!(l = strv_append(arg_property, optarg)))
4039 strv_free(arg_property);
4042 /* If the user asked for a particular
4043 * property, show it to him, even if it is
4062 arg_session = false;
4066 arg_no_block = true;
4074 arg_dot = DOT_ORDER;
4078 arg_dot = DOT_REQUIRE;
4094 arg_no_reload = true;
4103 arg_defaults = true;
4110 log_error("Unknown option code %c", c);
4118 static int halt_parse_argv(int argc, char *argv[]) {
4127 static const struct option options[] = {
4128 { "help", no_argument, NULL, ARG_HELP },
4129 { "halt", no_argument, NULL, ARG_HALT },
4130 { "poweroff", no_argument, NULL, 'p' },
4131 { "reboot", no_argument, NULL, ARG_REBOOT },
4132 { "force", no_argument, NULL, 'f' },
4133 { "wtmp-only", no_argument, NULL, 'w' },
4134 { "no-wtmp", no_argument, NULL, 'd' },
4135 { "no-sync", no_argument, NULL, 'n' },
4136 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4137 { NULL, 0, NULL, 0 }
4145 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4146 if (runlevel == '0' || runlevel == '6')
4147 arg_immediate = true;
4149 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4157 arg_action = ACTION_HALT;
4161 if (arg_action != ACTION_REBOOT)
4162 arg_action = ACTION_POWEROFF;
4166 arg_action = ACTION_REBOOT;
4170 arg_immediate = true;
4191 /* Compatibility nops */
4198 log_error("Unknown option code %c", c);
4203 if (optind < argc) {
4204 log_error("Too many arguments.");
4211 static int parse_time_spec(const char *t, usec_t *_u) {
4215 if (streq(t, "now"))
4217 else if (t[0] == '+') {
4220 if (safe_atou64(t + 1, &u) < 0)
4223 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4232 hour = strtol(t, &e, 10);
4233 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4236 minute = strtol(e+1, &e, 10);
4237 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4240 n = now(CLOCK_REALTIME);
4241 s = (time_t) (n / USEC_PER_SEC);
4244 assert_se(localtime_r(&s, &tm));
4246 tm.tm_hour = (int) hour;
4247 tm.tm_min = (int) minute;
4250 assert_se(s = mktime(&tm));
4252 *_u = (usec_t) s * USEC_PER_SEC;
4255 *_u += USEC_PER_DAY;
4261 static int shutdown_parse_argv(int argc, char *argv[]) {
4268 static const struct option options[] = {
4269 { "help", no_argument, NULL, ARG_HELP },
4270 { "halt", no_argument, NULL, 'H' },
4271 { "poweroff", no_argument, NULL, 'P' },
4272 { "reboot", no_argument, NULL, 'r' },
4273 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4274 { NULL, 0, NULL, 0 }
4282 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4290 arg_action = ACTION_HALT;
4294 arg_action = ACTION_POWEROFF;
4298 arg_action = ACTION_REBOOT;
4302 if (arg_action != ACTION_HALT)
4303 arg_action = ACTION_POWEROFF;
4316 /* Compatibility nops */
4320 arg_action = ACTION_CANCEL_SHUTDOWN;
4327 log_error("Unknown option code %c", c);
4332 if (argc > optind) {
4333 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4334 log_error("Failed to parse time specification: %s", argv[optind]);
4338 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4340 /* We skip the time argument */
4341 if (argc > optind + 1)
4342 arg_wall = argv + optind + 1;
4349 static int telinit_parse_argv(int argc, char *argv[]) {
4356 static const struct option options[] = {
4357 { "help", no_argument, NULL, ARG_HELP },
4358 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4359 { NULL, 0, NULL, 0 }
4362 static const struct {
4366 { '0', ACTION_POWEROFF },
4367 { '6', ACTION_REBOOT },
4368 { '1', ACTION_RESCUE },
4369 { '2', ACTION_RUNLEVEL2 },
4370 { '3', ACTION_RUNLEVEL3 },
4371 { '4', ACTION_RUNLEVEL4 },
4372 { '5', ACTION_RUNLEVEL5 },
4373 { 's', ACTION_RESCUE },
4374 { 'S', ACTION_RESCUE },
4375 { 'q', ACTION_RELOAD },
4376 { 'Q', ACTION_RELOAD },
4377 { 'u', ACTION_REEXEC },
4378 { 'U', ACTION_REEXEC }
4387 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4402 log_error("Unknown option code %c", c);
4407 if (optind >= argc) {
4412 if (optind + 1 < argc) {
4413 log_error("Too many arguments.");
4417 if (strlen(argv[optind]) != 1) {
4418 log_error("Expected single character argument.");
4422 for (i = 0; i < ELEMENTSOF(table); i++)
4423 if (table[i].from == argv[optind][0])
4426 if (i >= ELEMENTSOF(table)) {
4427 log_error("Unknown command %s.", argv[optind]);
4431 arg_action = table[i].to;
4438 static int runlevel_parse_argv(int argc, char *argv[]) {
4444 static const struct option options[] = {
4445 { "help", no_argument, NULL, ARG_HELP },
4446 { NULL, 0, NULL, 0 }
4454 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4465 log_error("Unknown option code %c", c);
4470 if (optind < argc) {
4471 log_error("Too many arguments.");
4478 static int parse_argv(int argc, char *argv[]) {
4482 if (program_invocation_short_name) {
4484 if (strstr(program_invocation_short_name, "halt")) {
4485 arg_action = ACTION_HALT;
4486 return halt_parse_argv(argc, argv);
4487 } else if (strstr(program_invocation_short_name, "poweroff")) {
4488 arg_action = ACTION_POWEROFF;
4489 return halt_parse_argv(argc, argv);
4490 } else if (strstr(program_invocation_short_name, "reboot")) {
4491 arg_action = ACTION_REBOOT;
4492 return halt_parse_argv(argc, argv);
4493 } else if (strstr(program_invocation_short_name, "shutdown")) {
4494 arg_action = ACTION_POWEROFF;
4495 return shutdown_parse_argv(argc, argv);
4496 } else if (strstr(program_invocation_short_name, "init")) {
4498 if (sd_booted() > 0) {
4499 arg_action = ACTION_INVALID;
4500 return telinit_parse_argv(argc, argv);
4502 /* Hmm, so some other init system is
4503 * running, we need to forward this
4504 * request to it. For now we simply
4505 * guess that it is Upstart. */
4507 execv("/lib/upstart/telinit", argv);
4509 log_error("Couldn't find an alternative telinit implementation to spawn.");
4513 } else if (strstr(program_invocation_short_name, "runlevel")) {
4514 arg_action = ACTION_RUNLEVEL;
4515 return runlevel_parse_argv(argc, argv);
4519 arg_action = ACTION_SYSTEMCTL;
4520 return systemctl_parse_argv(argc, argv);
4523 static int action_to_runlevel(void) {
4525 static const char table[_ACTION_MAX] = {
4526 [ACTION_HALT] = '0',
4527 [ACTION_POWEROFF] = '0',
4528 [ACTION_REBOOT] = '6',
4529 [ACTION_RUNLEVEL2] = '2',
4530 [ACTION_RUNLEVEL3] = '3',
4531 [ACTION_RUNLEVEL4] = '4',
4532 [ACTION_RUNLEVEL5] = '5',
4533 [ACTION_RESCUE] = '1'
4536 assert(arg_action < _ACTION_MAX);
4538 return table[arg_action];
4541 static int talk_upstart(void) {
4542 DBusMessage *m = NULL, *reply = NULL;
4544 int previous, rl, r;
4546 env1_buf[] = "RUNLEVEL=X",
4547 env2_buf[] = "PREVLEVEL=X";
4548 char *env1 = env1_buf, *env2 = env2_buf;
4549 const char *emit = "runlevel";
4550 dbus_bool_t b_false = FALSE;
4551 DBusMessageIter iter, sub;
4552 DBusConnection *bus;
4554 dbus_error_init(&error);
4556 if (!(rl = action_to_runlevel()))
4559 if (utmp_get_runlevel(&previous, NULL) < 0)
4562 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4563 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4568 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4573 if ((r = bus_check_peercred(bus)) < 0) {
4574 log_error("Failed to verify owner of bus.");
4578 if (!(m = dbus_message_new_method_call(
4579 "com.ubuntu.Upstart",
4580 "/com/ubuntu/Upstart",
4581 "com.ubuntu.Upstart0_6",
4584 log_error("Could not allocate message.");
4589 dbus_message_iter_init_append(m, &iter);
4591 env1_buf[sizeof(env1_buf)-2] = rl;
4592 env2_buf[sizeof(env2_buf)-2] = previous;
4594 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4595 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4596 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4597 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4598 !dbus_message_iter_close_container(&iter, &sub) ||
4599 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4600 log_error("Could not append arguments to message.");
4605 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4607 if (error_is_no_service(&error)) {
4612 log_error("Failed to issue method call: %s", bus_error_message(&error));
4621 dbus_message_unref(m);
4624 dbus_message_unref(reply);
4627 dbus_connection_flush(bus);
4628 dbus_connection_close(bus);
4629 dbus_connection_unref(bus);
4632 dbus_error_free(&error);
4637 static int talk_initctl(void) {
4638 struct init_request request;
4642 if (!(rl = action_to_runlevel()))
4646 request.magic = INIT_MAGIC;
4647 request.sleeptime = 0;
4648 request.cmd = INIT_CMD_RUNLVL;
4649 request.runlevel = rl;
4651 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4653 if (errno == ENOENT)
4656 log_error("Failed to open "INIT_FIFO": %m");
4661 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4662 close_nointr_nofail(fd);
4665 log_error("Failed to write to "INIT_FIFO": %m");
4666 return errno ? -errno : -EIO;
4672 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4674 static const struct {
4682 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4684 { "list-units", LESS, 1, list_units },
4685 { "list-jobs", EQUAL, 1, list_jobs },
4686 { "clear-jobs", EQUAL, 1, daemon_reload },
4687 { "load", MORE, 2, load_unit },
4688 { "cancel", MORE, 2, cancel_job },
4689 { "start", MORE, 2, start_unit },
4690 { "stop", MORE, 2, start_unit },
4691 { "reload", MORE, 2, start_unit },
4692 { "restart", MORE, 2, start_unit },
4693 { "try-restart", MORE, 2, start_unit },
4694 { "reload-or-restart", MORE, 2, start_unit },
4695 { "reload-or-try-restart", MORE, 2, start_unit },
4696 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4697 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4698 { "isolate", EQUAL, 2, start_unit },
4699 { "is-active", MORE, 2, check_unit },
4700 { "check", MORE, 2, check_unit },
4701 { "show", MORE, 1, show },
4702 { "status", MORE, 2, show },
4703 { "monitor", EQUAL, 1, monitor },
4704 { "dump", EQUAL, 1, dump },
4705 { "dot", EQUAL, 1, dot },
4706 { "snapshot", LESS, 2, snapshot },
4707 { "delete", MORE, 2, delete_snapshot },
4708 { "daemon-reload", EQUAL, 1, daemon_reload },
4709 { "daemon-reexec", EQUAL, 1, daemon_reload },
4710 { "daemon-exit", EQUAL, 1, daemon_reload },
4711 { "show-environment", EQUAL, 1, show_enviroment },
4712 { "set-environment", MORE, 2, set_environment },
4713 { "unset-environment", MORE, 2, set_environment },
4714 { "halt", EQUAL, 1, start_special },
4715 { "poweroff", EQUAL, 1, start_special },
4716 { "reboot", EQUAL, 1, start_special },
4717 { "default", EQUAL, 1, start_special },
4718 { "rescue", EQUAL, 1, start_special },
4719 { "emergency", EQUAL, 1, start_special },
4720 { "reset-failed", MORE, 1, reset_failed },
4721 { "enable", MORE, 2, enable_unit },
4722 { "disable", MORE, 2, enable_unit },
4723 { "is-enabled", MORE, 2, enable_unit }
4733 left = argc - optind;
4736 /* Special rule: no arguments means "list-units" */
4739 if (streq(argv[optind], "help")) {
4744 for (i = 0; i < ELEMENTSOF(verbs); i++)
4745 if (streq(argv[optind], verbs[i].verb))
4748 if (i >= ELEMENTSOF(verbs)) {
4749 log_error("Unknown operation %s", argv[optind]);
4754 switch (verbs[i].argc_cmp) {
4757 if (left != verbs[i].argc) {
4758 log_error("Invalid number of arguments.");
4765 if (left < verbs[i].argc) {
4766 log_error("Too few arguments.");
4773 if (left > verbs[i].argc) {
4774 log_error("Too many arguments.");
4781 assert_not_reached("Unknown comparison operator.");
4784 /* Require a bus connection for all operations but
4786 if (!streq(verbs[i].verb, "enable") &&
4787 !streq(verbs[i].verb, "disable") &&
4789 log_error("Failed to get D-Bus connection: %s", error->message);
4793 return verbs[i].dispatch(bus, argv + optind, left);
4796 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4798 struct msghdr msghdr;
4800 union sockaddr_union sockaddr;
4801 struct shutdownd_command c;
4809 strncpy(c.wall_message, message, sizeof(c.wall_message));
4811 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4815 sockaddr.sa.sa_family = AF_UNIX;
4816 sockaddr.un.sun_path[0] = 0;
4817 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4820 iovec.iov_base = (char*) &c;
4821 iovec.iov_len = sizeof(c);
4824 msghdr.msg_name = &sockaddr;
4825 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4827 msghdr.msg_iov = &iovec;
4828 msghdr.msg_iovlen = 1;
4830 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4831 close_nointr_nofail(fd);
4835 close_nointr_nofail(fd);
4839 static int reload_with_fallback(DBusConnection *bus) {
4842 /* First, try systemd via D-Bus. */
4843 if (daemon_reload(bus, NULL, 0) > 0)
4847 /* Nothing else worked, so let's try signals */
4848 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4850 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4851 log_error("kill() failed: %m");
4858 static int start_with_fallback(DBusConnection *bus) {
4861 /* First, try systemd via D-Bus. */
4862 if (start_unit(bus, NULL, 0) >= 0)
4866 /* Hmm, talking to systemd via D-Bus didn't work. Then
4867 * let's try to talk to Upstart via D-Bus. */
4868 if (talk_upstart() > 0)
4871 /* Nothing else worked, so let's try
4873 if (talk_initctl() > 0)
4876 log_error("Failed to talk to init daemon.");
4880 warn_wall(arg_action);
4884 static int halt_main(DBusConnection *bus) {
4887 if (geteuid() != 0) {
4888 log_error("Must be root.");
4894 char date[FORMAT_TIMESTAMP_MAX];
4896 m = strv_join(arg_wall, " ");
4897 r = send_shutdownd(arg_when,
4898 arg_action == ACTION_HALT ? 'H' :
4899 arg_action == ACTION_POWEROFF ? 'P' :
4906 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4908 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4909 format_timestamp(date, sizeof(date), arg_when));
4914 if (!arg_dry && !arg_immediate)
4915 return start_with_fallback(bus);
4918 if (sd_booted() > 0)
4919 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4920 else if ((r = utmp_put_shutdown(0)) < 0)
4921 log_warning("Failed to write utmp record: %s", strerror(-r));
4930 /* Make sure C-A-D is handled by the kernel from this
4932 reboot(RB_ENABLE_CAD);
4934 switch (arg_action) {
4937 log_info("Halting.");
4938 reboot(RB_HALT_SYSTEM);
4941 case ACTION_POWEROFF:
4942 log_info("Powering off.");
4943 reboot(RB_POWER_OFF);
4947 log_info("Rebooting.");
4948 reboot(RB_AUTOBOOT);
4952 assert_not_reached("Unknown halt action.");
4955 /* We should never reach this. */
4959 static int runlevel_main(void) {
4960 int r, runlevel, previous;
4962 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4963 printf("unknown\n");
4968 previous <= 0 ? 'N' : previous,
4969 runlevel <= 0 ? 'N' : runlevel);
4974 int main(int argc, char*argv[]) {
4975 int r, retval = EXIT_FAILURE;
4976 DBusConnection *bus = NULL;
4979 dbus_error_init(&error);
4981 log_parse_environment();
4984 if ((r = parse_argv(argc, argv)) < 0)
4987 retval = EXIT_SUCCESS;
4991 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
4992 * let's shortcut this */
4993 if (arg_action == ACTION_RUNLEVEL) {
4994 r = runlevel_main();
4995 retval = r < 0 ? EXIT_FAILURE : r;
4999 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5001 switch (arg_action) {
5003 case ACTION_SYSTEMCTL:
5004 r = systemctl_main(bus, argc, argv, &error);
5008 case ACTION_POWEROFF:
5013 case ACTION_RUNLEVEL2:
5014 case ACTION_RUNLEVEL3:
5015 case ACTION_RUNLEVEL4:
5016 case ACTION_RUNLEVEL5:
5018 case ACTION_EMERGENCY:
5019 case ACTION_DEFAULT:
5020 r = start_with_fallback(bus);
5025 r = reload_with_fallback(bus);
5028 case ACTION_CANCEL_SHUTDOWN:
5029 r = send_shutdownd(0, 0, false, NULL);
5032 case ACTION_INVALID:
5033 case ACTION_RUNLEVEL:
5035 assert_not_reached("Unknown action");
5038 retval = r < 0 ? EXIT_FAILURE : r;
5043 dbus_connection_flush(bus);
5044 dbus_connection_close(bus);
5045 dbus_connection_unref(bus);
5048 dbus_error_free(&error);
5052 strv_free(arg_property);