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.");
1176 /* Returns 1 if we managed to issue the request, and 0 if we
1177 * failed due to systemd not being around. This is then used
1178 * as indication to try a fallback mechanism. */
1182 dbus_message_unref(m);
1185 dbus_message_unref(reply);
1190 static enum action verb_to_action(const char *verb) {
1191 if (streq(verb, "halt"))
1193 else if (streq(verb, "poweroff"))
1194 return ACTION_POWEROFF;
1195 else if (streq(verb, "reboot"))
1196 return ACTION_REBOOT;
1197 else if (streq(verb, "rescue"))
1198 return ACTION_RESCUE;
1199 else if (streq(verb, "emergency"))
1200 return ACTION_EMERGENCY;
1201 else if (streq(verb, "default"))
1202 return ACTION_DEFAULT;
1204 return ACTION_INVALID;
1207 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1209 static const char * const table[_ACTION_MAX] = {
1210 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1211 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1212 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1213 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1214 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1215 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1216 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1217 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1218 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1219 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1224 const char *method, *mode, *one_name;
1228 dbus_error_init(&error);
1232 if (arg_action == ACTION_SYSTEMCTL) {
1234 streq(args[0], "stop") ? "StopUnit" :
1235 streq(args[0], "reload") ? "ReloadUnit" :
1236 streq(args[0], "restart") ? "RestartUnit" :
1237 streq(args[0], "try-restart") ? "TryRestartUnit" :
1238 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1239 streq(args[0], "reload-or-try-restart") ||
1240 streq(args[0], "force-reload") ||
1241 streq(args[0], "condrestart") ? "ReloadOrTryRestartUnit" :
1245 (streq(args[0], "isolate") ||
1246 streq(args[0], "rescue") ||
1247 streq(args[0], "emergency")) ? "isolate" :
1251 one_name = table[verb_to_action(args[0])];
1254 assert(arg_action < ELEMENTSOF(table));
1255 assert(table[arg_action]);
1257 method = "StartUnit";
1259 mode = (arg_action == ACTION_EMERGENCY ||
1260 arg_action == ACTION_RESCUE) ? "isolate" : "replace";
1262 one_name = table[arg_action];
1265 if (!arg_no_block) {
1266 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1267 log_error("Could not watch jobs: %s", strerror(-ret));
1271 if (!(s = set_new(string_hash_func, string_compare_func))) {
1272 log_error("Failed to allocate set.");
1279 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1282 for (i = 1; i < n; i++)
1283 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1288 ret = translate_bus_error_to_exit_status(r, &error);
1290 dbus_error_free(&error);
1295 if ((r = wait_for_jobs(bus, s)) < 0) {
1304 dbus_error_free(&error);
1309 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1315 r = start_unit(bus, args, n);
1318 warn_wall(verb_to_action(args[0]));
1323 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1324 DBusMessage *m = NULL, *reply = NULL;
1326 *interface = "org.freedesktop.systemd1.Unit",
1327 *property = "ActiveState";
1328 int r = 3; /* According to LSB: "program is not running" */
1335 dbus_error_init(&error);
1337 for (i = 1; i < n; i++) {
1338 const char *path = NULL;
1340 DBusMessageIter iter, sub;
1342 if (!(m = dbus_message_new_method_call(
1343 "org.freedesktop.systemd1",
1344 "/org/freedesktop/systemd1",
1345 "org.freedesktop.systemd1.Manager",
1347 log_error("Could not allocate message.");
1352 if (!dbus_message_append_args(m,
1353 DBUS_TYPE_STRING, &args[i],
1354 DBUS_TYPE_INVALID)) {
1355 log_error("Could not append arguments to message.");
1360 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1362 /* Hmm, cannot figure out anything about this unit... */
1366 dbus_error_free(&error);
1370 if (!dbus_message_get_args(reply, &error,
1371 DBUS_TYPE_OBJECT_PATH, &path,
1372 DBUS_TYPE_INVALID)) {
1373 log_error("Failed to parse reply: %s", bus_error_message(&error));
1378 dbus_message_unref(m);
1379 if (!(m = dbus_message_new_method_call(
1380 "org.freedesktop.systemd1",
1382 "org.freedesktop.DBus.Properties",
1384 log_error("Could not allocate message.");
1389 if (!dbus_message_append_args(m,
1390 DBUS_TYPE_STRING, &interface,
1391 DBUS_TYPE_STRING, &property,
1392 DBUS_TYPE_INVALID)) {
1393 log_error("Could not append arguments to message.");
1398 dbus_message_unref(reply);
1399 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1400 log_error("Failed to issue method call: %s", bus_error_message(&error));
1405 if (!dbus_message_iter_init(reply, &iter) ||
1406 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1407 log_error("Failed to parse reply.");
1412 dbus_message_iter_recurse(&iter, &sub);
1414 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1415 log_error("Failed to parse reply.");
1420 dbus_message_iter_get_basic(&sub, &state);
1425 if (streq(state, "active") || streq(state, "reloading"))
1428 dbus_message_unref(m);
1429 dbus_message_unref(reply);
1435 dbus_message_unref(m);
1438 dbus_message_unref(reply);
1440 dbus_error_free(&error);
1445 typedef struct ExecStatusInfo {
1451 usec_t start_timestamp;
1452 usec_t exit_timestamp;
1457 LIST_FIELDS(struct ExecStatusInfo, exec);
1460 static void exec_status_info_free(ExecStatusInfo *i) {
1468 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1469 uint64_t start_timestamp, exit_timestamp;
1470 DBusMessageIter sub2, sub3;
1474 int32_t code, status;
1480 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1483 dbus_message_iter_recurse(sub, &sub2);
1485 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1488 if (!(i->path = strdup(path)))
1491 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1492 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1496 dbus_message_iter_recurse(&sub2, &sub3);
1497 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1498 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1499 dbus_message_iter_next(&sub3);
1504 if (!(i->argv = new0(char*, n+1)))
1508 dbus_message_iter_recurse(&sub2, &sub3);
1509 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1512 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1513 dbus_message_iter_get_basic(&sub3, &s);
1514 dbus_message_iter_next(&sub3);
1516 if (!(i->argv[n++] = strdup(s)))
1520 if (!dbus_message_iter_next(&sub2) ||
1521 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1522 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1523 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1524 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1525 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1526 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1530 i->start_timestamp = (usec_t) start_timestamp;
1531 i->exit_timestamp = (usec_t) exit_timestamp;
1532 i->pid = (pid_t) pid;
1539 typedef struct UnitStatusInfo {
1541 const char *load_state;
1542 const char *active_state;
1543 const char *sub_state;
1545 const char *description;
1548 const char *default_control_group;
1550 usec_t inactive_exit_timestamp;
1551 usec_t active_enter_timestamp;
1552 usec_t active_exit_timestamp;
1553 usec_t inactive_enter_timestamp;
1555 bool need_daemon_reload;
1560 const char *status_text;
1564 usec_t start_timestamp;
1565 usec_t exit_timestamp;
1567 int exit_code, exit_status;
1570 unsigned n_accepted;
1571 unsigned n_connections;
1575 const char *sysfs_path;
1577 /* Mount, Automount */
1583 LIST_HEAD(ExecStatusInfo, exec);
1586 static void print_status_info(UnitStatusInfo *i) {
1588 const char *on, *off, *ss;
1590 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1591 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1595 /* This shows pretty information about a unit. See
1596 * print_property() for a low-level property printer */
1598 printf("%s", strna(i->id));
1600 if (i->description && !streq_ptr(i->id, i->description))
1601 printf(" - %s", i->description);
1605 if (streq_ptr(i->load_state, "failed")) {
1606 on = ansi_highlight(true);
1607 off = ansi_highlight(false);
1612 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1614 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1616 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1618 if (streq_ptr(i->active_state, "failed")) {
1619 on = ansi_highlight(true);
1620 off = ansi_highlight(false);
1621 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1622 on = ansi_highlight_green(true);
1623 off = ansi_highlight_green(false);
1628 printf("\t Active: %s%s (%s)%s",
1630 strna(i->active_state),
1634 printf("\t Active: %s%s%s",
1636 strna(i->active_state),
1639 timestamp = (streq_ptr(i->active_state, "active") ||
1640 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1641 (streq_ptr(i->active_state, "inactive") ||
1642 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1643 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1644 i->active_exit_timestamp;
1646 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1647 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1650 printf(" since [%s; %s]\n", s2, s1);
1652 printf(" since [%s]\n", s2);
1657 printf("\t Device: %s\n", i->sysfs_path);
1659 printf("\t Where: %s\n", i->where);
1661 printf("\t What: %s\n", i->what);
1664 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1666 LIST_FOREACH(exec, p, i->exec) {
1669 /* Only show exited processes here */
1673 t = strv_join(p->argv, " ");
1674 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1677 if (p->code == CLD_EXITED) {
1680 printf("status=%i", p->status);
1682 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1686 printf("signal=%s", signal_to_string(p->status));
1689 if (i->main_pid == p->pid &&
1690 i->start_timestamp == p->start_timestamp &&
1691 i->exit_timestamp == p->start_timestamp)
1692 /* Let's not show this twice */
1695 if (p->pid == i->control_pid)
1699 if (i->main_pid > 0 || i->control_pid > 0) {
1702 if (i->main_pid > 0) {
1703 printf("Main PID: %u", (unsigned) i->main_pid);
1707 get_process_name(i->main_pid, &t);
1712 } else if (i->exit_code > 0) {
1713 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1715 if (i->exit_code == CLD_EXITED) {
1718 printf("status=%i", i->exit_status);
1720 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1724 printf("signal=%s", signal_to_string(i->exit_status));
1729 if (i->main_pid > 0 && i->control_pid > 0)
1732 if (i->control_pid > 0) {
1735 printf(" Control: %u", (unsigned) i->control_pid);
1737 get_process_name(i->control_pid, &t);
1748 printf("\t Status: \"%s\"\n", i->status_text);
1750 if (i->default_control_group) {
1753 printf("\t CGroup: %s\n", i->default_control_group);
1755 if ((c = columns()) > 18)
1760 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1763 if (i->need_daemon_reload)
1764 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1765 ansi_highlight(true),
1766 ansi_highlight(false),
1767 arg_session ? "--session" : "--system");
1770 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1772 switch (dbus_message_iter_get_arg_type(iter)) {
1774 case DBUS_TYPE_STRING: {
1777 dbus_message_iter_get_basic(iter, &s);
1780 if (streq(name, "Id"))
1782 else if (streq(name, "LoadState"))
1784 else if (streq(name, "ActiveState"))
1785 i->active_state = s;
1786 else if (streq(name, "SubState"))
1788 else if (streq(name, "Description"))
1790 else if (streq(name, "FragmentPath"))
1792 else if (streq(name, "SysVPath")) {
1795 } else if (streq(name, "DefaultControlGroup"))
1796 i->default_control_group = s;
1797 else if (streq(name, "StatusText"))
1799 else if (streq(name, "SysFSPath"))
1801 else if (streq(name, "Where"))
1803 else if (streq(name, "What"))
1810 case DBUS_TYPE_BOOLEAN: {
1813 dbus_message_iter_get_basic(iter, &b);
1815 if (streq(name, "Accept"))
1817 else if (streq(name, "NeedDaemonReload"))
1818 i->need_daemon_reload = b;
1823 case DBUS_TYPE_UINT32: {
1826 dbus_message_iter_get_basic(iter, &u);
1828 if (streq(name, "MainPID")) {
1830 i->main_pid = (pid_t) u;
1833 } else if (streq(name, "ControlPID"))
1834 i->control_pid = (pid_t) u;
1835 else if (streq(name, "ExecMainPID")) {
1837 i->main_pid = (pid_t) u;
1838 } else if (streq(name, "NAccepted"))
1840 else if (streq(name, "NConnections"))
1841 i->n_connections = u;
1846 case DBUS_TYPE_INT32: {
1849 dbus_message_iter_get_basic(iter, &j);
1851 if (streq(name, "ExecMainCode"))
1852 i->exit_code = (int) j;
1853 else if (streq(name, "ExecMainStatus"))
1854 i->exit_status = (int) j;
1859 case DBUS_TYPE_UINT64: {
1862 dbus_message_iter_get_basic(iter, &u);
1864 if (streq(name, "ExecMainStartTimestamp"))
1865 i->start_timestamp = (usec_t) u;
1866 else if (streq(name, "ExecMainExitTimestamp"))
1867 i->exit_timestamp = (usec_t) u;
1868 else if (streq(name, "ActiveEnterTimestamp"))
1869 i->active_enter_timestamp = (usec_t) u;
1870 else if (streq(name, "InactiveEnterTimestamp"))
1871 i->inactive_enter_timestamp = (usec_t) u;
1872 else if (streq(name, "InactiveExitTimestamp"))
1873 i->inactive_exit_timestamp = (usec_t) u;
1874 else if (streq(name, "ActiveExitTimestamp"))
1875 i->active_exit_timestamp = (usec_t) u;
1880 case DBUS_TYPE_ARRAY: {
1882 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1883 startswith(name, "Exec")) {
1884 DBusMessageIter sub;
1886 dbus_message_iter_recurse(iter, &sub);
1887 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1888 ExecStatusInfo *info;
1891 if (!(info = new0(ExecStatusInfo, 1)))
1894 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1899 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1901 dbus_message_iter_next(&sub);
1912 static int print_property(const char *name, DBusMessageIter *iter) {
1916 /* This is a low-level property printer, see
1917 * print_status_info() for the nicer output */
1919 if (arg_property && !strv_find(arg_property, name))
1922 switch (dbus_message_iter_get_arg_type(iter)) {
1924 case DBUS_TYPE_STRING: {
1926 dbus_message_iter_get_basic(iter, &s);
1928 if (arg_all || s[0])
1929 printf("%s=%s\n", name, s);
1934 case DBUS_TYPE_BOOLEAN: {
1936 dbus_message_iter_get_basic(iter, &b);
1937 printf("%s=%s\n", name, yes_no(b));
1942 case DBUS_TYPE_UINT64: {
1944 dbus_message_iter_get_basic(iter, &u);
1946 /* Yes, heuristics! But we can change this check
1947 * should it turn out to not be sufficient */
1949 if (strstr(name, "Timestamp")) {
1950 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1952 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1953 printf("%s=%s\n", name, strempty(t));
1954 } else if (strstr(name, "USec")) {
1955 char timespan[FORMAT_TIMESPAN_MAX];
1957 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1959 printf("%s=%llu\n", name, (unsigned long long) u);
1964 case DBUS_TYPE_UINT32: {
1966 dbus_message_iter_get_basic(iter, &u);
1968 if (strstr(name, "UMask") || strstr(name, "Mode"))
1969 printf("%s=%04o\n", name, u);
1971 printf("%s=%u\n", name, (unsigned) u);
1976 case DBUS_TYPE_INT32: {
1978 dbus_message_iter_get_basic(iter, &i);
1980 printf("%s=%i\n", name, (int) i);
1984 case DBUS_TYPE_STRUCT: {
1985 DBusMessageIter sub;
1986 dbus_message_iter_recurse(iter, &sub);
1988 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1991 dbus_message_iter_get_basic(&sub, &u);
1994 printf("%s=%u\n", name, (unsigned) u);
1996 printf("%s=\n", name);
1999 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2002 dbus_message_iter_get_basic(&sub, &s);
2004 if (arg_all || s[0])
2005 printf("%s=%s\n", name, s);
2013 case DBUS_TYPE_ARRAY:
2015 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2016 DBusMessageIter sub;
2019 dbus_message_iter_recurse(iter, &sub);
2021 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2022 printf("%s=", name);
2024 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2027 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2028 dbus_message_iter_get_basic(&sub, &s);
2029 printf("%s%s", space ? " " : "", s);
2032 dbus_message_iter_next(&sub);
2040 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2041 DBusMessageIter sub;
2043 dbus_message_iter_recurse(iter, &sub);
2045 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2046 printf("%s=", name);
2048 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2051 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2052 dbus_message_iter_get_basic(&sub, &u);
2055 dbus_message_iter_next(&sub);
2063 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2064 DBusMessageIter sub, sub2;
2066 dbus_message_iter_recurse(iter, &sub);
2067 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2068 const char *type, *path;
2070 dbus_message_iter_recurse(&sub, &sub2);
2072 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2073 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2074 printf("%s=%s\n", type, path);
2076 dbus_message_iter_next(&sub);
2081 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2082 DBusMessageIter sub, sub2;
2084 dbus_message_iter_recurse(iter, &sub);
2085 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2087 uint64_t value, next_elapse;
2089 dbus_message_iter_recurse(&sub, &sub2);
2091 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2092 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2093 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2094 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2096 printf("%s={ value=%s ; next_elapse=%s }\n",
2098 format_timespan(timespan1, sizeof(timespan1), value),
2099 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2102 dbus_message_iter_next(&sub);
2107 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2108 DBusMessageIter sub;
2110 dbus_message_iter_recurse(iter, &sub);
2111 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2112 ExecStatusInfo info;
2115 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2116 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2119 t = strv_join(info.argv, " ");
2121 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2125 yes_no(info.ignore),
2126 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2127 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2128 (unsigned) info. pid,
2129 sigchld_code_to_string(info.code),
2131 info.code == CLD_EXITED ? "" : "/",
2132 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2138 strv_free(info.argv);
2140 dbus_message_iter_next(&sub);
2150 printf("%s=[unprintable]\n", name);
2155 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2156 DBusMessage *m = NULL, *reply = NULL;
2157 const char *interface = "";
2160 DBusMessageIter iter, sub, sub2, sub3;
2161 UnitStatusInfo info;
2169 dbus_error_init(&error);
2171 if (!(m = dbus_message_new_method_call(
2172 "org.freedesktop.systemd1",
2174 "org.freedesktop.DBus.Properties",
2176 log_error("Could not allocate message.");
2181 if (!dbus_message_append_args(m,
2182 DBUS_TYPE_STRING, &interface,
2183 DBUS_TYPE_INVALID)) {
2184 log_error("Could not append arguments to message.");
2189 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2190 log_error("Failed to issue method call: %s", bus_error_message(&error));
2195 if (!dbus_message_iter_init(reply, &iter) ||
2196 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2197 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2198 log_error("Failed to parse reply.");
2203 dbus_message_iter_recurse(&iter, &sub);
2210 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2213 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2214 log_error("Failed to parse reply.");
2219 dbus_message_iter_recurse(&sub, &sub2);
2221 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2222 log_error("Failed to parse reply.");
2227 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2228 log_error("Failed to parse reply.");
2233 dbus_message_iter_recurse(&sub2, &sub3);
2235 if (show_properties)
2236 r = print_property(name, &sub3);
2238 r = status_property(name, &sub3, &info);
2241 log_error("Failed to parse reply.");
2246 dbus_message_iter_next(&sub);
2251 if (!show_properties)
2252 print_status_info(&info);
2254 if (!streq_ptr(info.active_state, "active") &&
2255 !streq_ptr(info.active_state, "reloading"))
2256 /* According to LSB: "program not running" */
2259 while ((p = info.exec)) {
2260 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2261 exec_status_info_free(p);
2266 dbus_message_unref(m);
2269 dbus_message_unref(reply);
2271 dbus_error_free(&error);
2276 static int show(DBusConnection *bus, char **args, unsigned n) {
2277 DBusMessage *m = NULL, *reply = NULL;
2281 bool show_properties, new_line = false;
2286 dbus_error_init(&error);
2288 show_properties = !streq(args[0], "status");
2290 if (show_properties && n <= 1) {
2291 /* If not argument is specified inspect the manager
2294 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2298 for (i = 1; i < n; i++) {
2299 const char *path = NULL;
2302 if (safe_atou32(args[i], &id) < 0) {
2304 /* Interpret as unit name */
2306 if (!(m = dbus_message_new_method_call(
2307 "org.freedesktop.systemd1",
2308 "/org/freedesktop/systemd1",
2309 "org.freedesktop.systemd1.Manager",
2311 log_error("Could not allocate message.");
2316 if (!dbus_message_append_args(m,
2317 DBUS_TYPE_STRING, &args[i],
2318 DBUS_TYPE_INVALID)) {
2319 log_error("Could not append arguments to message.");
2324 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2326 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2327 log_error("Failed to issue method call: %s", bus_error_message(&error));
2332 dbus_error_free(&error);
2334 dbus_message_unref(m);
2335 if (!(m = dbus_message_new_method_call(
2336 "org.freedesktop.systemd1",
2337 "/org/freedesktop/systemd1",
2338 "org.freedesktop.systemd1.Manager",
2340 log_error("Could not allocate message.");
2345 if (!dbus_message_append_args(m,
2346 DBUS_TYPE_STRING, &args[i],
2347 DBUS_TYPE_INVALID)) {
2348 log_error("Could not append arguments to message.");
2353 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2354 log_error("Failed to issue method call: %s", bus_error_message(&error));
2356 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2357 ret = 4; /* According to LSB: "program or service status is unknown" */
2364 } else if (show_properties) {
2366 /* Interpret as job id */
2368 if (!(m = dbus_message_new_method_call(
2369 "org.freedesktop.systemd1",
2370 "/org/freedesktop/systemd1",
2371 "org.freedesktop.systemd1.Manager",
2373 log_error("Could not allocate message.");
2378 if (!dbus_message_append_args(m,
2379 DBUS_TYPE_UINT32, &id,
2380 DBUS_TYPE_INVALID)) {
2381 log_error("Could not append arguments to message.");
2386 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2387 log_error("Failed to issue method call: %s", bus_error_message(&error));
2393 /* Interpret as PID */
2395 if (!(m = dbus_message_new_method_call(
2396 "org.freedesktop.systemd1",
2397 "/org/freedesktop/systemd1",
2398 "org.freedesktop.systemd1.Manager",
2400 log_error("Could not allocate message.");
2405 if (!dbus_message_append_args(m,
2406 DBUS_TYPE_UINT32, &id,
2407 DBUS_TYPE_INVALID)) {
2408 log_error("Could not append arguments to message.");
2413 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2414 log_error("Failed to issue method call: %s", bus_error_message(&error));
2420 if (!dbus_message_get_args(reply, &error,
2421 DBUS_TYPE_OBJECT_PATH, &path,
2422 DBUS_TYPE_INVALID)) {
2423 log_error("Failed to parse reply: %s", bus_error_message(&error));
2428 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2431 dbus_message_unref(m);
2432 dbus_message_unref(reply);
2438 dbus_message_unref(m);
2441 dbus_message_unref(reply);
2443 dbus_error_free(&error);
2448 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2450 DBusMessage *m = NULL, *reply = NULL;
2455 dbus_error_init(&error);
2457 log_debug("Got D-Bus request: %s.%s() on %s",
2458 dbus_message_get_interface(message),
2459 dbus_message_get_member(message),
2460 dbus_message_get_path(message));
2462 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2463 log_error("Warning! D-Bus connection terminated.");
2464 dbus_connection_close(connection);
2466 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2467 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2468 const char *id, *path;
2470 if (!dbus_message_get_args(message, &error,
2471 DBUS_TYPE_STRING, &id,
2472 DBUS_TYPE_OBJECT_PATH, &path,
2474 log_error("Failed to parse message: %s", bus_error_message(&error));
2475 else if (streq(dbus_message_get_member(message), "UnitNew"))
2476 printf("Unit %s added.\n", id);
2478 printf("Unit %s removed.\n", id);
2480 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2481 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2485 if (!dbus_message_get_args(message, &error,
2486 DBUS_TYPE_UINT32, &id,
2487 DBUS_TYPE_OBJECT_PATH, &path,
2489 log_error("Failed to parse message: %s", bus_error_message(&error));
2490 else if (streq(dbus_message_get_member(message), "JobNew"))
2491 printf("Job %u added.\n", id);
2493 printf("Job %u removed.\n", id);
2496 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2498 const char *path, *interface, *property = "Id";
2499 DBusMessageIter iter, sub;
2501 path = dbus_message_get_path(message);
2503 if (!dbus_message_get_args(message, &error,
2504 DBUS_TYPE_STRING, &interface,
2505 DBUS_TYPE_INVALID)) {
2506 log_error("Failed to parse message: %s", bus_error_message(&error));
2510 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2511 !streq(interface, "org.freedesktop.systemd1.Unit"))
2514 if (!(m = dbus_message_new_method_call(
2515 "org.freedesktop.systemd1",
2517 "org.freedesktop.DBus.Properties",
2519 log_error("Could not allocate message.");
2523 if (!dbus_message_append_args(m,
2524 DBUS_TYPE_STRING, &interface,
2525 DBUS_TYPE_STRING, &property,
2526 DBUS_TYPE_INVALID)) {
2527 log_error("Could not append arguments to message.");
2531 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2532 log_error("Failed to issue method call: %s", bus_error_message(&error));
2536 if (!dbus_message_iter_init(reply, &iter) ||
2537 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2538 log_error("Failed to parse reply.");
2542 dbus_message_iter_recurse(&iter, &sub);
2544 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2547 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2548 log_error("Failed to parse reply.");
2552 dbus_message_iter_get_basic(&sub, &id);
2553 printf("Unit %s changed.\n", id);
2557 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2558 log_error("Failed to parse reply.");
2562 dbus_message_iter_get_basic(&sub, &id);
2563 printf("Job %u changed.\n", id);
2569 dbus_message_unref(m);
2572 dbus_message_unref(reply);
2574 dbus_error_free(&error);
2575 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2579 dbus_message_unref(m);
2582 dbus_message_unref(reply);
2584 dbus_error_free(&error);
2585 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2588 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2589 DBusMessage *m = NULL, *reply = NULL;
2593 dbus_error_init(&error);
2596 dbus_bus_add_match(bus,
2598 "sender='org.freedesktop.systemd1',"
2599 "interface='org.freedesktop.systemd1.Manager',"
2600 "path='/org/freedesktop/systemd1'",
2603 if (dbus_error_is_set(&error)) {
2604 log_error("Failed to add match: %s", bus_error_message(&error));
2609 dbus_bus_add_match(bus,
2611 "sender='org.freedesktop.systemd1',"
2612 "interface='org.freedesktop.DBus.Properties',"
2613 "member='PropertiesChanged'",
2616 if (dbus_error_is_set(&error)) {
2617 log_error("Failed to add match: %s", bus_error_message(&error));
2623 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2624 log_error("Failed to add filter.");
2629 if (!(m = dbus_message_new_method_call(
2630 "org.freedesktop.systemd1",
2631 "/org/freedesktop/systemd1",
2632 "org.freedesktop.systemd1.Manager",
2634 log_error("Could not allocate message.");
2639 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2640 log_error("Failed to issue method call: %s", bus_error_message(&error));
2645 while (dbus_connection_read_write_dispatch(bus, -1))
2652 /* This is slightly dirty, since we don't undo the filter or the matches. */
2655 dbus_message_unref(m);
2658 dbus_message_unref(reply);
2660 dbus_error_free(&error);
2665 static int dump(DBusConnection *bus, char **args, unsigned n) {
2666 DBusMessage *m = NULL, *reply = NULL;
2671 dbus_error_init(&error);
2673 if (!(m = dbus_message_new_method_call(
2674 "org.freedesktop.systemd1",
2675 "/org/freedesktop/systemd1",
2676 "org.freedesktop.systemd1.Manager",
2678 log_error("Could not allocate message.");
2682 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2683 log_error("Failed to issue method call: %s", bus_error_message(&error));
2688 if (!dbus_message_get_args(reply, &error,
2689 DBUS_TYPE_STRING, &text,
2690 DBUS_TYPE_INVALID)) {
2691 log_error("Failed to parse reply: %s", bus_error_message(&error));
2696 fputs(text, stdout);
2702 dbus_message_unref(m);
2705 dbus_message_unref(reply);
2707 dbus_error_free(&error);
2712 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2713 DBusMessage *m = NULL, *reply = NULL;
2716 const char *name = "", *path, *id;
2717 dbus_bool_t cleanup = FALSE;
2718 DBusMessageIter iter, sub;
2720 *interface = "org.freedesktop.systemd1.Unit",
2723 dbus_error_init(&error);
2725 if (!(m = dbus_message_new_method_call(
2726 "org.freedesktop.systemd1",
2727 "/org/freedesktop/systemd1",
2728 "org.freedesktop.systemd1.Manager",
2729 "CreateSnapshot"))) {
2730 log_error("Could not allocate message.");
2737 if (!dbus_message_append_args(m,
2738 DBUS_TYPE_STRING, &name,
2739 DBUS_TYPE_BOOLEAN, &cleanup,
2740 DBUS_TYPE_INVALID)) {
2741 log_error("Could not append arguments to message.");
2746 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2747 log_error("Failed to issue method call: %s", bus_error_message(&error));
2752 if (!dbus_message_get_args(reply, &error,
2753 DBUS_TYPE_OBJECT_PATH, &path,
2754 DBUS_TYPE_INVALID)) {
2755 log_error("Failed to parse reply: %s", bus_error_message(&error));
2760 dbus_message_unref(m);
2761 if (!(m = dbus_message_new_method_call(
2762 "org.freedesktop.systemd1",
2764 "org.freedesktop.DBus.Properties",
2766 log_error("Could not allocate message.");
2770 if (!dbus_message_append_args(m,
2771 DBUS_TYPE_STRING, &interface,
2772 DBUS_TYPE_STRING, &property,
2773 DBUS_TYPE_INVALID)) {
2774 log_error("Could not append arguments to message.");
2779 dbus_message_unref(reply);
2780 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2781 log_error("Failed to issue method call: %s", bus_error_message(&error));
2786 if (!dbus_message_iter_init(reply, &iter) ||
2787 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2788 log_error("Failed to parse reply.");
2793 dbus_message_iter_recurse(&iter, &sub);
2795 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2796 log_error("Failed to parse reply.");
2801 dbus_message_iter_get_basic(&sub, &id);
2809 dbus_message_unref(m);
2812 dbus_message_unref(reply);
2814 dbus_error_free(&error);
2819 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2820 DBusMessage *m = NULL, *reply = NULL;
2828 dbus_error_init(&error);
2830 for (i = 1; i < n; i++) {
2831 const char *path = NULL;
2833 if (!(m = dbus_message_new_method_call(
2834 "org.freedesktop.systemd1",
2835 "/org/freedesktop/systemd1",
2836 "org.freedesktop.systemd1.Manager",
2838 log_error("Could not allocate message.");
2843 if (!dbus_message_append_args(m,
2844 DBUS_TYPE_STRING, &args[i],
2845 DBUS_TYPE_INVALID)) {
2846 log_error("Could not append arguments to message.");
2851 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2852 log_error("Failed to issue method call: %s", bus_error_message(&error));
2857 if (!dbus_message_get_args(reply, &error,
2858 DBUS_TYPE_OBJECT_PATH, &path,
2859 DBUS_TYPE_INVALID)) {
2860 log_error("Failed to parse reply: %s", bus_error_message(&error));
2865 dbus_message_unref(m);
2866 if (!(m = dbus_message_new_method_call(
2867 "org.freedesktop.systemd1",
2869 "org.freedesktop.systemd1.Snapshot",
2871 log_error("Could not allocate message.");
2876 dbus_message_unref(reply);
2877 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2878 log_error("Failed to issue method call: %s", bus_error_message(&error));
2883 dbus_message_unref(m);
2884 dbus_message_unref(reply);
2892 dbus_message_unref(m);
2895 dbus_message_unref(reply);
2897 dbus_error_free(&error);
2902 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2903 DBusMessage *m = NULL, *reply = NULL;
2908 dbus_error_init(&error);
2910 if (arg_action == ACTION_RELOAD)
2912 else if (arg_action == ACTION_REEXEC)
2913 method = "Reexecute";
2915 assert(arg_action == ACTION_SYSTEMCTL);
2918 streq(args[0], "clear-jobs") ||
2919 streq(args[0], "cancel") ? "ClearJobs" :
2920 streq(args[0], "daemon-reexec") ? "Reexecute" :
2921 streq(args[0], "reset-failed") ? "ResetFailed" :
2922 streq(args[0], "daemon-exit") ? "Exit" :
2926 if (!(m = dbus_message_new_method_call(
2927 "org.freedesktop.systemd1",
2928 "/org/freedesktop/systemd1",
2929 "org.freedesktop.systemd1.Manager",
2931 log_error("Could not allocate message.");
2935 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2937 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2938 /* There's always a fallback possible for
2939 * legacy actions. */
2944 log_error("Failed to issue method call: %s", bus_error_message(&error));
2953 dbus_message_unref(m);
2956 dbus_message_unref(reply);
2958 dbus_error_free(&error);
2963 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
2964 DBusMessage *m = NULL, *reply = NULL;
2970 dbus_error_init(&error);
2973 return daemon_reload(bus, args, n);
2975 for (i = 1; i < n; i++) {
2977 if (!(m = dbus_message_new_method_call(
2978 "org.freedesktop.systemd1",
2979 "/org/freedesktop/systemd1",
2980 "org.freedesktop.systemd1.Manager",
2981 "ResetFailedUnit"))) {
2982 log_error("Could not allocate message.");
2987 if (!dbus_message_append_args(m,
2988 DBUS_TYPE_STRING, args + i,
2989 DBUS_TYPE_INVALID)) {
2990 log_error("Could not append arguments to message.");
2995 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2996 log_error("Failed to issue method call: %s", bus_error_message(&error));
3001 dbus_message_unref(m);
3002 dbus_message_unref(reply);
3010 dbus_message_unref(m);
3013 dbus_message_unref(reply);
3015 dbus_error_free(&error);
3020 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3021 DBusMessage *m = NULL, *reply = NULL;
3023 DBusMessageIter iter, sub, sub2;
3026 *interface = "org.freedesktop.systemd1.Manager",
3027 *property = "Environment";
3029 dbus_error_init(&error);
3031 if (!(m = dbus_message_new_method_call(
3032 "org.freedesktop.systemd1",
3033 "/org/freedesktop/systemd1",
3034 "org.freedesktop.DBus.Properties",
3036 log_error("Could not allocate message.");
3040 if (!dbus_message_append_args(m,
3041 DBUS_TYPE_STRING, &interface,
3042 DBUS_TYPE_STRING, &property,
3043 DBUS_TYPE_INVALID)) {
3044 log_error("Could not append arguments to message.");
3049 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3050 log_error("Failed to issue method call: %s", bus_error_message(&error));
3055 if (!dbus_message_iter_init(reply, &iter) ||
3056 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3057 log_error("Failed to parse reply.");
3062 dbus_message_iter_recurse(&iter, &sub);
3064 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3065 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3066 log_error("Failed to parse reply.");
3071 dbus_message_iter_recurse(&sub, &sub2);
3073 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3076 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3077 log_error("Failed to parse reply.");
3082 dbus_message_iter_get_basic(&sub2, &text);
3083 printf("%s\n", text);
3085 dbus_message_iter_next(&sub2);
3092 dbus_message_unref(m);
3095 dbus_message_unref(reply);
3097 dbus_error_free(&error);
3102 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3103 DBusMessage *m = NULL, *reply = NULL;
3107 DBusMessageIter iter, sub;
3110 dbus_error_init(&error);
3112 method = streq(args[0], "set-environment")
3114 : "UnsetEnvironment";
3116 if (!(m = dbus_message_new_method_call(
3117 "org.freedesktop.systemd1",
3118 "/org/freedesktop/systemd1",
3119 "org.freedesktop.systemd1.Manager",
3122 log_error("Could not allocate message.");
3126 dbus_message_iter_init_append(m, &iter);
3128 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3129 log_error("Could not append arguments to message.");
3134 for (i = 1; i < n; i++)
3135 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3136 log_error("Could not append arguments to message.");
3141 if (!dbus_message_iter_close_container(&iter, &sub)) {
3142 log_error("Could not append arguments to message.");
3147 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3148 log_error("Failed to issue method call: %s", bus_error_message(&error));
3157 dbus_message_unref(m);
3160 dbus_message_unref(reply);
3162 dbus_error_free(&error);
3175 static Hashmap *will_install = NULL, *have_installed = NULL;
3176 static Set *remove_symlinks_to = NULL;
3178 static void install_info_free(InstallInfo *i) {
3183 strv_free(i->aliases);
3184 strv_free(i->wanted_by);
3188 static void install_info_hashmap_free(Hashmap *m) {
3191 while ((i = hashmap_steal_first(m)))
3192 install_info_free(i);
3197 static bool unit_name_valid(const char *name) {
3199 /* This is a minimal version of unit_name_valid() from
3205 if (ignore_file(name))
3211 static int install_info_add(const char *name) {
3215 assert(will_install);
3217 if (!unit_name_valid(name))
3220 if (hashmap_get(have_installed, name) ||
3221 hashmap_get(will_install, name))
3224 if (!(i = new0(InstallInfo, 1))) {
3229 if (!(i->name = strdup(name))) {
3234 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3241 install_info_free(i);
3246 static int config_parse_also(
3247 const char *filename,
3249 const char *section,
3263 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3267 if (!(n = strndup(w, l)))
3270 r = install_info_add(n);
3280 static int mark_symlink_for_removal(const char *p) {
3285 assert(path_is_absolute(p));
3287 if (!remove_symlinks_to)
3290 if (!(n = strdup(p)))
3293 path_kill_slashes(n);
3295 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3297 return r == -EEXIST ? 0 : r;
3303 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3312 if (!(d = fdopendir(fd))) {
3313 close_nointr_nofail(fd);
3319 while ((de = readdir(d))) {
3320 bool is_dir = false, is_link = false;
3322 if (ignore_file(de->d_name))
3325 if (de->d_type == DT_LNK)
3327 else if (de->d_type == DT_DIR)
3329 else if (de->d_type == DT_UNKNOWN) {
3332 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3333 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3340 is_link = S_ISLNK(st.st_mode);
3341 is_dir = S_ISDIR(st.st_mode);
3349 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3350 log_error("Failed to open %s/%s: %m", root, de->d_name);
3357 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3358 log_error("Failed to allocate directory string.");
3359 close_nointr_nofail(nfd);
3364 /* This will close nfd, regardless whether it succeeds or not */
3365 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3371 } else if (is_link) {
3375 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3376 log_error("Failed to allocate symlink string.");
3381 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3382 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3390 if ((c = canonicalize_file_name(dest))) {
3391 /* This might fail if the destination
3392 * is already removed */
3398 path_kill_slashes(dest);
3399 if (set_get(remove_symlinks_to, dest)) {
3402 log_info("rm '%s'", p);
3404 if (unlink(p) < 0) {
3405 log_error("Cannot unlink symlink %s: %m", p);
3410 rmdir_parents(p, config_path);
3411 path_kill_slashes(p);
3413 if (!set_get(remove_symlinks_to, p)) {
3415 if ((r = mark_symlink_for_removal(p)) < 0) {
3434 static int remove_marked_symlinks(const char *config_path) {
3438 assert(config_path);
3440 if (set_size(remove_symlinks_to) <= 0)
3443 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3450 if ((cfd = dup(fd)) < 0) {
3455 /* This takes possession of cfd and closes it */
3456 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3462 close_nointr_nofail(fd);
3467 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3474 if (streq(verb, "enable")) {
3477 mkdir_parents(new_path, 0755);
3479 if (symlink(old_path, new_path) >= 0) {
3482 log_info("ln -s '%s' '%s'", old_path, new_path);
3487 if (errno != EEXIST) {
3488 log_error("Cannot link %s to %s: %m", old_path, new_path);
3492 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3494 if (errno == EINVAL) {
3495 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3499 log_error("readlink() failed: %s", strerror(-r));
3503 if (streq(dest, old_path)) {
3509 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3518 log_info("ln -s '%s' '%s'", old_path, new_path);
3520 if (symlink(old_path, new_path) >= 0)
3523 log_error("Cannot link %s to %s: %m", old_path, new_path);
3526 } else if (streq(verb, "disable")) {
3529 if ((r = mark_symlink_for_removal(old_path)) < 0)
3532 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3533 if (errno == ENOENT)
3536 if (errno == EINVAL) {
3537 log_warning("File %s not a symlink, ignoring.", old_path);
3541 log_error("readlink() failed: %s", strerror(-r));
3545 if (!streq(dest, old_path)) {
3546 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3553 if ((r = mark_symlink_for_removal(new_path)) < 0)
3557 log_info("rm '%s'", new_path);
3559 if (unlink(new_path) >= 0)
3562 log_error("Cannot unlink %s: %m", new_path);
3565 } else if (streq(verb, "is-enabled")) {
3568 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3570 if (errno == ENOENT || errno == EINVAL)
3573 log_error("readlink() failed: %s", strerror(-r));
3577 if (streq(dest, old_path)) {
3585 assert_not_reached("Unknown action.");
3588 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3590 char *alias_path = NULL;
3595 assert(config_path);
3597 STRV_FOREACH(s, i->aliases) {
3599 if (!unit_name_valid(*s)) {
3600 log_error("Invalid name %s.", *s);
3606 if (!(alias_path = path_make_absolute(*s, config_path))) {
3607 log_error("Out of memory");
3612 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3615 if (streq(verb, "disable"))
3616 rmdir_parents(alias_path, config_path);
3627 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3629 char *alias_path = NULL;
3634 assert(config_path);
3636 STRV_FOREACH(s, i->wanted_by) {
3637 if (!unit_name_valid(*s)) {
3638 log_error("Invalid name %s.", *s);
3646 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3647 log_error("Out of memory");
3652 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3655 if (streq(verb, "disable"))
3656 rmdir_parents(alias_path, config_path);
3667 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3669 const ConfigItem items[] = {
3670 { "Alias", config_parse_strv, &i->aliases, "Install" },
3671 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3672 { "Also", config_parse_also, NULL, "Install" },
3674 { NULL, NULL, NULL, NULL }
3678 char *filename = NULL;
3685 STRV_FOREACH(p, paths->unit_path) {
3688 if (!(filename = path_make_absolute(i->name, *p))) {
3689 log_error("Out of memory");
3693 /* Ensure that we don't follow symlinks */
3694 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3695 if ((f = fdopen(fd, "re")))
3698 if (errno == ELOOP) {
3699 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3704 if (errno != ENOENT) {
3705 log_error("Failed to open %s: %m", filename);
3715 log_error("Couldn't find %s.", i->name);
3721 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3728 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3731 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3734 if ((r = mark_symlink_for_removal(filename)) < 0)
3737 if ((r = remove_marked_symlinks(config_path)) < 0)
3743 static char *get_config_path(void) {
3745 if (arg_session && arg_global)
3746 return strdup(SESSION_CONFIG_UNIT_PATH);
3751 if (session_config_home(&p) < 0)
3757 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3760 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3764 char *config_path = NULL;
3767 const char *verb = args[0];
3769 dbus_error_init(&error);
3772 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3773 log_error("Failed to determine lookup paths: %s", strerror(-r));
3777 if (!(config_path = get_config_path())) {
3778 log_error("Failed to determine config path");
3783 will_install = hashmap_new(string_hash_func, string_compare_func);
3784 have_installed = hashmap_new(string_hash_func, string_compare_func);
3786 if (!will_install || !have_installed) {
3787 log_error("Failed to allocate unit sets.");
3792 if (!arg_defaults && streq(verb, "disable"))
3793 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3794 log_error("Failed to allocate symlink sets.");
3799 for (j = 1; j < n; j++)
3800 if ((r = install_info_add(args[j])) < 0)
3803 while ((i = hashmap_first(will_install))) {
3806 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3808 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3816 /* In test mode and found something */
3822 if (streq(verb, "is-enabled"))
3823 r = r > 0 ? 0 : -ENOENT;
3825 /* Don't try to reload anything if the user asked us to not do this */
3827 /* Don't try to reload anything when updating a unit globally */
3829 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3830 (arg_session || sd_booted() > 0) &&
3831 /* Don't try to reload anything if we are running in a chroot environment */
3832 (arg_session || running_in_chroot() <= 0) ) {
3835 if ((q = daemon_reload(bus, args, n)) < 0)
3840 install_info_hashmap_free(will_install);
3841 install_info_hashmap_free(have_installed);
3843 set_free_free(remove_symlinks_to);
3845 lookup_paths_free(&paths);
3852 static int systemctl_help(void) {
3854 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3855 "Send control commands to or query the systemd manager.\n\n"
3856 " -h --help Show this help\n"
3857 " -t --type=TYPE List only units of a particular type\n"
3858 " -p --property=NAME Show only properties by this name\n"
3859 " -a --all Show all units/properties, including dead/empty ones\n"
3860 " --full Don't ellipsize unit names on output\n"
3861 " --fail When queueing a new job, fail if conflicting jobs are\n"
3863 " -q --quiet Suppress output\n"
3864 " --no-block Do not wait until operation finished\n"
3865 " --system Connect to system bus\n"
3866 " --session Connect to session bus\n"
3867 " --order When generating graph for dot, show only order\n"
3868 " --require When generating graph for dot, show only requirement\n"
3869 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3870 " --global Enable/disable unit files globally\n"
3871 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3873 " --force When enabling unit files, override existing symlinks\n"
3874 " --defaults When disabling unit files, remove default symlinks only\n\n"
3876 " list-units List units\n"
3877 " start [NAME...] Start (activate) one or more units\n"
3878 " stop [NAME...] Stop (deactivate) one or more units\n"
3879 " reload [NAME...] Reload one or more units\n"
3880 " restart [NAME...] Start or restart one or more units\n"
3881 " try-restart [NAME...] Restart one or more units if active\n"
3882 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3883 " otherwise start or restart\n"
3884 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3885 " otherwise restart if active\n"
3886 " isolate [NAME] Start one unit and stop all others\n"
3887 " is-active [NAME...] Check whether units are active\n"
3888 " status [NAME...|PID...] Show runtime status of one or more units\n"
3889 " show [NAME...|JOB...] Show properties of one or more\n"
3890 " units/jobs or the manager\n"
3891 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3893 " enable [NAME...] Enable one or more unit files\n"
3894 " disable [NAME...] Disable one or more unit files\n"
3895 " is-enabled [NAME...] Check whether unit files are enabled\n"
3896 " load [NAME...] Load one or more units\n"
3897 " list-jobs List jobs\n"
3898 " cancel [JOB...] Cancel all, one, or more jobs\n"
3899 " monitor Monitor unit/job changes\n"
3900 " dump Dump server status\n"
3901 " dot Dump dependency graph for dot(1)\n"
3902 " snapshot [NAME] Create a snapshot\n"
3903 " delete [NAME...] Remove one or more snapshots\n"
3904 " daemon-reload Reload systemd manager configuration\n"
3905 " daemon-reexec Reexecute systemd manager\n"
3906 " daemon-exit Ask the systemd manager to quit\n"
3907 " show-environment Dump environment\n"
3908 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3909 " unset-environment [NAME...] Unset one or more environment variables\n"
3910 " halt Shut down and halt the system\n"
3911 " poweroff Shut down and power-off the system\n"
3912 " reboot Shut down and reboot the system\n"
3913 " rescue Enter system rescue mode\n"
3914 " emergency Enter system emergency mode\n"
3915 " default Enter system default mode\n",
3916 program_invocation_short_name);
3921 static int halt_help(void) {
3923 printf("%s [OPTIONS...]\n\n"
3924 "%s the system.\n\n"
3925 " --help Show this help\n"
3926 " --halt Halt the machine\n"
3927 " -p --poweroff Switch off the machine\n"
3928 " --reboot Reboot the machine\n"
3929 " -f --force Force immediate halt/power-off/reboot\n"
3930 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3931 " -d --no-wtmp Don't write wtmp record\n"
3932 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3933 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3934 program_invocation_short_name,
3935 arg_action == ACTION_REBOOT ? "Reboot" :
3936 arg_action == ACTION_POWEROFF ? "Power off" :
3942 static int shutdown_help(void) {
3944 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3945 "Shut down the system.\n\n"
3946 " --help Show this help\n"
3947 " -H --halt Halt the machine\n"
3948 " -P --poweroff Power-off the machine\n"
3949 " -r --reboot Reboot the machine\n"
3950 " -h Equivalent to --poweroff, overriden by --halt\n"
3951 " -k Don't halt/power-off/reboot, just send warnings\n"
3952 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3953 " -c Cancel a pending shutdown\n",
3954 program_invocation_short_name);
3959 static int telinit_help(void) {
3961 printf("%s [OPTIONS...] {COMMAND}\n\n"
3962 "Send control commands to the init daemon.\n\n"
3963 " --help Show this help\n"
3964 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3966 " 0 Power-off the machine\n"
3967 " 6 Reboot the machine\n"
3968 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3969 " 1, s, S Enter rescue mode\n"
3970 " q, Q Reload init daemon configuration\n"
3971 " u, U Reexecute init daemon\n",
3972 program_invocation_short_name);
3977 static int runlevel_help(void) {
3979 printf("%s [OPTIONS...]\n\n"
3980 "Prints the previous and current runlevel of the init system.\n\n"
3981 " --help Show this help\n",
3982 program_invocation_short_name);
3987 static int systemctl_parse_argv(int argc, char *argv[]) {
4004 static const struct option options[] = {
4005 { "help", no_argument, NULL, 'h' },
4006 { "type", required_argument, NULL, 't' },
4007 { "property", required_argument, NULL, 'p' },
4008 { "all", no_argument, NULL, 'a' },
4009 { "full", no_argument, NULL, ARG_FULL },
4010 { "fail", no_argument, NULL, ARG_FAIL },
4011 { "session", no_argument, NULL, ARG_SESSION },
4012 { "system", no_argument, NULL, ARG_SYSTEM },
4013 { "global", no_argument, NULL, ARG_GLOBAL },
4014 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4015 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4016 { "quiet", no_argument, NULL, 'q' },
4017 { "order", no_argument, NULL, ARG_ORDER },
4018 { "require", no_argument, NULL, ARG_REQUIRE },
4019 { "force", no_argument, NULL, ARG_FORCE },
4020 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4021 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4022 { NULL, 0, NULL, 0 }
4030 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4045 if (!(l = strv_append(arg_property, optarg)))
4048 strv_free(arg_property);
4051 /* If the user asked for a particular
4052 * property, show it to him, even if it is
4071 arg_session = false;
4075 arg_no_block = true;
4083 arg_dot = DOT_ORDER;
4087 arg_dot = DOT_REQUIRE;
4103 arg_no_reload = true;
4112 arg_defaults = true;
4119 log_error("Unknown option code %c", c);
4127 static int halt_parse_argv(int argc, char *argv[]) {
4136 static const struct option options[] = {
4137 { "help", no_argument, NULL, ARG_HELP },
4138 { "halt", no_argument, NULL, ARG_HALT },
4139 { "poweroff", no_argument, NULL, 'p' },
4140 { "reboot", no_argument, NULL, ARG_REBOOT },
4141 { "force", no_argument, NULL, 'f' },
4142 { "wtmp-only", no_argument, NULL, 'w' },
4143 { "no-wtmp", no_argument, NULL, 'd' },
4144 { "no-sync", no_argument, NULL, 'n' },
4145 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4146 { NULL, 0, NULL, 0 }
4154 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4155 if (runlevel == '0' || runlevel == '6')
4156 arg_immediate = true;
4158 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4166 arg_action = ACTION_HALT;
4170 if (arg_action != ACTION_REBOOT)
4171 arg_action = ACTION_POWEROFF;
4175 arg_action = ACTION_REBOOT;
4179 arg_immediate = true;
4200 /* Compatibility nops */
4207 log_error("Unknown option code %c", c);
4212 if (optind < argc) {
4213 log_error("Too many arguments.");
4220 static int parse_time_spec(const char *t, usec_t *_u) {
4224 if (streq(t, "now"))
4226 else if (t[0] == '+') {
4229 if (safe_atou64(t + 1, &u) < 0)
4232 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4241 hour = strtol(t, &e, 10);
4242 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4245 minute = strtol(e+1, &e, 10);
4246 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4249 n = now(CLOCK_REALTIME);
4250 s = (time_t) (n / USEC_PER_SEC);
4253 assert_se(localtime_r(&s, &tm));
4255 tm.tm_hour = (int) hour;
4256 tm.tm_min = (int) minute;
4259 assert_se(s = mktime(&tm));
4261 *_u = (usec_t) s * USEC_PER_SEC;
4264 *_u += USEC_PER_DAY;
4270 static int shutdown_parse_argv(int argc, char *argv[]) {
4277 static const struct option options[] = {
4278 { "help", no_argument, NULL, ARG_HELP },
4279 { "halt", no_argument, NULL, 'H' },
4280 { "poweroff", no_argument, NULL, 'P' },
4281 { "reboot", no_argument, NULL, 'r' },
4282 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4283 { NULL, 0, NULL, 0 }
4291 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4299 arg_action = ACTION_HALT;
4303 arg_action = ACTION_POWEROFF;
4307 arg_action = ACTION_REBOOT;
4311 if (arg_action != ACTION_HALT)
4312 arg_action = ACTION_POWEROFF;
4325 /* Compatibility nops */
4329 arg_action = ACTION_CANCEL_SHUTDOWN;
4336 log_error("Unknown option code %c", c);
4341 if (argc > optind) {
4342 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4343 log_error("Failed to parse time specification: %s", argv[optind]);
4347 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4349 /* We skip the time argument */
4350 if (argc > optind + 1)
4351 arg_wall = argv + optind + 1;
4358 static int telinit_parse_argv(int argc, char *argv[]) {
4365 static const struct option options[] = {
4366 { "help", no_argument, NULL, ARG_HELP },
4367 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4368 { NULL, 0, NULL, 0 }
4371 static const struct {
4375 { '0', ACTION_POWEROFF },
4376 { '6', ACTION_REBOOT },
4377 { '1', ACTION_RESCUE },
4378 { '2', ACTION_RUNLEVEL2 },
4379 { '3', ACTION_RUNLEVEL3 },
4380 { '4', ACTION_RUNLEVEL4 },
4381 { '5', ACTION_RUNLEVEL5 },
4382 { 's', ACTION_RESCUE },
4383 { 'S', ACTION_RESCUE },
4384 { 'q', ACTION_RELOAD },
4385 { 'Q', ACTION_RELOAD },
4386 { 'u', ACTION_REEXEC },
4387 { 'U', ACTION_REEXEC }
4396 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4411 log_error("Unknown option code %c", c);
4416 if (optind >= argc) {
4421 if (optind + 1 < argc) {
4422 log_error("Too many arguments.");
4426 if (strlen(argv[optind]) != 1) {
4427 log_error("Expected single character argument.");
4431 for (i = 0; i < ELEMENTSOF(table); i++)
4432 if (table[i].from == argv[optind][0])
4435 if (i >= ELEMENTSOF(table)) {
4436 log_error("Unknown command %s.", argv[optind]);
4440 arg_action = table[i].to;
4447 static int runlevel_parse_argv(int argc, char *argv[]) {
4453 static const struct option options[] = {
4454 { "help", no_argument, NULL, ARG_HELP },
4455 { NULL, 0, NULL, 0 }
4463 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4474 log_error("Unknown option code %c", c);
4479 if (optind < argc) {
4480 log_error("Too many arguments.");
4487 static int parse_argv(int argc, char *argv[]) {
4491 if (program_invocation_short_name) {
4493 if (strstr(program_invocation_short_name, "halt")) {
4494 arg_action = ACTION_HALT;
4495 return halt_parse_argv(argc, argv);
4496 } else if (strstr(program_invocation_short_name, "poweroff")) {
4497 arg_action = ACTION_POWEROFF;
4498 return halt_parse_argv(argc, argv);
4499 } else if (strstr(program_invocation_short_name, "reboot")) {
4500 arg_action = ACTION_REBOOT;
4501 return halt_parse_argv(argc, argv);
4502 } else if (strstr(program_invocation_short_name, "shutdown")) {
4503 arg_action = ACTION_POWEROFF;
4504 return shutdown_parse_argv(argc, argv);
4505 } else if (strstr(program_invocation_short_name, "init")) {
4507 if (sd_booted() > 0) {
4508 arg_action = ACTION_INVALID;
4509 return telinit_parse_argv(argc, argv);
4511 /* Hmm, so some other init system is
4512 * running, we need to forward this
4513 * request to it. For now we simply
4514 * guess that it is Upstart. */
4516 execv("/lib/upstart/telinit", argv);
4518 log_error("Couldn't find an alternative telinit implementation to spawn.");
4522 } else if (strstr(program_invocation_short_name, "runlevel")) {
4523 arg_action = ACTION_RUNLEVEL;
4524 return runlevel_parse_argv(argc, argv);
4528 arg_action = ACTION_SYSTEMCTL;
4529 return systemctl_parse_argv(argc, argv);
4532 static int action_to_runlevel(void) {
4534 static const char table[_ACTION_MAX] = {
4535 [ACTION_HALT] = '0',
4536 [ACTION_POWEROFF] = '0',
4537 [ACTION_REBOOT] = '6',
4538 [ACTION_RUNLEVEL2] = '2',
4539 [ACTION_RUNLEVEL3] = '3',
4540 [ACTION_RUNLEVEL4] = '4',
4541 [ACTION_RUNLEVEL5] = '5',
4542 [ACTION_RESCUE] = '1'
4545 assert(arg_action < _ACTION_MAX);
4547 return table[arg_action];
4550 static int talk_upstart(void) {
4551 DBusMessage *m = NULL, *reply = NULL;
4553 int previous, rl, r;
4555 env1_buf[] = "RUNLEVEL=X",
4556 env2_buf[] = "PREVLEVEL=X";
4557 char *env1 = env1_buf, *env2 = env2_buf;
4558 const char *emit = "runlevel";
4559 dbus_bool_t b_false = FALSE;
4560 DBusMessageIter iter, sub;
4561 DBusConnection *bus;
4563 dbus_error_init(&error);
4565 if (!(rl = action_to_runlevel()))
4568 if (utmp_get_runlevel(&previous, NULL) < 0)
4571 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4572 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4577 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4582 if ((r = bus_check_peercred(bus)) < 0) {
4583 log_error("Failed to verify owner of bus.");
4587 if (!(m = dbus_message_new_method_call(
4588 "com.ubuntu.Upstart",
4589 "/com/ubuntu/Upstart",
4590 "com.ubuntu.Upstart0_6",
4593 log_error("Could not allocate message.");
4598 dbus_message_iter_init_append(m, &iter);
4600 env1_buf[sizeof(env1_buf)-2] = rl;
4601 env2_buf[sizeof(env2_buf)-2] = previous;
4603 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4604 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4605 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4606 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4607 !dbus_message_iter_close_container(&iter, &sub) ||
4608 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4609 log_error("Could not append arguments to message.");
4614 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4616 if (error_is_no_service(&error)) {
4621 log_error("Failed to issue method call: %s", bus_error_message(&error));
4630 dbus_message_unref(m);
4633 dbus_message_unref(reply);
4636 dbus_connection_close(bus);
4637 dbus_connection_unref(bus);
4640 dbus_error_free(&error);
4645 static int talk_initctl(void) {
4646 struct init_request request;
4650 if (!(rl = action_to_runlevel()))
4654 request.magic = INIT_MAGIC;
4655 request.sleeptime = 0;
4656 request.cmd = INIT_CMD_RUNLVL;
4657 request.runlevel = rl;
4659 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4661 if (errno == ENOENT)
4664 log_error("Failed to open "INIT_FIFO": %m");
4669 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4670 close_nointr_nofail(fd);
4673 log_error("Failed to write to "INIT_FIFO": %m");
4674 return errno ? -errno : -EIO;
4680 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4682 static const struct {
4690 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4692 { "list-units", LESS, 1, list_units },
4693 { "list-jobs", EQUAL, 1, list_jobs },
4694 { "clear-jobs", EQUAL, 1, daemon_reload },
4695 { "load", MORE, 2, load_unit },
4696 { "cancel", MORE, 2, cancel_job },
4697 { "start", MORE, 2, start_unit },
4698 { "stop", MORE, 2, start_unit },
4699 { "reload", MORE, 2, start_unit },
4700 { "restart", MORE, 2, start_unit },
4701 { "try-restart", MORE, 2, start_unit },
4702 { "reload-or-restart", MORE, 2, start_unit },
4703 { "reload-or-try-restart", MORE, 2, start_unit },
4704 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4705 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4706 { "isolate", EQUAL, 2, start_unit },
4707 { "is-active", MORE, 2, check_unit },
4708 { "check", MORE, 2, check_unit },
4709 { "show", MORE, 1, show },
4710 { "status", MORE, 2, show },
4711 { "monitor", EQUAL, 1, monitor },
4712 { "dump", EQUAL, 1, dump },
4713 { "dot", EQUAL, 1, dot },
4714 { "snapshot", LESS, 2, snapshot },
4715 { "delete", MORE, 2, delete_snapshot },
4716 { "daemon-reload", EQUAL, 1, daemon_reload },
4717 { "daemon-reexec", EQUAL, 1, daemon_reload },
4718 { "daemon-exit", EQUAL, 1, daemon_reload },
4719 { "show-environment", EQUAL, 1, show_enviroment },
4720 { "set-environment", MORE, 2, set_environment },
4721 { "unset-environment", MORE, 2, set_environment },
4722 { "halt", EQUAL, 1, start_special },
4723 { "poweroff", EQUAL, 1, start_special },
4724 { "reboot", EQUAL, 1, start_special },
4725 { "default", EQUAL, 1, start_special },
4726 { "rescue", EQUAL, 1, start_special },
4727 { "emergency", EQUAL, 1, start_special },
4728 { "reset-failed", MORE, 1, reset_failed },
4729 { "enable", MORE, 2, enable_unit },
4730 { "disable", MORE, 2, enable_unit },
4731 { "is-enabled", MORE, 2, enable_unit }
4741 left = argc - optind;
4744 /* Special rule: no arguments means "list-units" */
4747 if (streq(argv[optind], "help")) {
4752 for (i = 0; i < ELEMENTSOF(verbs); i++)
4753 if (streq(argv[optind], verbs[i].verb))
4756 if (i >= ELEMENTSOF(verbs)) {
4757 log_error("Unknown operation %s", argv[optind]);
4762 switch (verbs[i].argc_cmp) {
4765 if (left != verbs[i].argc) {
4766 log_error("Invalid number of arguments.");
4773 if (left < verbs[i].argc) {
4774 log_error("Too few arguments.");
4781 if (left > verbs[i].argc) {
4782 log_error("Too many arguments.");
4789 assert_not_reached("Unknown comparison operator.");
4792 /* Require a bus connection for all operations but
4794 if (!streq(verbs[i].verb, "enable") &&
4795 !streq(verbs[i].verb, "disable") &&
4797 log_error("Failed to get D-Bus connection: %s", error->message);
4801 return verbs[i].dispatch(bus, argv + optind, left);
4804 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4806 struct msghdr msghdr;
4808 union sockaddr_union sockaddr;
4809 struct shutdownd_command c;
4817 strncpy(c.wall_message, message, sizeof(c.wall_message));
4819 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4823 sockaddr.sa.sa_family = AF_UNIX;
4824 sockaddr.un.sun_path[0] = 0;
4825 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4828 iovec.iov_base = (char*) &c;
4829 iovec.iov_len = sizeof(c);
4832 msghdr.msg_name = &sockaddr;
4833 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4835 msghdr.msg_iov = &iovec;
4836 msghdr.msg_iovlen = 1;
4838 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4839 close_nointr_nofail(fd);
4843 close_nointr_nofail(fd);
4847 static int reload_with_fallback(DBusConnection *bus) {
4850 /* First, try systemd via D-Bus. */
4851 if (daemon_reload(bus, NULL, 0) > 0)
4855 /* Nothing else worked, so let's try signals */
4856 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4858 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4859 log_error("kill() failed: %m");
4866 static int start_with_fallback(DBusConnection *bus) {
4869 /* First, try systemd via D-Bus. */
4870 if (start_unit(bus, NULL, 0) > 0)
4874 /* Hmm, talking to systemd via D-Bus didn't work. Then
4875 * let's try to talk to Upstart via D-Bus. */
4876 if (talk_upstart() > 0)
4879 /* Nothing else worked, so let's try
4881 if (talk_initctl() > 0)
4884 log_error("Failed to talk to init daemon.");
4888 warn_wall(arg_action);
4892 static int halt_main(DBusConnection *bus) {
4895 if (geteuid() != 0) {
4896 log_error("Must be root.");
4902 char date[FORMAT_TIMESTAMP_MAX];
4904 m = strv_join(arg_wall, " ");
4905 r = send_shutdownd(arg_when,
4906 arg_action == ACTION_HALT ? 'H' :
4907 arg_action == ACTION_POWEROFF ? 'P' :
4914 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4916 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4917 format_timestamp(date, sizeof(date), arg_when));
4922 if (!arg_dry && !arg_immediate)
4923 return start_with_fallback(bus);
4926 if (sd_booted() > 0)
4927 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4928 else if ((r = utmp_put_shutdown(0)) < 0)
4929 log_warning("Failed to write utmp record: %s", strerror(-r));
4938 /* Make sure C-A-D is handled by the kernel from this
4940 reboot(RB_ENABLE_CAD);
4942 switch (arg_action) {
4945 log_info("Halting.");
4946 reboot(RB_HALT_SYSTEM);
4949 case ACTION_POWEROFF:
4950 log_info("Powering off.");
4951 reboot(RB_POWER_OFF);
4955 log_info("Rebooting.");
4956 reboot(RB_AUTOBOOT);
4960 assert_not_reached("Unknown halt action.");
4963 /* We should never reach this. */
4967 static int runlevel_main(void) {
4968 int r, runlevel, previous;
4970 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4971 printf("unknown\n");
4976 previous <= 0 ? 'N' : previous,
4977 runlevel <= 0 ? 'N' : runlevel);
4982 int main(int argc, char*argv[]) {
4983 int r, retval = EXIT_FAILURE;
4984 DBusConnection *bus = NULL;
4987 dbus_error_init(&error);
4989 log_parse_environment();
4992 if ((r = parse_argv(argc, argv)) < 0)
4995 retval = EXIT_SUCCESS;
4999 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5000 * let's shortcut this */
5001 if (arg_action == ACTION_RUNLEVEL) {
5002 r = runlevel_main();
5003 retval = r < 0 ? EXIT_FAILURE : r;
5007 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5009 switch (arg_action) {
5011 case ACTION_SYSTEMCTL:
5012 r = systemctl_main(bus, argc, argv, &error);
5016 case ACTION_POWEROFF:
5021 case ACTION_RUNLEVEL2:
5022 case ACTION_RUNLEVEL3:
5023 case ACTION_RUNLEVEL4:
5024 case ACTION_RUNLEVEL5:
5026 case ACTION_EMERGENCY:
5027 case ACTION_DEFAULT:
5028 r = start_with_fallback(bus);
5033 r = reload_with_fallback(bus);
5036 case ACTION_CANCEL_SHUTDOWN:
5037 r = send_shutdownd(0, 0, false, NULL);
5040 case ACTION_INVALID:
5041 case ACTION_RUNLEVEL:
5043 assert_not_reached("Unknown action");
5046 retval = r < 0 ? EXIT_FAILURE : r;
5051 dbus_connection_close(bus);
5052 dbus_connection_unref(bus);
5055 dbus_error_free(&error);
5059 strv_free(arg_property);