1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/reboot.h>
28 #include <sys/ioctl.h>
32 #include <sys/socket.h>
35 #include <dbus/dbus.h>
41 #include "utmp-wtmp.h"
45 #include "dbus-common.h"
46 #include "cgroup-show.h"
47 #include "cgroup-util.h"
49 #include "path-lookup.h"
50 #include "conf-parser.h"
51 #include "sd-daemon.h"
52 #include "shutdownd.h"
53 #include "exit-status.h"
54 #include "bus-errors.h"
57 static const char *arg_type = NULL;
58 static char **arg_property = NULL;
59 static bool arg_all = false;
60 static bool arg_fail = false;
61 static bool arg_session = false;
62 static bool arg_global = false;
63 static bool arg_immediate = false;
64 static bool arg_no_block = false;
65 static bool arg_no_wtmp = false;
66 static bool arg_no_sync = false;
67 static bool arg_no_wall = false;
68 static bool arg_no_reload = false;
69 static bool arg_dry = false;
70 static bool arg_quiet = false;
71 static bool arg_full = false;
72 static bool arg_force = false;
73 static bool arg_defaults = false;
74 static char **arg_wall = NULL;
75 static usec_t arg_when = 0;
92 ACTION_CANCEL_SHUTDOWN,
94 } arg_action = ACTION_SYSTEMCTL;
101 static bool private_bus = false;
103 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
105 static bool on_tty(void) {
108 if (_unlikely_(t < 0))
109 t = isatty(STDOUT_FILENO) > 0;
114 static const char *ansi_highlight(bool b) {
119 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
122 static const char *ansi_highlight_green(bool b) {
127 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
130 static bool error_is_no_service(const DBusError *error) {
133 if (!dbus_error_is_set(error))
136 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
139 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
142 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
145 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
148 if (!dbus_error_is_set(error))
151 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
152 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
153 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
154 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
155 return EXIT_NOPERMISSION;
157 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
158 return EXIT_NOTINSTALLED;
160 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
161 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
162 return EXIT_NOTIMPLEMENTED;
164 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
165 return EXIT_NOTCONFIGURED;
173 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
178 if (dbus_message_iter_get_arg_type(iter) != type)
181 dbus_message_iter_get_basic(iter, data);
183 if (!dbus_message_iter_next(iter) != !next)
189 static void warn_wall(enum action action) {
190 static const char *table[_ACTION_MAX] = {
191 [ACTION_HALT] = "The system is going down for system halt NOW!",
192 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
193 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
194 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
195 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
204 if (!(p = strv_join(arg_wall, " "))) {
205 log_error("Failed to join strings.");
221 utmp_wall(table[action]);
226 const char *description;
227 const char *load_state;
228 const char *active_state;
229 const char *sub_state;
230 const char *following;
231 const char *unit_path;
233 const char *job_type;
234 const char *job_path;
237 static int compare_unit_info(const void *a, const void *b) {
239 const struct unit_info *u = a, *v = b;
241 d1 = strrchr(u->id, '.');
242 d2 = strrchr(v->id, '.');
247 if ((r = strcasecmp(d1, d2)) != 0)
251 return strcasecmp(u->id, v->id);
254 static int list_units(DBusConnection *bus, char **args, unsigned n) {
255 DBusMessage *m = NULL, *reply = NULL;
258 DBusMessageIter iter, sub, sub2;
259 unsigned c = 0, k, n_units = 0;
260 struct unit_info *unit_infos = NULL;
262 dbus_error_init(&error);
266 if (!(m = dbus_message_new_method_call(
267 "org.freedesktop.systemd1",
268 "/org/freedesktop/systemd1",
269 "org.freedesktop.systemd1.Manager",
271 log_error("Could not allocate message.");
275 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
276 log_error("Failed to issue method call: %s", bus_error_message(&error));
281 if (!dbus_message_iter_init(reply, &iter) ||
282 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
283 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
284 log_error("Failed to parse reply.");
289 dbus_message_iter_recurse(&iter, &sub);
291 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
294 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
295 log_error("Failed to parse reply.");
303 n_units = MAX(2*c, 16);
304 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
307 log_error("Failed to allocate unit array.");
317 dbus_message_iter_recurse(&sub, &sub2);
319 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
320 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
321 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
322 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
323 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
324 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
325 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
326 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
327 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
328 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
329 log_error("Failed to parse reply.");
334 dbus_message_iter_next(&sub);
338 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
340 if (isatty(STDOUT_FILENO)) {
341 if (columns() >= 80+12 || arg_full)
342 printf("%-25s %-6s %-12s %-18s %-15s %s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB", "DESCRIPTION");
344 printf("%-25s %-6s %-12s %-18s %-15s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB");
347 for (k = 0; k < c; k++) {
349 struct unit_info *u = unit_infos+k;
351 if ((!arg_type || ((dot = strrchr(u->id, '.')) &&
352 streq(dot+1, arg_type))) &&
353 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0)) {
356 const char *on_loaded, *off_loaded;
357 const char *on_active, *off_active;
359 if (!streq(u->load_state, "loaded")) {
360 on_loaded = ansi_highlight(true);
361 off_loaded = ansi_highlight(false);
363 on_loaded = off_loaded = "";
365 if (streq(u->active_state, "failed")) {
366 on_active = ansi_highlight(true);
367 off_active = ansi_highlight(false);
369 on_active = off_active = "";
371 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
373 printf("%-25s %s%-6s%s %s%-12s %-18s%s%n",
375 on_loaded, u->load_state, off_loaded,
376 on_active, u->active_state, u->sub_state, off_active,
381 a -= strlen(on_loaded) + strlen(off_loaded);
382 a -= strlen(on_active) + strlen(off_active);
385 printf(" %-15s%n", u->job_type, &b);
389 if (a + b + 1 < columns()) {
394 printf(" %s", u->description);
396 printf(" %.*s", columns() - a - b - 1, u->description);
403 if (isatty(STDOUT_FILENO)) {
405 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
406 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
407 "SUB = The low-level unit activation state, values depend on unit type.\n"
408 "JOB = Pending job for the unit.\n");
411 printf("\n%u units listed.\n", c);
413 printf("\n%u units listed. Pass --all to see inactive units, too.\n", c);
420 dbus_message_unref(m);
423 dbus_message_unref(reply);
427 dbus_error_free(&error);
432 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
433 static const char * const colors[] = {
434 "Requires", "[color=\"black\"]",
435 "RequiresOverridable", "[color=\"black\"]",
436 "Requisite", "[color=\"darkblue\"]",
437 "RequisiteOverridable", "[color=\"darkblue\"]",
438 "Wants", "[color=\"darkgrey\"]",
439 "Conflicts", "[color=\"red\"]",
440 "ConflictedBy", "[color=\"red\"]",
441 "After", "[color=\"green\"]"
444 const char *c = NULL;
451 for (i = 0; i < ELEMENTSOF(colors); i += 2)
452 if (streq(colors[i], prop)) {
460 if (arg_dot != DOT_ALL)
461 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
464 switch (dbus_message_iter_get_arg_type(iter)) {
466 case DBUS_TYPE_ARRAY:
468 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
471 dbus_message_iter_recurse(iter, &sub);
473 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
476 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
477 dbus_message_iter_get_basic(&sub, &s);
478 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
480 dbus_message_iter_next(&sub);
490 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
491 DBusMessage *m = NULL, *reply = NULL;
492 const char *interface = "org.freedesktop.systemd1.Unit";
495 DBusMessageIter iter, sub, sub2, sub3;
500 dbus_error_init(&error);
502 if (!(m = dbus_message_new_method_call(
503 "org.freedesktop.systemd1",
505 "org.freedesktop.DBus.Properties",
507 log_error("Could not allocate message.");
512 if (!dbus_message_append_args(m,
513 DBUS_TYPE_STRING, &interface,
514 DBUS_TYPE_INVALID)) {
515 log_error("Could not append arguments to message.");
520 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
521 log_error("Failed to issue method call: %s", bus_error_message(&error));
526 if (!dbus_message_iter_init(reply, &iter) ||
527 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
528 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
529 log_error("Failed to parse reply.");
534 dbus_message_iter_recurse(&iter, &sub);
536 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
539 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
540 log_error("Failed to parse reply.");
545 dbus_message_iter_recurse(&sub, &sub2);
547 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
548 log_error("Failed to parse reply.");
553 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
554 log_error("Failed to parse reply.");
559 dbus_message_iter_recurse(&sub2, &sub3);
561 if (dot_one_property(name, prop, &sub3)) {
562 log_error("Failed to parse reply.");
567 dbus_message_iter_next(&sub);
574 dbus_message_unref(m);
577 dbus_message_unref(reply);
579 dbus_error_free(&error);
584 static int dot(DBusConnection *bus, char **args, unsigned n) {
585 DBusMessage *m = NULL, *reply = NULL;
588 DBusMessageIter iter, sub, sub2;
590 dbus_error_init(&error);
594 if (!(m = dbus_message_new_method_call(
595 "org.freedesktop.systemd1",
596 "/org/freedesktop/systemd1",
597 "org.freedesktop.systemd1.Manager",
599 log_error("Could not allocate message.");
603 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
604 log_error("Failed to issue method call: %s", bus_error_message(&error));
609 if (!dbus_message_iter_init(reply, &iter) ||
610 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
611 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
612 log_error("Failed to parse reply.");
617 printf("digraph systemd {\n");
619 dbus_message_iter_recurse(&iter, &sub);
620 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
621 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
623 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
624 log_error("Failed to parse reply.");
629 dbus_message_iter_recurse(&sub, &sub2);
631 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
632 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
633 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
634 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
635 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
636 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
637 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
638 log_error("Failed to parse reply.");
643 if ((r = dot_one(bus, id, unit_path)) < 0)
646 /* printf("\t\"%s\";\n", id); */
647 dbus_message_iter_next(&sub);
652 log_info(" Color legend: black = Requires\n"
653 " dark blue = Requisite\n"
654 " dark grey = Wants\n"
658 if (isatty(fileno(stdout)))
659 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
660 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
666 dbus_message_unref(m);
669 dbus_message_unref(reply);
671 dbus_error_free(&error);
676 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
677 DBusMessage *m = NULL, *reply = NULL;
680 DBusMessageIter iter, sub, sub2;
683 dbus_error_init(&error);
687 if (!(m = dbus_message_new_method_call(
688 "org.freedesktop.systemd1",
689 "/org/freedesktop/systemd1",
690 "org.freedesktop.systemd1.Manager",
692 log_error("Could not allocate message.");
696 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
697 log_error("Failed to issue method call: %s", bus_error_message(&error));
702 if (!dbus_message_iter_init(reply, &iter) ||
703 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
704 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
705 log_error("Failed to parse reply.");
710 dbus_message_iter_recurse(&iter, &sub);
712 if (isatty(STDOUT_FILENO))
713 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
715 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
716 const char *name, *type, *state, *job_path, *unit_path;
720 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
721 log_error("Failed to parse reply.");
726 dbus_message_iter_recurse(&sub, &sub2);
728 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
729 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
730 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
731 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
732 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
733 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
734 log_error("Failed to parse reply.");
739 e = arg_full ? NULL : ellipsize(name, 25, 33);
740 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
745 dbus_message_iter_next(&sub);
748 if (isatty(STDOUT_FILENO))
749 printf("\n%u jobs listed.\n", k);
755 dbus_message_unref(m);
758 dbus_message_unref(reply);
760 dbus_error_free(&error);
765 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
766 DBusMessage *m = NULL, *reply = NULL;
771 dbus_error_init(&error);
776 for (i = 1; i < n; i++) {
778 if (!(m = dbus_message_new_method_call(
779 "org.freedesktop.systemd1",
780 "/org/freedesktop/systemd1",
781 "org.freedesktop.systemd1.Manager",
783 log_error("Could not allocate message.");
788 if (!dbus_message_append_args(m,
789 DBUS_TYPE_STRING, &args[i],
790 DBUS_TYPE_INVALID)) {
791 log_error("Could not append arguments to message.");
796 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
797 log_error("Failed to issue method call: %s", bus_error_message(&error));
802 dbus_message_unref(m);
803 dbus_message_unref(reply);
812 dbus_message_unref(m);
815 dbus_message_unref(reply);
817 dbus_error_free(&error);
822 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
823 DBusMessage *m = NULL, *reply = NULL;
828 dbus_error_init(&error);
834 return daemon_reload(bus, args, n);
836 for (i = 1; i < n; i++) {
840 if (!(m = dbus_message_new_method_call(
841 "org.freedesktop.systemd1",
842 "/org/freedesktop/systemd1",
843 "org.freedesktop.systemd1.Manager",
845 log_error("Could not allocate message.");
850 if ((r = safe_atou(args[i], &id)) < 0) {
851 log_error("Failed to parse job id: %s", strerror(-r));
855 assert_cc(sizeof(uint32_t) == sizeof(id));
856 if (!dbus_message_append_args(m,
857 DBUS_TYPE_UINT32, &id,
858 DBUS_TYPE_INVALID)) {
859 log_error("Could not append arguments to message.");
864 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
865 log_error("Failed to issue method call: %s", bus_error_message(&error));
870 if (!dbus_message_get_args(reply, &error,
871 DBUS_TYPE_OBJECT_PATH, &path,
872 DBUS_TYPE_INVALID)) {
873 log_error("Failed to parse reply: %s", bus_error_message(&error));
878 dbus_message_unref(m);
879 if (!(m = dbus_message_new_method_call(
880 "org.freedesktop.systemd1",
882 "org.freedesktop.systemd1.Job",
884 log_error("Could not allocate message.");
889 dbus_message_unref(reply);
890 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
891 log_error("Failed to issue method call: %s", bus_error_message(&error));
896 dbus_message_unref(m);
897 dbus_message_unref(reply);
905 dbus_message_unref(m);
908 dbus_message_unref(reply);
910 dbus_error_free(&error);
915 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
916 DBusMessage *m = NULL, *reply = NULL;
917 dbus_bool_t b = FALSE;
918 DBusMessageIter iter, sub;
920 *interface = "org.freedesktop.systemd1.Unit",
921 *property = "NeedDaemonReload",
924 /* We ignore all errors here, since this is used to show a warning only */
926 if (!(m = dbus_message_new_method_call(
927 "org.freedesktop.systemd1",
928 "/org/freedesktop/systemd1",
929 "org.freedesktop.systemd1.Manager",
933 if (!dbus_message_append_args(m,
934 DBUS_TYPE_STRING, &unit,
938 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
941 if (!dbus_message_get_args(reply, NULL,
942 DBUS_TYPE_OBJECT_PATH, &path,
946 dbus_message_unref(m);
947 if (!(m = dbus_message_new_method_call(
948 "org.freedesktop.systemd1",
950 "org.freedesktop.DBus.Properties",
954 if (!dbus_message_append_args(m,
955 DBUS_TYPE_STRING, &interface,
956 DBUS_TYPE_STRING, &property,
957 DBUS_TYPE_INVALID)) {
961 dbus_message_unref(reply);
962 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
965 if (!dbus_message_iter_init(reply, &iter) ||
966 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
969 dbus_message_iter_recurse(&iter, &sub);
971 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
974 dbus_message_iter_get_basic(&sub, &b);
978 dbus_message_unref(m);
981 dbus_message_unref(reply);
986 typedef struct WaitData {
991 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
999 dbus_error_init(&error);
1001 log_debug("Got D-Bus request: %s.%s() on %s",
1002 dbus_message_get_interface(message),
1003 dbus_message_get_member(message),
1004 dbus_message_get_path(message));
1006 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1007 log_error("Warning! D-Bus connection terminated.");
1008 dbus_connection_close(connection);
1010 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1013 dbus_bool_t success = true;
1015 if (!dbus_message_get_args(message, &error,
1016 DBUS_TYPE_UINT32, &id,
1017 DBUS_TYPE_OBJECT_PATH, &path,
1018 DBUS_TYPE_BOOLEAN, &success,
1020 log_error("Failed to parse message: %s", bus_error_message(&error));
1024 if ((p = set_remove(d->set, (char*) path)))
1032 dbus_error_free(&error);
1033 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1036 static int enable_wait_for_jobs(DBusConnection *bus) {
1044 dbus_error_init(&error);
1045 dbus_bus_add_match(bus,
1047 "sender='org.freedesktop.systemd1',"
1048 "interface='org.freedesktop.systemd1.Manager',"
1049 "member='JobRemoved',"
1050 "path='/org/freedesktop/systemd1'",
1053 if (dbus_error_is_set(&error)) {
1054 log_error("Failed to add match: %s", bus_error_message(&error));
1055 dbus_error_free(&error);
1059 /* This is slightly dirty, since we don't undo the match registrations. */
1063 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1074 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1075 log_error("Failed to add filter.");
1080 while (!set_isempty(s) &&
1081 dbus_connection_read_write_dispatch(bus, -1))
1084 if (!arg_quiet && d.failed)
1085 log_error("Job failed, see system logs for details.");
1087 r = d.failed ? -EIO : 0;
1090 /* This is slightly dirty, since we don't undo the filter registration. */
1095 static int start_unit_one(
1096 DBusConnection *bus,
1103 DBusMessage *m = NULL, *reply = NULL;
1112 assert(arg_no_block || s);
1114 if (!(m = dbus_message_new_method_call(
1115 "org.freedesktop.systemd1",
1116 "/org/freedesktop/systemd1",
1117 "org.freedesktop.systemd1.Manager",
1119 log_error("Could not allocate message.");
1124 if (!dbus_message_append_args(m,
1125 DBUS_TYPE_STRING, &name,
1126 DBUS_TYPE_STRING, &mode,
1127 DBUS_TYPE_INVALID)) {
1128 log_error("Could not append arguments to message.");
1133 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1135 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1136 /* There's always a fallback possible for
1137 * legacy actions. */
1142 log_error("Failed to issue method call: %s", bus_error_message(error));
1147 if (!dbus_message_get_args(reply, error,
1148 DBUS_TYPE_OBJECT_PATH, &path,
1149 DBUS_TYPE_INVALID)) {
1150 log_error("Failed to parse reply: %s", bus_error_message(error));
1155 if (need_daemon_reload(bus, name))
1156 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1157 arg_session ? "--session" : "--system");
1159 if (!arg_no_block) {
1162 if (!(p = strdup(path))) {
1163 log_error("Failed to duplicate path.");
1168 if ((r = set_put(s, p)) < 0) {
1170 log_error("Failed to add path to set.");
1179 dbus_message_unref(m);
1182 dbus_message_unref(reply);
1187 static enum action verb_to_action(const char *verb) {
1188 if (streq(verb, "halt"))
1190 else if (streq(verb, "poweroff"))
1191 return ACTION_POWEROFF;
1192 else if (streq(verb, "reboot"))
1193 return ACTION_REBOOT;
1194 else if (streq(verb, "rescue"))
1195 return ACTION_RESCUE;
1196 else if (streq(verb, "emergency"))
1197 return ACTION_EMERGENCY;
1198 else if (streq(verb, "default"))
1199 return ACTION_DEFAULT;
1201 return ACTION_INVALID;
1204 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1206 static const char * const table[_ACTION_MAX] = {
1207 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1208 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1209 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1210 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1211 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1212 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1213 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1214 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1215 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1216 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1221 const char *method, *mode, *one_name;
1225 dbus_error_init(&error);
1229 if (arg_action == ACTION_SYSTEMCTL) {
1231 streq(args[0], "stop") ? "StopUnit" :
1232 streq(args[0], "reload") ? "ReloadUnit" :
1233 streq(args[0], "restart") ? "RestartUnit" :
1234 streq(args[0], "try-restart") ? "TryRestartUnit" :
1235 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
1236 streq(args[0], "reload-or-try-restart") ||
1237 streq(args[0], "force-reload") ||
1238 streq(args[0], "condrestart") ? "ReloadOrTryRestartUnit" :
1242 (streq(args[0], "isolate") ||
1243 streq(args[0], "rescue") ||
1244 streq(args[0], "emergency")) ? "isolate" :
1248 one_name = table[verb_to_action(args[0])];
1251 assert(arg_action < ELEMENTSOF(table));
1252 assert(table[arg_action]);
1254 method = "StartUnit";
1256 mode = (arg_action == ACTION_EMERGENCY ||
1257 arg_action == ACTION_RESCUE) ? "isolate" : "replace";
1259 one_name = table[arg_action];
1262 if (!arg_no_block) {
1263 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1264 log_error("Could not watch jobs: %s", strerror(-ret));
1268 if (!(s = set_new(string_hash_func, string_compare_func))) {
1269 log_error("Failed to allocate set.");
1276 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1279 for (i = 1; i < n; i++)
1280 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1281 ret = translate_bus_error_to_exit_status(r, &error);
1282 dbus_error_free(&error);
1287 if ((r = wait_for_jobs(bus, s)) < 0) {
1296 dbus_error_free(&error);
1301 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1307 r = start_unit(bus, args, n);
1310 warn_wall(verb_to_action(args[0]));
1315 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1316 DBusMessage *m = NULL, *reply = NULL;
1318 *interface = "org.freedesktop.systemd1.Unit",
1319 *property = "ActiveState";
1320 int r = 3; /* According to LSB: "program is not running" */
1327 dbus_error_init(&error);
1329 for (i = 1; i < n; i++) {
1330 const char *path = NULL;
1332 DBusMessageIter iter, sub;
1334 if (!(m = dbus_message_new_method_call(
1335 "org.freedesktop.systemd1",
1336 "/org/freedesktop/systemd1",
1337 "org.freedesktop.systemd1.Manager",
1339 log_error("Could not allocate message.");
1344 if (!dbus_message_append_args(m,
1345 DBUS_TYPE_STRING, &args[i],
1346 DBUS_TYPE_INVALID)) {
1347 log_error("Could not append arguments to message.");
1352 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1354 /* Hmm, cannot figure out anything about this unit... */
1358 dbus_error_free(&error);
1362 if (!dbus_message_get_args(reply, &error,
1363 DBUS_TYPE_OBJECT_PATH, &path,
1364 DBUS_TYPE_INVALID)) {
1365 log_error("Failed to parse reply: %s", bus_error_message(&error));
1370 dbus_message_unref(m);
1371 if (!(m = dbus_message_new_method_call(
1372 "org.freedesktop.systemd1",
1374 "org.freedesktop.DBus.Properties",
1376 log_error("Could not allocate message.");
1381 if (!dbus_message_append_args(m,
1382 DBUS_TYPE_STRING, &interface,
1383 DBUS_TYPE_STRING, &property,
1384 DBUS_TYPE_INVALID)) {
1385 log_error("Could not append arguments to message.");
1390 dbus_message_unref(reply);
1391 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1392 log_error("Failed to issue method call: %s", bus_error_message(&error));
1397 if (!dbus_message_iter_init(reply, &iter) ||
1398 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1399 log_error("Failed to parse reply.");
1404 dbus_message_iter_recurse(&iter, &sub);
1406 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1407 log_error("Failed to parse reply.");
1412 dbus_message_iter_get_basic(&sub, &state);
1417 if (streq(state, "active") || streq(state, "reloading"))
1420 dbus_message_unref(m);
1421 dbus_message_unref(reply);
1427 dbus_message_unref(m);
1430 dbus_message_unref(reply);
1432 dbus_error_free(&error);
1437 typedef struct ExecStatusInfo {
1443 usec_t start_timestamp;
1444 usec_t exit_timestamp;
1449 LIST_FIELDS(struct ExecStatusInfo, exec);
1452 static void exec_status_info_free(ExecStatusInfo *i) {
1460 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1461 uint64_t start_timestamp, exit_timestamp;
1462 DBusMessageIter sub2, sub3;
1466 int32_t code, status;
1472 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1475 dbus_message_iter_recurse(sub, &sub2);
1477 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1480 if (!(i->path = strdup(path)))
1483 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1484 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1488 dbus_message_iter_recurse(&sub2, &sub3);
1489 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1490 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1491 dbus_message_iter_next(&sub3);
1496 if (!(i->argv = new0(char*, n+1)))
1500 dbus_message_iter_recurse(&sub2, &sub3);
1501 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1504 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1505 dbus_message_iter_get_basic(&sub3, &s);
1506 dbus_message_iter_next(&sub3);
1508 if (!(i->argv[n++] = strdup(s)))
1512 if (!dbus_message_iter_next(&sub2) ||
1513 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1514 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1515 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1516 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1517 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1518 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1522 i->start_timestamp = (usec_t) start_timestamp;
1523 i->exit_timestamp = (usec_t) exit_timestamp;
1524 i->pid = (pid_t) pid;
1531 typedef struct UnitStatusInfo {
1533 const char *load_state;
1534 const char *active_state;
1535 const char *sub_state;
1537 const char *description;
1540 const char *default_control_group;
1542 usec_t inactive_exit_timestamp;
1543 usec_t active_enter_timestamp;
1544 usec_t active_exit_timestamp;
1545 usec_t inactive_enter_timestamp;
1547 bool need_daemon_reload;
1552 const char *status_text;
1556 usec_t start_timestamp;
1557 usec_t exit_timestamp;
1559 int exit_code, exit_status;
1562 unsigned n_accepted;
1563 unsigned n_connections;
1567 const char *sysfs_path;
1569 /* Mount, Automount */
1575 LIST_HEAD(ExecStatusInfo, exec);
1578 static void print_status_info(UnitStatusInfo *i) {
1580 const char *on, *off, *ss;
1582 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1583 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1587 /* This shows pretty information about a unit. See
1588 * print_property() for a low-level property printer */
1590 printf("%s", strna(i->id));
1592 if (i->description && !streq_ptr(i->id, i->description))
1593 printf(" - %s", i->description);
1597 if (streq_ptr(i->load_state, "failed")) {
1598 on = ansi_highlight(true);
1599 off = ansi_highlight(false);
1604 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1606 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1608 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1610 if (streq_ptr(i->active_state, "failed")) {
1611 on = ansi_highlight(true);
1612 off = ansi_highlight(false);
1613 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1614 on = ansi_highlight_green(true);
1615 off = ansi_highlight_green(false);
1620 printf("\t Active: %s%s (%s)%s",
1622 strna(i->active_state),
1626 printf("\t Active: %s%s%s",
1628 strna(i->active_state),
1631 timestamp = (streq_ptr(i->active_state, "active") ||
1632 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1633 (streq_ptr(i->active_state, "inactive") ||
1634 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1635 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1636 i->active_exit_timestamp;
1638 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1639 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1642 printf(" since [%s; %s]\n", s2, s1);
1644 printf(" since [%s]\n", s2);
1649 printf("\t Device: %s\n", i->sysfs_path);
1651 printf("\t Where: %s\n", i->where);
1653 printf("\t What: %s\n", i->what);
1656 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1658 LIST_FOREACH(exec, p, i->exec) {
1661 /* Only show exited processes here */
1665 t = strv_join(p->argv, " ");
1666 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1669 if (p->code == CLD_EXITED) {
1672 printf("status=%i", p->status);
1674 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1678 printf("signal=%s", signal_to_string(p->status));
1681 if (i->main_pid == p->pid &&
1682 i->start_timestamp == p->start_timestamp &&
1683 i->exit_timestamp == p->start_timestamp)
1684 /* Let's not show this twice */
1687 if (p->pid == i->control_pid)
1691 if (i->main_pid > 0 || i->control_pid > 0) {
1694 if (i->main_pid > 0) {
1695 printf("Main PID: %u", (unsigned) i->main_pid);
1699 get_process_name(i->main_pid, &t);
1704 } else if (i->exit_code > 0) {
1705 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1707 if (i->exit_code == CLD_EXITED) {
1710 printf("status=%i", i->exit_status);
1712 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1716 printf("signal=%s", signal_to_string(i->exit_status));
1721 if (i->main_pid > 0 && i->control_pid > 0)
1724 if (i->control_pid > 0) {
1727 printf(" Control: %u", (unsigned) i->control_pid);
1729 get_process_name(i->control_pid, &t);
1740 printf("\t Status: \"%s\"\n", i->status_text);
1742 if (i->default_control_group) {
1745 printf("\t CGroup: %s\n", i->default_control_group);
1747 if ((c = columns()) > 18)
1752 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1755 if (i->need_daemon_reload)
1756 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1757 ansi_highlight(true),
1758 ansi_highlight(false),
1759 arg_session ? "--session" : "--system");
1762 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1764 switch (dbus_message_iter_get_arg_type(iter)) {
1766 case DBUS_TYPE_STRING: {
1769 dbus_message_iter_get_basic(iter, &s);
1772 if (streq(name, "Id"))
1774 else if (streq(name, "LoadState"))
1776 else if (streq(name, "ActiveState"))
1777 i->active_state = s;
1778 else if (streq(name, "SubState"))
1780 else if (streq(name, "Description"))
1782 else if (streq(name, "FragmentPath"))
1784 else if (streq(name, "SysVPath")) {
1787 } else if (streq(name, "DefaultControlGroup"))
1788 i->default_control_group = s;
1789 else if (streq(name, "StatusText"))
1791 else if (streq(name, "SysFSPath"))
1793 else if (streq(name, "Where"))
1795 else if (streq(name, "What"))
1802 case DBUS_TYPE_BOOLEAN: {
1805 dbus_message_iter_get_basic(iter, &b);
1807 if (streq(name, "Accept"))
1809 else if (streq(name, "NeedDaemonReload"))
1810 i->need_daemon_reload = b;
1815 case DBUS_TYPE_UINT32: {
1818 dbus_message_iter_get_basic(iter, &u);
1820 if (streq(name, "MainPID")) {
1822 i->main_pid = (pid_t) u;
1825 } else if (streq(name, "ControlPID"))
1826 i->control_pid = (pid_t) u;
1827 else if (streq(name, "ExecMainPID")) {
1829 i->main_pid = (pid_t) u;
1830 } else if (streq(name, "NAccepted"))
1832 else if (streq(name, "NConnections"))
1833 i->n_connections = u;
1838 case DBUS_TYPE_INT32: {
1841 dbus_message_iter_get_basic(iter, &j);
1843 if (streq(name, "ExecMainCode"))
1844 i->exit_code = (int) j;
1845 else if (streq(name, "ExecMainStatus"))
1846 i->exit_status = (int) j;
1851 case DBUS_TYPE_UINT64: {
1854 dbus_message_iter_get_basic(iter, &u);
1856 if (streq(name, "ExecMainStartTimestamp"))
1857 i->start_timestamp = (usec_t) u;
1858 else if (streq(name, "ExecMainExitTimestamp"))
1859 i->exit_timestamp = (usec_t) u;
1860 else if (streq(name, "ActiveEnterTimestamp"))
1861 i->active_enter_timestamp = (usec_t) u;
1862 else if (streq(name, "InactiveEnterTimestamp"))
1863 i->inactive_enter_timestamp = (usec_t) u;
1864 else if (streq(name, "InactiveExitTimestamp"))
1865 i->inactive_exit_timestamp = (usec_t) u;
1866 else if (streq(name, "ActiveExitTimestamp"))
1867 i->active_exit_timestamp = (usec_t) u;
1872 case DBUS_TYPE_ARRAY: {
1874 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1875 startswith(name, "Exec")) {
1876 DBusMessageIter sub;
1878 dbus_message_iter_recurse(iter, &sub);
1879 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1880 ExecStatusInfo *info;
1883 if (!(info = new0(ExecStatusInfo, 1)))
1886 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1891 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1893 dbus_message_iter_next(&sub);
1904 static int print_property(const char *name, DBusMessageIter *iter) {
1908 /* This is a low-level property printer, see
1909 * print_status_info() for the nicer output */
1911 if (arg_property && !strv_find(arg_property, name))
1914 switch (dbus_message_iter_get_arg_type(iter)) {
1916 case DBUS_TYPE_STRING: {
1918 dbus_message_iter_get_basic(iter, &s);
1920 if (arg_all || s[0])
1921 printf("%s=%s\n", name, s);
1926 case DBUS_TYPE_BOOLEAN: {
1928 dbus_message_iter_get_basic(iter, &b);
1929 printf("%s=%s\n", name, yes_no(b));
1934 case DBUS_TYPE_UINT64: {
1936 dbus_message_iter_get_basic(iter, &u);
1938 /* Yes, heuristics! But we can change this check
1939 * should it turn out to not be sufficient */
1941 if (strstr(name, "Timestamp")) {
1942 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1944 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1945 printf("%s=%s\n", name, strempty(t));
1946 } else if (strstr(name, "USec")) {
1947 char timespan[FORMAT_TIMESPAN_MAX];
1949 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1951 printf("%s=%llu\n", name, (unsigned long long) u);
1956 case DBUS_TYPE_UINT32: {
1958 dbus_message_iter_get_basic(iter, &u);
1960 if (strstr(name, "UMask") || strstr(name, "Mode"))
1961 printf("%s=%04o\n", name, u);
1963 printf("%s=%u\n", name, (unsigned) u);
1968 case DBUS_TYPE_INT32: {
1970 dbus_message_iter_get_basic(iter, &i);
1972 printf("%s=%i\n", name, (int) i);
1976 case DBUS_TYPE_STRUCT: {
1977 DBusMessageIter sub;
1978 dbus_message_iter_recurse(iter, &sub);
1980 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1983 dbus_message_iter_get_basic(&sub, &u);
1986 printf("%s=%u\n", name, (unsigned) u);
1988 printf("%s=\n", name);
1991 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1994 dbus_message_iter_get_basic(&sub, &s);
1996 if (arg_all || s[0])
1997 printf("%s=%s\n", name, s);
2005 case DBUS_TYPE_ARRAY:
2007 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2008 DBusMessageIter sub;
2011 dbus_message_iter_recurse(iter, &sub);
2013 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2014 printf("%s=", name);
2016 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2019 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2020 dbus_message_iter_get_basic(&sub, &s);
2021 printf("%s%s", space ? " " : "", s);
2024 dbus_message_iter_next(&sub);
2032 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2033 DBusMessageIter sub;
2035 dbus_message_iter_recurse(iter, &sub);
2037 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2038 printf("%s=", name);
2040 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2043 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2044 dbus_message_iter_get_basic(&sub, &u);
2047 dbus_message_iter_next(&sub);
2055 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2056 DBusMessageIter sub, sub2;
2058 dbus_message_iter_recurse(iter, &sub);
2059 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2060 const char *type, *path;
2062 dbus_message_iter_recurse(&sub, &sub2);
2064 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2065 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2066 printf("%s=%s\n", type, path);
2068 dbus_message_iter_next(&sub);
2073 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2074 DBusMessageIter sub, sub2;
2076 dbus_message_iter_recurse(iter, &sub);
2077 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2079 uint64_t value, next_elapse;
2081 dbus_message_iter_recurse(&sub, &sub2);
2083 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2084 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2085 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2086 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2088 printf("%s={ value=%s ; next_elapse=%s }\n",
2090 format_timespan(timespan1, sizeof(timespan1), value),
2091 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2094 dbus_message_iter_next(&sub);
2099 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2100 DBusMessageIter sub;
2102 dbus_message_iter_recurse(iter, &sub);
2103 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2104 ExecStatusInfo info;
2107 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2108 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2111 t = strv_join(info.argv, " ");
2113 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2117 yes_no(info.ignore),
2118 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2119 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2120 (unsigned) info. pid,
2121 sigchld_code_to_string(info.code),
2123 info.code == CLD_EXITED ? "" : "/",
2124 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2130 strv_free(info.argv);
2132 dbus_message_iter_next(&sub);
2142 printf("%s=[unprintable]\n", name);
2147 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2148 DBusMessage *m = NULL, *reply = NULL;
2149 const char *interface = "";
2152 DBusMessageIter iter, sub, sub2, sub3;
2153 UnitStatusInfo info;
2161 dbus_error_init(&error);
2163 if (!(m = dbus_message_new_method_call(
2164 "org.freedesktop.systemd1",
2166 "org.freedesktop.DBus.Properties",
2168 log_error("Could not allocate message.");
2173 if (!dbus_message_append_args(m,
2174 DBUS_TYPE_STRING, &interface,
2175 DBUS_TYPE_INVALID)) {
2176 log_error("Could not append arguments to message.");
2181 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2182 log_error("Failed to issue method call: %s", bus_error_message(&error));
2187 if (!dbus_message_iter_init(reply, &iter) ||
2188 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2189 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2190 log_error("Failed to parse reply.");
2195 dbus_message_iter_recurse(&iter, &sub);
2202 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2205 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2206 log_error("Failed to parse reply.");
2211 dbus_message_iter_recurse(&sub, &sub2);
2213 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2214 log_error("Failed to parse reply.");
2219 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2220 log_error("Failed to parse reply.");
2225 dbus_message_iter_recurse(&sub2, &sub3);
2227 if (show_properties)
2228 r = print_property(name, &sub3);
2230 r = status_property(name, &sub3, &info);
2233 log_error("Failed to parse reply.");
2238 dbus_message_iter_next(&sub);
2243 if (!show_properties)
2244 print_status_info(&info);
2246 if (!streq_ptr(info.active_state, "active") &&
2247 !streq_ptr(info.active_state, "reloading"))
2248 /* According to LSB: "program not running" */
2251 while ((p = info.exec)) {
2252 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2253 exec_status_info_free(p);
2258 dbus_message_unref(m);
2261 dbus_message_unref(reply);
2263 dbus_error_free(&error);
2268 static int show(DBusConnection *bus, char **args, unsigned n) {
2269 DBusMessage *m = NULL, *reply = NULL;
2273 bool show_properties, new_line = false;
2278 dbus_error_init(&error);
2280 show_properties = !streq(args[0], "status");
2282 if (show_properties && n <= 1) {
2283 /* If not argument is specified inspect the manager
2286 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2290 for (i = 1; i < n; i++) {
2291 const char *path = NULL;
2294 if (safe_atou32(args[i], &id) < 0) {
2296 /* Interpret as unit name */
2298 if (!(m = dbus_message_new_method_call(
2299 "org.freedesktop.systemd1",
2300 "/org/freedesktop/systemd1",
2301 "org.freedesktop.systemd1.Manager",
2303 log_error("Could not allocate message.");
2308 if (!dbus_message_append_args(m,
2309 DBUS_TYPE_STRING, &args[i],
2310 DBUS_TYPE_INVALID)) {
2311 log_error("Could not append arguments to message.");
2316 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2318 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2319 log_error("Failed to issue method call: %s", bus_error_message(&error));
2324 dbus_error_free(&error);
2326 dbus_message_unref(m);
2327 if (!(m = dbus_message_new_method_call(
2328 "org.freedesktop.systemd1",
2329 "/org/freedesktop/systemd1",
2330 "org.freedesktop.systemd1.Manager",
2332 log_error("Could not allocate message.");
2337 if (!dbus_message_append_args(m,
2338 DBUS_TYPE_STRING, &args[i],
2339 DBUS_TYPE_INVALID)) {
2340 log_error("Could not append arguments to message.");
2345 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2346 log_error("Failed to issue method call: %s", bus_error_message(&error));
2348 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2349 ret = 4; /* According to LSB: "program or service status is unknown" */
2356 } else if (show_properties) {
2358 /* Interpret as job id */
2360 if (!(m = dbus_message_new_method_call(
2361 "org.freedesktop.systemd1",
2362 "/org/freedesktop/systemd1",
2363 "org.freedesktop.systemd1.Manager",
2365 log_error("Could not allocate message.");
2370 if (!dbus_message_append_args(m,
2371 DBUS_TYPE_UINT32, &id,
2372 DBUS_TYPE_INVALID)) {
2373 log_error("Could not append arguments to message.");
2378 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2379 log_error("Failed to issue method call: %s", bus_error_message(&error));
2385 /* Interpret as PID */
2387 if (!(m = dbus_message_new_method_call(
2388 "org.freedesktop.systemd1",
2389 "/org/freedesktop/systemd1",
2390 "org.freedesktop.systemd1.Manager",
2392 log_error("Could not allocate message.");
2397 if (!dbus_message_append_args(m,
2398 DBUS_TYPE_UINT32, &id,
2399 DBUS_TYPE_INVALID)) {
2400 log_error("Could not append arguments to message.");
2405 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2406 log_error("Failed to issue method call: %s", bus_error_message(&error));
2412 if (!dbus_message_get_args(reply, &error,
2413 DBUS_TYPE_OBJECT_PATH, &path,
2414 DBUS_TYPE_INVALID)) {
2415 log_error("Failed to parse reply: %s", bus_error_message(&error));
2420 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2423 dbus_message_unref(m);
2424 dbus_message_unref(reply);
2430 dbus_message_unref(m);
2433 dbus_message_unref(reply);
2435 dbus_error_free(&error);
2440 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2442 DBusMessage *m = NULL, *reply = NULL;
2447 dbus_error_init(&error);
2449 log_debug("Got D-Bus request: %s.%s() on %s",
2450 dbus_message_get_interface(message),
2451 dbus_message_get_member(message),
2452 dbus_message_get_path(message));
2454 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2455 log_error("Warning! D-Bus connection terminated.");
2456 dbus_connection_close(connection);
2458 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2459 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2460 const char *id, *path;
2462 if (!dbus_message_get_args(message, &error,
2463 DBUS_TYPE_STRING, &id,
2464 DBUS_TYPE_OBJECT_PATH, &path,
2466 log_error("Failed to parse message: %s", bus_error_message(&error));
2467 else if (streq(dbus_message_get_member(message), "UnitNew"))
2468 printf("Unit %s added.\n", id);
2470 printf("Unit %s removed.\n", id);
2472 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2473 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2477 if (!dbus_message_get_args(message, &error,
2478 DBUS_TYPE_UINT32, &id,
2479 DBUS_TYPE_OBJECT_PATH, &path,
2481 log_error("Failed to parse message: %s", bus_error_message(&error));
2482 else if (streq(dbus_message_get_member(message), "JobNew"))
2483 printf("Job %u added.\n", id);
2485 printf("Job %u removed.\n", id);
2488 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2490 const char *path, *interface, *property = "Id";
2491 DBusMessageIter iter, sub;
2493 path = dbus_message_get_path(message);
2495 if (!dbus_message_get_args(message, &error,
2496 DBUS_TYPE_STRING, &interface,
2497 DBUS_TYPE_INVALID)) {
2498 log_error("Failed to parse message: %s", bus_error_message(&error));
2502 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2503 !streq(interface, "org.freedesktop.systemd1.Unit"))
2506 if (!(m = dbus_message_new_method_call(
2507 "org.freedesktop.systemd1",
2509 "org.freedesktop.DBus.Properties",
2511 log_error("Could not allocate message.");
2515 if (!dbus_message_append_args(m,
2516 DBUS_TYPE_STRING, &interface,
2517 DBUS_TYPE_STRING, &property,
2518 DBUS_TYPE_INVALID)) {
2519 log_error("Could not append arguments to message.");
2523 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2524 log_error("Failed to issue method call: %s", bus_error_message(&error));
2528 if (!dbus_message_iter_init(reply, &iter) ||
2529 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2530 log_error("Failed to parse reply.");
2534 dbus_message_iter_recurse(&iter, &sub);
2536 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2539 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2540 log_error("Failed to parse reply.");
2544 dbus_message_iter_get_basic(&sub, &id);
2545 printf("Unit %s changed.\n", id);
2549 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2550 log_error("Failed to parse reply.");
2554 dbus_message_iter_get_basic(&sub, &id);
2555 printf("Job %u changed.\n", id);
2561 dbus_message_unref(m);
2564 dbus_message_unref(reply);
2566 dbus_error_free(&error);
2567 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2571 dbus_message_unref(m);
2574 dbus_message_unref(reply);
2576 dbus_error_free(&error);
2577 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2580 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2581 DBusMessage *m = NULL, *reply = NULL;
2585 dbus_error_init(&error);
2588 dbus_bus_add_match(bus,
2590 "sender='org.freedesktop.systemd1',"
2591 "interface='org.freedesktop.systemd1.Manager',"
2592 "path='/org/freedesktop/systemd1'",
2595 if (dbus_error_is_set(&error)) {
2596 log_error("Failed to add match: %s", bus_error_message(&error));
2601 dbus_bus_add_match(bus,
2603 "sender='org.freedesktop.systemd1',"
2604 "interface='org.freedesktop.DBus.Properties',"
2605 "member='PropertiesChanged'",
2608 if (dbus_error_is_set(&error)) {
2609 log_error("Failed to add match: %s", bus_error_message(&error));
2615 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2616 log_error("Failed to add filter.");
2621 if (!(m = dbus_message_new_method_call(
2622 "org.freedesktop.systemd1",
2623 "/org/freedesktop/systemd1",
2624 "org.freedesktop.systemd1.Manager",
2626 log_error("Could not allocate message.");
2631 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2632 log_error("Failed to issue method call: %s", bus_error_message(&error));
2637 while (dbus_connection_read_write_dispatch(bus, -1))
2644 /* This is slightly dirty, since we don't undo the filter or the matches. */
2647 dbus_message_unref(m);
2650 dbus_message_unref(reply);
2652 dbus_error_free(&error);
2657 static int dump(DBusConnection *bus, char **args, unsigned n) {
2658 DBusMessage *m = NULL, *reply = NULL;
2663 dbus_error_init(&error);
2665 if (!(m = dbus_message_new_method_call(
2666 "org.freedesktop.systemd1",
2667 "/org/freedesktop/systemd1",
2668 "org.freedesktop.systemd1.Manager",
2670 log_error("Could not allocate message.");
2674 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2675 log_error("Failed to issue method call: %s", bus_error_message(&error));
2680 if (!dbus_message_get_args(reply, &error,
2681 DBUS_TYPE_STRING, &text,
2682 DBUS_TYPE_INVALID)) {
2683 log_error("Failed to parse reply: %s", bus_error_message(&error));
2688 fputs(text, stdout);
2694 dbus_message_unref(m);
2697 dbus_message_unref(reply);
2699 dbus_error_free(&error);
2704 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2705 DBusMessage *m = NULL, *reply = NULL;
2708 const char *name = "", *path, *id;
2709 dbus_bool_t cleanup = FALSE;
2710 DBusMessageIter iter, sub;
2712 *interface = "org.freedesktop.systemd1.Unit",
2715 dbus_error_init(&error);
2717 if (!(m = dbus_message_new_method_call(
2718 "org.freedesktop.systemd1",
2719 "/org/freedesktop/systemd1",
2720 "org.freedesktop.systemd1.Manager",
2721 "CreateSnapshot"))) {
2722 log_error("Could not allocate message.");
2729 if (!dbus_message_append_args(m,
2730 DBUS_TYPE_STRING, &name,
2731 DBUS_TYPE_BOOLEAN, &cleanup,
2732 DBUS_TYPE_INVALID)) {
2733 log_error("Could not append arguments to message.");
2738 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2739 log_error("Failed to issue method call: %s", bus_error_message(&error));
2744 if (!dbus_message_get_args(reply, &error,
2745 DBUS_TYPE_OBJECT_PATH, &path,
2746 DBUS_TYPE_INVALID)) {
2747 log_error("Failed to parse reply: %s", bus_error_message(&error));
2752 dbus_message_unref(m);
2753 if (!(m = dbus_message_new_method_call(
2754 "org.freedesktop.systemd1",
2756 "org.freedesktop.DBus.Properties",
2758 log_error("Could not allocate message.");
2762 if (!dbus_message_append_args(m,
2763 DBUS_TYPE_STRING, &interface,
2764 DBUS_TYPE_STRING, &property,
2765 DBUS_TYPE_INVALID)) {
2766 log_error("Could not append arguments to message.");
2771 dbus_message_unref(reply);
2772 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2773 log_error("Failed to issue method call: %s", bus_error_message(&error));
2778 if (!dbus_message_iter_init(reply, &iter) ||
2779 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2780 log_error("Failed to parse reply.");
2785 dbus_message_iter_recurse(&iter, &sub);
2787 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2788 log_error("Failed to parse reply.");
2793 dbus_message_iter_get_basic(&sub, &id);
2801 dbus_message_unref(m);
2804 dbus_message_unref(reply);
2806 dbus_error_free(&error);
2811 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2812 DBusMessage *m = NULL, *reply = NULL;
2820 dbus_error_init(&error);
2822 for (i = 1; i < n; i++) {
2823 const char *path = NULL;
2825 if (!(m = dbus_message_new_method_call(
2826 "org.freedesktop.systemd1",
2827 "/org/freedesktop/systemd1",
2828 "org.freedesktop.systemd1.Manager",
2830 log_error("Could not allocate message.");
2835 if (!dbus_message_append_args(m,
2836 DBUS_TYPE_STRING, &args[i],
2837 DBUS_TYPE_INVALID)) {
2838 log_error("Could not append arguments to message.");
2843 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2844 log_error("Failed to issue method call: %s", bus_error_message(&error));
2849 if (!dbus_message_get_args(reply, &error,
2850 DBUS_TYPE_OBJECT_PATH, &path,
2851 DBUS_TYPE_INVALID)) {
2852 log_error("Failed to parse reply: %s", bus_error_message(&error));
2857 dbus_message_unref(m);
2858 if (!(m = dbus_message_new_method_call(
2859 "org.freedesktop.systemd1",
2861 "org.freedesktop.systemd1.Snapshot",
2863 log_error("Could not allocate message.");
2868 dbus_message_unref(reply);
2869 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2870 log_error("Failed to issue method call: %s", bus_error_message(&error));
2875 dbus_message_unref(m);
2876 dbus_message_unref(reply);
2884 dbus_message_unref(m);
2887 dbus_message_unref(reply);
2889 dbus_error_free(&error);
2894 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2895 DBusMessage *m = NULL, *reply = NULL;
2900 dbus_error_init(&error);
2902 if (arg_action == ACTION_RELOAD)
2904 else if (arg_action == ACTION_REEXEC)
2905 method = "Reexecute";
2907 assert(arg_action == ACTION_SYSTEMCTL);
2910 streq(args[0], "clear-jobs") ||
2911 streq(args[0], "cancel") ? "ClearJobs" :
2912 streq(args[0], "daemon-reexec") ? "Reexecute" :
2913 streq(args[0], "reset-failed") ? "ResetFailed" :
2914 streq(args[0], "daemon-exit") ? "Exit" :
2918 if (!(m = dbus_message_new_method_call(
2919 "org.freedesktop.systemd1",
2920 "/org/freedesktop/systemd1",
2921 "org.freedesktop.systemd1.Manager",
2923 log_error("Could not allocate message.");
2927 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2929 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2930 /* There's always a fallback possible for
2931 * legacy actions. */
2936 log_error("Failed to issue method call: %s", bus_error_message(&error));
2945 dbus_message_unref(m);
2948 dbus_message_unref(reply);
2950 dbus_error_free(&error);
2955 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
2956 DBusMessage *m = NULL, *reply = NULL;
2962 dbus_error_init(&error);
2965 return daemon_reload(bus, args, n);
2967 for (i = 1; i < n; i++) {
2969 if (!(m = dbus_message_new_method_call(
2970 "org.freedesktop.systemd1",
2971 "/org/freedesktop/systemd1",
2972 "org.freedesktop.systemd1.Manager",
2973 "ResetFailedUnit"))) {
2974 log_error("Could not allocate message.");
2979 if (!dbus_message_append_args(m,
2980 DBUS_TYPE_STRING, args + i,
2981 DBUS_TYPE_INVALID)) {
2982 log_error("Could not append arguments to message.");
2987 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2988 log_error("Failed to issue method call: %s", bus_error_message(&error));
2993 dbus_message_unref(m);
2994 dbus_message_unref(reply);
3002 dbus_message_unref(m);
3005 dbus_message_unref(reply);
3007 dbus_error_free(&error);
3012 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3013 DBusMessage *m = NULL, *reply = NULL;
3015 DBusMessageIter iter, sub, sub2;
3018 *interface = "org.freedesktop.systemd1.Manager",
3019 *property = "Environment";
3021 dbus_error_init(&error);
3023 if (!(m = dbus_message_new_method_call(
3024 "org.freedesktop.systemd1",
3025 "/org/freedesktop/systemd1",
3026 "org.freedesktop.DBus.Properties",
3028 log_error("Could not allocate message.");
3032 if (!dbus_message_append_args(m,
3033 DBUS_TYPE_STRING, &interface,
3034 DBUS_TYPE_STRING, &property,
3035 DBUS_TYPE_INVALID)) {
3036 log_error("Could not append arguments to message.");
3041 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3042 log_error("Failed to issue method call: %s", bus_error_message(&error));
3047 if (!dbus_message_iter_init(reply, &iter) ||
3048 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3049 log_error("Failed to parse reply.");
3054 dbus_message_iter_recurse(&iter, &sub);
3056 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3057 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3058 log_error("Failed to parse reply.");
3063 dbus_message_iter_recurse(&sub, &sub2);
3065 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3068 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3069 log_error("Failed to parse reply.");
3074 dbus_message_iter_get_basic(&sub2, &text);
3075 printf("%s\n", text);
3077 dbus_message_iter_next(&sub2);
3084 dbus_message_unref(m);
3087 dbus_message_unref(reply);
3089 dbus_error_free(&error);
3094 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3095 DBusMessage *m = NULL, *reply = NULL;
3099 DBusMessageIter iter, sub;
3102 dbus_error_init(&error);
3104 method = streq(args[0], "set-environment")
3106 : "UnsetEnvironment";
3108 if (!(m = dbus_message_new_method_call(
3109 "org.freedesktop.systemd1",
3110 "/org/freedesktop/systemd1",
3111 "org.freedesktop.systemd1.Manager",
3114 log_error("Could not allocate message.");
3118 dbus_message_iter_init_append(m, &iter);
3120 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3121 log_error("Could not append arguments to message.");
3126 for (i = 1; i < n; i++)
3127 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3128 log_error("Could not append arguments to message.");
3133 if (!dbus_message_iter_close_container(&iter, &sub)) {
3134 log_error("Could not append arguments to message.");
3139 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3140 log_error("Failed to issue method call: %s", bus_error_message(&error));
3149 dbus_message_unref(m);
3152 dbus_message_unref(reply);
3154 dbus_error_free(&error);
3167 static Hashmap *will_install = NULL, *have_installed = NULL;
3168 static Set *remove_symlinks_to = NULL;
3170 static void install_info_free(InstallInfo *i) {
3175 strv_free(i->aliases);
3176 strv_free(i->wanted_by);
3180 static void install_info_hashmap_free(Hashmap *m) {
3183 while ((i = hashmap_steal_first(m)))
3184 install_info_free(i);
3189 static bool unit_name_valid(const char *name) {
3191 /* This is a minimal version of unit_name_valid() from
3197 if (ignore_file(name))
3203 static int install_info_add(const char *name) {
3207 assert(will_install);
3209 if (!unit_name_valid(name))
3212 if (hashmap_get(have_installed, name) ||
3213 hashmap_get(will_install, name))
3216 if (!(i = new0(InstallInfo, 1))) {
3221 if (!(i->name = strdup(name))) {
3226 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3233 install_info_free(i);
3238 static int config_parse_also(
3239 const char *filename,
3241 const char *section,
3255 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3259 if (!(n = strndup(w, l)))
3262 r = install_info_add(n);
3272 static int mark_symlink_for_removal(const char *p) {
3277 assert(path_is_absolute(p));
3279 if (!remove_symlinks_to)
3282 if (!(n = strdup(p)))
3285 path_kill_slashes(n);
3287 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3289 return r == -EEXIST ? 0 : r;
3295 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3304 if (!(d = fdopendir(fd))) {
3305 close_nointr_nofail(fd);
3311 while ((de = readdir(d))) {
3312 bool is_dir = false, is_link = false;
3314 if (ignore_file(de->d_name))
3317 if (de->d_type == DT_LNK)
3319 else if (de->d_type == DT_DIR)
3321 else if (de->d_type == DT_UNKNOWN) {
3324 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3325 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3332 is_link = S_ISLNK(st.st_mode);
3333 is_dir = S_ISDIR(st.st_mode);
3341 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3342 log_error("Failed to open %s/%s: %m", root, de->d_name);
3349 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3350 log_error("Failed to allocate directory string.");
3351 close_nointr_nofail(nfd);
3356 /* This will close nfd, regardless whether it succeeds or not */
3357 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3363 } else if (is_link) {
3367 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3368 log_error("Failed to allocate symlink string.");
3373 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3374 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3382 if ((c = canonicalize_file_name(dest))) {
3383 /* This might fail if the destination
3384 * is already removed */
3390 path_kill_slashes(dest);
3391 if (set_get(remove_symlinks_to, dest)) {
3394 log_info("rm '%s'", p);
3396 if (unlink(p) < 0) {
3397 log_error("Cannot unlink symlink %s: %m", p);
3402 rmdir_parents(p, config_path);
3403 path_kill_slashes(p);
3405 if (!set_get(remove_symlinks_to, p)) {
3407 if ((r = mark_symlink_for_removal(p)) < 0) {
3426 static int remove_marked_symlinks(const char *config_path) {
3430 assert(config_path);
3432 if (set_size(remove_symlinks_to) <= 0)
3435 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3442 if ((cfd = dup(fd)) < 0) {
3447 /* This takes possession of cfd and closes it */
3448 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3454 close_nointr_nofail(fd);
3459 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3466 if (streq(verb, "enable")) {
3469 mkdir_parents(new_path, 0755);
3471 if (symlink(old_path, new_path) >= 0) {
3474 log_info("ln -s '%s' '%s'", old_path, new_path);
3479 if (errno != EEXIST) {
3480 log_error("Cannot link %s to %s: %m", old_path, new_path);
3484 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3486 if (errno == EINVAL) {
3487 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3491 log_error("readlink() failed: %s", strerror(-r));
3495 if (streq(dest, old_path)) {
3501 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3510 log_info("ln -s '%s' '%s'", old_path, new_path);
3512 if (symlink(old_path, new_path) >= 0)
3515 log_error("Cannot link %s to %s: %m", old_path, new_path);
3518 } else if (streq(verb, "disable")) {
3521 if ((r = mark_symlink_for_removal(old_path)) < 0)
3524 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3525 if (errno == ENOENT)
3528 if (errno == EINVAL) {
3529 log_warning("File %s not a symlink, ignoring.", old_path);
3533 log_error("readlink() failed: %s", strerror(-r));
3537 if (!streq(dest, old_path)) {
3538 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3545 if ((r = mark_symlink_for_removal(new_path)) < 0)
3549 log_info("rm '%s'", new_path);
3551 if (unlink(new_path) >= 0)
3554 log_error("Cannot unlink %s: %m", new_path);
3557 } else if (streq(verb, "is-enabled")) {
3560 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3562 if (errno == ENOENT || errno == EINVAL)
3565 log_error("readlink() failed: %s", strerror(-r));
3569 if (streq(dest, old_path)) {
3577 assert_not_reached("Unknown action.");
3580 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3582 char *alias_path = NULL;
3587 assert(config_path);
3589 STRV_FOREACH(s, i->aliases) {
3591 if (!unit_name_valid(*s)) {
3592 log_error("Invalid name %s.", *s);
3598 if (!(alias_path = path_make_absolute(*s, config_path))) {
3599 log_error("Out of memory");
3604 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3607 if (streq(verb, "disable"))
3608 rmdir_parents(alias_path, config_path);
3619 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3621 char *alias_path = NULL;
3626 assert(config_path);
3628 STRV_FOREACH(s, i->wanted_by) {
3629 if (!unit_name_valid(*s)) {
3630 log_error("Invalid name %s.", *s);
3638 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3639 log_error("Out of memory");
3644 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3647 if (streq(verb, "disable"))
3648 rmdir_parents(alias_path, config_path);
3659 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3661 const ConfigItem items[] = {
3662 { "Alias", config_parse_strv, &i->aliases, "Install" },
3663 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3664 { "Also", config_parse_also, NULL, "Install" },
3666 { NULL, NULL, NULL, NULL }
3670 char *filename = NULL;
3677 STRV_FOREACH(p, paths->unit_path) {
3680 if (!(filename = path_make_absolute(i->name, *p))) {
3681 log_error("Out of memory");
3685 /* Ensure that we don't follow symlinks */
3686 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3687 if ((f = fdopen(fd, "re")))
3690 if (errno == ELOOP) {
3691 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3696 if (errno != ENOENT) {
3697 log_error("Failed to open %s: %m", filename);
3707 log_error("Couldn't find %s.", i->name);
3713 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3720 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3723 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3726 if ((r = mark_symlink_for_removal(filename)) < 0)
3729 if ((r = remove_marked_symlinks(config_path)) < 0)
3735 static char *get_config_path(void) {
3737 if (arg_session && arg_global)
3738 return strdup(SESSION_CONFIG_UNIT_PATH);
3743 if (session_config_home(&p) < 0)
3749 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3752 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3756 char *config_path = NULL;
3759 const char *verb = args[0];
3761 dbus_error_init(&error);
3764 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3765 log_error("Failed to determine lookup paths: %s", strerror(-r));
3769 if (!(config_path = get_config_path())) {
3770 log_error("Failed to determine config path");
3775 will_install = hashmap_new(string_hash_func, string_compare_func);
3776 have_installed = hashmap_new(string_hash_func, string_compare_func);
3778 if (!will_install || !have_installed) {
3779 log_error("Failed to allocate unit sets.");
3784 if (!arg_defaults && streq(verb, "disable"))
3785 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3786 log_error("Failed to allocate symlink sets.");
3791 for (j = 1; j < n; j++)
3792 if ((r = install_info_add(args[j])) < 0)
3795 while ((i = hashmap_first(will_install))) {
3798 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3800 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3808 /* In test mode and found something */
3814 if (streq(verb, "is-enabled"))
3815 r = r > 0 ? 0 : -ENOENT;
3817 /* Don't try to reload anything if the user asked us to not do this */
3819 /* Don't try to reload anything when updating a unit globally */
3821 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3822 (arg_session || sd_booted() > 0) &&
3823 /* Don't try to reload anything if we are running in a chroot environment */
3824 (arg_session || running_in_chroot() <= 0) ) {
3827 if ((q = daemon_reload(bus, args, n)) < 0)
3832 install_info_hashmap_free(will_install);
3833 install_info_hashmap_free(have_installed);
3835 set_free_free(remove_symlinks_to);
3837 lookup_paths_free(&paths);
3844 static int systemctl_help(void) {
3846 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3847 "Send control commands to or query the systemd manager.\n\n"
3848 " -h --help Show this help\n"
3849 " --version Show package version\n"
3850 " -t --type=TYPE List only units of a particular type\n"
3851 " -p --property=NAME Show only properties by this name\n"
3852 " -a --all Show all units/properties, including dead/empty ones\n"
3853 " --full Don't ellipsize unit names on output\n"
3854 " --fail When queueing a new job, fail if conflicting jobs are\n"
3856 " -q --quiet Suppress output\n"
3857 " --no-block Do not wait until operation finished\n"
3858 " --system Connect to system bus\n"
3859 " --session Connect to session bus\n"
3860 " --order When generating graph for dot, show only order\n"
3861 " --require When generating graph for dot, show only requirement\n"
3862 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3863 " --global Enable/disable unit files globally\n"
3864 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3866 " --force When enabling unit files, override existing symlinks\n"
3867 " --defaults When disabling unit files, remove default symlinks only\n\n"
3869 " list-units List units\n"
3870 " start [NAME...] Start (activate) one or more units\n"
3871 " stop [NAME...] Stop (deactivate) one or more units\n"
3872 " reload [NAME...] Reload one or more units\n"
3873 " restart [NAME...] Start or restart one or more units\n"
3874 " try-restart [NAME...] Restart one or more units if active\n"
3875 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3876 " otherwise start or restart\n"
3877 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3878 " otherwise restart if active\n"
3879 " isolate [NAME] Start one unit and stop all others\n"
3880 " is-active [NAME...] Check whether units are active\n"
3881 " status [NAME...|PID...] Show runtime status of one or more units\n"
3882 " show [NAME...|JOB...] Show properties of one or more\n"
3883 " units/jobs or the manager\n"
3884 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3886 " enable [NAME...] Enable one or more unit files\n"
3887 " disable [NAME...] Disable one or more unit files\n"
3888 " is-enabled [NAME...] Check whether unit files are enabled\n"
3889 " load [NAME...] Load one or more units\n"
3890 " list-jobs List jobs\n"
3891 " cancel [JOB...] Cancel all, one, or more jobs\n"
3892 " monitor Monitor unit/job changes\n"
3893 " dump Dump server status\n"
3894 " dot Dump dependency graph for dot(1)\n"
3895 " snapshot [NAME] Create a snapshot\n"
3896 " delete [NAME...] Remove one or more snapshots\n"
3897 " daemon-reload Reload systemd manager configuration\n"
3898 " daemon-reexec Reexecute systemd manager\n"
3899 " daemon-exit Ask the systemd manager to quit\n"
3900 " show-environment Dump environment\n"
3901 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3902 " unset-environment [NAME...] Unset one or more environment variables\n"
3903 " halt Shut down and halt the system\n"
3904 " poweroff Shut down and power-off the system\n"
3905 " reboot Shut down and reboot the system\n"
3906 " rescue Enter system rescue mode\n"
3907 " emergency Enter system emergency mode\n"
3908 " default Enter system default mode\n",
3909 program_invocation_short_name);
3914 static int halt_help(void) {
3916 printf("%s [OPTIONS...]\n\n"
3917 "%s the system.\n\n"
3918 " --help Show this help\n"
3919 " --halt Halt the machine\n"
3920 " -p --poweroff Switch off the machine\n"
3921 " --reboot Reboot the machine\n"
3922 " -f --force Force immediate halt/power-off/reboot\n"
3923 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3924 " -d --no-wtmp Don't write wtmp record\n"
3925 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3926 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3927 program_invocation_short_name,
3928 arg_action == ACTION_REBOOT ? "Reboot" :
3929 arg_action == ACTION_POWEROFF ? "Power off" :
3935 static int shutdown_help(void) {
3937 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3938 "Shut down the system.\n\n"
3939 " --help Show this help\n"
3940 " -H --halt Halt the machine\n"
3941 " -P --poweroff Power-off the machine\n"
3942 " -r --reboot Reboot the machine\n"
3943 " -h Equivalent to --poweroff, overriden by --halt\n"
3944 " -k Don't halt/power-off/reboot, just send warnings\n"
3945 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3946 " -c Cancel a pending shutdown\n",
3947 program_invocation_short_name);
3952 static int telinit_help(void) {
3954 printf("%s [OPTIONS...] {COMMAND}\n\n"
3955 "Send control commands to the init daemon.\n\n"
3956 " --help Show this help\n"
3957 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3959 " 0 Power-off the machine\n"
3960 " 6 Reboot the machine\n"
3961 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3962 " 1, s, S Enter rescue mode\n"
3963 " q, Q Reload init daemon configuration\n"
3964 " u, U Reexecute init daemon\n",
3965 program_invocation_short_name);
3970 static int runlevel_help(void) {
3972 printf("%s [OPTIONS...]\n\n"
3973 "Prints the previous and current runlevel of the init system.\n\n"
3974 " --help Show this help\n",
3975 program_invocation_short_name);
3980 static int systemctl_parse_argv(int argc, char *argv[]) {
3998 static const struct option options[] = {
3999 { "help", no_argument, NULL, 'h' },
4000 { "version", no_argument, NULL, ARG_VERSION },
4001 { "type", required_argument, NULL, 't' },
4002 { "property", required_argument, NULL, 'p' },
4003 { "all", no_argument, NULL, 'a' },
4004 { "full", no_argument, NULL, ARG_FULL },
4005 { "fail", no_argument, NULL, ARG_FAIL },
4006 { "session", no_argument, NULL, ARG_SESSION },
4007 { "system", no_argument, NULL, ARG_SYSTEM },
4008 { "global", no_argument, NULL, ARG_GLOBAL },
4009 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4010 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4011 { "quiet", no_argument, NULL, 'q' },
4012 { "order", no_argument, NULL, ARG_ORDER },
4013 { "require", no_argument, NULL, ARG_REQUIRE },
4014 { "force", no_argument, NULL, ARG_FORCE },
4015 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4016 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4017 { NULL, 0, NULL, 0 }
4025 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4034 puts(PACKAGE_STRING);
4036 puts(SYSTEMD_FEATURES);
4046 if (!(l = strv_append(arg_property, optarg)))
4049 strv_free(arg_property);
4052 /* If the user asked for a particular
4053 * property, show it to him, even if it is
4072 arg_session = false;
4076 arg_no_block = true;
4084 arg_dot = DOT_ORDER;
4088 arg_dot = DOT_REQUIRE;
4104 arg_no_reload = true;
4113 arg_defaults = true;
4120 log_error("Unknown option code %c", c);
4128 static int halt_parse_argv(int argc, char *argv[]) {
4137 static const struct option options[] = {
4138 { "help", no_argument, NULL, ARG_HELP },
4139 { "halt", no_argument, NULL, ARG_HALT },
4140 { "poweroff", no_argument, NULL, 'p' },
4141 { "reboot", no_argument, NULL, ARG_REBOOT },
4142 { "force", no_argument, NULL, 'f' },
4143 { "wtmp-only", no_argument, NULL, 'w' },
4144 { "no-wtmp", no_argument, NULL, 'd' },
4145 { "no-sync", no_argument, NULL, 'n' },
4146 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4147 { NULL, 0, NULL, 0 }
4155 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4156 if (runlevel == '0' || runlevel == '6')
4157 arg_immediate = true;
4159 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4167 arg_action = ACTION_HALT;
4171 if (arg_action != ACTION_REBOOT)
4172 arg_action = ACTION_POWEROFF;
4176 arg_action = ACTION_REBOOT;
4180 arg_immediate = true;
4201 /* Compatibility nops */
4208 log_error("Unknown option code %c", c);
4213 if (optind < argc) {
4214 log_error("Too many arguments.");
4221 static int parse_time_spec(const char *t, usec_t *_u) {
4225 if (streq(t, "now"))
4227 else if (t[0] == '+') {
4230 if (safe_atou64(t + 1, &u) < 0)
4233 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4242 hour = strtol(t, &e, 10);
4243 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4246 minute = strtol(e+1, &e, 10);
4247 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4250 n = now(CLOCK_REALTIME);
4251 s = (time_t) (n / USEC_PER_SEC);
4254 assert_se(localtime_r(&s, &tm));
4256 tm.tm_hour = (int) hour;
4257 tm.tm_min = (int) minute;
4260 assert_se(s = mktime(&tm));
4262 *_u = (usec_t) s * USEC_PER_SEC;
4265 *_u += USEC_PER_DAY;
4271 static int shutdown_parse_argv(int argc, char *argv[]) {
4278 static const struct option options[] = {
4279 { "help", no_argument, NULL, ARG_HELP },
4280 { "halt", no_argument, NULL, 'H' },
4281 { "poweroff", no_argument, NULL, 'P' },
4282 { "reboot", no_argument, NULL, 'r' },
4283 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4284 { NULL, 0, NULL, 0 }
4292 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4300 arg_action = ACTION_HALT;
4304 arg_action = ACTION_POWEROFF;
4308 arg_action = ACTION_REBOOT;
4312 if (arg_action != ACTION_HALT)
4313 arg_action = ACTION_POWEROFF;
4326 /* Compatibility nops */
4330 arg_action = ACTION_CANCEL_SHUTDOWN;
4337 log_error("Unknown option code %c", c);
4342 if (argc > optind) {
4343 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4344 log_error("Failed to parse time specification: %s", argv[optind]);
4348 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4350 /* We skip the time argument */
4351 if (argc > optind + 1)
4352 arg_wall = argv + optind + 1;
4359 static int telinit_parse_argv(int argc, char *argv[]) {
4366 static const struct option options[] = {
4367 { "help", no_argument, NULL, ARG_HELP },
4368 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4369 { NULL, 0, NULL, 0 }
4372 static const struct {
4376 { '0', ACTION_POWEROFF },
4377 { '6', ACTION_REBOOT },
4378 { '1', ACTION_RESCUE },
4379 { '2', ACTION_RUNLEVEL2 },
4380 { '3', ACTION_RUNLEVEL3 },
4381 { '4', ACTION_RUNLEVEL4 },
4382 { '5', ACTION_RUNLEVEL5 },
4383 { 's', ACTION_RESCUE },
4384 { 'S', ACTION_RESCUE },
4385 { 'q', ACTION_RELOAD },
4386 { 'Q', ACTION_RELOAD },
4387 { 'u', ACTION_REEXEC },
4388 { 'U', ACTION_REEXEC }
4397 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4412 log_error("Unknown option code %c", c);
4417 if (optind >= argc) {
4422 if (optind + 1 < argc) {
4423 log_error("Too many arguments.");
4427 if (strlen(argv[optind]) != 1) {
4428 log_error("Expected single character argument.");
4432 for (i = 0; i < ELEMENTSOF(table); i++)
4433 if (table[i].from == argv[optind][0])
4436 if (i >= ELEMENTSOF(table)) {
4437 log_error("Unknown command %s.", argv[optind]);
4441 arg_action = table[i].to;
4448 static int runlevel_parse_argv(int argc, char *argv[]) {
4454 static const struct option options[] = {
4455 { "help", no_argument, NULL, ARG_HELP },
4456 { NULL, 0, NULL, 0 }
4464 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4475 log_error("Unknown option code %c", c);
4480 if (optind < argc) {
4481 log_error("Too many arguments.");
4488 static int parse_argv(int argc, char *argv[]) {
4492 if (program_invocation_short_name) {
4494 if (strstr(program_invocation_short_name, "halt")) {
4495 arg_action = ACTION_HALT;
4496 return halt_parse_argv(argc, argv);
4497 } else if (strstr(program_invocation_short_name, "poweroff")) {
4498 arg_action = ACTION_POWEROFF;
4499 return halt_parse_argv(argc, argv);
4500 } else if (strstr(program_invocation_short_name, "reboot")) {
4501 arg_action = ACTION_REBOOT;
4502 return halt_parse_argv(argc, argv);
4503 } else if (strstr(program_invocation_short_name, "shutdown")) {
4504 arg_action = ACTION_POWEROFF;
4505 return shutdown_parse_argv(argc, argv);
4506 } else if (strstr(program_invocation_short_name, "init")) {
4508 if (sd_booted() > 0) {
4509 arg_action = ACTION_INVALID;
4510 return telinit_parse_argv(argc, argv);
4512 /* Hmm, so some other init system is
4513 * running, we need to forward this
4514 * request to it. For now we simply
4515 * guess that it is Upstart. */
4517 execv("/lib/upstart/telinit", argv);
4519 log_error("Couldn't find an alternative telinit implementation to spawn.");
4523 } else if (strstr(program_invocation_short_name, "runlevel")) {
4524 arg_action = ACTION_RUNLEVEL;
4525 return runlevel_parse_argv(argc, argv);
4529 arg_action = ACTION_SYSTEMCTL;
4530 return systemctl_parse_argv(argc, argv);
4533 static int action_to_runlevel(void) {
4535 static const char table[_ACTION_MAX] = {
4536 [ACTION_HALT] = '0',
4537 [ACTION_POWEROFF] = '0',
4538 [ACTION_REBOOT] = '6',
4539 [ACTION_RUNLEVEL2] = '2',
4540 [ACTION_RUNLEVEL3] = '3',
4541 [ACTION_RUNLEVEL4] = '4',
4542 [ACTION_RUNLEVEL5] = '5',
4543 [ACTION_RESCUE] = '1'
4546 assert(arg_action < _ACTION_MAX);
4548 return table[arg_action];
4551 static int talk_upstart(void) {
4552 DBusMessage *m = NULL, *reply = NULL;
4554 int previous, rl, r;
4556 env1_buf[] = "RUNLEVEL=X",
4557 env2_buf[] = "PREVLEVEL=X";
4558 char *env1 = env1_buf, *env2 = env2_buf;
4559 const char *emit = "runlevel";
4560 dbus_bool_t b_false = FALSE;
4561 DBusMessageIter iter, sub;
4562 DBusConnection *bus;
4564 dbus_error_init(&error);
4566 if (!(rl = action_to_runlevel()))
4569 if (utmp_get_runlevel(&previous, NULL) < 0)
4572 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4573 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4578 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4583 if ((r = bus_check_peercred(bus)) < 0) {
4584 log_error("Failed to verify owner of bus.");
4588 if (!(m = dbus_message_new_method_call(
4589 "com.ubuntu.Upstart",
4590 "/com/ubuntu/Upstart",
4591 "com.ubuntu.Upstart0_6",
4594 log_error("Could not allocate message.");
4599 dbus_message_iter_init_append(m, &iter);
4601 env1_buf[sizeof(env1_buf)-2] = rl;
4602 env2_buf[sizeof(env2_buf)-2] = previous;
4604 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4605 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4606 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4607 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4608 !dbus_message_iter_close_container(&iter, &sub) ||
4609 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4610 log_error("Could not append arguments to message.");
4615 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4617 if (error_is_no_service(&error)) {
4622 log_error("Failed to issue method call: %s", bus_error_message(&error));
4631 dbus_message_unref(m);
4634 dbus_message_unref(reply);
4637 dbus_connection_flush(bus);
4638 dbus_connection_close(bus);
4639 dbus_connection_unref(bus);
4642 dbus_error_free(&error);
4647 static int talk_initctl(void) {
4648 struct init_request request;
4652 if (!(rl = action_to_runlevel()))
4656 request.magic = INIT_MAGIC;
4657 request.sleeptime = 0;
4658 request.cmd = INIT_CMD_RUNLVL;
4659 request.runlevel = rl;
4661 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4663 if (errno == ENOENT)
4666 log_error("Failed to open "INIT_FIFO": %m");
4671 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4672 close_nointr_nofail(fd);
4675 log_error("Failed to write to "INIT_FIFO": %m");
4676 return errno ? -errno : -EIO;
4682 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4684 static const struct {
4692 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4694 { "list-units", LESS, 1, list_units },
4695 { "list-jobs", EQUAL, 1, list_jobs },
4696 { "clear-jobs", EQUAL, 1, daemon_reload },
4697 { "load", MORE, 2, load_unit },
4698 { "cancel", MORE, 2, cancel_job },
4699 { "start", MORE, 2, start_unit },
4700 { "stop", MORE, 2, start_unit },
4701 { "reload", MORE, 2, start_unit },
4702 { "restart", MORE, 2, start_unit },
4703 { "try-restart", MORE, 2, start_unit },
4704 { "reload-or-restart", MORE, 2, start_unit },
4705 { "reload-or-try-restart", MORE, 2, start_unit },
4706 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4707 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4708 { "isolate", EQUAL, 2, start_unit },
4709 { "is-active", MORE, 2, check_unit },
4710 { "check", MORE, 2, check_unit },
4711 { "show", MORE, 1, show },
4712 { "status", MORE, 2, show },
4713 { "monitor", EQUAL, 1, monitor },
4714 { "dump", EQUAL, 1, dump },
4715 { "dot", EQUAL, 1, dot },
4716 { "snapshot", LESS, 2, snapshot },
4717 { "delete", MORE, 2, delete_snapshot },
4718 { "daemon-reload", EQUAL, 1, daemon_reload },
4719 { "daemon-reexec", EQUAL, 1, daemon_reload },
4720 { "daemon-exit", EQUAL, 1, daemon_reload },
4721 { "show-environment", EQUAL, 1, show_enviroment },
4722 { "set-environment", MORE, 2, set_environment },
4723 { "unset-environment", MORE, 2, set_environment },
4724 { "halt", EQUAL, 1, start_special },
4725 { "poweroff", EQUAL, 1, start_special },
4726 { "reboot", EQUAL, 1, start_special },
4727 { "default", EQUAL, 1, start_special },
4728 { "rescue", EQUAL, 1, start_special },
4729 { "emergency", EQUAL, 1, start_special },
4730 { "reset-failed", MORE, 1, reset_failed },
4731 { "enable", MORE, 2, enable_unit },
4732 { "disable", MORE, 2, enable_unit },
4733 { "is-enabled", MORE, 2, enable_unit }
4743 left = argc - optind;
4746 /* Special rule: no arguments means "list-units" */
4749 if (streq(argv[optind], "help")) {
4754 for (i = 0; i < ELEMENTSOF(verbs); i++)
4755 if (streq(argv[optind], verbs[i].verb))
4758 if (i >= ELEMENTSOF(verbs)) {
4759 log_error("Unknown operation %s", argv[optind]);
4764 switch (verbs[i].argc_cmp) {
4767 if (left != verbs[i].argc) {
4768 log_error("Invalid number of arguments.");
4775 if (left < verbs[i].argc) {
4776 log_error("Too few arguments.");
4783 if (left > verbs[i].argc) {
4784 log_error("Too many arguments.");
4791 assert_not_reached("Unknown comparison operator.");
4794 /* Require a bus connection for all operations but
4796 if (!streq(verbs[i].verb, "enable") &&
4797 !streq(verbs[i].verb, "disable") &&
4799 log_error("Failed to get D-Bus connection: %s", error->message);
4803 return verbs[i].dispatch(bus, argv + optind, left);
4806 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4808 struct msghdr msghdr;
4810 union sockaddr_union sockaddr;
4811 struct shutdownd_command c;
4819 strncpy(c.wall_message, message, sizeof(c.wall_message));
4821 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4825 sockaddr.sa.sa_family = AF_UNIX;
4826 sockaddr.un.sun_path[0] = 0;
4827 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4830 iovec.iov_base = (char*) &c;
4831 iovec.iov_len = sizeof(c);
4834 msghdr.msg_name = &sockaddr;
4835 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4837 msghdr.msg_iov = &iovec;
4838 msghdr.msg_iovlen = 1;
4840 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4841 close_nointr_nofail(fd);
4845 close_nointr_nofail(fd);
4849 static int reload_with_fallback(DBusConnection *bus) {
4852 /* First, try systemd via D-Bus. */
4853 if (daemon_reload(bus, NULL, 0) > 0)
4857 /* Nothing else worked, so let's try signals */
4858 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4860 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4861 log_error("kill() failed: %m");
4868 static int start_with_fallback(DBusConnection *bus) {
4871 /* First, try systemd via D-Bus. */
4872 if (start_unit(bus, NULL, 0) >= 0)
4876 /* Hmm, talking to systemd via D-Bus didn't work. Then
4877 * let's try to talk to Upstart via D-Bus. */
4878 if (talk_upstart() > 0)
4881 /* Nothing else worked, so let's try
4883 if (talk_initctl() > 0)
4886 log_error("Failed to talk to init daemon.");
4890 warn_wall(arg_action);
4894 static int halt_main(DBusConnection *bus) {
4897 if (geteuid() != 0) {
4898 log_error("Must be root.");
4904 char date[FORMAT_TIMESTAMP_MAX];
4906 m = strv_join(arg_wall, " ");
4907 r = send_shutdownd(arg_when,
4908 arg_action == ACTION_HALT ? 'H' :
4909 arg_action == ACTION_POWEROFF ? 'P' :
4916 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4918 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4919 format_timestamp(date, sizeof(date), arg_when));
4924 if (!arg_dry && !arg_immediate)
4925 return start_with_fallback(bus);
4928 if (sd_booted() > 0)
4929 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4930 else if ((r = utmp_put_shutdown(0)) < 0)
4931 log_warning("Failed to write utmp record: %s", strerror(-r));
4940 /* Make sure C-A-D is handled by the kernel from this
4942 reboot(RB_ENABLE_CAD);
4944 switch (arg_action) {
4947 log_info("Halting.");
4948 reboot(RB_HALT_SYSTEM);
4951 case ACTION_POWEROFF:
4952 log_info("Powering off.");
4953 reboot(RB_POWER_OFF);
4957 log_info("Rebooting.");
4958 reboot(RB_AUTOBOOT);
4962 assert_not_reached("Unknown halt action.");
4965 /* We should never reach this. */
4969 static int runlevel_main(void) {
4970 int r, runlevel, previous;
4972 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4973 printf("unknown\n");
4978 previous <= 0 ? 'N' : previous,
4979 runlevel <= 0 ? 'N' : runlevel);
4984 int main(int argc, char*argv[]) {
4985 int r, retval = EXIT_FAILURE;
4986 DBusConnection *bus = NULL;
4989 dbus_error_init(&error);
4991 log_parse_environment();
4994 if ((r = parse_argv(argc, argv)) < 0)
4997 retval = EXIT_SUCCESS;
5001 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5002 * let's shortcut this */
5003 if (arg_action == ACTION_RUNLEVEL) {
5004 r = runlevel_main();
5005 retval = r < 0 ? EXIT_FAILURE : r;
5009 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5011 switch (arg_action) {
5013 case ACTION_SYSTEMCTL:
5014 r = systemctl_main(bus, argc, argv, &error);
5018 case ACTION_POWEROFF:
5023 case ACTION_RUNLEVEL2:
5024 case ACTION_RUNLEVEL3:
5025 case ACTION_RUNLEVEL4:
5026 case ACTION_RUNLEVEL5:
5028 case ACTION_EMERGENCY:
5029 case ACTION_DEFAULT:
5030 r = start_with_fallback(bus);
5035 r = reload_with_fallback(bus);
5038 case ACTION_CANCEL_SHUTDOWN:
5039 r = send_shutdownd(0, 0, false, NULL);
5042 case ACTION_INVALID:
5043 case ACTION_RUNLEVEL:
5045 assert_not_reached("Unknown action");
5048 retval = r < 0 ? EXIT_FAILURE : r;
5053 dbus_connection_flush(bus);
5054 dbus_connection_close(bus);
5055 dbus_connection_unref(bus);
5058 dbus_error_free(&error);
5062 strv_free(arg_property);