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"
55 static const char *arg_type = NULL;
56 static char **arg_property = NULL;
57 static bool arg_all = false;
58 static bool arg_fail = false;
59 static bool arg_session = false;
60 static bool arg_global = false;
61 static bool arg_immediate = false;
62 static bool arg_no_block = false;
63 static bool arg_no_wtmp = false;
64 static bool arg_no_sync = false;
65 static bool arg_no_wall = false;
66 static bool arg_no_reload = false;
67 static bool arg_dry = false;
68 static bool arg_quiet = false;
69 static bool arg_full = false;
70 static bool arg_force = false;
71 static bool arg_defaults = false;
72 static bool arg_sysv_compat = false; /* this is undocumented, and
73 * exists simply to make
74 * implementation of SysV
75 * compatible shell glue
77 static char **arg_wall = NULL;
78 static usec_t arg_when = 0;
95 ACTION_CANCEL_SHUTDOWN,
97 } arg_action = ACTION_SYSTEMCTL;
104 static bool private_bus = false;
106 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
108 static bool on_tty(void) {
111 if (_unlikely_(t < 0))
112 t = isatty(STDOUT_FILENO) > 0;
117 static const char *ansi_highlight(bool b) {
122 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
125 static const char *ansi_highlight_green(bool b) {
130 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
133 static bool error_is_no_service(const DBusError *error) {
136 if (!dbus_error_is_set(error))
139 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
142 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
145 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
148 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
153 if (dbus_message_iter_get_arg_type(iter) != type)
156 dbus_message_iter_get_basic(iter, data);
158 if (!dbus_message_iter_next(iter) != !next)
164 static void warn_wall(enum action action) {
165 static const char *table[_ACTION_MAX] = {
166 [ACTION_HALT] = "The system is going down for system halt NOW!",
167 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
168 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
169 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
170 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
179 if (!(p = strv_join(arg_wall, " "))) {
180 log_error("Failed to join strings.");
196 utmp_wall(table[action]);
201 const char *description;
202 const char *load_state;
203 const char *active_state;
204 const char *sub_state;
205 const char *following;
206 const char *unit_path;
208 const char *job_type;
209 const char *job_path;
212 static int compare_unit_info(const void *a, const void *b) {
214 const struct unit_info *u = a, *v = b;
216 d1 = strrchr(u->id, '.');
217 d2 = strrchr(v->id, '.');
222 if ((r = strcasecmp(d1, d2)) != 0)
226 return strcasecmp(u->id, v->id);
229 static int list_units(DBusConnection *bus, char **args, unsigned n) {
230 DBusMessage *m = NULL, *reply = NULL;
233 DBusMessageIter iter, sub, sub2;
234 unsigned c = 0, k, n_units = 0;
235 struct unit_info *unit_infos = NULL;
237 dbus_error_init(&error);
241 if (!(m = dbus_message_new_method_call(
242 "org.freedesktop.systemd1",
243 "/org/freedesktop/systemd1",
244 "org.freedesktop.systemd1.Manager",
246 log_error("Could not allocate message.");
250 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
251 log_error("Failed to issue method call: %s", bus_error_message(&error));
256 if (!dbus_message_iter_init(reply, &iter) ||
257 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
258 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
259 log_error("Failed to parse reply.");
264 dbus_message_iter_recurse(&iter, &sub);
266 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
269 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
270 log_error("Failed to parse reply.");
278 n_units = MAX(2*c, 16);
279 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
282 log_error("Failed to allocate unit array.");
292 dbus_message_iter_recurse(&sub, &sub2);
294 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
295 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
296 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
297 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
298 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
299 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
300 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
301 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
302 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
303 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
304 log_error("Failed to parse reply.");
309 dbus_message_iter_next(&sub);
313 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
315 if (isatty(STDOUT_FILENO)) {
316 if (columns() >= 80+12 || arg_full)
317 printf("%-25s %-6s %-12s %-18s %-15s %s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB", "DESCRIPTION");
319 printf("%-25s %-6s %-12s %-18s %-15s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB");
322 for (k = 0; k < c; k++) {
324 struct unit_info *u = unit_infos+k;
326 if ((!arg_type || ((dot = strrchr(u->id, '.')) &&
327 streq(dot+1, arg_type))) &&
328 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0)) {
331 const char *on_loaded, *off_loaded;
332 const char *on_active, *off_active;
334 if (!streq(u->load_state, "loaded")) {
335 on_loaded = ansi_highlight(true);
336 off_loaded = ansi_highlight(false);
338 on_loaded = off_loaded = "";
340 if (streq(u->active_state, "failed")) {
341 on_active = ansi_highlight(true);
342 off_active = ansi_highlight(false);
344 on_active = off_active = "";
346 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
348 printf("%-25s %s%-6s%s %s%-12s %-18s%s%n",
350 on_loaded, u->load_state, off_loaded,
351 on_active, u->active_state, u->sub_state, off_active,
356 a -= strlen(on_loaded) + strlen(off_loaded);
357 a -= strlen(on_active) + strlen(off_active);
360 printf(" %-15s%n", u->job_type, &b);
364 if (a + b + 1 < columns()) {
369 printf(" %s", u->description);
371 printf(" %.*s", columns() - a - b - 1, u->description);
378 if (isatty(STDOUT_FILENO)) {
380 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
381 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
382 "SUB = The low-level unit activation state, values depend on unit type.\n"
383 "JOB = Pending job for the unit.\n");
386 printf("\n%u units listed.\n", c);
388 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
395 dbus_message_unref(m);
398 dbus_message_unref(reply);
402 dbus_error_free(&error);
407 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
408 static const char * const colors[] = {
409 "Requires", "[color=\"black\"]",
410 "RequiresOverridable", "[color=\"black\"]",
411 "Requisite", "[color=\"darkblue\"]",
412 "RequisiteOverridable", "[color=\"darkblue\"]",
413 "Wants", "[color=\"darkgrey\"]",
414 "Conflicts", "[color=\"red\"]",
415 "ConflictedBy", "[color=\"red\"]",
416 "After", "[color=\"green\"]"
419 const char *c = NULL;
426 for (i = 0; i < ELEMENTSOF(colors); i += 2)
427 if (streq(colors[i], prop)) {
435 if (arg_dot != DOT_ALL)
436 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
439 switch (dbus_message_iter_get_arg_type(iter)) {
441 case DBUS_TYPE_ARRAY:
443 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
446 dbus_message_iter_recurse(iter, &sub);
448 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
451 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
452 dbus_message_iter_get_basic(&sub, &s);
453 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
455 dbus_message_iter_next(&sub);
465 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
466 DBusMessage *m = NULL, *reply = NULL;
467 const char *interface = "org.freedesktop.systemd1.Unit";
470 DBusMessageIter iter, sub, sub2, sub3;
475 dbus_error_init(&error);
477 if (!(m = dbus_message_new_method_call(
478 "org.freedesktop.systemd1",
480 "org.freedesktop.DBus.Properties",
482 log_error("Could not allocate message.");
487 if (!dbus_message_append_args(m,
488 DBUS_TYPE_STRING, &interface,
489 DBUS_TYPE_INVALID)) {
490 log_error("Could not append arguments to message.");
495 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
496 log_error("Failed to issue method call: %s", bus_error_message(&error));
501 if (!dbus_message_iter_init(reply, &iter) ||
502 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
503 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
504 log_error("Failed to parse reply.");
509 dbus_message_iter_recurse(&iter, &sub);
511 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
514 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
515 log_error("Failed to parse reply.");
520 dbus_message_iter_recurse(&sub, &sub2);
522 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
523 log_error("Failed to parse reply.");
528 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
529 log_error("Failed to parse reply.");
534 dbus_message_iter_recurse(&sub2, &sub3);
536 if (dot_one_property(name, prop, &sub3)) {
537 log_error("Failed to parse reply.");
542 dbus_message_iter_next(&sub);
549 dbus_message_unref(m);
552 dbus_message_unref(reply);
554 dbus_error_free(&error);
559 static int dot(DBusConnection *bus, char **args, unsigned n) {
560 DBusMessage *m = NULL, *reply = NULL;
563 DBusMessageIter iter, sub, sub2;
565 dbus_error_init(&error);
569 if (!(m = dbus_message_new_method_call(
570 "org.freedesktop.systemd1",
571 "/org/freedesktop/systemd1",
572 "org.freedesktop.systemd1.Manager",
574 log_error("Could not allocate message.");
578 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
579 log_error("Failed to issue method call: %s", bus_error_message(&error));
584 if (!dbus_message_iter_init(reply, &iter) ||
585 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
586 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
587 log_error("Failed to parse reply.");
592 printf("digraph systemd {\n");
594 dbus_message_iter_recurse(&iter, &sub);
595 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
596 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
598 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
599 log_error("Failed to parse reply.");
604 dbus_message_iter_recurse(&sub, &sub2);
606 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
607 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
608 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
609 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
610 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
611 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
612 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
613 log_error("Failed to parse reply.");
618 if ((r = dot_one(bus, id, unit_path)) < 0)
621 /* printf("\t\"%s\";\n", id); */
622 dbus_message_iter_next(&sub);
627 log_info(" Color legend: black = Requires\n"
628 " dark blue = Requisite\n"
629 " dark grey = Wants\n"
633 if (isatty(fileno(stdout)))
634 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
635 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
641 dbus_message_unref(m);
644 dbus_message_unref(reply);
646 dbus_error_free(&error);
651 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
652 DBusMessage *m = NULL, *reply = NULL;
655 DBusMessageIter iter, sub, sub2;
658 dbus_error_init(&error);
662 if (!(m = dbus_message_new_method_call(
663 "org.freedesktop.systemd1",
664 "/org/freedesktop/systemd1",
665 "org.freedesktop.systemd1.Manager",
667 log_error("Could not allocate message.");
671 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
672 log_error("Failed to issue method call: %s", bus_error_message(&error));
677 if (!dbus_message_iter_init(reply, &iter) ||
678 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
679 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
680 log_error("Failed to parse reply.");
685 dbus_message_iter_recurse(&iter, &sub);
687 if (isatty(STDOUT_FILENO))
688 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
690 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
691 const char *name, *type, *state, *job_path, *unit_path;
695 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
696 log_error("Failed to parse reply.");
701 dbus_message_iter_recurse(&sub, &sub2);
703 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
704 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
705 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
706 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
707 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
708 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
709 log_error("Failed to parse reply.");
714 e = arg_full ? NULL : ellipsize(name, 25, 33);
715 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
720 dbus_message_iter_next(&sub);
723 if (isatty(STDOUT_FILENO))
724 printf("\n%u jobs listed.\n", k);
730 dbus_message_unref(m);
733 dbus_message_unref(reply);
735 dbus_error_free(&error);
740 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
741 DBusMessage *m = NULL, *reply = NULL;
746 dbus_error_init(&error);
751 for (i = 1; i < n; i++) {
753 if (!(m = dbus_message_new_method_call(
754 "org.freedesktop.systemd1",
755 "/org/freedesktop/systemd1",
756 "org.freedesktop.systemd1.Manager",
758 log_error("Could not allocate message.");
763 if (!dbus_message_append_args(m,
764 DBUS_TYPE_STRING, &args[i],
765 DBUS_TYPE_INVALID)) {
766 log_error("Could not append arguments to message.");
771 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
772 log_error("Failed to issue method call: %s", bus_error_message(&error));
777 dbus_message_unref(m);
778 dbus_message_unref(reply);
787 dbus_message_unref(m);
790 dbus_message_unref(reply);
792 dbus_error_free(&error);
797 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
798 DBusMessage *m = NULL, *reply = NULL;
803 dbus_error_init(&error);
809 return daemon_reload(bus, args, n);
811 for (i = 1; i < n; i++) {
815 if (!(m = dbus_message_new_method_call(
816 "org.freedesktop.systemd1",
817 "/org/freedesktop/systemd1",
818 "org.freedesktop.systemd1.Manager",
820 log_error("Could not allocate message.");
825 if ((r = safe_atou(args[i], &id)) < 0) {
826 log_error("Failed to parse job id: %s", strerror(-r));
830 assert_cc(sizeof(uint32_t) == sizeof(id));
831 if (!dbus_message_append_args(m,
832 DBUS_TYPE_UINT32, &id,
833 DBUS_TYPE_INVALID)) {
834 log_error("Could not append arguments to message.");
839 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
840 log_error("Failed to issue method call: %s", bus_error_message(&error));
845 if (!dbus_message_get_args(reply, &error,
846 DBUS_TYPE_OBJECT_PATH, &path,
847 DBUS_TYPE_INVALID)) {
848 log_error("Failed to parse reply: %s", bus_error_message(&error));
853 dbus_message_unref(m);
854 if (!(m = dbus_message_new_method_call(
855 "org.freedesktop.systemd1",
857 "org.freedesktop.systemd1.Job",
859 log_error("Could not allocate message.");
864 dbus_message_unref(reply);
865 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
866 log_error("Failed to issue method call: %s", bus_error_message(&error));
871 dbus_message_unref(m);
872 dbus_message_unref(reply);
880 dbus_message_unref(m);
883 dbus_message_unref(reply);
885 dbus_error_free(&error);
890 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
891 DBusMessage *m = NULL, *reply = NULL;
892 dbus_bool_t b = FALSE;
893 DBusMessageIter iter, sub;
895 *interface = "org.freedesktop.systemd1.Unit",
896 *property = "NeedDaemonReload",
899 /* We ignore all errors here, since this is used to show a warning only */
901 if (!(m = dbus_message_new_method_call(
902 "org.freedesktop.systemd1",
903 "/org/freedesktop/systemd1",
904 "org.freedesktop.systemd1.Manager",
908 if (!dbus_message_append_args(m,
909 DBUS_TYPE_STRING, &unit,
913 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
916 if (!dbus_message_get_args(reply, NULL,
917 DBUS_TYPE_OBJECT_PATH, &path,
921 dbus_message_unref(m);
922 if (!(m = dbus_message_new_method_call(
923 "org.freedesktop.systemd1",
925 "org.freedesktop.DBus.Properties",
929 if (!dbus_message_append_args(m,
930 DBUS_TYPE_STRING, &interface,
931 DBUS_TYPE_STRING, &property,
932 DBUS_TYPE_INVALID)) {
936 dbus_message_unref(reply);
937 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
940 if (!dbus_message_iter_init(reply, &iter) ||
941 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
944 dbus_message_iter_recurse(&iter, &sub);
946 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
949 dbus_message_iter_get_basic(&sub, &b);
953 dbus_message_unref(m);
956 dbus_message_unref(reply);
961 typedef struct WaitData {
966 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
974 dbus_error_init(&error);
976 log_debug("Got D-Bus request: %s.%s() on %s",
977 dbus_message_get_interface(message),
978 dbus_message_get_member(message),
979 dbus_message_get_path(message));
981 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
982 log_error("Warning! D-Bus connection terminated.");
983 dbus_connection_close(connection);
985 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
988 dbus_bool_t success = true;
990 if (!dbus_message_get_args(message, &error,
991 DBUS_TYPE_UINT32, &id,
992 DBUS_TYPE_OBJECT_PATH, &path,
993 DBUS_TYPE_BOOLEAN, &success,
995 log_error("Failed to parse message: %s", bus_error_message(&error));
999 if ((p = set_remove(d->set, (char*) path)))
1007 dbus_error_free(&error);
1008 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1011 static int enable_wait_for_jobs(DBusConnection *bus) {
1019 dbus_error_init(&error);
1020 dbus_bus_add_match(bus,
1022 "sender='org.freedesktop.systemd1',"
1023 "interface='org.freedesktop.systemd1.Manager',"
1024 "member='JobRemoved',"
1025 "path='/org/freedesktop/systemd1'",
1028 if (dbus_error_is_set(&error)) {
1029 log_error("Failed to add match: %s", bus_error_message(&error));
1030 dbus_error_free(&error);
1034 /* This is slightly dirty, since we don't undo the match registrations. */
1038 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1049 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1050 log_error("Failed to add filter.");
1055 while (!set_isempty(s) &&
1056 dbus_connection_read_write_dispatch(bus, -1))
1059 if (!arg_quiet && d.failed)
1060 log_error("Job failed, see logs for details.");
1062 r = d.failed ? -EIO : 0;
1065 /* This is slightly dirty, since we don't undo the filter registration. */
1070 static int start_unit_one(
1071 DBusConnection *bus,
1077 DBusMessage *m = NULL, *reply = NULL;
1086 assert(arg_no_block || s);
1088 dbus_error_init(&error);
1090 if (!(m = dbus_message_new_method_call(
1091 "org.freedesktop.systemd1",
1092 "/org/freedesktop/systemd1",
1093 "org.freedesktop.systemd1.Manager",
1095 log_error("Could not allocate message.");
1100 if (!dbus_message_append_args(m,
1101 DBUS_TYPE_STRING, &name,
1102 DBUS_TYPE_STRING, &mode,
1103 DBUS_TYPE_INVALID)) {
1104 log_error("Could not append arguments to message.");
1109 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1111 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
1112 /* There's always a fallback possible for
1113 * legacy actions. */
1118 log_error("Failed to issue method call: %s", bus_error_message(&error));
1123 if (!dbus_message_get_args(reply, &error,
1124 DBUS_TYPE_OBJECT_PATH, &path,
1125 DBUS_TYPE_INVALID)) {
1126 log_error("Failed to parse reply: %s", bus_error_message(&error));
1131 if (need_daemon_reload(bus, name))
1132 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1133 arg_session ? "--session" : "--system");
1135 if (!arg_no_block) {
1138 if (!(p = strdup(path))) {
1139 log_error("Failed to duplicate path.");
1144 if ((r = set_put(s, p)) < 0) {
1146 log_error("Failed to add path to set.");
1155 dbus_message_unref(m);
1158 dbus_message_unref(reply);
1160 dbus_error_free(&error);
1165 static enum action verb_to_action(const char *verb) {
1166 if (streq(verb, "halt"))
1168 else if (streq(verb, "poweroff"))
1169 return ACTION_POWEROFF;
1170 else if (streq(verb, "reboot"))
1171 return ACTION_REBOOT;
1172 else if (streq(verb, "rescue"))
1173 return ACTION_RESCUE;
1174 else if (streq(verb, "emergency"))
1175 return ACTION_EMERGENCY;
1176 else if (streq(verb, "default"))
1177 return ACTION_DEFAULT;
1179 return ACTION_INVALID;
1182 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1184 static const char * const table[_ACTION_MAX] = {
1185 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1186 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1187 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1188 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1189 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1190 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1191 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1192 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1193 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1194 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1199 const char *method, *mode, *one_name;
1204 if (arg_action == ACTION_SYSTEMCTL) {
1206 streq(args[0], "stop") ? "StopUnit" :
1207 streq(args[0], "reload") ? "ReloadUnit" :
1208 streq(args[0], "restart") ? "RestartUnit" :
1209 streq(args[0], "try-restart") ? "TryRestartUnit" :
1210 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1211 streq(args[0], "reload-or-try-restart") ||
1212 streq(args[0], "force-reload") ||
1213 streq(args[0], "condrestart") ? "ReloadOrTryRestartUnit" :
1217 (streq(args[0], "isolate") ||
1218 streq(args[0], "rescue") ||
1219 streq(args[0], "emergency")) ? "isolate" :
1223 one_name = table[verb_to_action(args[0])];
1226 assert(arg_action < ELEMENTSOF(table));
1227 assert(table[arg_action]);
1229 method = "StartUnit";
1231 mode = (arg_action == ACTION_EMERGENCY ||
1232 arg_action == ACTION_RESCUE) ? "isolate" : "replace";
1234 one_name = table[arg_action];
1237 if (!arg_no_block) {
1238 if ((r = enable_wait_for_jobs(bus)) < 0) {
1239 log_error("Could not watch jobs: %s", strerror(-r));
1243 if (!(s = set_new(string_hash_func, string_compare_func))) {
1244 log_error("Failed to allocate set.");
1253 if ((r = start_unit_one(bus, method, one_name, mode, s)) <= 0)
1256 for (i = 1; i < n; i++)
1257 if ((r = start_unit_one(bus, method, args[i], mode, s)) < 0)
1262 if ((r = wait_for_jobs(bus, s)) < 0)
1274 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1280 r = start_unit(bus, args, n);
1283 warn_wall(verb_to_action(args[0]));
1288 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1289 DBusMessage *m = NULL, *reply = NULL;
1291 *interface = "org.freedesktop.systemd1.Unit",
1292 *property = "ActiveState";
1293 int r = -EADDRNOTAVAIL;
1300 dbus_error_init(&error);
1302 for (i = 1; i < n; i++) {
1303 const char *path = NULL;
1305 DBusMessageIter iter, sub;
1307 if (!(m = dbus_message_new_method_call(
1308 "org.freedesktop.systemd1",
1309 "/org/freedesktop/systemd1",
1310 "org.freedesktop.systemd1.Manager",
1312 log_error("Could not allocate message.");
1317 if (!dbus_message_append_args(m,
1318 DBUS_TYPE_STRING, &args[i],
1319 DBUS_TYPE_INVALID)) {
1320 log_error("Could not append arguments to message.");
1325 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1327 /* Hmm, cannot figure out anything about this unit... */
1331 dbus_error_free(&error);
1335 if (!dbus_message_get_args(reply, &error,
1336 DBUS_TYPE_OBJECT_PATH, &path,
1337 DBUS_TYPE_INVALID)) {
1338 log_error("Failed to parse reply: %s", bus_error_message(&error));
1343 dbus_message_unref(m);
1344 if (!(m = dbus_message_new_method_call(
1345 "org.freedesktop.systemd1",
1347 "org.freedesktop.DBus.Properties",
1349 log_error("Could not allocate message.");
1354 if (!dbus_message_append_args(m,
1355 DBUS_TYPE_STRING, &interface,
1356 DBUS_TYPE_STRING, &property,
1357 DBUS_TYPE_INVALID)) {
1358 log_error("Could not append arguments to message.");
1363 dbus_message_unref(reply);
1364 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1365 log_error("Failed to issue method call: %s", bus_error_message(&error));
1370 if (!dbus_message_iter_init(reply, &iter) ||
1371 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1372 log_error("Failed to parse reply.");
1377 dbus_message_iter_recurse(&iter, &sub);
1379 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1380 log_error("Failed to parse reply.");
1385 dbus_message_iter_get_basic(&sub, &state);
1390 if (streq(state, "active") || streq(state, "reloading"))
1393 dbus_message_unref(m);
1394 dbus_message_unref(reply);
1400 dbus_message_unref(m);
1403 dbus_message_unref(reply);
1405 dbus_error_free(&error);
1410 typedef struct ExecStatusInfo {
1416 usec_t start_timestamp;
1417 usec_t exit_timestamp;
1422 LIST_FIELDS(struct ExecStatusInfo, exec);
1425 static void exec_status_info_free(ExecStatusInfo *i) {
1433 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1434 uint64_t start_timestamp, exit_timestamp;
1435 DBusMessageIter sub2, sub3;
1439 int32_t code, status;
1445 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1448 dbus_message_iter_recurse(sub, &sub2);
1450 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1453 if (!(i->path = strdup(path)))
1456 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1457 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1461 dbus_message_iter_recurse(&sub2, &sub3);
1462 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1463 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1464 dbus_message_iter_next(&sub3);
1469 if (!(i->argv = new0(char*, n+1)))
1473 dbus_message_iter_recurse(&sub2, &sub3);
1474 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1477 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1478 dbus_message_iter_get_basic(&sub3, &s);
1479 dbus_message_iter_next(&sub3);
1481 if (!(i->argv[n++] = strdup(s)))
1485 if (!dbus_message_iter_next(&sub2) ||
1486 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1487 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1488 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1489 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1490 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1491 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1495 i->start_timestamp = (usec_t) start_timestamp;
1496 i->exit_timestamp = (usec_t) exit_timestamp;
1497 i->pid = (pid_t) pid;
1504 typedef struct UnitStatusInfo {
1506 const char *load_state;
1507 const char *active_state;
1508 const char *sub_state;
1510 const char *description;
1513 const char *default_control_group;
1515 usec_t inactive_exit_timestamp;
1516 usec_t active_enter_timestamp;
1517 usec_t active_exit_timestamp;
1518 usec_t inactive_enter_timestamp;
1520 bool need_daemon_reload;
1525 const char *status_text;
1529 usec_t start_timestamp;
1530 usec_t exit_timestamp;
1532 int exit_code, exit_status;
1535 unsigned n_accepted;
1536 unsigned n_connections;
1540 const char *sysfs_path;
1542 /* Mount, Automount */
1548 LIST_HEAD(ExecStatusInfo, exec);
1551 static void print_status_info(UnitStatusInfo *i) {
1553 const char *on, *off, *ss;
1555 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1556 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1560 /* This shows pretty information about a unit. See
1561 * print_property() for a low-level property printer */
1563 printf("%s", strna(i->id));
1565 if (i->description && !streq_ptr(i->id, i->description))
1566 printf(" - %s", i->description);
1570 if (streq_ptr(i->load_state, "failed")) {
1571 on = ansi_highlight(true);
1572 off = ansi_highlight(false);
1577 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1579 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1581 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1583 if (streq_ptr(i->active_state, "failed")) {
1584 on = ansi_highlight(true);
1585 off = ansi_highlight(false);
1586 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1587 on = ansi_highlight_green(true);
1588 off = ansi_highlight_green(false);
1593 printf("\t Active: %s%s (%s)%s",
1595 strna(i->active_state),
1599 printf("\t Active: %s%s%s",
1601 strna(i->active_state),
1604 timestamp = (streq_ptr(i->active_state, "active") ||
1605 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1606 (streq_ptr(i->active_state, "inactive") ||
1607 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1608 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1609 i->active_exit_timestamp;
1611 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1612 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1615 printf(" since [%s; %s]\n", s2, s1);
1617 printf(" since [%s]\n", s2);
1622 printf("\t Device: %s\n", i->sysfs_path);
1624 printf("\t Where: %s\n", i->where);
1626 printf("\t What: %s\n", i->what);
1629 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1631 LIST_FOREACH(exec, p, i->exec) {
1634 /* Only show exited processes here */
1638 t = strv_join(p->argv, " ");
1639 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1642 if (p->code == CLD_EXITED) {
1645 printf("status=%i", p->status);
1647 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1651 printf("signal=%s", signal_to_string(p->status));
1654 if (i->main_pid == p->pid &&
1655 i->start_timestamp == p->start_timestamp &&
1656 i->exit_timestamp == p->start_timestamp)
1657 /* Let's not show this twice */
1660 if (p->pid == i->control_pid)
1664 if (i->main_pid > 0 || i->control_pid > 0) {
1667 if (i->main_pid > 0) {
1668 printf("Main PID: %u", (unsigned) i->main_pid);
1672 get_process_name(i->main_pid, &t);
1677 } else if (i->exit_code > 0) {
1678 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1680 if (i->exit_code == CLD_EXITED) {
1683 printf("status=%i", i->exit_status);
1685 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1689 printf("signal=%s", signal_to_string(i->exit_status));
1694 if (i->main_pid > 0 && i->control_pid > 0)
1697 if (i->control_pid > 0) {
1700 printf(" Control: %u", (unsigned) i->control_pid);
1702 get_process_name(i->control_pid, &t);
1713 printf("\t Status: \"%s\"\n", i->status_text);
1715 if (i->default_control_group) {
1718 printf("\t CGroup: %s\n", i->default_control_group);
1720 if ((c = columns()) > 18)
1725 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1728 if (i->need_daemon_reload)
1729 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1730 ansi_highlight(true),
1731 ansi_highlight(false),
1732 arg_session ? "--session" : "--system");
1735 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1737 switch (dbus_message_iter_get_arg_type(iter)) {
1739 case DBUS_TYPE_STRING: {
1742 dbus_message_iter_get_basic(iter, &s);
1745 if (streq(name, "Id"))
1747 else if (streq(name, "LoadState"))
1749 else if (streq(name, "ActiveState"))
1750 i->active_state = s;
1751 else if (streq(name, "SubState"))
1753 else if (streq(name, "Description"))
1755 else if (streq(name, "FragmentPath"))
1757 else if (streq(name, "SysVPath")) {
1760 } else if (streq(name, "DefaultControlGroup"))
1761 i->default_control_group = s;
1762 else if (streq(name, "StatusText"))
1764 else if (streq(name, "SysFSPath"))
1766 else if (streq(name, "Where"))
1768 else if (streq(name, "What"))
1775 case DBUS_TYPE_BOOLEAN: {
1778 dbus_message_iter_get_basic(iter, &b);
1780 if (streq(name, "Accept"))
1782 else if (streq(name, "NeedDaemonReload"))
1783 i->need_daemon_reload = b;
1788 case DBUS_TYPE_UINT32: {
1791 dbus_message_iter_get_basic(iter, &u);
1793 if (streq(name, "MainPID")) {
1795 i->main_pid = (pid_t) u;
1798 } else if (streq(name, "ControlPID"))
1799 i->control_pid = (pid_t) u;
1800 else if (streq(name, "ExecMainPID")) {
1802 i->main_pid = (pid_t) u;
1803 } else if (streq(name, "NAccepted"))
1805 else if (streq(name, "NConnections"))
1806 i->n_connections = u;
1811 case DBUS_TYPE_INT32: {
1814 dbus_message_iter_get_basic(iter, &j);
1816 if (streq(name, "ExecMainCode"))
1817 i->exit_code = (int) j;
1818 else if (streq(name, "ExecMainStatus"))
1819 i->exit_status = (int) j;
1824 case DBUS_TYPE_UINT64: {
1827 dbus_message_iter_get_basic(iter, &u);
1829 if (streq(name, "ExecMainStartTimestamp"))
1830 i->start_timestamp = (usec_t) u;
1831 else if (streq(name, "ExecMainExitTimestamp"))
1832 i->exit_timestamp = (usec_t) u;
1833 else if (streq(name, "ActiveEnterTimestamp"))
1834 i->active_enter_timestamp = (usec_t) u;
1835 else if (streq(name, "InactiveEnterTimestamp"))
1836 i->inactive_enter_timestamp = (usec_t) u;
1837 else if (streq(name, "InactiveExitTimestamp"))
1838 i->inactive_exit_timestamp = (usec_t) u;
1839 else if (streq(name, "ActiveExitTimestamp"))
1840 i->active_exit_timestamp = (usec_t) u;
1845 case DBUS_TYPE_ARRAY: {
1847 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1848 startswith(name, "Exec")) {
1849 DBusMessageIter sub;
1851 dbus_message_iter_recurse(iter, &sub);
1852 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1853 ExecStatusInfo *info;
1856 if (!(info = new0(ExecStatusInfo, 1)))
1859 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1864 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1866 dbus_message_iter_next(&sub);
1877 static int print_property(const char *name, DBusMessageIter *iter) {
1881 /* This is a low-level property printer, see
1882 * print_status_info() for the nicer output */
1884 if (arg_property && !strv_find(arg_property, name))
1887 switch (dbus_message_iter_get_arg_type(iter)) {
1889 case DBUS_TYPE_STRING: {
1891 dbus_message_iter_get_basic(iter, &s);
1893 if (arg_all || s[0])
1894 printf("%s=%s\n", name, s);
1899 case DBUS_TYPE_BOOLEAN: {
1901 dbus_message_iter_get_basic(iter, &b);
1902 printf("%s=%s\n", name, yes_no(b));
1907 case DBUS_TYPE_UINT64: {
1909 dbus_message_iter_get_basic(iter, &u);
1911 /* Yes, heuristics! But we can change this check
1912 * should it turn out to not be sufficient */
1914 if (strstr(name, "Timestamp")) {
1915 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1917 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1918 printf("%s=%s\n", name, strempty(t));
1919 } else if (strstr(name, "USec")) {
1920 char timespan[FORMAT_TIMESPAN_MAX];
1922 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1924 printf("%s=%llu\n", name, (unsigned long long) u);
1929 case DBUS_TYPE_UINT32: {
1931 dbus_message_iter_get_basic(iter, &u);
1933 if (strstr(name, "UMask") || strstr(name, "Mode"))
1934 printf("%s=%04o\n", name, u);
1936 printf("%s=%u\n", name, (unsigned) u);
1941 case DBUS_TYPE_INT32: {
1943 dbus_message_iter_get_basic(iter, &i);
1945 printf("%s=%i\n", name, (int) i);
1949 case DBUS_TYPE_STRUCT: {
1950 DBusMessageIter sub;
1951 dbus_message_iter_recurse(iter, &sub);
1953 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1956 dbus_message_iter_get_basic(&sub, &u);
1959 printf("%s=%u\n", name, (unsigned) u);
1961 printf("%s=\n", name);
1964 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1967 dbus_message_iter_get_basic(&sub, &s);
1969 if (arg_all || s[0])
1970 printf("%s=%s\n", name, s);
1978 case DBUS_TYPE_ARRAY:
1980 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
1981 DBusMessageIter sub;
1984 dbus_message_iter_recurse(iter, &sub);
1986 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1987 printf("%s=", name);
1989 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1992 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1993 dbus_message_iter_get_basic(&sub, &s);
1994 printf("%s%s", space ? " " : "", s);
1997 dbus_message_iter_next(&sub);
2005 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2006 DBusMessageIter sub;
2008 dbus_message_iter_recurse(iter, &sub);
2010 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2011 printf("%s=", name);
2013 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2016 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2017 dbus_message_iter_get_basic(&sub, &u);
2020 dbus_message_iter_next(&sub);
2028 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2029 DBusMessageIter sub, sub2;
2031 dbus_message_iter_recurse(iter, &sub);
2032 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2033 const char *type, *path;
2035 dbus_message_iter_recurse(&sub, &sub2);
2037 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2038 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2039 printf("%s=%s\n", type, path);
2041 dbus_message_iter_next(&sub);
2046 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2047 DBusMessageIter sub, sub2;
2049 dbus_message_iter_recurse(iter, &sub);
2050 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2052 uint64_t value, next_elapse;
2054 dbus_message_iter_recurse(&sub, &sub2);
2056 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2057 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2058 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2059 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2061 printf("%s={ value=%s ; next_elapse=%s }\n",
2063 format_timespan(timespan1, sizeof(timespan1), value),
2064 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2067 dbus_message_iter_next(&sub);
2072 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2073 DBusMessageIter sub;
2075 dbus_message_iter_recurse(iter, &sub);
2076 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2077 ExecStatusInfo info;
2080 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2081 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2084 t = strv_join(info.argv, " ");
2086 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2090 yes_no(info.ignore),
2091 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2092 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2093 (unsigned) info. pid,
2094 sigchld_code_to_string(info.code),
2096 info.code == CLD_EXITED ? "" : "/",
2097 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2103 strv_free(info.argv);
2105 dbus_message_iter_next(&sub);
2115 printf("%s=[unprintable]\n", name);
2120 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2121 DBusMessage *m = NULL, *reply = NULL;
2122 const char *interface = "";
2125 DBusMessageIter iter, sub, sub2, sub3;
2126 UnitStatusInfo info;
2134 dbus_error_init(&error);
2136 if (!(m = dbus_message_new_method_call(
2137 "org.freedesktop.systemd1",
2139 "org.freedesktop.DBus.Properties",
2141 log_error("Could not allocate message.");
2146 if (!dbus_message_append_args(m,
2147 DBUS_TYPE_STRING, &interface,
2148 DBUS_TYPE_INVALID)) {
2149 log_error("Could not append arguments to message.");
2154 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2155 log_error("Failed to issue method call: %s", bus_error_message(&error));
2160 if (!dbus_message_iter_init(reply, &iter) ||
2161 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2162 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2163 log_error("Failed to parse reply.");
2168 dbus_message_iter_recurse(&iter, &sub);
2175 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2178 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2179 log_error("Failed to parse reply.");
2184 dbus_message_iter_recurse(&sub, &sub2);
2186 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2187 log_error("Failed to parse reply.");
2192 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2193 log_error("Failed to parse reply.");
2198 dbus_message_iter_recurse(&sub2, &sub3);
2200 if (show_properties)
2201 r = print_property(name, &sub3);
2203 r = status_property(name, &sub3, &info);
2206 log_error("Failed to parse reply.");
2211 dbus_message_iter_next(&sub);
2216 if (!show_properties) {
2217 if (arg_sysv_compat &&
2218 !streq_ptr(info.active_state, "active") &&
2219 !streq_ptr(info.active_state, "reloading")) {
2221 /* If the SysV compatibility mode is on, we
2222 * will refuse to run "status" on units that
2224 log_error("Unit not active.");
2227 print_status_info(&info);
2230 while ((p = info.exec)) {
2231 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2232 exec_status_info_free(p);
2237 dbus_message_unref(m);
2240 dbus_message_unref(reply);
2242 dbus_error_free(&error);
2247 static int show(DBusConnection *bus, char **args, unsigned n) {
2248 DBusMessage *m = NULL, *reply = NULL;
2252 bool show_properties, new_line = false;
2257 dbus_error_init(&error);
2259 show_properties = !streq(args[0], "status");
2261 if (show_properties && n <= 1) {
2262 /* If not argument is specified inspect the manager
2265 r = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2269 for (i = 1; i < n; i++) {
2270 const char *path = NULL;
2273 if (safe_atou32(args[i], &id) < 0) {
2275 /* Interpret as unit name */
2277 if (!(m = dbus_message_new_method_call(
2278 "org.freedesktop.systemd1",
2279 "/org/freedesktop/systemd1",
2280 "org.freedesktop.systemd1.Manager",
2282 log_error("Could not allocate message.");
2287 if (!dbus_message_append_args(m,
2288 DBUS_TYPE_STRING, &args[i],
2289 DBUS_TYPE_INVALID)) {
2290 log_error("Could not append arguments to message.");
2295 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2297 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2298 log_error("Failed to issue method call: %s", bus_error_message(&error));
2303 dbus_error_free(&error);
2305 dbus_message_unref(m);
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))) {
2325 log_error("Failed to issue method call: %s", bus_error_message(&error));
2331 } else if (show_properties) {
2333 /* Interpret as job id */
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_UINT32, &id,
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));
2360 /* Interpret as PID */
2362 if (!(m = dbus_message_new_method_call(
2363 "org.freedesktop.systemd1",
2364 "/org/freedesktop/systemd1",
2365 "org.freedesktop.systemd1.Manager",
2367 log_error("Could not allocate message.");
2372 if (!dbus_message_append_args(m,
2373 DBUS_TYPE_UINT32, &id,
2374 DBUS_TYPE_INVALID)) {
2375 log_error("Could not append arguments to message.");
2380 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2381 log_error("Failed to issue method call: %s", bus_error_message(&error));
2387 if (!dbus_message_get_args(reply, &error,
2388 DBUS_TYPE_OBJECT_PATH, &path,
2389 DBUS_TYPE_INVALID)) {
2390 log_error("Failed to parse reply: %s", bus_error_message(&error));
2395 if ((r = show_one(bus, path, show_properties, &new_line)) < 0)
2398 dbus_message_unref(m);
2399 dbus_message_unref(reply);
2407 dbus_message_unref(m);
2410 dbus_message_unref(reply);
2412 dbus_error_free(&error);
2417 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2419 DBusMessage *m = NULL, *reply = NULL;
2424 dbus_error_init(&error);
2426 log_debug("Got D-Bus request: %s.%s() on %s",
2427 dbus_message_get_interface(message),
2428 dbus_message_get_member(message),
2429 dbus_message_get_path(message));
2431 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2432 log_error("Warning! D-Bus connection terminated.");
2433 dbus_connection_close(connection);
2435 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2436 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2437 const char *id, *path;
2439 if (!dbus_message_get_args(message, &error,
2440 DBUS_TYPE_STRING, &id,
2441 DBUS_TYPE_OBJECT_PATH, &path,
2443 log_error("Failed to parse message: %s", bus_error_message(&error));
2444 else if (streq(dbus_message_get_member(message), "UnitNew"))
2445 printf("Unit %s added.\n", id);
2447 printf("Unit %s removed.\n", id);
2449 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2450 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2454 if (!dbus_message_get_args(message, &error,
2455 DBUS_TYPE_UINT32, &id,
2456 DBUS_TYPE_OBJECT_PATH, &path,
2458 log_error("Failed to parse message: %s", bus_error_message(&error));
2459 else if (streq(dbus_message_get_member(message), "JobNew"))
2460 printf("Job %u added.\n", id);
2462 printf("Job %u removed.\n", id);
2465 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2467 const char *path, *interface, *property = "Id";
2468 DBusMessageIter iter, sub;
2470 path = dbus_message_get_path(message);
2472 if (!dbus_message_get_args(message, &error,
2473 DBUS_TYPE_STRING, &interface,
2474 DBUS_TYPE_INVALID)) {
2475 log_error("Failed to parse message: %s", bus_error_message(&error));
2479 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2480 !streq(interface, "org.freedesktop.systemd1.Unit"))
2483 if (!(m = dbus_message_new_method_call(
2484 "org.freedesktop.systemd1",
2486 "org.freedesktop.DBus.Properties",
2488 log_error("Could not allocate message.");
2492 if (!dbus_message_append_args(m,
2493 DBUS_TYPE_STRING, &interface,
2494 DBUS_TYPE_STRING, &property,
2495 DBUS_TYPE_INVALID)) {
2496 log_error("Could not append arguments to message.");
2500 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2501 log_error("Failed to issue method call: %s", bus_error_message(&error));
2505 if (!dbus_message_iter_init(reply, &iter) ||
2506 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2507 log_error("Failed to parse reply.");
2511 dbus_message_iter_recurse(&iter, &sub);
2513 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2516 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2517 log_error("Failed to parse reply.");
2521 dbus_message_iter_get_basic(&sub, &id);
2522 printf("Unit %s changed.\n", id);
2526 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2527 log_error("Failed to parse reply.");
2531 dbus_message_iter_get_basic(&sub, &id);
2532 printf("Job %u changed.\n", id);
2538 dbus_message_unref(m);
2541 dbus_message_unref(reply);
2543 dbus_error_free(&error);
2544 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2548 dbus_message_unref(m);
2551 dbus_message_unref(reply);
2553 dbus_error_free(&error);
2554 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2557 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2558 DBusMessage *m = NULL, *reply = NULL;
2562 dbus_error_init(&error);
2565 dbus_bus_add_match(bus,
2567 "sender='org.freedesktop.systemd1',"
2568 "interface='org.freedesktop.systemd1.Manager',"
2569 "path='/org/freedesktop/systemd1'",
2572 if (dbus_error_is_set(&error)) {
2573 log_error("Failed to add match: %s", bus_error_message(&error));
2578 dbus_bus_add_match(bus,
2580 "sender='org.freedesktop.systemd1',"
2581 "interface='org.freedesktop.DBus.Properties',"
2582 "member='PropertiesChanged'",
2585 if (dbus_error_is_set(&error)) {
2586 log_error("Failed to add match: %s", bus_error_message(&error));
2592 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2593 log_error("Failed to add filter.");
2598 if (!(m = dbus_message_new_method_call(
2599 "org.freedesktop.systemd1",
2600 "/org/freedesktop/systemd1",
2601 "org.freedesktop.systemd1.Manager",
2603 log_error("Could not allocate message.");
2608 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2609 log_error("Failed to issue method call: %s", bus_error_message(&error));
2614 while (dbus_connection_read_write_dispatch(bus, -1))
2621 /* This is slightly dirty, since we don't undo the filter or the matches. */
2624 dbus_message_unref(m);
2627 dbus_message_unref(reply);
2629 dbus_error_free(&error);
2634 static int dump(DBusConnection *bus, char **args, unsigned n) {
2635 DBusMessage *m = NULL, *reply = NULL;
2640 dbus_error_init(&error);
2642 if (!(m = dbus_message_new_method_call(
2643 "org.freedesktop.systemd1",
2644 "/org/freedesktop/systemd1",
2645 "org.freedesktop.systemd1.Manager",
2647 log_error("Could not allocate message.");
2651 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2652 log_error("Failed to issue method call: %s", bus_error_message(&error));
2657 if (!dbus_message_get_args(reply, &error,
2658 DBUS_TYPE_STRING, &text,
2659 DBUS_TYPE_INVALID)) {
2660 log_error("Failed to parse reply: %s", bus_error_message(&error));
2665 fputs(text, stdout);
2671 dbus_message_unref(m);
2674 dbus_message_unref(reply);
2676 dbus_error_free(&error);
2681 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2682 DBusMessage *m = NULL, *reply = NULL;
2685 const char *name = "", *path, *id;
2686 dbus_bool_t cleanup = FALSE;
2687 DBusMessageIter iter, sub;
2689 *interface = "org.freedesktop.systemd1.Unit",
2692 dbus_error_init(&error);
2694 if (!(m = dbus_message_new_method_call(
2695 "org.freedesktop.systemd1",
2696 "/org/freedesktop/systemd1",
2697 "org.freedesktop.systemd1.Manager",
2698 "CreateSnapshot"))) {
2699 log_error("Could not allocate message.");
2706 if (!dbus_message_append_args(m,
2707 DBUS_TYPE_STRING, &name,
2708 DBUS_TYPE_BOOLEAN, &cleanup,
2709 DBUS_TYPE_INVALID)) {
2710 log_error("Could not append arguments to message.");
2715 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2716 log_error("Failed to issue method call: %s", bus_error_message(&error));
2721 if (!dbus_message_get_args(reply, &error,
2722 DBUS_TYPE_OBJECT_PATH, &path,
2723 DBUS_TYPE_INVALID)) {
2724 log_error("Failed to parse reply: %s", bus_error_message(&error));
2729 dbus_message_unref(m);
2730 if (!(m = dbus_message_new_method_call(
2731 "org.freedesktop.systemd1",
2733 "org.freedesktop.DBus.Properties",
2735 log_error("Could not allocate message.");
2739 if (!dbus_message_append_args(m,
2740 DBUS_TYPE_STRING, &interface,
2741 DBUS_TYPE_STRING, &property,
2742 DBUS_TYPE_INVALID)) {
2743 log_error("Could not append arguments to message.");
2748 dbus_message_unref(reply);
2749 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2750 log_error("Failed to issue method call: %s", bus_error_message(&error));
2755 if (!dbus_message_iter_init(reply, &iter) ||
2756 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2757 log_error("Failed to parse reply.");
2762 dbus_message_iter_recurse(&iter, &sub);
2764 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2765 log_error("Failed to parse reply.");
2770 dbus_message_iter_get_basic(&sub, &id);
2778 dbus_message_unref(m);
2781 dbus_message_unref(reply);
2783 dbus_error_free(&error);
2788 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2789 DBusMessage *m = NULL, *reply = NULL;
2797 dbus_error_init(&error);
2799 for (i = 1; i < n; i++) {
2800 const char *path = NULL;
2802 if (!(m = dbus_message_new_method_call(
2803 "org.freedesktop.systemd1",
2804 "/org/freedesktop/systemd1",
2805 "org.freedesktop.systemd1.Manager",
2807 log_error("Could not allocate message.");
2812 if (!dbus_message_append_args(m,
2813 DBUS_TYPE_STRING, &args[i],
2814 DBUS_TYPE_INVALID)) {
2815 log_error("Could not append arguments to message.");
2820 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2821 log_error("Failed to issue method call: %s", bus_error_message(&error));
2826 if (!dbus_message_get_args(reply, &error,
2827 DBUS_TYPE_OBJECT_PATH, &path,
2828 DBUS_TYPE_INVALID)) {
2829 log_error("Failed to parse reply: %s", bus_error_message(&error));
2834 dbus_message_unref(m);
2835 if (!(m = dbus_message_new_method_call(
2836 "org.freedesktop.systemd1",
2838 "org.freedesktop.systemd1.Snapshot",
2840 log_error("Could not allocate message.");
2845 dbus_message_unref(reply);
2846 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2847 log_error("Failed to issue method call: %s", bus_error_message(&error));
2852 dbus_message_unref(m);
2853 dbus_message_unref(reply);
2861 dbus_message_unref(m);
2864 dbus_message_unref(reply);
2866 dbus_error_free(&error);
2871 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2872 DBusMessage *m = NULL, *reply = NULL;
2877 dbus_error_init(&error);
2879 if (arg_action == ACTION_RELOAD)
2881 else if (arg_action == ACTION_REEXEC)
2882 method = "Reexecute";
2884 assert(arg_action == ACTION_SYSTEMCTL);
2887 streq(args[0], "clear-jobs") ||
2888 streq(args[0], "cancel") ? "ClearJobs" :
2889 streq(args[0], "daemon-reexec") ? "Reexecute" :
2890 streq(args[0], "reset-failed") ? "ResetFailed" :
2891 streq(args[0], "daemon-exit") ? "Exit" :
2895 if (!(m = dbus_message_new_method_call(
2896 "org.freedesktop.systemd1",
2897 "/org/freedesktop/systemd1",
2898 "org.freedesktop.systemd1.Manager",
2900 log_error("Could not allocate message.");
2904 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2906 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2907 /* There's always a fallback possible for
2908 * legacy actions. */
2913 log_error("Failed to issue method call: %s", bus_error_message(&error));
2922 dbus_message_unref(m);
2925 dbus_message_unref(reply);
2927 dbus_error_free(&error);
2932 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
2933 DBusMessage *m = NULL, *reply = NULL;
2939 dbus_error_init(&error);
2942 return daemon_reload(bus, args, n);
2944 for (i = 1; i < n; i++) {
2946 if (!(m = dbus_message_new_method_call(
2947 "org.freedesktop.systemd1",
2948 "/org/freedesktop/systemd1",
2949 "org.freedesktop.systemd1.Manager",
2950 "ResetFailedUnit"))) {
2951 log_error("Could not allocate message.");
2956 if (!dbus_message_append_args(m,
2957 DBUS_TYPE_STRING, args + i,
2958 DBUS_TYPE_INVALID)) {
2959 log_error("Could not append arguments to message.");
2964 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2965 log_error("Failed to issue method call: %s", bus_error_message(&error));
2970 dbus_message_unref(m);
2971 dbus_message_unref(reply);
2979 dbus_message_unref(m);
2982 dbus_message_unref(reply);
2984 dbus_error_free(&error);
2989 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
2990 DBusMessage *m = NULL, *reply = NULL;
2992 DBusMessageIter iter, sub, sub2;
2995 *interface = "org.freedesktop.systemd1.Manager",
2996 *property = "Environment";
2998 dbus_error_init(&error);
3000 if (!(m = dbus_message_new_method_call(
3001 "org.freedesktop.systemd1",
3002 "/org/freedesktop/systemd1",
3003 "org.freedesktop.DBus.Properties",
3005 log_error("Could not allocate message.");
3009 if (!dbus_message_append_args(m,
3010 DBUS_TYPE_STRING, &interface,
3011 DBUS_TYPE_STRING, &property,
3012 DBUS_TYPE_INVALID)) {
3013 log_error("Could not append arguments to message.");
3018 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3019 log_error("Failed to issue method call: %s", bus_error_message(&error));
3024 if (!dbus_message_iter_init(reply, &iter) ||
3025 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3026 log_error("Failed to parse reply.");
3031 dbus_message_iter_recurse(&iter, &sub);
3033 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3034 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3035 log_error("Failed to parse reply.");
3040 dbus_message_iter_recurse(&sub, &sub2);
3042 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3045 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3046 log_error("Failed to parse reply.");
3051 dbus_message_iter_get_basic(&sub2, &text);
3052 printf("%s\n", text);
3054 dbus_message_iter_next(&sub2);
3061 dbus_message_unref(m);
3064 dbus_message_unref(reply);
3066 dbus_error_free(&error);
3071 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3072 DBusMessage *m = NULL, *reply = NULL;
3076 DBusMessageIter iter, sub;
3079 dbus_error_init(&error);
3081 method = streq(args[0], "set-environment")
3083 : "UnsetEnvironment";
3085 if (!(m = dbus_message_new_method_call(
3086 "org.freedesktop.systemd1",
3087 "/org/freedesktop/systemd1",
3088 "org.freedesktop.systemd1.Manager",
3091 log_error("Could not allocate message.");
3095 dbus_message_iter_init_append(m, &iter);
3097 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3098 log_error("Could not append arguments to message.");
3103 for (i = 1; i < n; i++)
3104 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3105 log_error("Could not append arguments to message.");
3110 if (!dbus_message_iter_close_container(&iter, &sub)) {
3111 log_error("Could not append arguments to message.");
3116 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3117 log_error("Failed to issue method call: %s", bus_error_message(&error));
3126 dbus_message_unref(m);
3129 dbus_message_unref(reply);
3131 dbus_error_free(&error);
3144 static Hashmap *will_install = NULL, *have_installed = NULL;
3145 static Set *remove_symlinks_to = NULL;
3147 static void install_info_free(InstallInfo *i) {
3152 strv_free(i->aliases);
3153 strv_free(i->wanted_by);
3157 static void install_info_hashmap_free(Hashmap *m) {
3160 while ((i = hashmap_steal_first(m)))
3161 install_info_free(i);
3166 static bool unit_name_valid(const char *name) {
3168 /* This is a minimal version of unit_name_valid() from
3174 if (ignore_file(name))
3180 static int install_info_add(const char *name) {
3184 assert(will_install);
3186 if (!unit_name_valid(name))
3189 if (hashmap_get(have_installed, name) ||
3190 hashmap_get(will_install, name))
3193 if (!(i = new0(InstallInfo, 1))) {
3198 if (!(i->name = strdup(name))) {
3203 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3210 install_info_free(i);
3215 static int config_parse_also(
3216 const char *filename,
3218 const char *section,
3232 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3236 if (!(n = strndup(w, l)))
3239 r = install_info_add(n);
3249 static int mark_symlink_for_removal(const char *p) {
3254 assert(path_is_absolute(p));
3256 if (!remove_symlinks_to)
3259 if (!(n = strdup(p)))
3262 path_kill_slashes(n);
3264 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3266 return r == -EEXIST ? 0 : r;
3272 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3281 if (!(d = fdopendir(fd))) {
3282 close_nointr_nofail(fd);
3288 while ((de = readdir(d))) {
3289 bool is_dir = false, is_link = false;
3291 if (ignore_file(de->d_name))
3294 if (de->d_type == DT_LNK)
3296 else if (de->d_type == DT_DIR)
3298 else if (de->d_type == DT_UNKNOWN) {
3301 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3302 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3309 is_link = S_ISLNK(st.st_mode);
3310 is_dir = S_ISDIR(st.st_mode);
3318 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3319 log_error("Failed to open %s/%s: %m", root, de->d_name);
3326 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3327 log_error("Failed to allocate directory string.");
3328 close_nointr_nofail(nfd);
3333 /* This will close nfd, regardless whether it succeeds or not */
3334 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3340 } else if (is_link) {
3344 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3345 log_error("Failed to allocate symlink string.");
3350 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3351 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3359 if ((c = canonicalize_file_name(dest))) {
3360 /* This might fail if the destination
3361 * is already removed */
3367 path_kill_slashes(dest);
3368 if (set_get(remove_symlinks_to, dest)) {
3371 log_info("rm '%s'", p);
3373 if (unlink(p) < 0) {
3374 log_error("Cannot unlink symlink %s: %m", p);
3379 rmdir_parents(p, config_path);
3380 path_kill_slashes(p);
3382 if (!set_get(remove_symlinks_to, p)) {
3384 if ((r = mark_symlink_for_removal(p)) < 0) {
3403 static int remove_marked_symlinks(const char *config_path) {
3407 assert(config_path);
3409 if (set_size(remove_symlinks_to) <= 0)
3412 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3419 if ((cfd = dup(fd)) < 0) {
3424 /* This takes possession of cfd and closes it */
3425 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3431 close_nointr_nofail(fd);
3436 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3443 if (streq(verb, "enable")) {
3446 mkdir_parents(new_path, 0755);
3448 if (symlink(old_path, new_path) >= 0) {
3451 log_info("ln -s '%s' '%s'", old_path, new_path);
3456 if (errno != EEXIST) {
3457 log_error("Cannot link %s to %s: %m", old_path, new_path);
3461 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3463 if (errno == EINVAL) {
3464 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3468 log_error("readlink() failed: %s", strerror(-r));
3472 if (streq(dest, old_path)) {
3478 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3487 log_info("ln -s '%s' '%s'", old_path, new_path);
3489 if (symlink(old_path, new_path) >= 0)
3492 log_error("Cannot link %s to %s: %m", old_path, new_path);
3495 } else if (streq(verb, "disable")) {
3498 if ((r = mark_symlink_for_removal(old_path)) < 0)
3501 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3502 if (errno == ENOENT)
3505 if (errno == EINVAL) {
3506 log_warning("File %s not a symlink, ignoring.", old_path);
3510 log_error("readlink() failed: %s", strerror(-r));
3514 if (!streq(dest, old_path)) {
3515 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3522 if ((r = mark_symlink_for_removal(new_path)) < 0)
3526 log_info("rm '%s'", new_path);
3528 if (unlink(new_path) >= 0)
3531 log_error("Cannot unlink %s: %m", new_path);
3534 } else if (streq(verb, "is-enabled")) {
3537 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3539 if (errno == ENOENT || errno == EINVAL)
3542 log_error("readlink() failed: %s", strerror(-r));
3546 if (streq(dest, old_path)) {
3554 assert_not_reached("Unknown action.");
3557 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3559 char *alias_path = NULL;
3564 assert(config_path);
3566 STRV_FOREACH(s, i->aliases) {
3568 if (!unit_name_valid(*s)) {
3569 log_error("Invalid name %s.", *s);
3575 if (!(alias_path = path_make_absolute(*s, config_path))) {
3576 log_error("Out of memory");
3581 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3584 if (streq(verb, "disable"))
3585 rmdir_parents(alias_path, config_path);
3596 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3598 char *alias_path = NULL;
3603 assert(config_path);
3605 STRV_FOREACH(s, i->wanted_by) {
3606 if (!unit_name_valid(*s)) {
3607 log_error("Invalid name %s.", *s);
3615 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3616 log_error("Out of memory");
3621 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3624 if (streq(verb, "disable"))
3625 rmdir_parents(alias_path, config_path);
3636 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3638 const ConfigItem items[] = {
3639 { "Alias", config_parse_strv, &i->aliases, "Install" },
3640 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3641 { "Also", config_parse_also, NULL, "Install" },
3643 { NULL, NULL, NULL, NULL }
3647 char *filename = NULL;
3654 STRV_FOREACH(p, paths->unit_path) {
3657 if (!(filename = path_make_absolute(i->name, *p))) {
3658 log_error("Out of memory");
3662 /* Ensure that we don't follow symlinks */
3663 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3664 if ((f = fdopen(fd, "re")))
3667 if (errno == ELOOP) {
3668 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3673 if (errno != ENOENT) {
3674 log_error("Failed to open %s: %m", filename);
3684 log_error("Couldn't find %s.", i->name);
3690 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3697 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3700 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3703 if ((r = mark_symlink_for_removal(filename)) < 0)
3706 if ((r = remove_marked_symlinks(config_path)) < 0)
3712 static char *get_config_path(void) {
3714 if (arg_session && arg_global)
3715 return strdup(SESSION_CONFIG_UNIT_PATH);
3720 if (session_config_home(&p) < 0)
3726 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3729 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3733 char *config_path = NULL;
3736 const char *verb = args[0];
3738 dbus_error_init(&error);
3741 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3742 log_error("Failed to determine lookup paths: %s", strerror(-r));
3746 if (!(config_path = get_config_path())) {
3747 log_error("Failed to determine config path");
3752 will_install = hashmap_new(string_hash_func, string_compare_func);
3753 have_installed = hashmap_new(string_hash_func, string_compare_func);
3755 if (!will_install || !have_installed) {
3756 log_error("Failed to allocate unit sets.");
3761 if (!arg_defaults && streq(verb, "disable"))
3762 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3763 log_error("Failed to allocate symlink sets.");
3768 for (j = 1; j < n; j++)
3769 if ((r = install_info_add(args[j])) < 0)
3772 while ((i = hashmap_first(will_install))) {
3775 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3777 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3785 /* In test mode and found something */
3791 if (streq(verb, "is-enabled"))
3792 r = r > 0 ? 0 : -ENOENT;
3794 /* Don't try to reload anything if the user asked us to not do this */
3796 /* Don't try to reload anything when updating a unit globally */
3798 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3799 (arg_session || sd_booted() > 0) &&
3800 /* Don't try to reload anything if we are running in a chroot environment */
3801 (arg_session || running_in_chroot() <= 0) ) {
3804 if ((q = daemon_reload(bus, args, n)) < 0)
3809 install_info_hashmap_free(will_install);
3810 install_info_hashmap_free(have_installed);
3812 set_free_free(remove_symlinks_to);
3814 lookup_paths_free(&paths);
3821 static int systemctl_help(void) {
3823 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3824 "Send control commands to or query the systemd manager.\n\n"
3825 " -h --help Show this help\n"
3826 " -t --type=TYPE List only units of a particular type\n"
3827 " -p --property=NAME Show only properties by this name\n"
3828 " -a --all Show all units/properties, including dead/empty ones\n"
3829 " --full Don't ellipsize unit names on output\n"
3830 " --fail When queueing a new job, fail if conflicting jobs are\n"
3832 " -q --quiet Suppress output\n"
3833 " --no-block Do not wait until operation finished\n"
3834 " --system Connect to system bus\n"
3835 " --session Connect to session bus\n"
3836 " --order When generating graph for dot, show only order\n"
3837 " --require When generating graph for dot, show only requirement\n"
3838 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3839 " --global Enable/disable unit files globally\n"
3840 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3842 " --force When enabling unit files, override existing symlinks\n"
3843 " --defaults When disabling unit files, remove default symlinks only\n\n"
3845 " list-units List units\n"
3846 " start [NAME...] Start (activate) one or more units\n"
3847 " stop [NAME...] Stop (deactivate) one or more units\n"
3848 " reload [NAME...] Reload one or more units\n"
3849 " restart [NAME...] Start or restart one or more units\n"
3850 " try-restart [NAME...] Restart one or more units if active\n"
3851 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3852 " otherwise start or restart\n"
3853 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3854 " otherwise restart if active\n"
3855 " isolate [NAME] Start one unit and stop all others\n"
3856 " is-active [NAME...] Check whether units are active\n"
3857 " status [NAME...|PID...] Show runtime status of one or more units\n"
3858 " show [NAME...|JOB...] Show properties of one or more\n"
3859 " units/jobs or the manager\n"
3860 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3862 " enable [NAME...] Enable one or more unit files\n"
3863 " disable [NAME...] Disable one or more unit files\n"
3864 " is-enabled [NAME...] Check whether unit files are enabled\n"
3865 " load [NAME...] Load one or more units\n"
3866 " list-jobs List jobs\n"
3867 " cancel [JOB...] Cancel all, one, or more jobs\n"
3868 " monitor Monitor unit/job changes\n"
3869 " dump Dump server status\n"
3870 " dot Dump dependency graph for dot(1)\n"
3871 " snapshot [NAME] Create a snapshot\n"
3872 " delete [NAME...] Remove one or more snapshots\n"
3873 " daemon-reload Reload systemd manager configuration\n"
3874 " daemon-reexec Reexecute systemd manager\n"
3875 " daemon-exit Ask the systemd manager to quit\n"
3876 " show-environment Dump environment\n"
3877 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3878 " unset-environment [NAME...] Unset one or more environment variables\n"
3879 " halt Shut down and halt the system\n"
3880 " poweroff Shut down and power-off the system\n"
3881 " reboot Shut down and reboot the system\n"
3882 " rescue Enter system rescue mode\n"
3883 " emergency Enter system emergency mode\n"
3884 " default Enter system default mode\n",
3885 program_invocation_short_name);
3890 static int halt_help(void) {
3892 printf("%s [OPTIONS...]\n\n"
3893 "%s the system.\n\n"
3894 " --help Show this help\n"
3895 " --halt Halt the machine\n"
3896 " -p --poweroff Switch off the machine\n"
3897 " --reboot Reboot the machine\n"
3898 " -f --force Force immediate halt/power-off/reboot\n"
3899 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3900 " -d --no-wtmp Don't write wtmp record\n"
3901 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3902 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3903 program_invocation_short_name,
3904 arg_action == ACTION_REBOOT ? "Reboot" :
3905 arg_action == ACTION_POWEROFF ? "Power off" :
3911 static int shutdown_help(void) {
3913 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3914 "Shut down the system.\n\n"
3915 " --help Show this help\n"
3916 " -H --halt Halt the machine\n"
3917 " -P --poweroff Power-off the machine\n"
3918 " -r --reboot Reboot the machine\n"
3919 " -h Equivalent to --poweroff, overriden by --halt\n"
3920 " -k Don't halt/power-off/reboot, just send warnings\n"
3921 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3922 " -c Cancel a pending shutdown\n",
3923 program_invocation_short_name);
3928 static int telinit_help(void) {
3930 printf("%s [OPTIONS...] {COMMAND}\n\n"
3931 "Send control commands to the init daemon.\n\n"
3932 " --help Show this help\n"
3933 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3935 " 0 Power-off the machine\n"
3936 " 6 Reboot the machine\n"
3937 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3938 " 1, s, S Enter rescue mode\n"
3939 " q, Q Reload init daemon configuration\n"
3940 " u, U Reexecute init daemon\n",
3941 program_invocation_short_name);
3946 static int runlevel_help(void) {
3948 printf("%s [OPTIONS...]\n\n"
3949 "Prints the previous and current runlevel of the init system.\n\n"
3950 " --help Show this help\n",
3951 program_invocation_short_name);
3956 static int systemctl_parse_argv(int argc, char *argv[]) {
3974 static const struct option options[] = {
3975 { "help", no_argument, NULL, 'h' },
3976 { "type", required_argument, NULL, 't' },
3977 { "property", required_argument, NULL, 'p' },
3978 { "all", no_argument, NULL, 'a' },
3979 { "full", no_argument, NULL, ARG_FULL },
3980 { "fail", no_argument, NULL, ARG_FAIL },
3981 { "session", no_argument, NULL, ARG_SESSION },
3982 { "system", no_argument, NULL, ARG_SYSTEM },
3983 { "global", no_argument, NULL, ARG_GLOBAL },
3984 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
3985 { "no-wall", no_argument, NULL, ARG_NO_WALL },
3986 { "quiet", no_argument, NULL, 'q' },
3987 { "order", no_argument, NULL, ARG_ORDER },
3988 { "require", no_argument, NULL, ARG_REQUIRE },
3989 { "force", no_argument, NULL, ARG_FORCE },
3990 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
3991 { "defaults", no_argument, NULL, ARG_DEFAULTS },
3992 { "sysv-compat", no_argument, NULL, ARG_SYSV_COMPAT },
3993 { NULL, 0, NULL, 0 }
4001 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4016 if (!(l = strv_append(arg_property, optarg)))
4019 strv_free(arg_property);
4022 /* If the user asked for a particular
4023 * property, show it to him, even if it is
4042 arg_session = false;
4046 arg_no_block = true;
4054 arg_dot = DOT_ORDER;
4058 arg_dot = DOT_REQUIRE;
4074 arg_no_reload = true;
4083 arg_defaults = true;
4086 case ARG_SYSV_COMPAT:
4087 arg_sysv_compat = true;
4094 log_error("Unknown option code %c", c);
4102 static int halt_parse_argv(int argc, char *argv[]) {
4111 static const struct option options[] = {
4112 { "help", no_argument, NULL, ARG_HELP },
4113 { "halt", no_argument, NULL, ARG_HALT },
4114 { "poweroff", no_argument, NULL, 'p' },
4115 { "reboot", no_argument, NULL, ARG_REBOOT },
4116 { "force", no_argument, NULL, 'f' },
4117 { "wtmp-only", no_argument, NULL, 'w' },
4118 { "no-wtmp", no_argument, NULL, 'd' },
4119 { "no-sync", no_argument, NULL, 'n' },
4120 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4121 { NULL, 0, NULL, 0 }
4129 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4130 if (runlevel == '0' || runlevel == '6')
4131 arg_immediate = true;
4133 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4141 arg_action = ACTION_HALT;
4145 if (arg_action != ACTION_REBOOT)
4146 arg_action = ACTION_POWEROFF;
4150 arg_action = ACTION_REBOOT;
4154 arg_immediate = true;
4175 /* Compatibility nops */
4182 log_error("Unknown option code %c", c);
4187 if (optind < argc) {
4188 log_error("Too many arguments.");
4195 static int parse_time_spec(const char *t, usec_t *_u) {
4199 if (streq(t, "now"))
4201 else if (t[0] == '+') {
4204 if (safe_atou64(t + 1, &u) < 0)
4207 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4216 hour = strtol(t, &e, 10);
4217 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4220 minute = strtol(e+1, &e, 10);
4221 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4224 n = now(CLOCK_REALTIME);
4225 s = (time_t) (n / USEC_PER_SEC);
4228 assert_se(localtime_r(&s, &tm));
4230 tm.tm_hour = (int) hour;
4231 tm.tm_min = (int) minute;
4234 assert_se(s = mktime(&tm));
4236 *_u = (usec_t) s * USEC_PER_SEC;
4239 *_u += USEC_PER_DAY;
4245 static int shutdown_parse_argv(int argc, char *argv[]) {
4252 static const struct option options[] = {
4253 { "help", no_argument, NULL, ARG_HELP },
4254 { "halt", no_argument, NULL, 'H' },
4255 { "poweroff", no_argument, NULL, 'P' },
4256 { "reboot", no_argument, NULL, 'r' },
4257 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4258 { NULL, 0, NULL, 0 }
4266 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4274 arg_action = ACTION_HALT;
4278 arg_action = ACTION_POWEROFF;
4282 arg_action = ACTION_REBOOT;
4286 if (arg_action != ACTION_HALT)
4287 arg_action = ACTION_POWEROFF;
4300 /* Compatibility nops */
4304 arg_action = ACTION_CANCEL_SHUTDOWN;
4311 log_error("Unknown option code %c", c);
4316 if (argc > optind) {
4317 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4318 log_error("Failed to parse time specification: %s", argv[optind]);
4322 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4324 /* We skip the time argument */
4325 if (argc > optind + 1)
4326 arg_wall = argv + optind + 1;
4333 static int telinit_parse_argv(int argc, char *argv[]) {
4340 static const struct option options[] = {
4341 { "help", no_argument, NULL, ARG_HELP },
4342 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4343 { NULL, 0, NULL, 0 }
4346 static const struct {
4350 { '0', ACTION_POWEROFF },
4351 { '6', ACTION_REBOOT },
4352 { '1', ACTION_RESCUE },
4353 { '2', ACTION_RUNLEVEL2 },
4354 { '3', ACTION_RUNLEVEL3 },
4355 { '4', ACTION_RUNLEVEL4 },
4356 { '5', ACTION_RUNLEVEL5 },
4357 { 's', ACTION_RESCUE },
4358 { 'S', ACTION_RESCUE },
4359 { 'q', ACTION_RELOAD },
4360 { 'Q', ACTION_RELOAD },
4361 { 'u', ACTION_REEXEC },
4362 { 'U', ACTION_REEXEC }
4371 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4386 log_error("Unknown option code %c", c);
4391 if (optind >= argc) {
4396 if (optind + 1 < argc) {
4397 log_error("Too many arguments.");
4401 if (strlen(argv[optind]) != 1) {
4402 log_error("Expected single character argument.");
4406 for (i = 0; i < ELEMENTSOF(table); i++)
4407 if (table[i].from == argv[optind][0])
4410 if (i >= ELEMENTSOF(table)) {
4411 log_error("Unknown command %s.", argv[optind]);
4415 arg_action = table[i].to;
4422 static int runlevel_parse_argv(int argc, char *argv[]) {
4428 static const struct option options[] = {
4429 { "help", no_argument, NULL, ARG_HELP },
4430 { NULL, 0, NULL, 0 }
4438 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4449 log_error("Unknown option code %c", c);
4454 if (optind < argc) {
4455 log_error("Too many arguments.");
4462 static int parse_argv(int argc, char *argv[]) {
4466 if (program_invocation_short_name) {
4468 if (strstr(program_invocation_short_name, "halt")) {
4469 arg_action = ACTION_HALT;
4470 return halt_parse_argv(argc, argv);
4471 } else if (strstr(program_invocation_short_name, "poweroff")) {
4472 arg_action = ACTION_POWEROFF;
4473 return halt_parse_argv(argc, argv);
4474 } else if (strstr(program_invocation_short_name, "reboot")) {
4475 arg_action = ACTION_REBOOT;
4476 return halt_parse_argv(argc, argv);
4477 } else if (strstr(program_invocation_short_name, "shutdown")) {
4478 arg_action = ACTION_POWEROFF;
4479 return shutdown_parse_argv(argc, argv);
4480 } else if (strstr(program_invocation_short_name, "init")) {
4482 if (sd_booted() > 0) {
4483 arg_action = ACTION_INVALID;
4484 return telinit_parse_argv(argc, argv);
4486 /* Hmm, so some other init system is
4487 * running, we need to forward this
4488 * request to it. For now we simply
4489 * guess that it is Upstart. */
4491 execv("/lib/upstart/telinit", argv);
4493 log_error("Couldn't find an alternative telinit implementation to spawn.");
4497 } else if (strstr(program_invocation_short_name, "runlevel")) {
4498 arg_action = ACTION_RUNLEVEL;
4499 return runlevel_parse_argv(argc, argv);
4503 arg_action = ACTION_SYSTEMCTL;
4504 return systemctl_parse_argv(argc, argv);
4507 static int action_to_runlevel(void) {
4509 static const char table[_ACTION_MAX] = {
4510 [ACTION_HALT] = '0',
4511 [ACTION_POWEROFF] = '0',
4512 [ACTION_REBOOT] = '6',
4513 [ACTION_RUNLEVEL2] = '2',
4514 [ACTION_RUNLEVEL3] = '3',
4515 [ACTION_RUNLEVEL4] = '4',
4516 [ACTION_RUNLEVEL5] = '5',
4517 [ACTION_RESCUE] = '1'
4520 assert(arg_action < _ACTION_MAX);
4522 return table[arg_action];
4525 static int talk_upstart(void) {
4526 DBusMessage *m = NULL, *reply = NULL;
4528 int previous, rl, r;
4530 env1_buf[] = "RUNLEVEL=X",
4531 env2_buf[] = "PREVLEVEL=X";
4532 char *env1 = env1_buf, *env2 = env2_buf;
4533 const char *emit = "runlevel";
4534 dbus_bool_t b_false = FALSE;
4535 DBusMessageIter iter, sub;
4536 DBusConnection *bus;
4538 dbus_error_init(&error);
4540 if (!(rl = action_to_runlevel()))
4543 if (utmp_get_runlevel(&previous, NULL) < 0)
4546 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4547 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4552 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4557 if ((r = bus_check_peercred(bus)) < 0) {
4558 log_error("Failed to verify owner of bus.");
4562 if (!(m = dbus_message_new_method_call(
4563 "com.ubuntu.Upstart",
4564 "/com/ubuntu/Upstart",
4565 "com.ubuntu.Upstart0_6",
4568 log_error("Could not allocate message.");
4573 dbus_message_iter_init_append(m, &iter);
4575 env1_buf[sizeof(env1_buf)-2] = rl;
4576 env2_buf[sizeof(env2_buf)-2] = previous;
4578 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4579 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4580 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4581 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4582 !dbus_message_iter_close_container(&iter, &sub) ||
4583 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4584 log_error("Could not append arguments to message.");
4589 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4591 if (error_is_no_service(&error)) {
4596 log_error("Failed to issue method call: %s", bus_error_message(&error));
4605 dbus_message_unref(m);
4608 dbus_message_unref(reply);
4611 dbus_connection_close(bus);
4612 dbus_connection_unref(bus);
4615 dbus_error_free(&error);
4620 static int talk_initctl(void) {
4621 struct init_request request;
4625 if (!(rl = action_to_runlevel()))
4629 request.magic = INIT_MAGIC;
4630 request.sleeptime = 0;
4631 request.cmd = INIT_CMD_RUNLVL;
4632 request.runlevel = rl;
4634 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4636 if (errno == ENOENT)
4639 log_error("Failed to open "INIT_FIFO": %m");
4644 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4645 close_nointr_nofail(fd);
4648 log_error("Failed to write to "INIT_FIFO": %m");
4649 return errno ? -errno : -EIO;
4655 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4657 static const struct {
4665 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4667 { "list-units", LESS, 1, list_units },
4668 { "list-jobs", EQUAL, 1, list_jobs },
4669 { "clear-jobs", EQUAL, 1, daemon_reload },
4670 { "load", MORE, 2, load_unit },
4671 { "cancel", MORE, 2, cancel_job },
4672 { "start", MORE, 2, start_unit },
4673 { "stop", MORE, 2, start_unit },
4674 { "reload", MORE, 2, start_unit },
4675 { "restart", MORE, 2, start_unit },
4676 { "try-restart", MORE, 2, start_unit },
4677 { "reload-or-restart", MORE, 2, start_unit },
4678 { "reload-or-try-restart", MORE, 2, start_unit },
4679 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4680 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4681 { "isolate", EQUAL, 2, start_unit },
4682 { "is-active", MORE, 2, check_unit },
4683 { "check", MORE, 2, check_unit },
4684 { "show", MORE, 1, show },
4685 { "status", MORE, 2, show },
4686 { "monitor", EQUAL, 1, monitor },
4687 { "dump", EQUAL, 1, dump },
4688 { "dot", EQUAL, 1, dot },
4689 { "snapshot", LESS, 2, snapshot },
4690 { "delete", MORE, 2, delete_snapshot },
4691 { "daemon-reload", EQUAL, 1, daemon_reload },
4692 { "daemon-reexec", EQUAL, 1, daemon_reload },
4693 { "daemon-exit", EQUAL, 1, daemon_reload },
4694 { "show-environment", EQUAL, 1, show_enviroment },
4695 { "set-environment", MORE, 2, set_environment },
4696 { "unset-environment", MORE, 2, set_environment },
4697 { "halt", EQUAL, 1, start_special },
4698 { "poweroff", EQUAL, 1, start_special },
4699 { "reboot", EQUAL, 1, start_special },
4700 { "default", EQUAL, 1, start_special },
4701 { "rescue", EQUAL, 1, start_special },
4702 { "emergency", EQUAL, 1, start_special },
4703 { "reset-failed", MORE, 1, reset_failed },
4704 { "enable", MORE, 2, enable_unit },
4705 { "disable", MORE, 2, enable_unit },
4706 { "is-enabled", MORE, 2, enable_unit }
4716 left = argc - optind;
4719 /* Special rule: no arguments means "list-units" */
4722 if (streq(argv[optind], "help")) {
4727 for (i = 0; i < ELEMENTSOF(verbs); i++)
4728 if (streq(argv[optind], verbs[i].verb))
4731 if (i >= ELEMENTSOF(verbs)) {
4732 log_error("Unknown operation %s", argv[optind]);
4737 switch (verbs[i].argc_cmp) {
4740 if (left != verbs[i].argc) {
4741 log_error("Invalid number of arguments.");
4748 if (left < verbs[i].argc) {
4749 log_error("Too few arguments.");
4756 if (left > verbs[i].argc) {
4757 log_error("Too many arguments.");
4764 assert_not_reached("Unknown comparison operator.");
4767 /* Require a bus connection for all operations but
4769 if (!streq(verbs[i].verb, "enable") &&
4770 !streq(verbs[i].verb, "disable") &&
4772 log_error("Failed to get D-Bus connection: %s", error->message);
4776 return verbs[i].dispatch(bus, argv + optind, left);
4779 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4781 struct msghdr msghdr;
4783 union sockaddr_union sockaddr;
4784 struct ucred *ucred;
4786 struct cmsghdr cmsghdr;
4787 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
4789 struct shutdownd_command c;
4797 strncpy(c.wall_message, message, sizeof(c.wall_message));
4799 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4803 sockaddr.sa.sa_family = AF_UNIX;
4804 sockaddr.un.sun_path[0] = 0;
4805 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4808 iovec.iov_base = (char*) &c;
4809 iovec.iov_len = sizeof(c);
4812 control.cmsghdr.cmsg_level = SOL_SOCKET;
4813 control.cmsghdr.cmsg_type = SCM_CREDENTIALS;
4814 control.cmsghdr.cmsg_len = CMSG_LEN(sizeof(struct ucred));
4816 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
4817 ucred->pid = getpid();
4818 ucred->uid = getuid();
4819 ucred->gid = getgid();
4822 msghdr.msg_name = &sockaddr;
4823 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4825 msghdr.msg_iov = &iovec;
4826 msghdr.msg_iovlen = 1;
4827 msghdr.msg_control = &control;
4828 msghdr.msg_controllen = control.cmsghdr.cmsg_len;
4830 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4831 close_nointr_nofail(fd);
4835 close_nointr_nofail(fd);
4839 static int reload_with_fallback(DBusConnection *bus) {
4842 /* First, try systemd via D-Bus. */
4843 if (daemon_reload(bus, NULL, 0) > 0)
4847 /* Nothing else worked, so let's try signals */
4848 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4850 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4851 log_error("kill() failed: %m");
4858 static int start_with_fallback(DBusConnection *bus) {
4861 /* First, try systemd via D-Bus. */
4862 if (start_unit(bus, NULL, 0) > 0)
4866 /* Hmm, talking to systemd via D-Bus didn't work. Then
4867 * let's try to talk to Upstart via D-Bus. */
4868 if (talk_upstart() > 0)
4871 /* Nothing else worked, so let's try
4873 if (talk_initctl() > 0)
4876 log_error("Failed to talk to init daemon.");
4880 warn_wall(arg_action);
4884 static int halt_main(DBusConnection *bus) {
4887 if (geteuid() != 0) {
4888 log_error("Must be root.");
4894 char date[FORMAT_TIMESTAMP_MAX];
4896 m = strv_join(arg_wall, " ");
4897 r = send_shutdownd(arg_when,
4898 arg_action == ACTION_HALT ? 'H' :
4899 arg_action == ACTION_POWEROFF ? 'P' :
4906 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4908 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4909 format_timestamp(date, sizeof(date), arg_when));
4914 if (!arg_dry && !arg_immediate)
4915 return start_with_fallback(bus);
4918 if (sd_booted() > 0)
4919 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4920 else if ((r = utmp_put_shutdown(0)) < 0)
4921 log_warning("Failed to write utmp record: %s", strerror(-r));
4930 /* Make sure C-A-D is handled by the kernel from this
4932 reboot(RB_ENABLE_CAD);
4934 switch (arg_action) {
4937 log_info("Halting.");
4938 reboot(RB_HALT_SYSTEM);
4941 case ACTION_POWEROFF:
4942 log_info("Powering off.");
4943 reboot(RB_POWER_OFF);
4947 log_info("Rebooting.");
4948 reboot(RB_AUTOBOOT);
4952 assert_not_reached("Unknown halt action.");
4955 /* We should never reach this. */
4959 static int runlevel_main(void) {
4960 int r, runlevel, previous;
4962 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4963 printf("unknown\n");
4968 previous <= 0 ? 'N' : previous,
4969 runlevel <= 0 ? 'N' : runlevel);
4974 int main(int argc, char*argv[]) {
4976 DBusConnection *bus = NULL;
4979 dbus_error_init(&error);
4981 log_parse_environment();
4984 if ((r = parse_argv(argc, argv)) < 0)
4991 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
4992 * let's shortcut this */
4993 if (arg_action == ACTION_RUNLEVEL) {
4994 retval = runlevel_main() < 0;
4998 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5000 switch (arg_action) {
5002 case ACTION_SYSTEMCTL: {
5003 retval = systemctl_main(bus, argc, argv, &error) < 0;
5008 case ACTION_POWEROFF:
5010 retval = halt_main(bus) < 0;
5013 case ACTION_RUNLEVEL2:
5014 case ACTION_RUNLEVEL3:
5015 case ACTION_RUNLEVEL4:
5016 case ACTION_RUNLEVEL5:
5018 case ACTION_EMERGENCY:
5019 case ACTION_DEFAULT:
5020 retval = start_with_fallback(bus) < 0;
5025 retval = reload_with_fallback(bus) < 0;
5028 case ACTION_CANCEL_SHUTDOWN:
5029 retval = send_shutdownd(0, 0, false, NULL) < 0;
5032 case ACTION_INVALID:
5033 case ACTION_RUNLEVEL:
5035 assert_not_reached("Unknown action");
5041 dbus_connection_close(bus);
5042 dbus_connection_unref(bus);
5045 dbus_error_free(&error);
5049 strv_free(arg_property);