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);
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);
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 ||
1258 arg_action == ACTION_RUNLEVEL2 ||
1259 arg_action == ACTION_RUNLEVEL3 ||
1260 arg_action == ACTION_RUNLEVEL4 ||
1261 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1263 one_name = table[arg_action];
1266 if (!arg_no_block) {
1267 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1268 log_error("Could not watch jobs: %s", strerror(-ret));
1272 if (!(s = set_new(string_hash_func, string_compare_func))) {
1273 log_error("Failed to allocate set.");
1280 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1283 for (i = 1; i < n; i++)
1284 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1285 ret = translate_bus_error_to_exit_status(r, &error);
1286 dbus_error_free(&error);
1291 if ((r = wait_for_jobs(bus, s)) < 0) {
1300 dbus_error_free(&error);
1305 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1311 r = start_unit(bus, args, n);
1314 warn_wall(verb_to_action(args[0]));
1319 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1320 DBusMessage *m = NULL, *reply = NULL;
1322 *interface = "org.freedesktop.systemd1.Unit",
1323 *property = "ActiveState";
1324 int r = 3; /* According to LSB: "program is not running" */
1331 dbus_error_init(&error);
1333 for (i = 1; i < n; i++) {
1334 const char *path = NULL;
1336 DBusMessageIter iter, sub;
1338 if (!(m = dbus_message_new_method_call(
1339 "org.freedesktop.systemd1",
1340 "/org/freedesktop/systemd1",
1341 "org.freedesktop.systemd1.Manager",
1343 log_error("Could not allocate message.");
1348 if (!dbus_message_append_args(m,
1349 DBUS_TYPE_STRING, &args[i],
1350 DBUS_TYPE_INVALID)) {
1351 log_error("Could not append arguments to message.");
1356 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1358 /* Hmm, cannot figure out anything about this unit... */
1362 dbus_error_free(&error);
1366 if (!dbus_message_get_args(reply, &error,
1367 DBUS_TYPE_OBJECT_PATH, &path,
1368 DBUS_TYPE_INVALID)) {
1369 log_error("Failed to parse reply: %s", bus_error_message(&error));
1374 dbus_message_unref(m);
1375 if (!(m = dbus_message_new_method_call(
1376 "org.freedesktop.systemd1",
1378 "org.freedesktop.DBus.Properties",
1380 log_error("Could not allocate message.");
1385 if (!dbus_message_append_args(m,
1386 DBUS_TYPE_STRING, &interface,
1387 DBUS_TYPE_STRING, &property,
1388 DBUS_TYPE_INVALID)) {
1389 log_error("Could not append arguments to message.");
1394 dbus_message_unref(reply);
1395 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1396 log_error("Failed to issue method call: %s", bus_error_message(&error));
1401 if (!dbus_message_iter_init(reply, &iter) ||
1402 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1403 log_error("Failed to parse reply.");
1408 dbus_message_iter_recurse(&iter, &sub);
1410 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1411 log_error("Failed to parse reply.");
1416 dbus_message_iter_get_basic(&sub, &state);
1421 if (streq(state, "active") || streq(state, "reloading"))
1424 dbus_message_unref(m);
1425 dbus_message_unref(reply);
1431 dbus_message_unref(m);
1434 dbus_message_unref(reply);
1436 dbus_error_free(&error);
1441 typedef struct ExecStatusInfo {
1447 usec_t start_timestamp;
1448 usec_t exit_timestamp;
1453 LIST_FIELDS(struct ExecStatusInfo, exec);
1456 static void exec_status_info_free(ExecStatusInfo *i) {
1464 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1465 uint64_t start_timestamp, exit_timestamp;
1466 DBusMessageIter sub2, sub3;
1470 int32_t code, status;
1476 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1479 dbus_message_iter_recurse(sub, &sub2);
1481 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1484 if (!(i->path = strdup(path)))
1487 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1488 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1492 dbus_message_iter_recurse(&sub2, &sub3);
1493 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1494 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1495 dbus_message_iter_next(&sub3);
1500 if (!(i->argv = new0(char*, n+1)))
1504 dbus_message_iter_recurse(&sub2, &sub3);
1505 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1508 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1509 dbus_message_iter_get_basic(&sub3, &s);
1510 dbus_message_iter_next(&sub3);
1512 if (!(i->argv[n++] = strdup(s)))
1516 if (!dbus_message_iter_next(&sub2) ||
1517 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1518 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1519 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1520 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1521 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1522 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1526 i->start_timestamp = (usec_t) start_timestamp;
1527 i->exit_timestamp = (usec_t) exit_timestamp;
1528 i->pid = (pid_t) pid;
1535 typedef struct UnitStatusInfo {
1537 const char *load_state;
1538 const char *active_state;
1539 const char *sub_state;
1541 const char *description;
1544 const char *default_control_group;
1546 usec_t inactive_exit_timestamp;
1547 usec_t active_enter_timestamp;
1548 usec_t active_exit_timestamp;
1549 usec_t inactive_enter_timestamp;
1551 bool need_daemon_reload;
1556 const char *status_text;
1560 usec_t start_timestamp;
1561 usec_t exit_timestamp;
1563 int exit_code, exit_status;
1566 unsigned n_accepted;
1567 unsigned n_connections;
1571 const char *sysfs_path;
1573 /* Mount, Automount */
1579 LIST_HEAD(ExecStatusInfo, exec);
1582 static void print_status_info(UnitStatusInfo *i) {
1584 const char *on, *off, *ss;
1586 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1587 char since2[FORMAT_TIMESTAMP_MAX], *s2;
1591 /* This shows pretty information about a unit. See
1592 * print_property() for a low-level property printer */
1594 printf("%s", strna(i->id));
1596 if (i->description && !streq_ptr(i->id, i->description))
1597 printf(" - %s", i->description);
1601 if (streq_ptr(i->load_state, "failed")) {
1602 on = ansi_highlight(true);
1603 off = ansi_highlight(false);
1608 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1610 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
1612 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1614 if (streq_ptr(i->active_state, "failed")) {
1615 on = ansi_highlight(true);
1616 off = ansi_highlight(false);
1617 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1618 on = ansi_highlight_green(true);
1619 off = ansi_highlight_green(false);
1624 printf("\t Active: %s%s (%s)%s",
1626 strna(i->active_state),
1630 printf("\t Active: %s%s%s",
1632 strna(i->active_state),
1635 timestamp = (streq_ptr(i->active_state, "active") ||
1636 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1637 (streq_ptr(i->active_state, "inactive") ||
1638 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
1639 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1640 i->active_exit_timestamp;
1642 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1643 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1646 printf(" since [%s; %s]\n", s2, s1);
1648 printf(" since [%s]\n", s2);
1653 printf("\t Device: %s\n", i->sysfs_path);
1655 printf("\t Where: %s\n", i->where);
1657 printf("\t What: %s\n", i->what);
1660 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1662 LIST_FOREACH(exec, p, i->exec) {
1665 /* Only show exited processes here */
1669 t = strv_join(p->argv, " ");
1670 printf("\t Process: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1673 if (p->code == CLD_EXITED) {
1676 printf("status=%i", p->status);
1678 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1682 printf("signal=%s", signal_to_string(p->status));
1685 if (i->main_pid == p->pid &&
1686 i->start_timestamp == p->start_timestamp &&
1687 i->exit_timestamp == p->start_timestamp)
1688 /* Let's not show this twice */
1691 if (p->pid == i->control_pid)
1695 if (i->main_pid > 0 || i->control_pid > 0) {
1698 if (i->main_pid > 0) {
1699 printf("Main PID: %u", (unsigned) i->main_pid);
1703 get_process_name(i->main_pid, &t);
1708 } else if (i->exit_code > 0) {
1709 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1711 if (i->exit_code == CLD_EXITED) {
1714 printf("status=%i", i->exit_status);
1716 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1720 printf("signal=%s", signal_to_string(i->exit_status));
1725 if (i->main_pid > 0 && i->control_pid > 0)
1728 if (i->control_pid > 0) {
1731 printf(" Control: %u", (unsigned) i->control_pid);
1733 get_process_name(i->control_pid, &t);
1744 printf("\t Status: \"%s\"\n", i->status_text);
1746 if (i->default_control_group) {
1749 printf("\t CGroup: %s\n", i->default_control_group);
1751 if ((c = columns()) > 18)
1756 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
1759 if (i->need_daemon_reload)
1760 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1761 ansi_highlight(true),
1762 ansi_highlight(false),
1763 arg_session ? "--session" : "--system");
1766 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1768 switch (dbus_message_iter_get_arg_type(iter)) {
1770 case DBUS_TYPE_STRING: {
1773 dbus_message_iter_get_basic(iter, &s);
1776 if (streq(name, "Id"))
1778 else if (streq(name, "LoadState"))
1780 else if (streq(name, "ActiveState"))
1781 i->active_state = s;
1782 else if (streq(name, "SubState"))
1784 else if (streq(name, "Description"))
1786 else if (streq(name, "FragmentPath"))
1788 else if (streq(name, "SysVPath")) {
1791 } else if (streq(name, "DefaultControlGroup"))
1792 i->default_control_group = s;
1793 else if (streq(name, "StatusText"))
1795 else if (streq(name, "SysFSPath"))
1797 else if (streq(name, "Where"))
1799 else if (streq(name, "What"))
1806 case DBUS_TYPE_BOOLEAN: {
1809 dbus_message_iter_get_basic(iter, &b);
1811 if (streq(name, "Accept"))
1813 else if (streq(name, "NeedDaemonReload"))
1814 i->need_daemon_reload = b;
1819 case DBUS_TYPE_UINT32: {
1822 dbus_message_iter_get_basic(iter, &u);
1824 if (streq(name, "MainPID")) {
1826 i->main_pid = (pid_t) u;
1829 } else if (streq(name, "ControlPID"))
1830 i->control_pid = (pid_t) u;
1831 else if (streq(name, "ExecMainPID")) {
1833 i->main_pid = (pid_t) u;
1834 } else if (streq(name, "NAccepted"))
1836 else if (streq(name, "NConnections"))
1837 i->n_connections = u;
1842 case DBUS_TYPE_INT32: {
1845 dbus_message_iter_get_basic(iter, &j);
1847 if (streq(name, "ExecMainCode"))
1848 i->exit_code = (int) j;
1849 else if (streq(name, "ExecMainStatus"))
1850 i->exit_status = (int) j;
1855 case DBUS_TYPE_UINT64: {
1858 dbus_message_iter_get_basic(iter, &u);
1860 if (streq(name, "ExecMainStartTimestamp"))
1861 i->start_timestamp = (usec_t) u;
1862 else if (streq(name, "ExecMainExitTimestamp"))
1863 i->exit_timestamp = (usec_t) u;
1864 else if (streq(name, "ActiveEnterTimestamp"))
1865 i->active_enter_timestamp = (usec_t) u;
1866 else if (streq(name, "InactiveEnterTimestamp"))
1867 i->inactive_enter_timestamp = (usec_t) u;
1868 else if (streq(name, "InactiveExitTimestamp"))
1869 i->inactive_exit_timestamp = (usec_t) u;
1870 else if (streq(name, "ActiveExitTimestamp"))
1871 i->active_exit_timestamp = (usec_t) u;
1876 case DBUS_TYPE_ARRAY: {
1878 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1879 startswith(name, "Exec")) {
1880 DBusMessageIter sub;
1882 dbus_message_iter_recurse(iter, &sub);
1883 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1884 ExecStatusInfo *info;
1887 if (!(info = new0(ExecStatusInfo, 1)))
1890 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1895 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1897 dbus_message_iter_next(&sub);
1908 static int print_property(const char *name, DBusMessageIter *iter) {
1912 /* This is a low-level property printer, see
1913 * print_status_info() for the nicer output */
1915 if (arg_property && !strv_find(arg_property, name))
1918 switch (dbus_message_iter_get_arg_type(iter)) {
1920 case DBUS_TYPE_STRING: {
1922 dbus_message_iter_get_basic(iter, &s);
1924 if (arg_all || s[0])
1925 printf("%s=%s\n", name, s);
1930 case DBUS_TYPE_BOOLEAN: {
1932 dbus_message_iter_get_basic(iter, &b);
1933 printf("%s=%s\n", name, yes_no(b));
1938 case DBUS_TYPE_UINT64: {
1940 dbus_message_iter_get_basic(iter, &u);
1942 /* Yes, heuristics! But we can change this check
1943 * should it turn out to not be sufficient */
1945 if (strstr(name, "Timestamp")) {
1946 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1948 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1949 printf("%s=%s\n", name, strempty(t));
1950 } else if (strstr(name, "USec")) {
1951 char timespan[FORMAT_TIMESPAN_MAX];
1953 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1955 printf("%s=%llu\n", name, (unsigned long long) u);
1960 case DBUS_TYPE_UINT32: {
1962 dbus_message_iter_get_basic(iter, &u);
1964 if (strstr(name, "UMask") || strstr(name, "Mode"))
1965 printf("%s=%04o\n", name, u);
1967 printf("%s=%u\n", name, (unsigned) u);
1972 case DBUS_TYPE_INT32: {
1974 dbus_message_iter_get_basic(iter, &i);
1976 printf("%s=%i\n", name, (int) i);
1980 case DBUS_TYPE_STRUCT: {
1981 DBusMessageIter sub;
1982 dbus_message_iter_recurse(iter, &sub);
1984 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1987 dbus_message_iter_get_basic(&sub, &u);
1990 printf("%s=%u\n", name, (unsigned) u);
1992 printf("%s=\n", name);
1995 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1998 dbus_message_iter_get_basic(&sub, &s);
2000 if (arg_all || s[0])
2001 printf("%s=%s\n", name, s);
2009 case DBUS_TYPE_ARRAY:
2011 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2012 DBusMessageIter sub;
2015 dbus_message_iter_recurse(iter, &sub);
2017 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2018 printf("%s=", name);
2020 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2023 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2024 dbus_message_iter_get_basic(&sub, &s);
2025 printf("%s%s", space ? " " : "", s);
2028 dbus_message_iter_next(&sub);
2036 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2037 DBusMessageIter sub;
2039 dbus_message_iter_recurse(iter, &sub);
2041 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2042 printf("%s=", name);
2044 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2047 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2048 dbus_message_iter_get_basic(&sub, &u);
2051 dbus_message_iter_next(&sub);
2059 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2060 DBusMessageIter sub, sub2;
2062 dbus_message_iter_recurse(iter, &sub);
2063 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2064 const char *type, *path;
2066 dbus_message_iter_recurse(&sub, &sub2);
2068 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2069 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2070 printf("%s=%s\n", type, path);
2072 dbus_message_iter_next(&sub);
2077 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2078 DBusMessageIter sub, sub2;
2080 dbus_message_iter_recurse(iter, &sub);
2081 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2083 uint64_t value, next_elapse;
2085 dbus_message_iter_recurse(&sub, &sub2);
2087 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2088 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2089 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2090 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2092 printf("%s={ value=%s ; next_elapse=%s }\n",
2094 format_timespan(timespan1, sizeof(timespan1), value),
2095 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2098 dbus_message_iter_next(&sub);
2103 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2104 DBusMessageIter sub;
2106 dbus_message_iter_recurse(iter, &sub);
2107 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2108 ExecStatusInfo info;
2111 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2112 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2115 t = strv_join(info.argv, " ");
2117 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2121 yes_no(info.ignore),
2122 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2123 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2124 (unsigned) info. pid,
2125 sigchld_code_to_string(info.code),
2127 info.code == CLD_EXITED ? "" : "/",
2128 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2134 strv_free(info.argv);
2136 dbus_message_iter_next(&sub);
2146 printf("%s=[unprintable]\n", name);
2151 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2152 DBusMessage *m = NULL, *reply = NULL;
2153 const char *interface = "";
2156 DBusMessageIter iter, sub, sub2, sub3;
2157 UnitStatusInfo info;
2165 dbus_error_init(&error);
2167 if (!(m = dbus_message_new_method_call(
2168 "org.freedesktop.systemd1",
2170 "org.freedesktop.DBus.Properties",
2172 log_error("Could not allocate message.");
2177 if (!dbus_message_append_args(m,
2178 DBUS_TYPE_STRING, &interface,
2179 DBUS_TYPE_INVALID)) {
2180 log_error("Could not append arguments to message.");
2185 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2186 log_error("Failed to issue method call: %s", bus_error_message(&error));
2191 if (!dbus_message_iter_init(reply, &iter) ||
2192 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2193 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2194 log_error("Failed to parse reply.");
2199 dbus_message_iter_recurse(&iter, &sub);
2206 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2209 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2210 log_error("Failed to parse reply.");
2215 dbus_message_iter_recurse(&sub, &sub2);
2217 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2218 log_error("Failed to parse reply.");
2223 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2224 log_error("Failed to parse reply.");
2229 dbus_message_iter_recurse(&sub2, &sub3);
2231 if (show_properties)
2232 r = print_property(name, &sub3);
2234 r = status_property(name, &sub3, &info);
2237 log_error("Failed to parse reply.");
2242 dbus_message_iter_next(&sub);
2247 if (!show_properties)
2248 print_status_info(&info);
2250 if (!streq_ptr(info.active_state, "active") &&
2251 !streq_ptr(info.active_state, "reloading"))
2252 /* According to LSB: "program not running" */
2255 while ((p = info.exec)) {
2256 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2257 exec_status_info_free(p);
2262 dbus_message_unref(m);
2265 dbus_message_unref(reply);
2267 dbus_error_free(&error);
2272 static int show(DBusConnection *bus, char **args, unsigned n) {
2273 DBusMessage *m = NULL, *reply = NULL;
2277 bool show_properties, new_line = false;
2282 dbus_error_init(&error);
2284 show_properties = !streq(args[0], "status");
2286 if (show_properties && n <= 1) {
2287 /* If not argument is specified inspect the manager
2290 ret = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2294 for (i = 1; i < n; i++) {
2295 const char *path = NULL;
2298 if (safe_atou32(args[i], &id) < 0) {
2300 /* Interpret as unit name */
2302 if (!(m = dbus_message_new_method_call(
2303 "org.freedesktop.systemd1",
2304 "/org/freedesktop/systemd1",
2305 "org.freedesktop.systemd1.Manager",
2307 log_error("Could not allocate message.");
2312 if (!dbus_message_append_args(m,
2313 DBUS_TYPE_STRING, &args[i],
2314 DBUS_TYPE_INVALID)) {
2315 log_error("Could not append arguments to message.");
2320 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2322 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2323 log_error("Failed to issue method call: %s", bus_error_message(&error));
2328 dbus_error_free(&error);
2330 dbus_message_unref(m);
2331 if (!(m = dbus_message_new_method_call(
2332 "org.freedesktop.systemd1",
2333 "/org/freedesktop/systemd1",
2334 "org.freedesktop.systemd1.Manager",
2336 log_error("Could not allocate message.");
2341 if (!dbus_message_append_args(m,
2342 DBUS_TYPE_STRING, &args[i],
2343 DBUS_TYPE_INVALID)) {
2344 log_error("Could not append arguments to message.");
2349 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2350 log_error("Failed to issue method call: %s", bus_error_message(&error));
2352 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2353 ret = 4; /* According to LSB: "program or service status is unknown" */
2360 } else if (show_properties) {
2362 /* Interpret as job id */
2364 if (!(m = dbus_message_new_method_call(
2365 "org.freedesktop.systemd1",
2366 "/org/freedesktop/systemd1",
2367 "org.freedesktop.systemd1.Manager",
2369 log_error("Could not allocate message.");
2374 if (!dbus_message_append_args(m,
2375 DBUS_TYPE_UINT32, &id,
2376 DBUS_TYPE_INVALID)) {
2377 log_error("Could not append arguments to message.");
2382 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2383 log_error("Failed to issue method call: %s", bus_error_message(&error));
2389 /* Interpret as PID */
2391 if (!(m = dbus_message_new_method_call(
2392 "org.freedesktop.systemd1",
2393 "/org/freedesktop/systemd1",
2394 "org.freedesktop.systemd1.Manager",
2396 log_error("Could not allocate message.");
2401 if (!dbus_message_append_args(m,
2402 DBUS_TYPE_UINT32, &id,
2403 DBUS_TYPE_INVALID)) {
2404 log_error("Could not append arguments to message.");
2409 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2410 log_error("Failed to issue method call: %s", bus_error_message(&error));
2416 if (!dbus_message_get_args(reply, &error,
2417 DBUS_TYPE_OBJECT_PATH, &path,
2418 DBUS_TYPE_INVALID)) {
2419 log_error("Failed to parse reply: %s", bus_error_message(&error));
2424 if ((r = show_one(bus, path, show_properties, &new_line)) != 0)
2427 dbus_message_unref(m);
2428 dbus_message_unref(reply);
2434 dbus_message_unref(m);
2437 dbus_message_unref(reply);
2439 dbus_error_free(&error);
2444 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2446 DBusMessage *m = NULL, *reply = NULL;
2451 dbus_error_init(&error);
2453 log_debug("Got D-Bus request: %s.%s() on %s",
2454 dbus_message_get_interface(message),
2455 dbus_message_get_member(message),
2456 dbus_message_get_path(message));
2458 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2459 log_error("Warning! D-Bus connection terminated.");
2460 dbus_connection_close(connection);
2462 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2463 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2464 const char *id, *path;
2466 if (!dbus_message_get_args(message, &error,
2467 DBUS_TYPE_STRING, &id,
2468 DBUS_TYPE_OBJECT_PATH, &path,
2470 log_error("Failed to parse message: %s", bus_error_message(&error));
2471 else if (streq(dbus_message_get_member(message), "UnitNew"))
2472 printf("Unit %s added.\n", id);
2474 printf("Unit %s removed.\n", id);
2476 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2477 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2481 if (!dbus_message_get_args(message, &error,
2482 DBUS_TYPE_UINT32, &id,
2483 DBUS_TYPE_OBJECT_PATH, &path,
2485 log_error("Failed to parse message: %s", bus_error_message(&error));
2486 else if (streq(dbus_message_get_member(message), "JobNew"))
2487 printf("Job %u added.\n", id);
2489 printf("Job %u removed.\n", id);
2492 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2494 const char *path, *interface, *property = "Id";
2495 DBusMessageIter iter, sub;
2497 path = dbus_message_get_path(message);
2499 if (!dbus_message_get_args(message, &error,
2500 DBUS_TYPE_STRING, &interface,
2501 DBUS_TYPE_INVALID)) {
2502 log_error("Failed to parse message: %s", bus_error_message(&error));
2506 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2507 !streq(interface, "org.freedesktop.systemd1.Unit"))
2510 if (!(m = dbus_message_new_method_call(
2511 "org.freedesktop.systemd1",
2513 "org.freedesktop.DBus.Properties",
2515 log_error("Could not allocate message.");
2519 if (!dbus_message_append_args(m,
2520 DBUS_TYPE_STRING, &interface,
2521 DBUS_TYPE_STRING, &property,
2522 DBUS_TYPE_INVALID)) {
2523 log_error("Could not append arguments to message.");
2527 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2528 log_error("Failed to issue method call: %s", bus_error_message(&error));
2532 if (!dbus_message_iter_init(reply, &iter) ||
2533 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2534 log_error("Failed to parse reply.");
2538 dbus_message_iter_recurse(&iter, &sub);
2540 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2543 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2544 log_error("Failed to parse reply.");
2548 dbus_message_iter_get_basic(&sub, &id);
2549 printf("Unit %s changed.\n", id);
2553 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2554 log_error("Failed to parse reply.");
2558 dbus_message_iter_get_basic(&sub, &id);
2559 printf("Job %u changed.\n", id);
2565 dbus_message_unref(m);
2568 dbus_message_unref(reply);
2570 dbus_error_free(&error);
2571 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2575 dbus_message_unref(m);
2578 dbus_message_unref(reply);
2580 dbus_error_free(&error);
2581 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2584 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2585 DBusMessage *m = NULL, *reply = NULL;
2589 dbus_error_init(&error);
2592 dbus_bus_add_match(bus,
2594 "sender='org.freedesktop.systemd1',"
2595 "interface='org.freedesktop.systemd1.Manager',"
2596 "path='/org/freedesktop/systemd1'",
2599 if (dbus_error_is_set(&error)) {
2600 log_error("Failed to add match: %s", bus_error_message(&error));
2605 dbus_bus_add_match(bus,
2607 "sender='org.freedesktop.systemd1',"
2608 "interface='org.freedesktop.DBus.Properties',"
2609 "member='PropertiesChanged'",
2612 if (dbus_error_is_set(&error)) {
2613 log_error("Failed to add match: %s", bus_error_message(&error));
2619 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2620 log_error("Failed to add filter.");
2625 if (!(m = dbus_message_new_method_call(
2626 "org.freedesktop.systemd1",
2627 "/org/freedesktop/systemd1",
2628 "org.freedesktop.systemd1.Manager",
2630 log_error("Could not allocate message.");
2635 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2636 log_error("Failed to issue method call: %s", bus_error_message(&error));
2641 while (dbus_connection_read_write_dispatch(bus, -1))
2648 /* This is slightly dirty, since we don't undo the filter or the matches. */
2651 dbus_message_unref(m);
2654 dbus_message_unref(reply);
2656 dbus_error_free(&error);
2661 static int dump(DBusConnection *bus, char **args, unsigned n) {
2662 DBusMessage *m = NULL, *reply = NULL;
2667 dbus_error_init(&error);
2669 if (!(m = dbus_message_new_method_call(
2670 "org.freedesktop.systemd1",
2671 "/org/freedesktop/systemd1",
2672 "org.freedesktop.systemd1.Manager",
2674 log_error("Could not allocate message.");
2678 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2679 log_error("Failed to issue method call: %s", bus_error_message(&error));
2684 if (!dbus_message_get_args(reply, &error,
2685 DBUS_TYPE_STRING, &text,
2686 DBUS_TYPE_INVALID)) {
2687 log_error("Failed to parse reply: %s", bus_error_message(&error));
2692 fputs(text, stdout);
2698 dbus_message_unref(m);
2701 dbus_message_unref(reply);
2703 dbus_error_free(&error);
2708 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2709 DBusMessage *m = NULL, *reply = NULL;
2712 const char *name = "", *path, *id;
2713 dbus_bool_t cleanup = FALSE;
2714 DBusMessageIter iter, sub;
2716 *interface = "org.freedesktop.systemd1.Unit",
2719 dbus_error_init(&error);
2721 if (!(m = dbus_message_new_method_call(
2722 "org.freedesktop.systemd1",
2723 "/org/freedesktop/systemd1",
2724 "org.freedesktop.systemd1.Manager",
2725 "CreateSnapshot"))) {
2726 log_error("Could not allocate message.");
2733 if (!dbus_message_append_args(m,
2734 DBUS_TYPE_STRING, &name,
2735 DBUS_TYPE_BOOLEAN, &cleanup,
2736 DBUS_TYPE_INVALID)) {
2737 log_error("Could not append arguments to message.");
2742 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2743 log_error("Failed to issue method call: %s", bus_error_message(&error));
2748 if (!dbus_message_get_args(reply, &error,
2749 DBUS_TYPE_OBJECT_PATH, &path,
2750 DBUS_TYPE_INVALID)) {
2751 log_error("Failed to parse reply: %s", bus_error_message(&error));
2756 dbus_message_unref(m);
2757 if (!(m = dbus_message_new_method_call(
2758 "org.freedesktop.systemd1",
2760 "org.freedesktop.DBus.Properties",
2762 log_error("Could not allocate message.");
2766 if (!dbus_message_append_args(m,
2767 DBUS_TYPE_STRING, &interface,
2768 DBUS_TYPE_STRING, &property,
2769 DBUS_TYPE_INVALID)) {
2770 log_error("Could not append arguments to message.");
2775 dbus_message_unref(reply);
2776 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2777 log_error("Failed to issue method call: %s", bus_error_message(&error));
2782 if (!dbus_message_iter_init(reply, &iter) ||
2783 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2784 log_error("Failed to parse reply.");
2789 dbus_message_iter_recurse(&iter, &sub);
2791 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2792 log_error("Failed to parse reply.");
2797 dbus_message_iter_get_basic(&sub, &id);
2805 dbus_message_unref(m);
2808 dbus_message_unref(reply);
2810 dbus_error_free(&error);
2815 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2816 DBusMessage *m = NULL, *reply = NULL;
2824 dbus_error_init(&error);
2826 for (i = 1; i < n; i++) {
2827 const char *path = NULL;
2829 if (!(m = dbus_message_new_method_call(
2830 "org.freedesktop.systemd1",
2831 "/org/freedesktop/systemd1",
2832 "org.freedesktop.systemd1.Manager",
2834 log_error("Could not allocate message.");
2839 if (!dbus_message_append_args(m,
2840 DBUS_TYPE_STRING, &args[i],
2841 DBUS_TYPE_INVALID)) {
2842 log_error("Could not append arguments to message.");
2847 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2848 log_error("Failed to issue method call: %s", bus_error_message(&error));
2853 if (!dbus_message_get_args(reply, &error,
2854 DBUS_TYPE_OBJECT_PATH, &path,
2855 DBUS_TYPE_INVALID)) {
2856 log_error("Failed to parse reply: %s", bus_error_message(&error));
2861 dbus_message_unref(m);
2862 if (!(m = dbus_message_new_method_call(
2863 "org.freedesktop.systemd1",
2865 "org.freedesktop.systemd1.Snapshot",
2867 log_error("Could not allocate message.");
2872 dbus_message_unref(reply);
2873 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2874 log_error("Failed to issue method call: %s", bus_error_message(&error));
2879 dbus_message_unref(m);
2880 dbus_message_unref(reply);
2888 dbus_message_unref(m);
2891 dbus_message_unref(reply);
2893 dbus_error_free(&error);
2898 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2899 DBusMessage *m = NULL, *reply = NULL;
2904 dbus_error_init(&error);
2906 if (arg_action == ACTION_RELOAD)
2908 else if (arg_action == ACTION_REEXEC)
2909 method = "Reexecute";
2911 assert(arg_action == ACTION_SYSTEMCTL);
2914 streq(args[0], "clear-jobs") ||
2915 streq(args[0], "cancel") ? "ClearJobs" :
2916 streq(args[0], "daemon-reexec") ? "Reexecute" :
2917 streq(args[0], "reset-failed") ? "ResetFailed" :
2918 streq(args[0], "daemon-exit") ? "Exit" :
2922 if (!(m = dbus_message_new_method_call(
2923 "org.freedesktop.systemd1",
2924 "/org/freedesktop/systemd1",
2925 "org.freedesktop.systemd1.Manager",
2927 log_error("Could not allocate message.");
2931 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2933 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2934 /* There's always a fallback possible for
2935 * legacy actions. */
2940 log_error("Failed to issue method call: %s", bus_error_message(&error));
2949 dbus_message_unref(m);
2952 dbus_message_unref(reply);
2954 dbus_error_free(&error);
2959 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
2960 DBusMessage *m = NULL, *reply = NULL;
2966 dbus_error_init(&error);
2969 return daemon_reload(bus, args, n);
2971 for (i = 1; i < n; i++) {
2973 if (!(m = dbus_message_new_method_call(
2974 "org.freedesktop.systemd1",
2975 "/org/freedesktop/systemd1",
2976 "org.freedesktop.systemd1.Manager",
2977 "ResetFailedUnit"))) {
2978 log_error("Could not allocate message.");
2983 if (!dbus_message_append_args(m,
2984 DBUS_TYPE_STRING, args + i,
2985 DBUS_TYPE_INVALID)) {
2986 log_error("Could not append arguments to message.");
2991 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2992 log_error("Failed to issue method call: %s", bus_error_message(&error));
2997 dbus_message_unref(m);
2998 dbus_message_unref(reply);
3006 dbus_message_unref(m);
3009 dbus_message_unref(reply);
3011 dbus_error_free(&error);
3016 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3017 DBusMessage *m = NULL, *reply = NULL;
3019 DBusMessageIter iter, sub, sub2;
3022 *interface = "org.freedesktop.systemd1.Manager",
3023 *property = "Environment";
3025 dbus_error_init(&error);
3027 if (!(m = dbus_message_new_method_call(
3028 "org.freedesktop.systemd1",
3029 "/org/freedesktop/systemd1",
3030 "org.freedesktop.DBus.Properties",
3032 log_error("Could not allocate message.");
3036 if (!dbus_message_append_args(m,
3037 DBUS_TYPE_STRING, &interface,
3038 DBUS_TYPE_STRING, &property,
3039 DBUS_TYPE_INVALID)) {
3040 log_error("Could not append arguments to message.");
3045 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3046 log_error("Failed to issue method call: %s", bus_error_message(&error));
3051 if (!dbus_message_iter_init(reply, &iter) ||
3052 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3053 log_error("Failed to parse reply.");
3058 dbus_message_iter_recurse(&iter, &sub);
3060 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3061 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3062 log_error("Failed to parse reply.");
3067 dbus_message_iter_recurse(&sub, &sub2);
3069 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3072 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3073 log_error("Failed to parse reply.");
3078 dbus_message_iter_get_basic(&sub2, &text);
3079 printf("%s\n", text);
3081 dbus_message_iter_next(&sub2);
3088 dbus_message_unref(m);
3091 dbus_message_unref(reply);
3093 dbus_error_free(&error);
3098 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3099 DBusMessage *m = NULL, *reply = NULL;
3103 DBusMessageIter iter, sub;
3106 dbus_error_init(&error);
3108 method = streq(args[0], "set-environment")
3110 : "UnsetEnvironment";
3112 if (!(m = dbus_message_new_method_call(
3113 "org.freedesktop.systemd1",
3114 "/org/freedesktop/systemd1",
3115 "org.freedesktop.systemd1.Manager",
3118 log_error("Could not allocate message.");
3122 dbus_message_iter_init_append(m, &iter);
3124 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3125 log_error("Could not append arguments to message.");
3130 for (i = 1; i < n; i++)
3131 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3132 log_error("Could not append arguments to message.");
3137 if (!dbus_message_iter_close_container(&iter, &sub)) {
3138 log_error("Could not append arguments to message.");
3143 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3144 log_error("Failed to issue method call: %s", bus_error_message(&error));
3153 dbus_message_unref(m);
3156 dbus_message_unref(reply);
3158 dbus_error_free(&error);
3171 static Hashmap *will_install = NULL, *have_installed = NULL;
3172 static Set *remove_symlinks_to = NULL;
3174 static void install_info_free(InstallInfo *i) {
3179 strv_free(i->aliases);
3180 strv_free(i->wanted_by);
3184 static void install_info_hashmap_free(Hashmap *m) {
3187 while ((i = hashmap_steal_first(m)))
3188 install_info_free(i);
3193 static bool unit_name_valid(const char *name) {
3195 /* This is a minimal version of unit_name_valid() from
3201 if (ignore_file(name))
3207 static int install_info_add(const char *name) {
3211 assert(will_install);
3213 if (!unit_name_valid(name))
3216 if (hashmap_get(have_installed, name) ||
3217 hashmap_get(will_install, name))
3220 if (!(i = new0(InstallInfo, 1))) {
3225 if (!(i->name = strdup(name))) {
3230 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3237 install_info_free(i);
3242 static int config_parse_also(
3243 const char *filename,
3245 const char *section,
3259 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3263 if (!(n = strndup(w, l)))
3266 r = install_info_add(n);
3276 static int mark_symlink_for_removal(const char *p) {
3281 assert(path_is_absolute(p));
3283 if (!remove_symlinks_to)
3286 if (!(n = strdup(p)))
3289 path_kill_slashes(n);
3291 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3293 return r == -EEXIST ? 0 : r;
3299 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3308 if (!(d = fdopendir(fd))) {
3309 close_nointr_nofail(fd);
3315 while ((de = readdir(d))) {
3316 bool is_dir = false, is_link = false;
3318 if (ignore_file(de->d_name))
3321 if (de->d_type == DT_LNK)
3323 else if (de->d_type == DT_DIR)
3325 else if (de->d_type == DT_UNKNOWN) {
3328 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3329 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3336 is_link = S_ISLNK(st.st_mode);
3337 is_dir = S_ISDIR(st.st_mode);
3345 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3346 log_error("Failed to open %s/%s: %m", root, de->d_name);
3353 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3354 log_error("Failed to allocate directory string.");
3355 close_nointr_nofail(nfd);
3360 /* This will close nfd, regardless whether it succeeds or not */
3361 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3367 } else if (is_link) {
3371 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3372 log_error("Failed to allocate symlink string.");
3377 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3378 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3386 if ((c = canonicalize_file_name(dest))) {
3387 /* This might fail if the destination
3388 * is already removed */
3394 path_kill_slashes(dest);
3395 if (set_get(remove_symlinks_to, dest)) {
3398 log_info("rm '%s'", p);
3400 if (unlink(p) < 0) {
3401 log_error("Cannot unlink symlink %s: %m", p);
3406 rmdir_parents(p, config_path);
3407 path_kill_slashes(p);
3409 if (!set_get(remove_symlinks_to, p)) {
3411 if ((r = mark_symlink_for_removal(p)) < 0) {
3430 static int remove_marked_symlinks(const char *config_path) {
3434 assert(config_path);
3436 if (set_size(remove_symlinks_to) <= 0)
3439 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3446 if ((cfd = dup(fd)) < 0) {
3451 /* This takes possession of cfd and closes it */
3452 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3458 close_nointr_nofail(fd);
3463 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3470 if (streq(verb, "enable")) {
3473 mkdir_parents(new_path, 0755);
3475 if (symlink(old_path, new_path) >= 0) {
3478 log_info("ln -s '%s' '%s'", old_path, new_path);
3483 if (errno != EEXIST) {
3484 log_error("Cannot link %s to %s: %m", old_path, new_path);
3488 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3490 if (errno == EINVAL) {
3491 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3495 log_error("readlink() failed: %s", strerror(-r));
3499 if (streq(dest, old_path)) {
3505 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3514 log_info("ln -s '%s' '%s'", old_path, new_path);
3516 if (symlink(old_path, new_path) >= 0)
3519 log_error("Cannot link %s to %s: %m", old_path, new_path);
3522 } else if (streq(verb, "disable")) {
3525 if ((r = mark_symlink_for_removal(old_path)) < 0)
3528 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3529 if (errno == ENOENT)
3532 if (errno == EINVAL) {
3533 log_warning("File %s not a symlink, ignoring.", old_path);
3537 log_error("readlink() failed: %s", strerror(-r));
3541 if (!streq(dest, old_path)) {
3542 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3549 if ((r = mark_symlink_for_removal(new_path)) < 0)
3553 log_info("rm '%s'", new_path);
3555 if (unlink(new_path) >= 0)
3558 log_error("Cannot unlink %s: %m", new_path);
3561 } else if (streq(verb, "is-enabled")) {
3564 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3566 if (errno == ENOENT || errno == EINVAL)
3569 log_error("readlink() failed: %s", strerror(-r));
3573 if (streq(dest, old_path)) {
3581 assert_not_reached("Unknown action.");
3584 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3586 char *alias_path = NULL;
3591 assert(config_path);
3593 STRV_FOREACH(s, i->aliases) {
3595 if (!unit_name_valid(*s)) {
3596 log_error("Invalid name %s.", *s);
3602 if (!(alias_path = path_make_absolute(*s, config_path))) {
3603 log_error("Out of memory");
3608 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3611 if (streq(verb, "disable"))
3612 rmdir_parents(alias_path, config_path);
3623 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3625 char *alias_path = NULL;
3630 assert(config_path);
3632 STRV_FOREACH(s, i->wanted_by) {
3633 if (!unit_name_valid(*s)) {
3634 log_error("Invalid name %s.", *s);
3642 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3643 log_error("Out of memory");
3648 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3651 if (streq(verb, "disable"))
3652 rmdir_parents(alias_path, config_path);
3663 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3665 const ConfigItem items[] = {
3666 { "Alias", config_parse_strv, &i->aliases, "Install" },
3667 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3668 { "Also", config_parse_also, NULL, "Install" },
3670 { NULL, NULL, NULL, NULL }
3674 char *filename = NULL;
3681 STRV_FOREACH(p, paths->unit_path) {
3684 if (!(filename = path_make_absolute(i->name, *p))) {
3685 log_error("Out of memory");
3689 /* Ensure that we don't follow symlinks */
3690 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3691 if ((f = fdopen(fd, "re")))
3694 if (errno == ELOOP) {
3695 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3700 if (errno != ENOENT) {
3701 log_error("Failed to open %s: %m", filename);
3711 log_error("Couldn't find %s.", i->name);
3717 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3724 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3727 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3730 if ((r = mark_symlink_for_removal(filename)) < 0)
3733 if ((r = remove_marked_symlinks(config_path)) < 0)
3739 static char *get_config_path(void) {
3741 if (arg_session && arg_global)
3742 return strdup(SESSION_CONFIG_UNIT_PATH);
3747 if (session_config_home(&p) < 0)
3753 return strdup(SYSTEM_CONFIG_UNIT_PATH);
3756 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3760 char *config_path = NULL;
3763 const char *verb = args[0];
3765 dbus_error_init(&error);
3768 if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3769 log_error("Failed to determine lookup paths: %s", strerror(-r));
3773 if (!(config_path = get_config_path())) {
3774 log_error("Failed to determine config path");
3779 will_install = hashmap_new(string_hash_func, string_compare_func);
3780 have_installed = hashmap_new(string_hash_func, string_compare_func);
3782 if (!will_install || !have_installed) {
3783 log_error("Failed to allocate unit sets.");
3788 if (!arg_defaults && streq(verb, "disable"))
3789 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3790 log_error("Failed to allocate symlink sets.");
3795 for (j = 1; j < n; j++)
3796 if ((r = install_info_add(args[j])) < 0)
3799 while ((i = hashmap_first(will_install))) {
3802 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3804 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3812 /* In test mode and found something */
3818 if (streq(verb, "is-enabled"))
3819 r = r > 0 ? 0 : -ENOENT;
3821 /* Don't try to reload anything if the user asked us to not do this */
3823 /* Don't try to reload anything when updating a unit globally */
3825 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3826 (arg_session || sd_booted() > 0) &&
3827 /* Don't try to reload anything if we are running in a chroot environment */
3828 (arg_session || running_in_chroot() <= 0) ) {
3831 if ((q = daemon_reload(bus, args, n)) < 0)
3836 install_info_hashmap_free(will_install);
3837 install_info_hashmap_free(have_installed);
3839 set_free_free(remove_symlinks_to);
3841 lookup_paths_free(&paths);
3848 static int systemctl_help(void) {
3850 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3851 "Send control commands to or query the systemd manager.\n\n"
3852 " -h --help Show this help\n"
3853 " --version Show package version\n"
3854 " -t --type=TYPE List only units of a particular type\n"
3855 " -p --property=NAME Show only properties by this name\n"
3856 " -a --all Show all units/properties, including dead/empty ones\n"
3857 " --full Don't ellipsize unit names on output\n"
3858 " --fail When queueing a new job, fail if conflicting jobs are\n"
3860 " -q --quiet Suppress output\n"
3861 " --no-block Do not wait until operation finished\n"
3862 " --system Connect to system bus\n"
3863 " --session Connect to session bus\n"
3864 " --order When generating graph for dot, show only order\n"
3865 " --require When generating graph for dot, show only requirement\n"
3866 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3867 " --global Enable/disable unit files globally\n"
3868 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
3870 " --force When enabling unit files, override existing symlinks\n"
3871 " --defaults When disabling unit files, remove default symlinks only\n\n"
3873 " list-units List units\n"
3874 " start [NAME...] Start (activate) one or more units\n"
3875 " stop [NAME...] Stop (deactivate) one or more units\n"
3876 " reload [NAME...] Reload one or more units\n"
3877 " restart [NAME...] Start or restart one or more units\n"
3878 " try-restart [NAME...] Restart one or more units if active\n"
3879 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
3880 " otherwise start or restart\n"
3881 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3882 " otherwise restart if active\n"
3883 " isolate [NAME] Start one unit and stop all others\n"
3884 " is-active [NAME...] Check whether units are active\n"
3885 " status [NAME...|PID...] Show runtime status of one or more units\n"
3886 " show [NAME...|JOB...] Show properties of one or more\n"
3887 " units/jobs or the manager\n"
3888 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
3890 " enable [NAME...] Enable one or more unit files\n"
3891 " disable [NAME...] Disable one or more unit files\n"
3892 " is-enabled [NAME...] Check whether unit files are enabled\n"
3893 " load [NAME...] Load one or more units\n"
3894 " list-jobs List jobs\n"
3895 " cancel [JOB...] Cancel all, one, or more jobs\n"
3896 " monitor Monitor unit/job changes\n"
3897 " dump Dump server status\n"
3898 " dot Dump dependency graph for dot(1)\n"
3899 " snapshot [NAME] Create a snapshot\n"
3900 " delete [NAME...] Remove one or more snapshots\n"
3901 " daemon-reload Reload systemd manager configuration\n"
3902 " daemon-reexec Reexecute systemd manager\n"
3903 " daemon-exit Ask the systemd manager to quit\n"
3904 " show-environment Dump environment\n"
3905 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
3906 " unset-environment [NAME...] Unset one or more environment variables\n"
3907 " halt Shut down and halt the system\n"
3908 " poweroff Shut down and power-off the system\n"
3909 " reboot Shut down and reboot the system\n"
3910 " rescue Enter system rescue mode\n"
3911 " emergency Enter system emergency mode\n"
3912 " default Enter system default mode\n",
3913 program_invocation_short_name);
3918 static int halt_help(void) {
3920 printf("%s [OPTIONS...]\n\n"
3921 "%s the system.\n\n"
3922 " --help Show this help\n"
3923 " --halt Halt the machine\n"
3924 " -p --poweroff Switch off the machine\n"
3925 " --reboot Reboot the machine\n"
3926 " -f --force Force immediate halt/power-off/reboot\n"
3927 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3928 " -d --no-wtmp Don't write wtmp record\n"
3929 " -n --no-sync Don't sync before halt/power-off/reboot\n"
3930 " --no-wall Don't send wall message before halt/power-off/reboot\n",
3931 program_invocation_short_name,
3932 arg_action == ACTION_REBOOT ? "Reboot" :
3933 arg_action == ACTION_POWEROFF ? "Power off" :
3939 static int shutdown_help(void) {
3941 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
3942 "Shut down the system.\n\n"
3943 " --help Show this help\n"
3944 " -H --halt Halt the machine\n"
3945 " -P --poweroff Power-off the machine\n"
3946 " -r --reboot Reboot the machine\n"
3947 " -h Equivalent to --poweroff, overriden by --halt\n"
3948 " -k Don't halt/power-off/reboot, just send warnings\n"
3949 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3950 " -c Cancel a pending shutdown\n",
3951 program_invocation_short_name);
3956 static int telinit_help(void) {
3958 printf("%s [OPTIONS...] {COMMAND}\n\n"
3959 "Send control commands to the init daemon.\n\n"
3960 " --help Show this help\n"
3961 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
3963 " 0 Power-off the machine\n"
3964 " 6 Reboot the machine\n"
3965 " 2, 3, 4, 5 Start runlevelX.target unit\n"
3966 " 1, s, S Enter rescue mode\n"
3967 " q, Q Reload init daemon configuration\n"
3968 " u, U Reexecute init daemon\n",
3969 program_invocation_short_name);
3974 static int runlevel_help(void) {
3976 printf("%s [OPTIONS...]\n\n"
3977 "Prints the previous and current runlevel of the init system.\n\n"
3978 " --help Show this help\n",
3979 program_invocation_short_name);
3984 static int systemctl_parse_argv(int argc, char *argv[]) {
4002 static const struct option options[] = {
4003 { "help", no_argument, NULL, 'h' },
4004 { "version", no_argument, NULL, ARG_VERSION },
4005 { "type", required_argument, NULL, 't' },
4006 { "property", required_argument, NULL, 'p' },
4007 { "all", no_argument, NULL, 'a' },
4008 { "full", no_argument, NULL, ARG_FULL },
4009 { "fail", no_argument, NULL, ARG_FAIL },
4010 { "session", no_argument, NULL, ARG_SESSION },
4011 { "system", no_argument, NULL, ARG_SYSTEM },
4012 { "global", no_argument, NULL, ARG_GLOBAL },
4013 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
4014 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4015 { "quiet", no_argument, NULL, 'q' },
4016 { "order", no_argument, NULL, ARG_ORDER },
4017 { "require", no_argument, NULL, ARG_REQUIRE },
4018 { "force", no_argument, NULL, ARG_FORCE },
4019 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
4020 { "defaults", no_argument, NULL, ARG_DEFAULTS },
4021 { NULL, 0, NULL, 0 }
4029 while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
4038 puts(PACKAGE_STRING);
4040 puts(SYSTEMD_FEATURES);
4050 if (!(l = strv_append(arg_property, optarg)))
4053 strv_free(arg_property);
4056 /* If the user asked for a particular
4057 * property, show it to him, even if it is
4076 arg_session = false;
4080 arg_no_block = true;
4088 arg_dot = DOT_ORDER;
4092 arg_dot = DOT_REQUIRE;
4108 arg_no_reload = true;
4117 arg_defaults = true;
4124 log_error("Unknown option code %c", c);
4132 static int halt_parse_argv(int argc, char *argv[]) {
4141 static const struct option options[] = {
4142 { "help", no_argument, NULL, ARG_HELP },
4143 { "halt", no_argument, NULL, ARG_HALT },
4144 { "poweroff", no_argument, NULL, 'p' },
4145 { "reboot", no_argument, NULL, ARG_REBOOT },
4146 { "force", no_argument, NULL, 'f' },
4147 { "wtmp-only", no_argument, NULL, 'w' },
4148 { "no-wtmp", no_argument, NULL, 'd' },
4149 { "no-sync", no_argument, NULL, 'n' },
4150 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4151 { NULL, 0, NULL, 0 }
4159 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4160 if (runlevel == '0' || runlevel == '6')
4161 arg_immediate = true;
4163 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4171 arg_action = ACTION_HALT;
4175 if (arg_action != ACTION_REBOOT)
4176 arg_action = ACTION_POWEROFF;
4180 arg_action = ACTION_REBOOT;
4184 arg_immediate = true;
4205 /* Compatibility nops */
4212 log_error("Unknown option code %c", c);
4217 if (optind < argc) {
4218 log_error("Too many arguments.");
4225 static int parse_time_spec(const char *t, usec_t *_u) {
4229 if (streq(t, "now"))
4231 else if (t[0] == '+') {
4234 if (safe_atou64(t + 1, &u) < 0)
4237 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4246 hour = strtol(t, &e, 10);
4247 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4250 minute = strtol(e+1, &e, 10);
4251 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4254 n = now(CLOCK_REALTIME);
4255 s = (time_t) (n / USEC_PER_SEC);
4258 assert_se(localtime_r(&s, &tm));
4260 tm.tm_hour = (int) hour;
4261 tm.tm_min = (int) minute;
4264 assert_se(s = mktime(&tm));
4266 *_u = (usec_t) s * USEC_PER_SEC;
4269 *_u += USEC_PER_DAY;
4275 static int shutdown_parse_argv(int argc, char *argv[]) {
4282 static const struct option options[] = {
4283 { "help", no_argument, NULL, ARG_HELP },
4284 { "halt", no_argument, NULL, 'H' },
4285 { "poweroff", no_argument, NULL, 'P' },
4286 { "reboot", no_argument, NULL, 'r' },
4287 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4288 { NULL, 0, NULL, 0 }
4296 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4304 arg_action = ACTION_HALT;
4308 arg_action = ACTION_POWEROFF;
4312 arg_action = ACTION_REBOOT;
4316 if (arg_action != ACTION_HALT)
4317 arg_action = ACTION_POWEROFF;
4330 /* Compatibility nops */
4334 arg_action = ACTION_CANCEL_SHUTDOWN;
4341 log_error("Unknown option code %c", c);
4346 if (argc > optind) {
4347 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4348 log_error("Failed to parse time specification: %s", argv[optind]);
4352 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4354 /* We skip the time argument */
4355 if (argc > optind + 1)
4356 arg_wall = argv + optind + 1;
4363 static int telinit_parse_argv(int argc, char *argv[]) {
4370 static const struct option options[] = {
4371 { "help", no_argument, NULL, ARG_HELP },
4372 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4373 { NULL, 0, NULL, 0 }
4376 static const struct {
4380 { '0', ACTION_POWEROFF },
4381 { '6', ACTION_REBOOT },
4382 { '1', ACTION_RESCUE },
4383 { '2', ACTION_RUNLEVEL2 },
4384 { '3', ACTION_RUNLEVEL3 },
4385 { '4', ACTION_RUNLEVEL4 },
4386 { '5', ACTION_RUNLEVEL5 },
4387 { 's', ACTION_RESCUE },
4388 { 'S', ACTION_RESCUE },
4389 { 'q', ACTION_RELOAD },
4390 { 'Q', ACTION_RELOAD },
4391 { 'u', ACTION_REEXEC },
4392 { 'U', ACTION_REEXEC }
4401 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4416 log_error("Unknown option code %c", c);
4421 if (optind >= argc) {
4426 if (optind + 1 < argc) {
4427 log_error("Too many arguments.");
4431 if (strlen(argv[optind]) != 1) {
4432 log_error("Expected single character argument.");
4436 for (i = 0; i < ELEMENTSOF(table); i++)
4437 if (table[i].from == argv[optind][0])
4440 if (i >= ELEMENTSOF(table)) {
4441 log_error("Unknown command %s.", argv[optind]);
4445 arg_action = table[i].to;
4452 static int runlevel_parse_argv(int argc, char *argv[]) {
4458 static const struct option options[] = {
4459 { "help", no_argument, NULL, ARG_HELP },
4460 { NULL, 0, NULL, 0 }
4468 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4479 log_error("Unknown option code %c", c);
4484 if (optind < argc) {
4485 log_error("Too many arguments.");
4492 static int parse_argv(int argc, char *argv[]) {
4496 if (program_invocation_short_name) {
4498 if (strstr(program_invocation_short_name, "halt")) {
4499 arg_action = ACTION_HALT;
4500 return halt_parse_argv(argc, argv);
4501 } else if (strstr(program_invocation_short_name, "poweroff")) {
4502 arg_action = ACTION_POWEROFF;
4503 return halt_parse_argv(argc, argv);
4504 } else if (strstr(program_invocation_short_name, "reboot")) {
4505 arg_action = ACTION_REBOOT;
4506 return halt_parse_argv(argc, argv);
4507 } else if (strstr(program_invocation_short_name, "shutdown")) {
4508 arg_action = ACTION_POWEROFF;
4509 return shutdown_parse_argv(argc, argv);
4510 } else if (strstr(program_invocation_short_name, "init")) {
4512 if (sd_booted() > 0) {
4513 arg_action = ACTION_INVALID;
4514 return telinit_parse_argv(argc, argv);
4516 /* Hmm, so some other init system is
4517 * running, we need to forward this
4518 * request to it. For now we simply
4519 * guess that it is Upstart. */
4521 execv("/lib/upstart/telinit", argv);
4523 log_error("Couldn't find an alternative telinit implementation to spawn.");
4527 } else if (strstr(program_invocation_short_name, "runlevel")) {
4528 arg_action = ACTION_RUNLEVEL;
4529 return runlevel_parse_argv(argc, argv);
4533 arg_action = ACTION_SYSTEMCTL;
4534 return systemctl_parse_argv(argc, argv);
4537 static int action_to_runlevel(void) {
4539 static const char table[_ACTION_MAX] = {
4540 [ACTION_HALT] = '0',
4541 [ACTION_POWEROFF] = '0',
4542 [ACTION_REBOOT] = '6',
4543 [ACTION_RUNLEVEL2] = '2',
4544 [ACTION_RUNLEVEL3] = '3',
4545 [ACTION_RUNLEVEL4] = '4',
4546 [ACTION_RUNLEVEL5] = '5',
4547 [ACTION_RESCUE] = '1'
4550 assert(arg_action < _ACTION_MAX);
4552 return table[arg_action];
4555 static int talk_upstart(void) {
4556 DBusMessage *m = NULL, *reply = NULL;
4558 int previous, rl, r;
4560 env1_buf[] = "RUNLEVEL=X",
4561 env2_buf[] = "PREVLEVEL=X";
4562 char *env1 = env1_buf, *env2 = env2_buf;
4563 const char *emit = "runlevel";
4564 dbus_bool_t b_false = FALSE;
4565 DBusMessageIter iter, sub;
4566 DBusConnection *bus;
4568 dbus_error_init(&error);
4570 if (!(rl = action_to_runlevel()))
4573 if (utmp_get_runlevel(&previous, NULL) < 0)
4576 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4577 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4582 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4587 if ((r = bus_check_peercred(bus)) < 0) {
4588 log_error("Failed to verify owner of bus.");
4592 if (!(m = dbus_message_new_method_call(
4593 "com.ubuntu.Upstart",
4594 "/com/ubuntu/Upstart",
4595 "com.ubuntu.Upstart0_6",
4598 log_error("Could not allocate message.");
4603 dbus_message_iter_init_append(m, &iter);
4605 env1_buf[sizeof(env1_buf)-2] = rl;
4606 env2_buf[sizeof(env2_buf)-2] = previous;
4608 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4609 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4610 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4611 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4612 !dbus_message_iter_close_container(&iter, &sub) ||
4613 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4614 log_error("Could not append arguments to message.");
4619 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4621 if (error_is_no_service(&error)) {
4626 log_error("Failed to issue method call: %s", bus_error_message(&error));
4635 dbus_message_unref(m);
4638 dbus_message_unref(reply);
4641 dbus_connection_flush(bus);
4642 dbus_connection_close(bus);
4643 dbus_connection_unref(bus);
4646 dbus_error_free(&error);
4651 static int talk_initctl(void) {
4652 struct init_request request;
4656 if (!(rl = action_to_runlevel()))
4660 request.magic = INIT_MAGIC;
4661 request.sleeptime = 0;
4662 request.cmd = INIT_CMD_RUNLVL;
4663 request.runlevel = rl;
4665 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4667 if (errno == ENOENT)
4670 log_error("Failed to open "INIT_FIFO": %m");
4675 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4676 close_nointr_nofail(fd);
4679 log_error("Failed to write to "INIT_FIFO": %m");
4680 return errno ? -errno : -EIO;
4686 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4688 static const struct {
4696 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4698 { "list-units", LESS, 1, list_units },
4699 { "list-jobs", EQUAL, 1, list_jobs },
4700 { "clear-jobs", EQUAL, 1, daemon_reload },
4701 { "load", MORE, 2, load_unit },
4702 { "cancel", MORE, 2, cancel_job },
4703 { "start", MORE, 2, start_unit },
4704 { "stop", MORE, 2, start_unit },
4705 { "reload", MORE, 2, start_unit },
4706 { "restart", MORE, 2, start_unit },
4707 { "try-restart", MORE, 2, start_unit },
4708 { "reload-or-restart", MORE, 2, start_unit },
4709 { "reload-or-try-restart", MORE, 2, start_unit },
4710 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
4711 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
4712 { "isolate", EQUAL, 2, start_unit },
4713 { "is-active", MORE, 2, check_unit },
4714 { "check", MORE, 2, check_unit },
4715 { "show", MORE, 1, show },
4716 { "status", MORE, 2, show },
4717 { "monitor", EQUAL, 1, monitor },
4718 { "dump", EQUAL, 1, dump },
4719 { "dot", EQUAL, 1, dot },
4720 { "snapshot", LESS, 2, snapshot },
4721 { "delete", MORE, 2, delete_snapshot },
4722 { "daemon-reload", EQUAL, 1, daemon_reload },
4723 { "daemon-reexec", EQUAL, 1, daemon_reload },
4724 { "daemon-exit", EQUAL, 1, daemon_reload },
4725 { "show-environment", EQUAL, 1, show_enviroment },
4726 { "set-environment", MORE, 2, set_environment },
4727 { "unset-environment", MORE, 2, set_environment },
4728 { "halt", EQUAL, 1, start_special },
4729 { "poweroff", EQUAL, 1, start_special },
4730 { "reboot", EQUAL, 1, start_special },
4731 { "default", EQUAL, 1, start_special },
4732 { "rescue", EQUAL, 1, start_special },
4733 { "emergency", EQUAL, 1, start_special },
4734 { "reset-failed", MORE, 1, reset_failed },
4735 { "enable", MORE, 2, enable_unit },
4736 { "disable", MORE, 2, enable_unit },
4737 { "is-enabled", MORE, 2, enable_unit }
4747 left = argc - optind;
4750 /* Special rule: no arguments means "list-units" */
4753 if (streq(argv[optind], "help")) {
4758 for (i = 0; i < ELEMENTSOF(verbs); i++)
4759 if (streq(argv[optind], verbs[i].verb))
4762 if (i >= ELEMENTSOF(verbs)) {
4763 log_error("Unknown operation %s", argv[optind]);
4768 switch (verbs[i].argc_cmp) {
4771 if (left != verbs[i].argc) {
4772 log_error("Invalid number of arguments.");
4779 if (left < verbs[i].argc) {
4780 log_error("Too few arguments.");
4787 if (left > verbs[i].argc) {
4788 log_error("Too many arguments.");
4795 assert_not_reached("Unknown comparison operator.");
4798 /* Require a bus connection for all operations but
4800 if (!streq(verbs[i].verb, "enable") &&
4801 !streq(verbs[i].verb, "disable") &&
4803 log_error("Failed to get D-Bus connection: %s", error->message);
4807 return verbs[i].dispatch(bus, argv + optind, left);
4810 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
4812 struct msghdr msghdr;
4814 union sockaddr_union sockaddr;
4815 struct shutdownd_command c;
4823 strncpy(c.wall_message, message, sizeof(c.wall_message));
4825 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4829 sockaddr.sa.sa_family = AF_UNIX;
4830 sockaddr.un.sun_path[0] = 0;
4831 strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
4834 iovec.iov_base = (char*) &c;
4835 iovec.iov_len = sizeof(c);
4838 msghdr.msg_name = &sockaddr;
4839 msghdr.msg_namelen = sizeof(sa_family_t) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
4841 msghdr.msg_iov = &iovec;
4842 msghdr.msg_iovlen = 1;
4844 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
4845 close_nointr_nofail(fd);
4849 close_nointr_nofail(fd);
4853 static int reload_with_fallback(DBusConnection *bus) {
4856 /* First, try systemd via D-Bus. */
4857 if (daemon_reload(bus, NULL, 0) > 0)
4861 /* Nothing else worked, so let's try signals */
4862 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4864 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4865 log_error("kill() failed: %m");
4872 static int start_with_fallback(DBusConnection *bus) {
4875 /* First, try systemd via D-Bus. */
4876 if (start_unit(bus, NULL, 0) >= 0)
4880 /* Hmm, talking to systemd via D-Bus didn't work. Then
4881 * let's try to talk to Upstart via D-Bus. */
4882 if (talk_upstart() > 0)
4885 /* Nothing else worked, so let's try
4887 if (talk_initctl() > 0)
4890 log_error("Failed to talk to init daemon.");
4894 warn_wall(arg_action);
4898 static int halt_main(DBusConnection *bus) {
4901 if (geteuid() != 0) {
4902 log_error("Must be root.");
4908 char date[FORMAT_TIMESTAMP_MAX];
4910 m = strv_join(arg_wall, " ");
4911 r = send_shutdownd(arg_when,
4912 arg_action == ACTION_HALT ? 'H' :
4913 arg_action == ACTION_POWEROFF ? 'P' :
4920 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
4922 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
4923 format_timestamp(date, sizeof(date), arg_when));
4928 if (!arg_dry && !arg_immediate)
4929 return start_with_fallback(bus);
4932 if (sd_booted() > 0)
4933 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
4934 else if ((r = utmp_put_shutdown(0)) < 0)
4935 log_warning("Failed to write utmp record: %s", strerror(-r));
4944 /* Make sure C-A-D is handled by the kernel from this
4946 reboot(RB_ENABLE_CAD);
4948 switch (arg_action) {
4951 log_info("Halting.");
4952 reboot(RB_HALT_SYSTEM);
4955 case ACTION_POWEROFF:
4956 log_info("Powering off.");
4957 reboot(RB_POWER_OFF);
4961 log_info("Rebooting.");
4962 reboot(RB_AUTOBOOT);
4966 assert_not_reached("Unknown halt action.");
4969 /* We should never reach this. */
4973 static int runlevel_main(void) {
4974 int r, runlevel, previous;
4976 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4977 printf("unknown\n");
4982 previous <= 0 ? 'N' : previous,
4983 runlevel <= 0 ? 'N' : runlevel);
4988 int main(int argc, char*argv[]) {
4989 int r, retval = EXIT_FAILURE;
4990 DBusConnection *bus = NULL;
4993 dbus_error_init(&error);
4995 log_parse_environment();
4998 if ((r = parse_argv(argc, argv)) < 0)
5001 retval = EXIT_SUCCESS;
5005 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5006 * let's shortcut this */
5007 if (arg_action == ACTION_RUNLEVEL) {
5008 r = runlevel_main();
5009 retval = r < 0 ? EXIT_FAILURE : r;
5013 bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5015 switch (arg_action) {
5017 case ACTION_SYSTEMCTL:
5018 r = systemctl_main(bus, argc, argv, &error);
5022 case ACTION_POWEROFF:
5027 case ACTION_RUNLEVEL2:
5028 case ACTION_RUNLEVEL3:
5029 case ACTION_RUNLEVEL4:
5030 case ACTION_RUNLEVEL5:
5032 case ACTION_EMERGENCY:
5033 case ACTION_DEFAULT:
5034 r = start_with_fallback(bus);
5039 r = reload_with_fallback(bus);
5042 case ACTION_CANCEL_SHUTDOWN:
5043 r = send_shutdownd(0, 0, false, NULL);
5046 case ACTION_INVALID:
5047 case ACTION_RUNLEVEL:
5049 assert_not_reached("Unknown action");
5052 retval = r < 0 ? EXIT_FAILURE : r;
5057 dbus_connection_flush(bus);
5058 dbus_connection_close(bus);
5059 dbus_connection_unref(bus);
5062 dbus_error_free(&error);
5066 strv_free(arg_property);